#[non_exhaustive]pub struct Config {
pub max_alloc: usize,
pub max_total_alloc: Option<usize>,
pub max_depth: usize,
pub canonical: bool,
}Expand description
Configuration for a decode session.
At construction time the codec validates the configuration; an invalid
config (max_alloc == 0, max_depth == 0) is rejected before any bytes
are read. Validation happens once, in Decoder::with_config /
IoDecoder::with_config (feature std) / the *_with_config free
functions,
not on every operation.
Config is #[non_exhaustive] so the project can add knobs in a MINOR
release without breaking downstream code. Build instances with
Config::new and the with_* builders, or via Default.
| Knob | Default | Purpose |
|---|---|---|
max_alloc | 1 GiB | cap on any single length-prefixed value |
max_total_alloc | None (same as max_alloc) | cap on the memory one decoded value builds in total |
max_depth | 128 | cap on nested derived types (stack-overflow guard) |
canonical | false | reject every non-canonical encoding |
The 1 GiB default suits files and other trusted, possibly large data.
For bytes that come from a peer, start from Config::network
(16 MiB per value and per message) and tighten it further if the
protocol’s messages are smaller.
§Examples
use pack_io::{Config, Decoder};
// Refuse to allocate more than 16 KiB for any single length-prefixed
// value (a `String`, a `Vec<u8>`, a collection element count, …),
// refuse nesting deeper than 32 derived types, and only accept the
// exact bytes the encoder would have produced.
let cfg = Config::new()
.with_max_alloc(16 * 1024)
.with_max_depth(32)
.with_canonical(true);
let dec = Decoder::with_config(&[], cfg).expect("valid config");
assert_eq!(dec.config(), cfg);Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.max_alloc: usizeMaximum number of bytes the decoder may allocate for any single
length-prefixed value (a String, a Vec<u8>, a collection element
count, a versioned struct body, …).
The default is 1 GiB, which is enough that well-formed inputs are
never rejected on size, while still refusing the obvious
hostile-length-prefix DoS before allocating. It is a limit per
value; the memory a whole decode builds is capped by
max_total_alloc, which follows this
value unless set separately. 1 GiB is a file-format default, not a
network one: for peer input use Config::network or a tighter
limit.
max_total_alloc: Option<usize>Maximum memory, in bytes, that one decoded value may build in
total. None (the default) means “the same as
max_alloc”.
Every collection charges size_of::<T>() per element slot, every
owned String / Vec<u8> / Bytes charges its length, and every
Box<T> / Rc<T> / Arc<T> charges the value it holds, against
one running total. A collection element that consumes no input at
all ((), Box<()>, a struct whose fields are all skip) is
charged at least 64 bytes, so a few bytes of input cannot drive an
element loop for long either. The decode fails with
SerialError::InvalidLength (declared set to the total) once
the total would pass the limit.
The total covers one value: each Decoder::read and
IoDecoder::read (feature std) starts a new one, and every free
function (decode, decode_with_config, …) decodes exactly one
value. Borrowed views (&str, &[u8] through
crate::DeserializeView) take no heap and are not charged.
max_depth: usizeMaximum nesting depth of derived types during one decode.
Every #[derive(Deserialize)] / #[derive(DeserializeView)] value
(struct or enum) counts as one level while its fields are being
decoded. The limit exists so that a few kilobytes of hostile input
for a recursive type cannot exhaust the thread’s stack, which aborts
the process rather than returning an error. Exceeding it returns
SerialError::DepthLimitExceeded.
The default of 128 matches serde_json and leaves ample headroom on
a 1 MiB stack in debug builds. Built-in container types (Vec,
Option, maps, tuples, …) do not count: they cannot recurse without
passing through a user type.
canonical: boolStrict canonical decoding. Off by default.
When true, the decoder accepts only the exact bytes the pack-io
encoder would produce for the decoded value, and rejects everything
else with SerialError::NonCanonical:
- varints with redundant zero high bytes (
[0x80, 0x00]for0); - map and set entries that are not in strictly increasing encoded-key order (this also rejects duplicates);
- a versioned struct written at any version other than the decoding type’s own: an older frame is a second encoding of the defaulted value, and a newer one carries fields the reader cannot check;
- unread bytes inside a versioned struct body;
- a retired field’s slot holding anything but its default.
Turn it on wherever the encoded bytes are hashed, signed, or used as a content address. Decode payloads from older or newer schema versions leniently (and re-encode them if you need their canonical form).
The guarantee covers every type built from pack-io’s own impls and
derives. A hand-written Deserialize impl or a with helper is
part of it only if it, too, accepts one encoding per value; serde
types follow the adapter’s rules (sets need
pack_io::serde::sorted_set).
Why it is off by default (re-evaluated for 2.0): lenient decoding
is correct — every valid encoding decodes to its value, the wire
specification permits lenient readers (docs/WIRE_FORMAT.md §2.1,
§4.3), and the encoder is deterministic either way. What canonical
mode adds is injectivity (one accepted byte string per value), which
only matters where the bytes themselves are trusted as an identity,
and it gives up reading other schema versions of versioned structs.
It also needs the raw input, so a canonical default would make every
streaming decoder fail to construct. And it is not free: about 25 %
on small-key map decoding on the v2.0 baseline machine, well beyond
the 5 % regression budget for everyone who does not need it.
Canonical mode is supported by the in-memory Decoder (and every
free function built on it). IoDecoder::with_config (feature std) rejects
it with SerialError::InvalidConfig; read the frame into memory
first (decode_from_with_config does that within the
configured max_alloc).
Implementations§
Source§impl Config
impl Config
Sourcepub const DEFAULT_MAX_ALLOC: usize
pub const DEFAULT_MAX_ALLOC: usize
Default value of Config::max_alloc: 1 GiB.
Sourcepub const DEFAULT_MAX_DEPTH: usize = 128
pub const DEFAULT_MAX_DEPTH: usize = 128
Default value of Config::max_depth: 128 nested derived types.
Sourcepub const NETWORK_MAX_ALLOC: usize
pub const NETWORK_MAX_ALLOC: usize
Per-value and per-message limit of Config::network: 16 MiB.
Sourcepub const fn new() -> Self
pub const fn new() -> Self
Default configuration: max_alloc = 1 GiB, a total budget equal to
max_alloc, max_depth = 128, lenient (non-canonical) decoding.
1 GiB is large enough to be irrelevant for well-formed inputs and
small enough to refuse the obvious length = u64::MAX attack before
allocating a single byte. For input from a peer, use
Config::network.
§Examples
let cfg = pack_io::Config::new();
assert_eq!(cfg.max_alloc, 1 << 30);
assert_eq!(cfg.max_total_alloc, None);
assert_eq!(cfg.total_alloc_limit(), 1 << 30);
assert_eq!(cfg.max_depth, 128);
assert!(!cfg.canonical);Sourcepub const fn network() -> Self
pub const fn network() -> Self
Limits for bytes received from a peer: 16 MiB for any single value and 16 MiB for everything one decoded message builds, depth 128, lenient decoding.
Use it (or something tighter) for every decode of network input;
the 1 GiB default of Config::new is meant for files and other
trusted data. A protocol whose messages are larger than 16 MiB
raises both limits explicitly.
§Examples
use pack_io::{Config, SerialError, decode_with_config, encode};
let cfg = Config::network();
assert_eq!(cfg.max_alloc, 16 << 20);
assert_eq!(cfg.total_alloc_limit(), 16 << 20);
// Ten 2 MiB strings: each fits the per-value limit, together they do
// not fit the message budget.
let big = vec!["x".repeat(2 << 20); 10];
let err = decode_with_config::<Vec<String>>(&encode(&big)?, cfg).unwrap_err();
assert!(matches!(err, SerialError::InvalidLength { .. }));Sourcepub const fn total_alloc_limit(&self) -> usize
pub const fn total_alloc_limit(&self) -> usize
The total budget this config enforces: Config::max_total_alloc
when set, otherwise Config::max_alloc.
§Examples
use pack_io::Config;
assert_eq!(Config::new().with_max_alloc(4096).total_alloc_limit(), 4096);
let split = Config::new().with_max_alloc(4096).with_max_total_alloc(1 << 20);
assert_eq!(split.total_alloc_limit(), 1 << 20);Sourcepub const fn with_max_alloc(self, max_alloc: usize) -> Self
pub const fn with_max_alloc(self, max_alloc: usize) -> Self
Replace max_alloc and return the updated config.
§Examples
let cfg = pack_io::Config::new().with_max_alloc(4096);
assert_eq!(cfg.max_alloc, 4096);Sourcepub const fn with_max_total_alloc(self, max_total_alloc: usize) -> Self
pub const fn with_max_total_alloc(self, max_total_alloc: usize) -> Self
Set the total budget for one decoded value
(Config::max_total_alloc) and return the updated config.
0 is rejected at decoder construction with
SerialError::InvalidConfig.
§Examples
// Strings of up to 64 KiB each, but no more than 1 MiB per message.
let cfg = pack_io::Config::new()
.with_max_alloc(64 * 1024)
.with_max_total_alloc(1 << 20);
assert_eq!(cfg.max_total_alloc, Some(1 << 20));Sourcepub const fn with_max_depth(self, max_depth: usize) -> Self
pub const fn with_max_depth(self, max_depth: usize) -> Self
Replace max_depth and return the updated config.
0 is rejected at decoder construction with
SerialError::InvalidConfig.
§Examples
let cfg = pack_io::Config::new().with_max_depth(16);
assert_eq!(cfg.max_depth, 16);Sourcepub const fn with_canonical(self, canonical: bool) -> Self
pub const fn with_canonical(self, canonical: bool) -> Self
Turn strict canonical decoding on or off and return the updated
config. See Config::canonical for exactly what is rejected.
§Examples
use pack_io::{Config, SerialError, decode_with_config};
// `[0x80, 0x00]` is an overlong (two-byte) encoding of 0.
let overlong = [0x80, 0x00];
assert_eq!(pack_io::decode::<u64>(&overlong).unwrap(), 0);
let strict = Config::new().with_canonical(true);
let err = decode_with_config::<u64>(&overlong, strict).unwrap_err();
assert!(matches!(err, SerialError::NonCanonical { reason: "varint" }));