From 079c278e007a7efc5d9744aa4ab44d350508a3a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dj8yf0=CE=BCl?= <26653921+dj8yfo@users.noreply.github.com> Date: Mon, 2 Oct 2023 17:25:42 +0300 Subject: [PATCH] doc: add examples for `borsh::to_vec`, `borsh::to_writer`, `borsh::object_length` (#238) --- borsh/src/ser/helpers.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/borsh/src/ser/helpers.rs b/borsh/src/ser/helpers.rs index 4f00d5ab4..da4da27da 100644 --- a/borsh/src/ser/helpers.rs +++ b/borsh/src/ser/helpers.rs @@ -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(value: &T) -> Result> where T: BorshSerialize + ?Sized, @@ -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(mut writer: W, value: &T) -> Result<()> where T: BorshSerialize + ?Sized, @@ -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(value: &T) -> Result where T: BorshSerialize + ?Sized,