Skip to main content

Config

Struct Config 

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

KnobDefaultPurpose
max_alloc1 GiBcap on any single length-prefixed value
max_depth128cap on nested derived types (stack-overflow guard)
canonicalfalsereject 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
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 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: 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 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);
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_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§

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.