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>
impl<'a> Decoder<'a>
Sourcepub fn new(bytes: &'a [u8]) -> Self
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);Sourcepub fn with_config(bytes: &'a [u8], config: Config) -> Result<Self>
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
SerialError::InvalidConfig if config.max_alloc == 0 or
config.max_depth == 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");Sourcepub fn config(&self) -> Config
pub fn config(&self) -> Config
The configuration this decoder enforces.
§Examples
use pack_io::{Config, Decoder};
let cfg = Config::new().with_max_depth(8);
let dec = Decoder::with_config(&[], cfg).unwrap();
assert_eq!(dec.config().max_depth, 8);Sourcepub fn position(&self) -> usize
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);Sourcepub fn remaining(&self) -> usize
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);Sourcepub fn is_empty(&self) -> bool
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);Sourcepub fn read<T: Deserialize>(&mut self) -> Result<T>
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.
Each top-level call starts a fresh Config::total_alloc_limit
budget for the value it decodes.
§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));Sourcepub fn read_length_prefixed_borrowed(&mut self) -> Result<&'a [u8]>
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::InvalidLengthif the prefix exceeds the configuredmax_alloc, OR exceeds the remaining input.SerialError::UnexpectedEofis folded intoInvalidLengthfor 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.
Sourcepub fn read_borrowed(&mut self, len: usize) -> Result<&'a [u8]>
pub fn read_borrowed(&mut self, len: usize) -> Result<&'a [u8]>
Read exactly len bytes as a borrowed slice of the input — no
length prefix, no allocation, no copy.
Use it for fixed-size fields whose length is known from the type or from an earlier field.
§Errors
SerialError::UnexpectedEof if fewer than len bytes remain; the
cursor does not move.
§Examples
use pack_io::Decoder;
let mut dec = Decoder::new(&[1, 2, 3, 4]);
let head: &[u8] = dec.read_borrowed(3).unwrap();
assert_eq!(head, &[1, 2, 3]);
assert_eq!(dec.remaining(), 1);Trait Implementations§
Source§impl Decode for Decoder<'_>
impl Decode for Decoder<'_>
Source§fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>>
fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>>
In-memory specialisation: a bounds check and a borrow of the input.
Source§fn read_length_prefixed(&mut self) -> Result<Vec<u8>>
fn read_length_prefixed(&mut self) -> Result<Vec<u8>>
In-memory specialisation: validates the length against the actual
buffer as well as max_alloc, so a truncated input is rejected
without allocating, charges it against the total budget, then
copies exactly the declared bytes.
Source§fn max_alloc(&self) -> usize
fn max_alloc(&self) -> usize
Config::max_alloc.Source§fn remaining_hint(&self) -> Option<usize>
fn remaining_hint(&self) -> Option<usize>
Source§fn depth(&self) -> usize
fn depth(&self) -> usize
0 for decoders that do not track
depth (the default).Source§fn enter_nested(&mut self) -> Result<()>
fn enter_nested(&mut self) -> Result<()>
Source§fn leave_nested(&mut self)
fn leave_nested(&mut self)
enter_nested; call it on the error path
too, so the decoder stays usable after a failed read.Source§fn consumed(&self) -> Option<&[u8]>
fn consumed(&self) -> Option<&[u8]>
Source§fn bytes_read(&self) -> Option<u64>
fn bytes_read(&self) -> Option<u64>
Source§fn unbacked(&self) -> usize
fn unbacked(&self) -> usize
charge_unbacked. Always 0 for decoders
that keep no running total (the default).Source§fn reset_unbacked(&mut self)
fn reset_unbacked(&mut self)
charge_unbacked,
starting the budget of a new top-level value. Read more