Skip to main content

Config

Struct Config 

Source
#[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.

KnobDefaultPurpose
max_alloc1 GiBcap on any single length-prefixed value
max_total_allocNone (same as max_alloc)cap on the memory one decoded value builds in total
max_depth128cap on nested derived types (stack-overflow guard)
canonicalfalsereject 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
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§max_alloc: usize

Maximum 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: usize

Maximum 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: bool

Strict 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] for 0);
  • 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

Source

pub const DEFAULT_MAX_ALLOC: usize

Default value of Config::max_alloc: 1 GiB.

Source

pub const DEFAULT_MAX_DEPTH: usize = 128

Default value of Config::max_depth: 128 nested derived types.

Source

pub const NETWORK_MAX_ALLOC: usize

Per-value and per-message limit of Config::network: 16 MiB.

Source

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);
Source

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 { .. }));
Source

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);
Source

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);
Source

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));
Source

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);
Source

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" }));

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Config

Source§

impl Debug for Config

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Config

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Eq for Config

Source§

impl PartialEq for Config

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Config

Auto Trait Implementations§

§

impl Forget for Config

§

impl Freeze for Config

§

impl Move for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnsafeUnpin for Config

§

impl UnwindSafe for Config

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.