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

gated by 'std' feature

Signed-off-by: Voker57 <[email protected]>
  • Loading branch information
Voker57 authored and rjzak committed Nov 27, 2024
1 parent 7c6ba83 commit c637e7b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
4 changes: 4 additions & 0 deletions ciborium/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ pub use crate::de::from_reader_with_buffer;
#[doc(inline)]
pub use crate::ser::into_writer;

#[cfg(feature = "std")]
#[doc(inline)]
pub use crate::ser::into_vec;

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

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

#[cfg(feature = "std")]
/// 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)
}
2 changes: 1 addition & 1 deletion ciborium/tests/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ fn codec<'de, T: Serialize + Clone, V: Debug + PartialEq + DeserializeOwned, F:
assert_eq!(bytes, encoded);

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

Expand Down

0 comments on commit c637e7b

Please sign in to comment.