Skip to content

Commit 079c278

Browse files
authored
doc: add examples for borsh::to_vec, borsh::to_writer, borsh::object_length (#238)
1 parent 57f9c25 commit 079c278

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

borsh/src/ser/helpers.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ use crate::io::{ErrorKind, Result, Write};
55
pub(super) const DEFAULT_SERIALIZER_CAPACITY: usize = 1024;
66

77
/// Serialize an object into a vector of bytes.
8+
/// # Example
9+
///
10+
/// ```
11+
/// assert_eq!(vec![12, 0, 0, 0, 0, 0, 0, 0], borsh::to_vec(&12u64).unwrap());
12+
/// ```
813
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
914
where
1015
T: BorshSerialize + ?Sized,
@@ -15,6 +20,14 @@ where
1520
}
1621

1722
/// Serializes an object directly into a `Writer`.
23+
/// # Example
24+
///
25+
/// ```
26+
/// # #[cfg(feature = "std")]
27+
/// let stderr = std::io::stderr();
28+
/// # #[cfg(feature = "std")]
29+
/// assert_eq!((), borsh::to_writer(&stderr, "hello_0x0a").unwrap());
30+
/// ```
1831
pub fn to_writer<T, W: Write>(mut writer: W, value: &T) -> Result<()>
1932
where
2033
T: BorshSerialize + ?Sized,
@@ -23,6 +36,26 @@ where
2336
}
2437

2538
/// Serializes an object without allocation to compute and return its length
39+
/// # Example
40+
///
41+
/// ```
42+
/// use borsh::BorshSerialize;
43+
///
44+
/// /// derive is only available if borsh is built with `features = ["derive"]`
45+
/// # #[cfg(feature = "derive")]
46+
/// #[derive(BorshSerialize)]
47+
/// struct A {
48+
/// tag: String,
49+
/// value: u64,
50+
/// };
51+
///
52+
/// # #[cfg(feature = "derive")]
53+
/// let a = A { tag: "hello".to_owned(), value: 42 };
54+
///
55+
/// assert_eq!(8, borsh::object_length(&12u64).unwrap());
56+
/// # #[cfg(feature = "derive")]
57+
/// assert_eq!(17, borsh::object_length(&a).unwrap());
58+
/// ```
2659
pub fn object_length<T>(value: &T) -> Result<usize>
2760
where
2861
T: BorshSerialize + ?Sized,

0 commit comments

Comments
 (0)