#[non_exhaustive]pub struct Config {
pub max_alloc: 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_depth | 128 | cap on nested derived types (stack-overflow guard) |
canonical | false | reject every non-canonical encoding |
§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 defending against the obvious hostile-length-prefix DoS. Independently of this cap, decoders never allocate more than the input can actually back (see the module docs). Tighten this in any context that accepts untrusted input from a low-budget producer.
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 fn new() -> Self
pub const fn new() -> Self
Default configuration: max_alloc = 1 GiB, 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.
§Examples
let cfg = pack_io::Config::new();
assert_eq!(cfg.max_alloc, 1 << 30);
assert_eq!(cfg.max_depth, 128);
assert!(!cfg.canonical);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_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" }));