pub trait Decode {
Show 16 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 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:
remaining_hintwhen it knows how much input is left, so collection pre-allocation is bounded by it;config,depth,enter_nestedandleave_nestedto enforceConfig::max_depth(the defaults do not track depth);consumedif it keeps the input in memory, so canonical mode can check map key order;bytes_read,unbackedandcharge_unbackedso that collections of elements that occupy no input bytes are bounded byConfig::max_allocacross the whole decode (bytes_readalready works whenconsumedis overridden).
Required Methods§
Sourcefn read_byte(&mut self) -> Result<u8>
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.
Sourcefn read_into(&mut self, out: &mut [u8]) -> Result<()>
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.
Sourcefn max_alloc(&self) -> usize
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§
Sourcefn remaining_hint(&self) -> Option<usize>
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.
Sourcefn config(&self) -> Config
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.
Sourcefn depth(&self) -> usize
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).
Sourcefn enter_nested(&mut self) -> Result<()>
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 { .. }));Sourcefn leave_nested(&mut self)
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.
Sourcefn consumed(&self) -> Option<&[u8]>
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.
Sourcefn bytes_read(&self) -> Option<u64>
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 their
memory with charge_unbacked. The
default derives it from consumed. A decoder
that returns None here opts out of that 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));Sourcefn unbacked(&self) -> usize
fn unbacked(&self) -> usize
Memory, in bytes, charged so far in this decode with
charge_unbacked. Always 0 for decoders
that keep no running total (the default).
Sourcefn charge_unbacked(&mut self, bytes: usize) -> Result<()>
fn charge_unbacked(&mut self, bytes: usize) -> Result<()>
Charge bytes of memory needed by collection elements that took no
input bytes, against Config::max_alloc for the whole decode.
The built-in collection impls call this; hand-written collection
impls rarely need to. The decoders this crate ships keep a running
total and refuse the decode once it would exceed max_alloc, so the
memory such elements occupy is bounded by max_alloc across the
whole decode, not per collection. The default keeps no total and
refuses only a single charge above max_alloc.
§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 { .. })));Sourcefn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>>
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 leftSourcefn read_varint_u64(&mut self) -> Result<u64>
fn read_varint_u64(&mut self) -> Result<u64>
Read a LEB128 varint as a u64.
§Errors
SerialError::VarintOverflowfor an encoding wider than 10 bytes or one whose value overflowsu64.SerialError::UnexpectedEoffor a truncated encoding.SerialError::NonCanonicalfor a multi-byte encoding with a redundant zero final byte, whenConfig::canonicalis on.
Sourcefn read_varint_u128(&mut self) -> Result<u128>
fn read_varint_u128(&mut self) -> Result<u128>
Sourcefn read_length_prefixed(&mut self) -> Result<Vec<u8>>
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 and validated against
Decode::max_alloc; the bytes are then read with
Decode::read_byte_cow, which never allocates ahead of the data
that actually exists.
§Errors
SerialError::InvalidLengthif the prefix exceedsmax_alloc.SerialError::UnexpectedEofif the source runs out before the declared length is satisfied.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".