Skip to content

Commit

Permalink
doc: add examples for borsh::to_vec and borsh::object_length
Browse files Browse the repository at this point in the history
  • Loading branch information
dj8yf0μl committed Oct 2, 2023
1 parent 57f9c25 commit b000f40
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions borsh/src/ser/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ use crate::io::{ErrorKind, Result, Write};
pub(super) const DEFAULT_SERIALIZER_CAPACITY: usize = 1024;

/// Serialize an object into a vector of bytes.
/// # Example
///
/// ```
/// assert_eq!(vec![12, 0, 0, 0, 0, 0, 0, 0], borsh::to_vec(&12u64).unwrap());
/// ```
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
where
T: BorshSerialize + ?Sized,
Expand All @@ -23,6 +28,26 @@ where
}

/// Serializes an object without allocation to compute and return its length
/// # Example
///
/// ```
/// use borsh::BorshSerialize;
///
/// /// derive is only available if borsh is built with `features = ["derive"]`
/// # #[cfg(feature = "derive")]
/// #[derive(BorshSerialize)]
/// struct A {
/// tag: String,
/// value: u64,
/// };
///
/// # #[cfg(feature = "derive")]
/// let a = A { tag: "hello".to_owned(), value: 42 };
///
/// assert_eq!(8, borsh::object_length(&12u64).unwrap());
/// # #[cfg(feature = "derive")]
/// assert_eq!(17, borsh::object_length(&a).unwrap());
/// ```
pub fn object_length<T>(value: &T) -> Result<usize>
where
T: BorshSerialize + ?Sized,
Expand Down

0 comments on commit b000f40

Please sign in to comment.