Skip to main content

Decoder

Struct Decoder 

Source
pub struct Decoder<'a> { /* private fields */ }
Expand description

In-memory decoder. Borrows from an input slice and advances a position pointer as values are read. Bounds-checked on every operation.

Implements Decode, so Deserialize impls written generically over D: Decode work directly through it.

§Examples

use pack_io::{Encoder, Decoder};

let mut enc = Encoder::new();
enc.write(&7_u64).unwrap();
enc.write(&true).unwrap();
let bytes = enc.into_inner();

let mut dec = Decoder::new(&bytes);
let n: u64 = dec.read().unwrap();
let b: bool = dec.read().unwrap();
assert_eq!(n, 7);
assert!(b);
assert!(dec.is_empty());

Implementations§

Source§

impl<'a> Decoder<'a>

Source

pub fn new(bytes: &'a [u8]) -> Self

Construct a decoder over bytes using the default Config (1 GiB max_alloc).

For tighter allocation limits on untrusted input, use Decoder::with_config instead.

§Examples
use pack_io::Decoder;

let bytes = pack_io::encode(&42_u64).unwrap();
let mut dec = Decoder::new(&bytes);
let n: u64 = dec.read().unwrap();
assert_eq!(n, 42);
Source

pub fn with_config(bytes: &'a [u8], config: Config) -> Result<Self>

Construct a decoder with the supplied configuration.

Use this when the input comes from an untrusted producer and the caller wants to bound per-value allocations.

§Errors

Returns SerialError::InvalidLength if config.max_alloc == 0.

§Examples
use pack_io::{Config, Decoder};

let cfg = Config::new().with_max_alloc(16 * 1024); // 16 KiB cap
let bytes = pack_io::encode(&"hello").unwrap();
let mut dec = Decoder::with_config(&bytes, cfg).unwrap();
let s: String = dec.read().unwrap();
assert_eq!(s, "hello");
Source

pub fn position(&self) -> usize

Bytes consumed so far from the start of the input.

§Examples
use pack_io::Decoder;

let bytes = pack_io::encode(&(1_u8, 2_u8)).unwrap();
let mut dec = Decoder::new(&bytes);
assert_eq!(dec.position(), 0);
let _: u8 = dec.read().unwrap();
assert_eq!(dec.position(), 1);
Source

pub fn remaining(&self) -> usize

Number of bytes remaining in the input.

§Examples
use pack_io::Decoder;

let bytes = pack_io::encode(&(1_u8, 2_u8, 3_u8)).unwrap();
let mut dec = Decoder::new(&bytes);
assert_eq!(dec.remaining(), 3);
let _: u8 = dec.read().unwrap();
assert_eq!(dec.remaining(), 2);
Source

pub fn is_empty(&self) -> bool

True when there are no more bytes to read.

Useful as the loop condition for multi-value decode passes that don’t have an explicit count up front.

§Examples
use pack_io::{Encoder, Decoder};

let mut enc = Encoder::new();
enc.write(&1_u64).unwrap();
enc.write(&2_u64).unwrap();
let bytes = enc.into_inner();

let mut dec = Decoder::new(&bytes);
let mut sum = 0_u64;
while !dec.is_empty() {
    sum += dec.read::<u64>().unwrap();
}
assert_eq!(sum, 3);
Source

pub fn read<T: Deserialize>(&mut self) -> Result<T>

Decode a value of type T from the current position, advancing the cursor by the number of bytes the value consumed.

§Errors

Returns any SerialError surfaced by T::deserialize.

§Examples

Reading several values in sequence:

use pack_io::{Encoder, Decoder};

let mut enc = Encoder::new();
enc.write(&7_u64).unwrap();
enc.write(&"hello").unwrap();
let bytes = enc.into_inner();

let mut dec = Decoder::new(&bytes);
let n: u64 = dec.read().unwrap();
let s: String = dec.read().unwrap();
assert_eq!((n, s.as_str()), (7, "hello"));

Reading a tuple in a single call:

use pack_io::Decoder;

let bytes = pack_io::encode(&(7_u64, true)).unwrap();
let mut dec = Decoder::new(&bytes);
let pair: (u64, bool) = dec.read().unwrap();
assert_eq!(pair, (7, true));
Source

pub fn read_length_prefixed_borrowed(&mut self) -> Result<&'a [u8]>

Read a length-prefixed byte run as a borrowed slice of the underlying input — no allocation, no copy.

The borrowed slice has the same lifetime 'a as the decoder’s input buffer, which lets caller-side &'a str / &'a [u8] decode paths return a borrow directly into that buffer. This is the seam the zero-copy crate::DeserializeView surface plugs into for &'a str and &'a [u8].

§Errors
  • SerialError::InvalidLength if the prefix exceeds the configured max_alloc, OR exceeds the remaining input.
  • SerialError::UnexpectedEof is folded into InvalidLength for this method, since the buffer length is known up front and a declared length running off the end is logically a length-prefix error, not a streaming EOF.

Trait Implementations§

Source§

impl<'a> Debug for Decoder<'a>

Source§

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

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

impl Decode for Decoder<'_>

Source§

fn read_length_prefixed(&mut self) -> Result<Vec<u8>>

In-memory specialisation: validates length against the actual buffer length too, not just max_alloc. Catches truncated inputs without allocating.

Source§

fn read_byte(&mut self) -> Result<u8>

Read the next byte, advancing the cursor. Read more
Source§

fn read_into(&mut self, out: &mut [u8]) -> Result<()>

Fill out with exactly out.len() bytes, advancing the cursor. Read more
Source§

fn max_alloc(&self) -> usize

Maximum number of bytes the decoder will allocate for a single length-prefixed value. Mirrors Config::max_alloc.
Source§

fn read_varint_u64(&mut self) -> Result<u64>

Read a LEB128 varint as a u64. Read more
Source§

fn read_varint_u128(&mut self) -> Result<u128>

Read a LEB128 varint as a u128. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Decoder<'a>

§

impl<'a> RefUnwindSafe for Decoder<'a>

§

impl<'a> Send for Decoder<'a>

§

impl<'a> Sync for Decoder<'a>

§

impl<'a> Unpin for Decoder<'a>

§

impl<'a> UnsafeUnpin for Decoder<'a>

§

impl<'a> UnwindSafe for Decoder<'a>

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.