From c637e7b9178ffa55110565be70233fc2ec1fe706 Mon Sep 17 00:00:00 2001 From: Voker57 Date: Fri, 14 Jun 2024 14:01:36 +0300 Subject: [PATCH] feat: implement ser::to_vec() for convenient serializing into a new Vec such shortcut is usually included in serde format libraries gated by 'std' feature Signed-off-by: Voker57 --- ciborium/src/lib.rs | 4 ++++ ciborium/src/ser/mod.rs | 12 ++++++++++++ ciborium/tests/codec.rs | 2 +- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/ciborium/src/lib.rs b/ciborium/src/lib.rs index f143943..cbbddf1 100644 --- a/ciborium/src/lib.rs +++ b/ciborium/src/lib.rs @@ -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; diff --git a/ciborium/src/ser/mod.rs b/ciborium/src/ser/mod.rs index 03dd1da..a5ad23d 100644 --- a/ciborium/src/ser/mod.rs +++ b/ciborium/src/ser/mod.rs @@ -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 +#[inline] +pub fn into_vec( + value: &T, +) -> Result, Error< as ciborium_io::Write>::Error>> { + let mut vector = vec![]; + let mut encoder = Serializer::from(&mut vector); + value.serialize(&mut encoder)?; + Ok(vector) +} diff --git a/ciborium/tests/codec.rs b/ciborium/tests/codec.rs index 560762b..bb66364 100644 --- a/ciborium/tests/codec.rs +++ b/ciborium/tests/codec.rs @@ -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);