Skip to content

Commit

Permalink
feat: implement ser::to_vec() for convenient serializing into a new V…
Browse files Browse the repository at this point in the history
…ec<u8>

such shortcut is usually included in serde format libraries

Signed-off-by: Iaroslav Gridin <[email protected]>
  • Loading branch information
Voker57 committed Jun 14, 2024
1 parent 7a9dd8f commit 351a4d3
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
3 changes: 3 additions & 0 deletions ciborium/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ pub use crate::de::from_reader_with_buffer;
#[doc(inline)]
pub use crate::ser::into_writer;

#[doc(inline)]
pub use crate::ser::into_vec;

#[doc(inline)]
pub use crate::value::Value;

Expand Down
11 changes: 11 additions & 0 deletions ciborium/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,3 +497,14 @@ where
let mut encoder = Serializer::from(writer);
value.serialize(&mut encoder)
}

/// Serializes as CBOR into a new Vec<u8>
#[inline]
pub fn into_vec<T: ?Sized + ser::Serialize>(
value: &T,
) -> Result<Vec<u8>, Error<<Vec<u8> as ciborium_io::Write>::Error>> {
let mut vector = vec![];
let mut encoder = Serializer::from(&mut vector);
value.serialize(&mut encoder)?;
Ok(vector)
}
10 changes: 5 additions & 5 deletions ciborium/tests/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use std::convert::TryFrom;
use std::fmt::Debug;

use ciborium::value::Value;
use ciborium::{cbor, de::from_reader, de::from_reader_with_buffer, ser::into_writer};
use ciborium::{
cbor, de::from_reader, de::from_reader_with_buffer, ser::into_vec, ser::into_writer,
};

use rstest::rstest;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
Expand Down Expand Up @@ -290,13 +292,11 @@ fn codec<'de, T: Serialize + Clone, V: Debug + PartialEq + DeserializeOwned, F:
let bytes = hex::decode(bytes).unwrap();

if !alternate {
let mut encoded = Vec::new();
into_writer(&input, &mut encoded).unwrap();
let encoded = into_vec(&input).unwrap();
eprintln!("{:x?} == {:x?}", bytes, encoded);
assert_eq!(bytes, encoded);

let mut encoded = Vec::new();
into_writer(&value, &mut encoded).unwrap();
let encoded = into_vec(&value).unwrap();
eprintln!("{:x?} == {:x?}", bytes, encoded);
assert_eq!(bytes, encoded);

Expand Down

0 comments on commit 351a4d3

Please sign in to comment.