Skip to main content

Decode

Trait Decode 

Source
pub trait Decode {
Show 17 methods // Required methods fn read_byte(&mut self) -> Result<u8>; fn read_into(&mut self, out: &mut [u8]) -> Result<()>; fn max_alloc(&self) -> usize; // Provided methods fn remaining_hint(&self) -> Option<usize> { ... } fn config(&self) -> Config { ... } fn depth(&self) -> usize { ... } fn enter_nested(&mut self) -> Result<()> { ... } fn leave_nested(&mut self) { ... } fn consumed(&self) -> Option<&[u8]> { ... } fn bytes_read(&self) -> Option<u64> { ... } fn unbacked(&self) -> usize { ... } fn charge_unbacked(&mut self, bytes: usize) -> Result<()> { ... } fn reset_unbacked(&mut self) { ... } fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>> { ... } fn read_varint_u64(&mut self) -> Result<u64> { ... } fn read_varint_u128(&mut self) -> Result<u128> { ... } fn read_length_prefixed(&mut self) -> Result<Vec<u8>> { ... }
}
Expand description

Source that a Deserialize implementation reads its wire-format bytes from.

Implemented by every concrete decoder in the crate (Decoder for the in-memory case, IoDecoder (feature std) for std::io::Read streams). User code rarely implements Decode directly — Deserialize impls are written generically over D: Decode.

All methods are total: on any byte sequence they either succeed (advancing the cursor) or return a SerialError. They never panic and never read past the input. The provided methods never allocate more than Decode::max_alloc for one value, and never size an allocation from a declared length beyond what Decode::remaining_hint says the input can supply.

§Implementing Decode

Only read_byte, read_into and max_alloc are required. The other methods have correct, bounded defaults. A custom decoder should additionally override:

Required Methods§

Source

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

Read the next byte, advancing the cursor.

§Errors

Returns SerialError::UnexpectedEof if the input is exhausted. Streaming decoders MAY return an I/O-flavoured error variant.

Source

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

Fill out with exactly out.len() bytes, advancing the cursor.

§Errors

Returns SerialError::UnexpectedEof on short read.

Source

fn max_alloc(&self) -> usize

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

Provided Methods§

Source

fn remaining_hint(&self) -> Option<usize>

An upper bound on the number of bytes that can still be read, when the decoder knows it.

In-memory decoders return Some(remaining). Streaming decoders return None (the default): the source length is unknown. Decode impls use the hint to refuse, before allocating, any declared length the input cannot possibly back.

Source

fn config(&self) -> Config

The configuration this decoder enforces.

The default reports Config::default with this decoder’s max_alloc. Decoders built by this crate return the exact config they were constructed with.

Source

fn depth(&self) -> usize

Current nesting depth: the number of derived values whose fields are being decoded right now. Always 0 for decoders that do not track depth (the default).

Source

fn enter_nested(&mut self) -> Result<()>

Record entry into one more level of nesting.

Derived Deserialize / DeserializeView impls call this before decoding their fields and leave_nested afterwards. Hand-written impls for recursive types should do the same. The default implementation does not track depth.

§Errors

SerialError::DepthLimitExceeded when the decoder is already at Config::max_depth.

§Examples
use pack_io::{Decode, Deserialize, Result};

// A hand-written recursive type: a linked list of bytes.
struct List(Option<(u8, Vec<List>)>);

impl Deserialize for List {
    fn deserialize<D: Decode + ?Sized>(dec: &mut D) -> Result<Self> {
        dec.enter_nested()?;
        let inner = Option::<(u8, Vec<List>)>::deserialize(dec);
        dec.leave_nested();
        Ok(List(inner?))
    }
}

// 10,000 levels of `Some((0, [ ... ]))` from 30 KB of input: refused
// with an error instead of overflowing the stack.
let mut hostile = Vec::new();
for _ in 0..10_000 { hostile.extend_from_slice(&[1, 0, 1]); }
hostile.push(0);
let err = pack_io::decode::<List>(&hostile).err().unwrap();
assert!(matches!(err, pack_io::SerialError::DepthLimitExceeded { .. }));
Source

fn leave_nested(&mut self)

Record exit from one level of nesting. Pairs with enter_nested; call it on the error path too, so the decoder stays usable after a failed read.

Source

fn consumed(&self) -> Option<&[u8]>

The bytes this decoder has consumed so far, when it keeps its input in memory.

The in-memory Decoder returns Some(&input[..position]); streaming decoders return None (the default). Canonical mode uses it to compare the raw encoded keys of map and set entries.

Source

fn bytes_read(&self) -> Option<u64>

Number of input bytes this decoder has consumed so far, when it counts them.

Collection decoders compare it before and after their elements to find elements that took no input bytes (zero-sized types, Box<()>, Rc<()>, structs whose fields are all skip, …) and charge them with charge_unbacked. The default derives it from consumed. A decoder that returns None here opts out of that part of the accounting, so a hostile element count for such a type is then bounded only by max_alloc elements per collection; every decoder this crate ships counts.

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

let mut dec = Decoder::new(&[1, 2, 3]);
let _ = dec.read_byte().unwrap();
assert_eq!(dec.bytes_read(), Some(1));
Source

fn unbacked(&self) -> usize

Memory, in bytes, charged so far for the value being decoded with charge_unbacked. Always 0 for decoders that keep no running total (the default).

Source

fn charge_unbacked(&mut self, bytes: usize) -> Result<()>

Charge bytes of memory the value being decoded needs against Config::total_alloc_limit.

The built-in impls call this for every collection slot, every owned string or byte buffer, every boxed value, and for collection elements that consumed no input. A hand-written Deserialize that allocates from a count it read should do the same. The decoders this crate ships keep a running total and refuse the decode once it would pass the limit, so the memory one value builds is bounded as a whole, not per collection. The default keeps no total and refuses only a single charge above the limit.

The name predates the 2.1 total budget, when only elements that consumed no input were charged.

§Errors

SerialError::InvalidLength (with declared set to the memory total in bytes) when the limit would be exceeded.

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

let mut dec = Decoder::with_config(&[], Config::new().with_max_alloc(100)).unwrap();
dec.charge_unbacked(60).unwrap();
assert_eq!(dec.unbacked(), 60);
assert!(matches!(dec.charge_unbacked(41), Err(SerialError::InvalidLength { .. })));
Source

fn reset_unbacked(&mut self)

Clear the running total of charge_unbacked, starting the budget of a new top-level value.

Decoder::read and IoDecoder::read (feature std) call it before each top-level value, so a long-lived decoder reading one message after another gives each message its own budget. Call it yourself between values when you decode with T::deserialize directly on one decoder. The default does nothing.

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

let mut dec = Decoder::with_config(&[], Config::new().with_max_alloc(100)).unwrap();
dec.charge_unbacked(60).unwrap();
dec.reset_unbacked();
assert_eq!(dec.unbacked(), 0);
Source

fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>>

Read exactly len bytes.

In-memory decoders return a borrow of their input (Cow::Borrowed, no copy). The default implementation reads into a fresh buffer that grows in bounded steps as the bytes actually arrive, so a large declared len over a short or stalled stream costs at most a small first chunk, not len bytes. When remaining_hint is known, a len beyond it is refused before anything is allocated.

This method does not check len against max_alloc; callers that took len from the wire must do that first (see read_length_prefixed).

§Errors

SerialError::UnexpectedEof if the input ends first.

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

let mut dec = Decoder::new(&[1, 2, 3, 4]);
assert_eq!(&*dec.read_byte_cow(3).unwrap(), &[1, 2, 3]);
assert!(dec.read_byte_cow(2).is_err()); // only one byte left
Source

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

Read a LEB128 varint as a u64.

§Errors
Source

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

Read a LEB128 varint as a u128.

§Errors

See Decode::read_varint_u64 (the width limit is 19 bytes).

Source

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

Read a length-prefixed byte run into a fresh Vec<u8>.

The length is read as a varint, validated against Decode::max_alloc and charged against the total budget (Decode::charge_unbacked); the bytes are then read with Decode::read_byte_cow, which never allocates ahead of the data that actually exists.

§Errors

Dyn Compatibility§

This trait is dyn compatible.

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

Implementors§

Source§

impl Decode for Decoder<'_>

Source§

impl<R: Read> Decode for IoDecoder<R>

Available on crate feature std only.