From 351a4d3ed2f4c9203d85697d2f8099fb7d7ed8b1 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 Signed-off-by: Iaroslav Gridin --- ciborium/src/lib.rs | 3 +++ ciborium/src/ser/mod.rs | 11 +++++++++++ ciborium/tests/codec.rs | 10 +++++----- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/ciborium/src/lib.rs b/ciborium/src/lib.rs index f143943..68215be 100644 --- a/ciborium/src/lib.rs +++ b/ciborium/src/lib.rs @@ -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; diff --git a/ciborium/src/ser/mod.rs b/ciborium/src/ser/mod.rs index 03dd1da..52d02fc 100644 --- a/ciborium/src/ser/mod.rs +++ b/ciborium/src/ser/mod.rs @@ -497,3 +497,14 @@ where let mut encoder = Serializer::from(writer); value.serialize(&mut encoder) } + +/// 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..641165a 100644 --- a/ciborium/tests/codec.rs +++ b/ciborium/tests/codec.rs @@ -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}; @@ -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);