Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement ser::to_vec() for convenient serializing into a new Vec<u8> #128

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading