pub struct Encoder { /* private fields */ }Expand description
In-memory encoder. Writes into an owned Vec<u8>; the buffer can be
reused across encodes by calling Encoder::take to swap it out.
Implements Encode, so Serialize impls written generically over
E: Encode work directly through it.
§Examples
use pack_io::Encoder;
let mut enc = Encoder::new();
enc.write(&7_u64).unwrap();
enc.write(&"hello").unwrap();
let bytes = enc.into_inner();
assert!(bytes.len() > 0);Implementations§
Source§impl Encoder
impl Encoder
Sourcepub fn new() -> Self
pub fn new() -> Self
Construct an encoder with an empty output buffer.
§Examples
let enc = pack_io::Encoder::new();
assert!(enc.as_bytes().is_empty());Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Construct an encoder with an output buffer pre-allocated to
capacity bytes.
Choose this over Encoder::new when the encoded size is roughly
known: a single Vec::with_capacity up front avoids the four to
eight grow-and-copy reallocations that a zero-capacity Vec
performs while doubling to the final size.
capacity is a hint — the encoder still grows the buffer if the
encoded value exceeds it. Setting it slightly too high is harmless;
setting it slightly too low costs at most one growth.
The Tier-1 crate::encode free function uses a small default
capacity internally so most one-shot encodes never grow at all.
§Examples
let enc = pack_io::Encoder::with_capacity(256);
assert!(enc.as_bytes().is_empty());Sourcepub fn into_buffer(buffer: Vec<u8>) -> Self
pub fn into_buffer(buffer: Vec<u8>) -> Self
Construct an encoder backed by buffer. The encoder appends to the
buffer rather than allocating its own — callers that re-use a single
Vec<u8> across many encodes avoid the per-call allocation.
§Examples
use pack_io::Encoder;
let buf = Vec::with_capacity(64);
let mut enc = Encoder::into_buffer(buf);
enc.write(&42_u64).unwrap();
let buf = enc.into_inner();
assert!(!buf.is_empty());Sourcepub fn into_inner(self) -> Vec<u8> ⓘ
pub fn into_inner(self) -> Vec<u8> ⓘ
Consume the encoder and return its underlying buffer.
Trait Implementations§
Source§impl Encode for Encoder
impl Encode for Encoder
Source§fn write_varint_u64(&mut self, value: u64) -> Result<()>
fn write_varint_u64(&mut self, value: u64) -> Result<()>
Override of Encode::write_varint_u64 specialised for the in-memory
encoder. Pushes each varint byte directly onto the underlying Vec,
reserving the full max-width up front so the loop never re-checks
capacity. Avoids the stack-buffer + extend_from_slice round-trip
the default impl would perform.
Source§fn write_varint_u128(&mut self, value: u128) -> Result<()>
fn write_varint_u128(&mut self, value: u128) -> Result<()>
Same specialisation as Encode::write_varint_u64, widened to 128
bits.