Skip to main content

Encode

Trait Encode 

Source
pub trait Encode {
    // Required methods
    fn write_byte(&mut self, byte: u8) -> Result<()>;
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;

    // Provided methods
    fn reserve(&mut self, additional: usize) { ... }
    fn write_varint_u64(&mut self, value: u64) -> Result<()> { ... }
    fn write_varint_u128(&mut self, value: u128) -> Result<()> { ... }
}
Expand description

Sink that a Serialize implementation writes its wire-format bytes into.

Implemented by every concrete encoder in the crate (Encoder for the in-memory case, crate::IoEncoder for std::io::Write streams). User code rarely implements Encode directly — Serialize impls are written generically over E: Encode so a single impl works for every encoder flavour.

§Examples

use pack_io::{Encode, Encoder, Result};

// A helper that writes a length-prefixed list of `u32`s into any encoder.
fn write_u32_list<E: Encode>(enc: &mut E, items: &[u32]) -> Result<()> {
    enc.write_varint_u64(items.len() as u64)?;
    for item in items {
        enc.write_varint_u64(u64::from(*item))?;
    }
    Ok(())
}

let mut enc = Encoder::new();
write_u32_list(&mut enc, &[1, 2, 3]).unwrap();

Required Methods§

Source

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

Append a single byte.

§Errors

Returns the encoder’s underlying error variant (I/O failure for streaming encoders; never errors for the in-memory Encoder).

Source

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

Append a slice of bytes.

§Errors

Same as Encode::write_byte.

Provided Methods§

Source

fn reserve(&mut self, additional: usize)

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

In-memory encoders MAY pre-allocate the requested capacity to avoid intermediate Vec growth. Streaming encoders typically ignore the hint. The default implementation is a no-op.

Source

fn write_varint_u64(&mut self, value: u64) -> Result<()>

Append a u64 as an unsigned LEB128 varint (1–10 bytes).

§Errors

Same as Encode::write_bytes.

Source

fn write_varint_u128(&mut self, value: u128) -> Result<()>

Append a u128 as an unsigned LEB128 varint (1–19 bytes).

§Errors

Same as Encode::write_bytes.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl Encode for Encoder

Source§

impl<W: Write> Encode for IoEncoder<W>

Available on crate feature std only.