Skip to content

Commit

Permalink
doc: add examples for borsh::to_vec, borsh::to_writer, `borsh::ob…
Browse files Browse the repository at this point in the history
…ject_length` (#238)
  • Loading branch information
dj8yfo committed Oct 2, 2023
1 parent 57f9c25 commit 079c278
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 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 @@ -15,6 +20,14 @@ where
}

/// Serializes an object directly into a `Writer`.
/// # Example
///
/// ```
/// # #[cfg(feature = "std")]
/// let stderr = std::io::stderr();
/// # #[cfg(feature = "std")]
/// assert_eq!((), borsh::to_writer(&stderr, "hello_0x0a").unwrap());
/// ```
pub fn to_writer<T, W: Write>(mut writer: W, value: &T) -> Result<()>
where
T: BorshSerialize + ?Sized,
Expand All @@ -23,6 +36,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 079c278

Please sign in to comment.