Skip to main content

Encoder

Struct Encoder 

Source
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

Source

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());
Source

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());
Source

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());
Source

pub fn as_bytes(&self) -> &[u8]

Borrow the encoded bytes accumulated so far, without consuming the encoder.

Prefer this over Encoder::into_inner when the caller wants to send / hash / inspect the bytes but keep writing more values.

§Examples
use pack_io::Encoder;

let mut enc = Encoder::new();
enc.write(&1_u64).unwrap();
let snapshot = enc.as_bytes().to_vec();
enc.write(&2_u64).unwrap();
assert_eq!(snapshot, &[0x01]);
assert_eq!(enc.as_bytes(), &[0x01, 0x02]);
Source

pub fn into_inner(self) -> Vec<u8>

Consume the encoder and return its underlying buffer.

The returned Vec<u8> is the exact bytes accumulated by every preceding write call.

§Examples
use pack_io::Encoder;

let mut enc = Encoder::new();
enc.write(&7_u64).unwrap();
let bytes: Vec<u8> = enc.into_inner();
assert_eq!(bytes, &[0x07]);
Source

pub fn take(&mut self) -> Vec<u8>

Swap the encoder’s buffer with a fresh empty one, returning the bytes written so far. Useful for “encode then send” loops that want to re-use the encoder across many messages.

After take, the encoder is empty and ready to encode the next message. The returned buffer is the previous contents.

§Examples
use pack_io::Encoder;

let mut enc = Encoder::new();
enc.write(&1_u64).unwrap();
let first = enc.take();
enc.write(&2_u64).unwrap();
let second = enc.take();
assert_eq!(first, &[0x01]);
assert_eq!(second, &[0x02]);
assert!(enc.as_bytes().is_empty());
Source

pub fn write<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()>

Encode value, appending its bytes to the internal buffer.

This is the Serialize-aware sibling of Encode::write_bytes. Prefer it for typed values; reserve write_bytes for raw byte passthrough.

§Errors

Propagates any error returned by the type’s Serialize implementation. The built-in primitive and collection impls in this crate never error on an in-memory encoder.

§Examples

Writing several values in sequence:

use pack_io::Encoder;

let mut enc = Encoder::new();
enc.write(&7_u64).unwrap();
enc.write(&"hello").unwrap();
enc.write(&vec![1u8, 2, 3]).unwrap();
assert!(!enc.as_bytes().is_empty());

Encoding a tuple in one call (anything that implements Serialize works):

use pack_io::Encoder;

let mut enc = Encoder::new();
enc.write(&(7_u64, "hello", true)).unwrap();
assert!(!enc.as_bytes().is_empty());

Trait Implementations§

Source§

impl Debug for Encoder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Encoder

Source§

fn default() -> Encoder

Returns the “default value” for a type. Read more
Source§

impl Encode for Encoder

Source§

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<()>

Same specialisation as Encode::write_varint_u64, widened to 128 bits.

Source§

fn write_byte(&mut self, byte: u8) -> Result<()>

Append a single byte. Read more
Source§

fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>

Append a slice of bytes. Read more
Source§

fn reserve(&mut self, additional: usize)

Hint that the caller is about to write additional more bytes. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.