pub struct Buffer(_);Expand description
A buffer for reusing allocations between any number of calls to Buffer::serialize and/or
Buffer::deserialize.
Usage
ⓘ
use bitcode::Buffer;
// We preallocate buffers with capacity 1000. This will allow us to serialize and deserialize
// without any allocations as long as the encoded object takes less than 1000 bytes.
let bytes = 1000;
let mut ser_buf = Buffer::with_capacity(bytes);
let mut de_buf = Buffer::with_capacity(bytes);
// The object that we will serialize.
let target: [u8; 5] = [1, 2, 3, 4, 5];
// We serialize into `ser_buf`. This won't cause any allocations.
let encoded: &[u8] = ser_buf.serialize(&target).unwrap();
assert!(encoded.len() <= bytes, "oh no we allocated");
// We deserialize into `de_buf` because `encoded` is borrowing `ser_buf`.
let decoded: [u8; 5] = de_buf.deserialize(&encoded).unwrap();
assert_eq!(target, decoded);
// If we need ownership of `encoded`, we can convert it to a vec.
// This will allocate, but it's still more efficient than calling bitcode::serialize.
let _owned: Vec<u8> = encoded.to_vec();Implementations§
source§impl Buffer
impl Buffer
sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Constructs a new buffer with at least the specified capacity in bytes.
source§impl Buffer
impl Buffer
sourcepub fn deserialize<'a, T>(&mut self, bytes: &'a [u8]) -> Result<T, Error>where
T: Deserialize<'a>,
pub fn deserialize<'a, T>(&mut self, bytes: &'a [u8]) -> Result<T, Error>where T: Deserialize<'a>,
Deserializes a &[u8] into an instance of T: Deserialize. Can reuse
the buffer’s allocations.
Warning: The format is subject to change between versions.