Skip to main content

pack_io/
codec.rs

1//! The codec primitives: the [`Encode`] / [`Decode`] behaviour traits, the
2//! concrete in-memory [`Encoder`] / [`Decoder`] types, the [`Config`] struct,
3//! and the Tier-1 [`encode`] / [`decode`] free functions.
4//!
5//! ## Layering
6//!
7//! - **Tier 1** — the [`encode`] / [`decode`] free functions. One line each
8//!   direction, no setup, no type parameters beyond the target type.
9//! - **Tier 2** — concrete encoder / decoder types. The in-memory pair
10//!   ([`Encoder`] + [`Decoder`]) lives in this module; the streaming pair
11//!   ([`crate::IoEncoder`] + [`crate::IoDecoder`]) lives in
12//!   [`crate::io`] and is `std`-gated. All four implement the [`Encode`] /
13//!   [`Decode`] behaviour traits, so [`Serialize`] / [`Deserialize`] impls
14//!   work through any of them.
15//! - **Tier 3** — implementing the [`Serialize`] / [`Deserialize`] traits
16//!   directly on your own types. Generic over `E: Encode` / `D: Decode`, so
17//!   one impl works for both in-memory and streaming codecs.
18//!
19//! ## Safety contract for decoders
20//!
21//! Every method on [`Decode`] is total: it either returns the requested
22//! value (advancing the read cursor) or returns a [`SerialError`]. It never
23//! panics and never reads past the input. Allocation is bounded twice over:
24//! no single length-prefixed value may exceed [`Config::max_alloc`], and no
25//! allocation is sized from a declared length before the bytes backing it
26//! are known to exist (in-memory decoders check the remaining input;
27//! streaming decoders grow their buffers only as data actually arrives).
28//! Nesting is bounded by [`Config::max_depth`].
29
30use alloc::borrow::Cow;
31use alloc::vec::Vec;
32
33use crate::error::{Result, SerialError};
34use crate::traits::{Deserialize, Serialize};
35use crate::varint;
36
37/// Configuration for a decode session.
38///
39/// At construction time the codec validates the configuration; an invalid
40/// config (`max_alloc == 0`, `max_depth == 0`) is rejected before any bytes
41/// are read. Validation happens once, in [`Decoder::with_config`] /
42/// `IoDecoder::with_config` (feature `std`) / the `*_with_config` free
43/// functions,
44/// not on every operation.
45///
46/// `Config` is `#[non_exhaustive]` so the project can add knobs in a MINOR
47/// release without breaking downstream code. Build instances with
48/// [`Config::new`] and the `with_*` builders, or via [`Default`].
49///
50/// | Knob | Default | Purpose |
51/// |---|---|---|
52/// | [`max_alloc`](Config::max_alloc) | 1 GiB | cap on any single length-prefixed value |
53/// | [`max_depth`](Config::max_depth) | 128 | cap on nested derived types (stack-overflow guard) |
54/// | [`canonical`](Config::canonical) | `false` | reject every non-canonical encoding |
55///
56/// # Examples
57///
58/// ```
59/// use pack_io::{Config, Decoder};
60///
61/// // Refuse to allocate more than 16 KiB for any single length-prefixed
62/// // value (a `String`, a `Vec<u8>`, a collection element count, …),
63/// // refuse nesting deeper than 32 derived types, and only accept the
64/// // exact bytes the encoder would have produced.
65/// let cfg = Config::new()
66///     .with_max_alloc(16 * 1024)
67///     .with_max_depth(32)
68///     .with_canonical(true);
69/// let dec = Decoder::with_config(&[], cfg).expect("valid config");
70/// assert_eq!(dec.config(), cfg);
71/// ```
72#[non_exhaustive]
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Config {
75    /// Maximum number of bytes the decoder may allocate for any single
76    /// length-prefixed value (a `String`, a `Vec<u8>`, a collection element
77    /// count, a versioned struct body, …).
78    ///
79    /// The default is 1 GiB, which is enough that well-formed inputs are
80    /// never rejected on size, while still defending against the obvious
81    /// hostile-length-prefix DoS. Independently of this cap, decoders never
82    /// allocate more than the input can actually back (see the module
83    /// docs). Tighten this in any context that accepts untrusted input from
84    /// a low-budget producer.
85    pub max_alloc: usize,
86
87    /// Maximum nesting depth of derived types during one decode.
88    ///
89    /// Every `#[derive(Deserialize)]` / `#[derive(DeserializeView)]` value
90    /// (struct or enum) counts as one level while its fields are being
91    /// decoded. The limit exists so that a few kilobytes of hostile input
92    /// for a recursive type cannot exhaust the thread's stack, which aborts
93    /// the process rather than returning an error. Exceeding it returns
94    /// [`SerialError::DepthLimitExceeded`].
95    ///
96    /// The default of 128 matches `serde_json` and leaves ample headroom on
97    /// a 1 MiB stack in debug builds. Built-in container types (`Vec`,
98    /// `Option`, maps, tuples, …) do not count: they cannot recurse without
99    /// passing through a user type.
100    pub max_depth: usize,
101
102    /// Strict canonical decoding. Off by default.
103    ///
104    /// When `true`, the decoder accepts only the exact bytes the pack-io
105    /// encoder would produce for the decoded value, and rejects everything
106    /// else with [`SerialError::NonCanonical`]:
107    ///
108    /// - varints with redundant zero high bytes (`[0x80, 0x00]` for `0`);
109    /// - map and set entries that are not in strictly increasing
110    ///   encoded-key order (this also rejects duplicates);
111    /// - a versioned struct written at any version other than the decoding
112    ///   type's own: an older frame is a second encoding of the defaulted
113    ///   value, and a newer one carries fields the reader cannot check;
114    /// - unread bytes inside a versioned struct body;
115    /// - a retired field's slot holding anything but its default.
116    ///
117    /// Turn it on wherever the encoded bytes are hashed, signed, or used as
118    /// a content address. Decode payloads from older or newer schema
119    /// versions leniently (and re-encode them if you need their canonical
120    /// form).
121    ///
122    /// The guarantee covers every type built from pack-io's own impls and
123    /// derives. A hand-written `Deserialize` impl or a `with` helper is
124    /// part of it only if it, too, accepts one encoding per value; serde
125    /// types follow the adapter's rules (sets need
126    /// `pack_io::serde::sorted_set`).
127    ///
128    /// **Why it is off by default** (re-evaluated for 2.0): lenient decoding
129    /// is correct — every valid encoding decodes to its value, the wire
130    /// specification permits lenient readers (`docs/WIRE_FORMAT.md` §2.1,
131    /// §4.3), and the encoder is deterministic either way. What canonical
132    /// mode adds is injectivity (one accepted byte string per value), which
133    /// only matters where the bytes themselves are trusted as an identity,
134    /// and it gives up reading other schema versions of versioned structs.
135    /// It also needs the raw input, so a canonical default would make every
136    /// streaming decoder fail to construct. And it is not free: about 25 %
137    /// on small-key map decoding on the v2.0 baseline machine, well beyond
138    /// the 5 % regression budget for everyone who does not need it.
139    ///
140    /// Canonical mode is supported by the in-memory [`Decoder`] (and every
141    /// free function built on it). `IoDecoder::with_config` (feature `std`) rejects
142    /// it with [`SerialError::InvalidConfig`]; read the frame into memory
143    /// first (`decode_from_with_config` does that within the
144    /// configured `max_alloc`).
145    pub canonical: bool,
146}
147
148impl Default for Config {
149    fn default() -> Self {
150        Self::new()
151    }
152}
153
154impl Config {
155    /// Default value of [`Config::max_alloc`]: 1 GiB.
156    pub const DEFAULT_MAX_ALLOC: usize = 1 << 30;
157
158    /// Default value of [`Config::max_depth`]: 128 nested derived types.
159    pub const DEFAULT_MAX_DEPTH: usize = 128;
160
161    /// Default configuration: `max_alloc = 1 GiB`, `max_depth = 128`,
162    /// lenient (non-canonical) decoding.
163    ///
164    /// 1 GiB is large enough to be irrelevant for well-formed inputs and
165    /// small enough to refuse the obvious `length = u64::MAX` attack before
166    /// allocating a single byte.
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// let cfg = pack_io::Config::new();
172    /// assert_eq!(cfg.max_alloc, 1 << 30);
173    /// assert_eq!(cfg.max_depth, 128);
174    /// assert!(!cfg.canonical);
175    /// ```
176    #[must_use]
177    pub const fn new() -> Self {
178        Self {
179            max_alloc: Self::DEFAULT_MAX_ALLOC,
180            max_depth: Self::DEFAULT_MAX_DEPTH,
181            canonical: false,
182        }
183    }
184
185    /// Replace `max_alloc` and return the updated config.
186    ///
187    /// # Examples
188    ///
189    /// ```
190    /// let cfg = pack_io::Config::new().with_max_alloc(4096);
191    /// assert_eq!(cfg.max_alloc, 4096);
192    /// ```
193    #[must_use]
194    pub const fn with_max_alloc(mut self, max_alloc: usize) -> Self {
195        self.max_alloc = max_alloc;
196        self
197    }
198
199    /// Replace `max_depth` and return the updated config.
200    ///
201    /// `0` is rejected at decoder construction with
202    /// [`SerialError::InvalidConfig`].
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// let cfg = pack_io::Config::new().with_max_depth(16);
208    /// assert_eq!(cfg.max_depth, 16);
209    /// ```
210    #[must_use]
211    pub const fn with_max_depth(mut self, max_depth: usize) -> Self {
212        self.max_depth = max_depth;
213        self
214    }
215
216    /// Turn strict canonical decoding on or off and return the updated
217    /// config. See [`Config::canonical`] for exactly what is rejected.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// use pack_io::{Config, SerialError, decode_with_config};
223    ///
224    /// // `[0x80, 0x00]` is an overlong (two-byte) encoding of 0.
225    /// let overlong = [0x80, 0x00];
226    /// assert_eq!(pack_io::decode::<u64>(&overlong).unwrap(), 0);
227    ///
228    /// let strict = Config::new().with_canonical(true);
229    /// let err = decode_with_config::<u64>(&overlong, strict).unwrap_err();
230    /// assert!(matches!(err, SerialError::NonCanonical { reason: "varint" }));
231    /// ```
232    #[must_use]
233    pub const fn with_canonical(mut self, canonical: bool) -> Self {
234        self.canonical = canonical;
235        self
236    }
237
238    /// Validate the configuration: `max_alloc` and `max_depth` must be at
239    /// least 1, otherwise [`SerialError::InvalidConfig`].
240    pub(crate) fn validate(self) -> Result<Self> {
241        if self.max_alloc == 0 {
242            return Err(SerialError::InvalidConfig {
243                reason: "max_alloc must be at least 1",
244            });
245        }
246        if self.max_depth == 0 {
247            return Err(SerialError::InvalidConfig {
248                reason: "max_depth must be at least 1",
249            });
250        }
251        Ok(self)
252    }
253}
254
255/// Upper bound on the bytes a decoder pre-allocates for a collection before
256/// any element has been read. Collections larger than this grow while they
257/// decode, so honest payloads pay at most a few reallocations while a
258/// hostile element count cannot reserve more than this up front.
259pub(crate) const PREALLOC_BYTES: usize = 64 * 1024;
260
261/// Pre-allocation bound for a collection read from a decoder that does not
262/// know how much input remains (a stream). Smaller than [`PREALLOC_BYTES`]
263/// because nothing else bounds it: a stalled stream that opens one hostile
264/// collection per nesting level would otherwise pin `max_depth` × 64 KiB.
265pub(crate) const STREAM_PREALLOC_BYTES: usize = 4 * 1024;
266
267/// Initial capacity for a collection of `count` elements of `T`.
268///
269/// Bounded three ways: by the declared count, by the number of input bytes
270/// that remain (when the decoder knows it; every element that needs storage
271/// almost always needs at least one byte of input), and by
272/// [`PREALLOC_BYTES`] worth of `T` ([`STREAM_PREALLOC_BYTES`] when the
273/// remaining input is unknown).
274#[inline]
275pub(crate) fn initial_capacity<T, D: Decode + ?Sized>(count: usize, decoder: &D) -> usize {
276    let per_element = core::mem::size_of::<T>().max(1);
277    match decoder.remaining_hint() {
278        Some(remaining) => count.min(PREALLOC_BYTES / per_element).min(remaining),
279        None => count.min(STREAM_PREALLOC_BYTES / per_element),
280    }
281}
282
283/// Decode `count` collection elements by calling `each` once per element,
284/// charging memory for elements that took no input bytes.
285///
286/// Most elements consume at least one input byte, so their number is
287/// bounded by the input itself. An element type that encodes to nothing
288/// (a zero-sized type, `Box<()>`, `Rc<()>`, a struct whose fields are all
289/// `skip`, a `with` helper that reads nothing) is not: a five-byte count
290/// could otherwise demand gigabytes. Every element beyond the number of
291/// input bytes the loop consumed is therefore charged
292/// `size_of::<T>()` bytes (at least 1) through [`Decode::charge_unbacked`],
293/// which refuses the decode once the running total for the whole decode
294/// exceeds [`Config::max_alloc`].
295///
296/// The check runs between chunks, not per element: the first chunk is
297/// [`PREALLOC_BYTES`] worth of `T` (so a typical collection is one chunk
298/// and one comparison), and later chunks double, never past what the
299/// remaining budget and input could cover. The inner loop is exactly the
300/// plain element loop.
301#[inline]
302pub(crate) fn decode_elements_counted<T, D, F>(
303    decoder: &mut D,
304    count: usize,
305    mut each: F,
306) -> Result<()>
307where
308    D: Decode + ?Sized,
309    F: FnMut(&mut D) -> Result<()>,
310{
311    let Some(start) = decoder.bytes_read() else {
312        // The decoder does not count its input, so element sizes cannot be
313        // observed. Documented on `Decode::bytes_read`.
314        for _ in 0..count {
315            each(decoder)?;
316        }
317        return Ok(());
318    };
319    let per_element = core::mem::size_of::<T>().max(1);
320    let mut done = 0usize;
321    let mut charged = 0usize;
322    let mut stop = count.min((PREALLOC_BYTES / per_element).max(1));
323    loop {
324        for _ in done..stop {
325            each(decoder)?;
326        }
327        done = stop;
328        // Fast path: at least one input byte per element so far, so no
329        // element can have been free.
330        let read = decoder.bytes_read().unwrap_or(start).wrapping_sub(start);
331        if done as u64 > read {
332            charged = charge_free_elements(decoder, done, read, charged, per_element)?;
333        }
334        if done == count {
335            return Ok(());
336        }
337        stop = next_element_stop(decoder, done, count, per_element)?;
338    }
339}
340
341/// Charge the elements among the first `done` that the `read` input bytes
342/// cannot account for, beyond the `charged` already paid for.
343#[cold]
344#[inline(never)]
345fn charge_free_elements<D: Decode + ?Sized>(
346    decoder: &mut D,
347    done: usize,
348    read: u64,
349    charged: usize,
350    per_element: usize,
351) -> Result<usize> {
352    // `read < done`, so the difference fits in `usize`.
353    let free = usize::try_from(done as u64 - read).unwrap_or(usize::MAX);
354    if free > charged {
355        decoder.charge_unbacked((free - charged).saturating_mul(per_element))?;
356        return Ok(free);
357    }
358    Ok(charged)
359}
360
361/// Where the next chunk of a counted element loop ends: double the elements
362/// decoded so far, but never more than the remaining budget for free
363/// elements plus the remaining input could pay for.
364///
365/// Every element still to come is either free (charged against the budget)
366/// or consumes at least one input byte, so when the decoder knows its
367/// remaining input and the elements left exceed both together, the decode
368/// cannot succeed: it is refused here, before the collection grows again.
369#[cold]
370#[inline(never)]
371fn next_element_stop<D: Decode + ?Sized>(
372    decoder: &D,
373    done: usize,
374    count: usize,
375    per_element: usize,
376) -> Result<usize> {
377    let free_budget = decoder.max_alloc().saturating_sub(decoder.unbacked()) / per_element;
378    let left = count - done;
379    let room = match decoder.remaining_hint() {
380        Some(input) => {
381            let room = free_budget.saturating_add(input);
382            if left > room {
383                let total = decoder
384                    .unbacked()
385                    .saturating_add(left.saturating_mul(per_element));
386                return Err(unbacked_limit_error(total, Some(input)));
387            }
388            room
389        }
390        None => free_budget,
391    };
392    let chunk = done.min(room).max(1);
393    Ok(done.saturating_add(chunk).min(count))
394}
395
396/// Per-element form of [`decode_elements_counted`], for loops the crate
397/// does not drive itself (the serde adapter's sequence and map access):
398/// call [`FreeElements::after_element`] once after each element.
399#[cfg(feature = "serde")]
400#[derive(Debug)]
401pub(crate) struct FreeElements {
402    start: Option<u64>,
403    done: usize,
404    charged: usize,
405}
406
407#[cfg(feature = "serde")]
408impl FreeElements {
409    /// Start counting at the decoder's current position.
410    #[inline]
411    pub(crate) fn new<D: Decode + ?Sized>(decoder: &D) -> Self {
412        Self {
413            start: decoder.bytes_read(),
414            done: 0,
415            charged: 0,
416        }
417    }
418
419    /// Record one more decoded element of `per_element` bytes in memory,
420    /// charging it if the input consumed so far cannot account for it.
421    #[inline]
422    pub(crate) fn after_element<D: Decode + ?Sized>(
423        &mut self,
424        decoder: &mut D,
425        per_element: usize,
426    ) -> Result<()> {
427        self.done += 1;
428        let Some(start) = self.start else {
429            return Ok(());
430        };
431        let read = decoder.bytes_read().unwrap_or(start).wrapping_sub(start);
432        if self.done as u64 > read {
433            self.charged =
434                charge_free_elements(decoder, self.done, read, self.charged, per_element.max(1))?;
435        }
436        Ok(())
437    }
438}
439
440/// The error for a decode whose collections need more memory for
441/// zero-input elements than [`Config::max_alloc`] allows.
442#[cold]
443pub(crate) fn unbacked_limit_error(total: usize, remaining: Option<usize>) -> SerialError {
444    SerialError::InvalidLength {
445        declared: total as u64,
446        remaining: remaining.unwrap_or(0),
447    }
448}
449
450/// Validate a declared element count against the decoder's `max_alloc`
451/// and convert it to `usize`.
452#[inline]
453pub(crate) fn guard_element_count<D: Decode + ?Sized>(declared: u64, decoder: &D) -> Result<usize> {
454    let max = decoder.max_alloc() as u64;
455    if declared > max {
456        return Err(SerialError::InvalidLength {
457            declared,
458            remaining: decoder.remaining_hint().unwrap_or(0),
459        });
460    }
461    usize::try_from(declared).map_err(|_| SerialError::IntegerOutOfRange)
462}
463
464// ---------------------------------------------------------------------------
465// Encode / Decode behaviour traits
466// ---------------------------------------------------------------------------
467
468/// Sink that a [`Serialize`] implementation writes its wire-format bytes
469/// into.
470///
471/// Implemented by every concrete encoder in the crate ([`Encoder`] for the
472/// in-memory case, `IoEncoder` (feature `std`) for `std::io::Write` streams). User
473/// code rarely implements `Encode` directly — `Serialize` impls are written
474/// generically over `E: Encode` so a single impl works for every encoder
475/// flavour.
476///
477/// # Examples
478///
479/// ```
480/// use pack_io::{Encode, Encoder, Result};
481///
482/// // A helper that writes a length-prefixed list of `u32`s into any encoder.
483/// fn write_u32_list<E: Encode>(enc: &mut E, items: &[u32]) -> Result<()> {
484///     enc.write_varint_u64(items.len() as u64)?;
485///     for item in items {
486///         enc.write_varint_u64(u64::from(*item))?;
487///     }
488///     Ok(())
489/// }
490///
491/// let mut enc = Encoder::new();
492/// write_u32_list(&mut enc, &[1, 2, 3]).unwrap();
493/// ```
494pub trait Encode {
495    /// Append a single byte.
496    ///
497    /// # Errors
498    ///
499    /// Returns the encoder's underlying error variant (I/O failure for
500    /// streaming encoders; never errors for the in-memory [`Encoder`]).
501    fn write_byte(&mut self, byte: u8) -> Result<()>;
502
503    /// Append a slice of bytes.
504    ///
505    /// # Errors
506    ///
507    /// Same as [`Encode::write_byte`].
508    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;
509
510    /// Hint that the caller is about to write `additional` more bytes.
511    ///
512    /// In-memory encoders MAY pre-allocate the requested capacity to avoid
513    /// intermediate `Vec` growth. Streaming encoders typically ignore the
514    /// hint. The default implementation is a no-op.
515    #[inline]
516    fn reserve(&mut self, additional: usize) {
517        let _ = additional;
518    }
519
520    /// Append a `u64` as an unsigned LEB128 varint (1–10 bytes).
521    ///
522    /// # Errors
523    ///
524    /// Same as [`Encode::write_bytes`].
525    #[inline]
526    fn write_varint_u64(&mut self, value: u64) -> Result<()> {
527        // Fast path for the overwhelmingly common case: value fits in a
528        // single byte. Skips the stack buffer + write_bytes round-trip.
529        if value < 0x80 {
530            return self.write_byte(value as u8);
531        }
532        let mut buf = [0u8; varint::MAX_VARINT_LEN_U64];
533        let n = varint::write_u64(value, &mut buf);
534        self.write_bytes(&buf[..n])
535    }
536
537    /// Append a `u128` as an unsigned LEB128 varint (1–19 bytes).
538    ///
539    /// # Errors
540    ///
541    /// Same as [`Encode::write_bytes`].
542    #[inline]
543    fn write_varint_u128(&mut self, value: u128) -> Result<()> {
544        let mut buf = [0u8; varint::MAX_VARINT_LEN_U128];
545        let n = varint::write_u128(value, &mut buf);
546        self.write_bytes(&buf[..n])
547    }
548}
549
550/// Source that a [`Deserialize`] implementation reads its wire-format bytes
551/// from.
552///
553/// Implemented by every concrete decoder in the crate ([`Decoder`] for the
554/// in-memory case, `IoDecoder` (feature `std`) for `std::io::Read` streams). User
555/// code rarely implements `Decode` directly — `Deserialize` impls are
556/// written generically over `D: Decode`.
557///
558/// All methods are **total**: on any byte sequence they either succeed
559/// (advancing the cursor) or return a [`SerialError`]. They never panic and
560/// never read past the input. The provided methods never allocate more
561/// than [`Decode::max_alloc`] for one value, and never size an allocation
562/// from a declared length beyond what [`Decode::remaining_hint`] says the
563/// input can supply.
564///
565/// # Implementing `Decode`
566///
567/// Only [`read_byte`](Decode::read_byte), [`read_into`](Decode::read_into)
568/// and [`max_alloc`](Decode::max_alloc) are required. The other methods
569/// have correct, bounded defaults. A custom decoder should additionally
570/// override:
571///
572/// - [`remaining_hint`](Decode::remaining_hint) when it knows how much
573///   input is left, so collection pre-allocation is bounded by it;
574/// - [`config`](Decode::config), [`depth`](Decode::depth),
575///   [`enter_nested`](Decode::enter_nested) and
576///   [`leave_nested`](Decode::leave_nested) to enforce
577///   [`Config::max_depth`] (the defaults do not track depth);
578/// - [`consumed`](Decode::consumed) if it keeps the input in memory, so
579///   canonical mode can check map key order;
580/// - [`bytes_read`](Decode::bytes_read), [`unbacked`](Decode::unbacked)
581///   and [`charge_unbacked`](Decode::charge_unbacked) so that collections
582///   of elements that occupy no input bytes are bounded by
583///   [`Config::max_alloc`] across the whole decode (`bytes_read` already
584///   works when `consumed` is overridden).
585pub trait Decode {
586    /// Read the next byte, advancing the cursor.
587    ///
588    /// # Errors
589    ///
590    /// Returns [`SerialError::UnexpectedEof`] if the input is exhausted.
591    /// Streaming decoders MAY return an I/O-flavoured error variant.
592    fn read_byte(&mut self) -> Result<u8>;
593
594    /// Fill `out` with exactly `out.len()` bytes, advancing the cursor.
595    ///
596    /// # Errors
597    ///
598    /// Returns [`SerialError::UnexpectedEof`] on short read.
599    fn read_into(&mut self, out: &mut [u8]) -> Result<()>;
600
601    /// Maximum number of bytes the decoder will allocate for a single
602    /// length-prefixed value. Mirrors [`Config::max_alloc`].
603    fn max_alloc(&self) -> usize;
604
605    /// An upper bound on the number of bytes that can still be read, when
606    /// the decoder knows it.
607    ///
608    /// In-memory decoders return `Some(remaining)`. Streaming decoders
609    /// return `None` (the default): the source length is unknown. Decode
610    /// impls use the hint to refuse, before allocating, any declared length
611    /// the input cannot possibly back.
612    #[inline]
613    fn remaining_hint(&self) -> Option<usize> {
614        None
615    }
616
617    /// The configuration this decoder enforces.
618    ///
619    /// The default reports [`Config::default`] with this decoder's
620    /// [`max_alloc`](Decode::max_alloc). Decoders built by this crate
621    /// return the exact config they were constructed with.
622    #[inline]
623    fn config(&self) -> Config {
624        Config::new().with_max_alloc(self.max_alloc())
625    }
626
627    /// Current nesting depth: the number of derived values whose fields are
628    /// being decoded right now. Always `0` for decoders that do not track
629    /// depth (the default).
630    #[inline]
631    fn depth(&self) -> usize {
632        0
633    }
634
635    /// Record entry into one more level of nesting.
636    ///
637    /// Derived `Deserialize` / `DeserializeView` impls call this before
638    /// decoding their fields and [`leave_nested`](Decode::leave_nested)
639    /// afterwards. Hand-written impls for **recursive** types should do the
640    /// same. The default implementation does not track depth.
641    ///
642    /// # Errors
643    ///
644    /// [`SerialError::DepthLimitExceeded`] when the decoder is already at
645    /// [`Config::max_depth`].
646    ///
647    /// # Examples
648    ///
649    /// ```
650    /// use pack_io::{Decode, Deserialize, Result};
651    ///
652    /// // A hand-written recursive type: a linked list of bytes.
653    /// struct List(Option<(u8, Vec<List>)>);
654    ///
655    /// impl Deserialize for List {
656    ///     fn deserialize<D: Decode + ?Sized>(dec: &mut D) -> Result<Self> {
657    ///         dec.enter_nested()?;
658    ///         let inner = Option::<(u8, Vec<List>)>::deserialize(dec);
659    ///         dec.leave_nested();
660    ///         Ok(List(inner?))
661    ///     }
662    /// }
663    ///
664    /// // 10,000 levels of `Some((0, [ ... ]))` from 30 KB of input: refused
665    /// // with an error instead of overflowing the stack.
666    /// let mut hostile = Vec::new();
667    /// for _ in 0..10_000 { hostile.extend_from_slice(&[1, 0, 1]); }
668    /// hostile.push(0);
669    /// let err = pack_io::decode::<List>(&hostile).err().unwrap();
670    /// assert!(matches!(err, pack_io::SerialError::DepthLimitExceeded { .. }));
671    /// ```
672    #[inline]
673    fn enter_nested(&mut self) -> Result<()> {
674        Ok(())
675    }
676
677    /// Record exit from one level of nesting. Pairs with
678    /// [`enter_nested`](Decode::enter_nested); call it on the error path
679    /// too, so the decoder stays usable after a failed read.
680    #[inline]
681    fn leave_nested(&mut self) {}
682
683    /// The bytes this decoder has consumed so far, when it keeps its input
684    /// in memory.
685    ///
686    /// The in-memory [`Decoder`] returns `Some(&input[..position])`;
687    /// streaming decoders return `None` (the default). Canonical mode uses
688    /// it to compare the raw encoded keys of map and set entries.
689    #[inline]
690    fn consumed(&self) -> Option<&[u8]> {
691        None
692    }
693
694    /// Number of input bytes this decoder has consumed so far, when it
695    /// counts them.
696    ///
697    /// Collection decoders compare it before and after their elements to
698    /// find elements that took no input bytes (zero-sized types, `Box<()>`,
699    /// `Rc<()>`, structs whose fields are all `skip`, …) and charge their
700    /// memory with [`charge_unbacked`](Decode::charge_unbacked). The
701    /// default derives it from [`consumed`](Decode::consumed). A decoder
702    /// that returns `None` here opts out of that accounting, so a hostile
703    /// element count for such a type is then bounded only by
704    /// [`max_alloc`](Decode::max_alloc) elements per collection; every
705    /// decoder this crate ships counts.
706    ///
707    /// # Examples
708    ///
709    /// ```
710    /// use pack_io::{Decode, Decoder};
711    ///
712    /// let mut dec = Decoder::new(&[1, 2, 3]);
713    /// let _ = dec.read_byte().unwrap();
714    /// assert_eq!(dec.bytes_read(), Some(1));
715    /// ```
716    #[inline]
717    fn bytes_read(&self) -> Option<u64> {
718        self.consumed().map(|bytes| bytes.len() as u64)
719    }
720
721    /// Memory, in bytes, charged so far in this decode with
722    /// [`charge_unbacked`](Decode::charge_unbacked). Always `0` for decoders
723    /// that keep no running total (the default).
724    #[inline]
725    fn unbacked(&self) -> usize {
726        0
727    }
728
729    /// Charge `bytes` of memory needed by collection elements that took no
730    /// input bytes, against [`Config::max_alloc`] for the whole decode.
731    ///
732    /// The built-in collection impls call this; hand-written collection
733    /// impls rarely need to. The decoders this crate ships keep a running
734    /// total and refuse the decode once it would exceed `max_alloc`, so the
735    /// memory such elements occupy is bounded by `max_alloc` across the
736    /// whole decode, not per collection. The default keeps no total and
737    /// refuses only a single charge above `max_alloc`.
738    ///
739    /// # Errors
740    ///
741    /// [`SerialError::InvalidLength`] (with `declared` set to the memory
742    /// total in bytes) when the limit would be exceeded.
743    ///
744    /// # Examples
745    ///
746    /// ```
747    /// use pack_io::{Config, Decode, Decoder, SerialError};
748    ///
749    /// let mut dec = Decoder::with_config(&[], Config::new().with_max_alloc(100)).unwrap();
750    /// dec.charge_unbacked(60).unwrap();
751    /// assert_eq!(dec.unbacked(), 60);
752    /// assert!(matches!(dec.charge_unbacked(41), Err(SerialError::InvalidLength { .. })));
753    /// ```
754    #[inline]
755    fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
756        if bytes > self.max_alloc() {
757            return Err(unbacked_limit_error(bytes, self.remaining_hint()));
758        }
759        Ok(())
760    }
761
762    /// Read exactly `len` bytes.
763    ///
764    /// In-memory decoders return a borrow of their input
765    /// ([`Cow::Borrowed`], no copy). The default implementation reads into
766    /// a fresh buffer that grows in bounded steps as the bytes actually
767    /// arrive, so a large declared `len` over a short or stalled stream
768    /// costs at most a small first chunk, not `len` bytes. When
769    /// [`remaining_hint`](Decode::remaining_hint) is known, a `len` beyond
770    /// it is refused before anything is allocated.
771    ///
772    /// This method does not check `len` against
773    /// [`max_alloc`](Decode::max_alloc); callers that took `len` from the
774    /// wire must do that first (see
775    /// [`read_length_prefixed`](Decode::read_length_prefixed)).
776    ///
777    /// # Errors
778    ///
779    /// [`SerialError::UnexpectedEof`] if the input ends first.
780    ///
781    /// # Examples
782    ///
783    /// ```
784    /// use pack_io::{Decode, Decoder};
785    ///
786    /// let mut dec = Decoder::new(&[1, 2, 3, 4]);
787    /// assert_eq!(&*dec.read_byte_cow(3).unwrap(), &[1, 2, 3]);
788    /// assert!(dec.read_byte_cow(2).is_err()); // only one byte left
789    /// ```
790    fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>> {
791        read_bytes_incrementally(self, len).map(Cow::Owned)
792    }
793
794    /// Read a LEB128 varint as a `u64`.
795    ///
796    /// # Errors
797    ///
798    /// - [`SerialError::VarintOverflow`] for an encoding wider than 10
799    ///   bytes or one whose value overflows `u64`.
800    /// - [`SerialError::UnexpectedEof`] for a truncated encoding.
801    /// - [`SerialError::NonCanonical`] for a multi-byte encoding with a
802    ///   redundant zero final byte, when [`Config::canonical`] is on.
803    #[inline]
804    fn read_varint_u64(&mut self) -> Result<u64> {
805        // Fast path for single-byte varints (values 0..=127, the
806        // overwhelmingly common case for length prefixes and small ints).
807        // It is the 1.0 decoder byte for byte: no configuration is read.
808        let first = self.read_byte()?;
809        if first < 0x80 {
810            return Ok(u64::from(first));
811        }
812        let mut result: u64 = u64::from(first & 0x7f);
813        let mut shift: u32 = 7;
814        for consumed in 2..=varint::MAX_VARINT_LEN_U64 {
815            let byte = self.read_byte()?;
816            // The 10th byte may only set bit 0 — anything else overflows u64.
817            if consumed == varint::MAX_VARINT_LEN_U64 && (byte & 0xfe) != 0 {
818                return Err(SerialError::VarintOverflow);
819            }
820            result |= u64::from(byte & 0x7f) << shift;
821            if byte & 0x80 == 0 {
822                // A zero final byte after a continuation byte adds nothing:
823                // the value has a shorter encoding. Only then is the
824                // configuration consulted, so lenient decoding pays one
825                // compare on multi-byte varints and nothing else. (The check
826                // stays inline: an out-of-line call here, even a cold one,
827                // measurably slowed every decode that inlines this loop.)
828                if byte == 0 && self.config().canonical {
829                    return Err(SerialError::NonCanonical { reason: "varint" });
830                }
831                return Ok(result);
832            }
833            shift += 7;
834        }
835        Err(SerialError::VarintOverflow)
836    }
837
838    /// Read a LEB128 varint as a `u128`.
839    ///
840    /// # Errors
841    ///
842    /// See [`Decode::read_varint_u64`] (the width limit is 19 bytes).
843    #[inline]
844    fn read_varint_u128(&mut self) -> Result<u128> {
845        let mut result: u128 = 0;
846        let mut shift: u32 = 0;
847        for consumed in 1..=varint::MAX_VARINT_LEN_U128 {
848            let byte = self.read_byte()?;
849            // The 19th byte may only set the low two bits.
850            if consumed == varint::MAX_VARINT_LEN_U128 && (byte & 0xfc) != 0 {
851                return Err(SerialError::VarintOverflow);
852            }
853            result |= u128::from(byte & 0x7f) << shift;
854            if byte & 0x80 == 0 {
855                if consumed > 1 && byte == 0 && self.config().canonical {
856                    return Err(SerialError::NonCanonical { reason: "varint" });
857                }
858                return Ok(result);
859            }
860            shift += 7;
861        }
862        Err(SerialError::VarintOverflow)
863    }
864
865    /// Read a length-prefixed byte run into a fresh `Vec<u8>`.
866    ///
867    /// The length is read as a varint and validated against
868    /// [`Decode::max_alloc`]; the bytes are then read with
869    /// [`Decode::read_byte_cow`], which never allocates ahead of the data
870    /// that actually exists.
871    ///
872    /// # Errors
873    ///
874    /// - [`SerialError::InvalidLength`] if the prefix exceeds `max_alloc`.
875    /// - [`SerialError::UnexpectedEof`] if the source runs out before the
876    ///   declared length is satisfied.
877    #[inline]
878    fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
879        let declared = self.read_varint_u64()?;
880        let len = guard_element_count(declared, self)?;
881        self.read_byte_cow(len).map(Cow::into_owned)
882    }
883}
884
885/// LEB128 `u64` decode loop specialised at compile time: with `CANONICAL`
886/// a redundant zero final byte is rejected, without it the loop is exactly
887/// the lenient 1.0 decoder. The integer `deserialize_many` impls read the
888/// canonical flag once per collection and call the matching instance, so
889/// lenient integer arrays pay nothing for canonical mode existing.
890#[inline]
891pub(crate) fn read_varint_u64_with<D: Decode + ?Sized, const CANONICAL: bool>(
892    decoder: &mut D,
893) -> Result<u64> {
894    let first = decoder.read_byte()?;
895    if first < 0x80 {
896        return Ok(u64::from(first));
897    }
898    let mut result: u64 = u64::from(first & 0x7f);
899    let mut shift: u32 = 7;
900    for consumed in 2..=varint::MAX_VARINT_LEN_U64 {
901        let byte = decoder.read_byte()?;
902        // The 10th byte may only set bit 0 — anything else overflows u64.
903        if consumed == varint::MAX_VARINT_LEN_U64 && (byte & 0xfe) != 0 {
904            return Err(SerialError::VarintOverflow);
905        }
906        result |= u64::from(byte & 0x7f) << shift;
907        if byte & 0x80 == 0 {
908            if CANONICAL && byte == 0 {
909                return Err(SerialError::NonCanonical { reason: "varint" });
910            }
911            return Ok(result);
912        }
913        shift += 7;
914    }
915    Err(SerialError::VarintOverflow)
916}
917
918/// The default body of [`Decode::read_byte_cow`]: read `len` bytes into a
919/// buffer that doubles (starting at [`PREALLOC_BYTES`]) only after the
920/// previous chunk has been filled from the source.
921///
922/// Peak allocation is therefore at most about twice the bytes the source
923/// actually delivered, plus one chunk — never the declared `len`.
924fn read_bytes_incrementally<D: Decode + ?Sized>(decoder: &mut D, len: usize) -> Result<Vec<u8>> {
925    if let Some(remaining) = decoder.remaining_hint() {
926        if len > remaining {
927            return Err(SerialError::UnexpectedEof {
928                needed: len,
929                remaining,
930            });
931        }
932    }
933    // The first chunk comes from a zeroed allocation (cheap for the common
934    // short value); later chunks double only after the previous one filled.
935    let mut filled = len.min(PREALLOC_BYTES);
936    let mut out: Vec<u8> = alloc::vec![0u8; filled];
937    decoder.read_into(&mut out)?;
938    while filled < len {
939        let target = len.min(filled.saturating_mul(2).max(PREALLOC_BYTES));
940        out.resize(target, 0);
941        decoder.read_into(&mut out[filled..target])?;
942        filled = target;
943    }
944    Ok(out)
945}
946
947// ---------------------------------------------------------------------------
948// In-memory Encoder
949// ---------------------------------------------------------------------------
950
951/// In-memory encoder. Writes into an owned `Vec<u8>`; the buffer can be
952/// reused across encodes by calling [`Encoder::take`] to swap it out.
953///
954/// Implements [`Encode`], so [`Serialize`] impls written generically over
955/// `E: Encode` work directly through it.
956///
957/// # Examples
958///
959/// ```
960/// use pack_io::Encoder;
961///
962/// let mut enc = Encoder::new();
963/// enc.write(&7_u64).unwrap();
964/// enc.write(&"hello").unwrap();
965/// let bytes = enc.into_inner();
966/// assert!(bytes.len() > 0);
967/// ```
968#[derive(Debug, Default)]
969pub struct Encoder {
970    out: Vec<u8>,
971}
972
973impl Encoder {
974    /// Construct an encoder with an empty output buffer.
975    ///
976    /// # Examples
977    ///
978    /// ```
979    /// let enc = pack_io::Encoder::new();
980    /// assert!(enc.as_bytes().is_empty());
981    /// ```
982    #[must_use]
983    pub fn new() -> Self {
984        Self { out: Vec::new() }
985    }
986
987    /// Construct an encoder with an output buffer pre-allocated to
988    /// `capacity` bytes.
989    ///
990    /// Choose this over [`Encoder::new`] when the encoded size is roughly
991    /// known: a single `Vec::with_capacity` up front avoids the four to
992    /// eight grow-and-copy reallocations that a zero-capacity `Vec`
993    /// performs while doubling to the final size.
994    ///
995    /// `capacity` is a hint — the encoder still grows the buffer if the
996    /// encoded value exceeds it. Setting it slightly too high is harmless;
997    /// setting it slightly too low costs at most one growth.
998    ///
999    /// The Tier-1 [`crate::encode`] free function uses a small default
1000    /// capacity internally so most one-shot encodes never grow at all.
1001    ///
1002    /// # Examples
1003    ///
1004    /// ```
1005    /// let enc = pack_io::Encoder::with_capacity(256);
1006    /// assert!(enc.as_bytes().is_empty());
1007    /// ```
1008    #[must_use]
1009    pub fn with_capacity(capacity: usize) -> Self {
1010        Self {
1011            out: Vec::with_capacity(capacity),
1012        }
1013    }
1014
1015    /// Construct an encoder backed by `buffer`. The encoder appends to the
1016    /// buffer rather than allocating its own — callers that re-use a single
1017    /// `Vec<u8>` across many encodes avoid the per-call allocation.
1018    ///
1019    /// # Examples
1020    ///
1021    /// ```
1022    /// use pack_io::Encoder;
1023    ///
1024    /// let buf = Vec::with_capacity(64);
1025    /// let mut enc = Encoder::into_buffer(buf);
1026    /// enc.write(&42_u64).unwrap();
1027    /// let buf = enc.into_inner();
1028    /// assert!(!buf.is_empty());
1029    /// ```
1030    #[must_use]
1031    pub fn into_buffer(buffer: Vec<u8>) -> Self {
1032        Self { out: buffer }
1033    }
1034
1035    /// Borrow the encoded bytes accumulated so far, without consuming the
1036    /// encoder.
1037    ///
1038    /// Prefer this over [`Encoder::into_inner`] when the caller wants to
1039    /// send / hash / inspect the bytes but keep writing more values.
1040    ///
1041    /// # Examples
1042    ///
1043    /// ```
1044    /// use pack_io::Encoder;
1045    ///
1046    /// let mut enc = Encoder::new();
1047    /// enc.write(&1_u64).unwrap();
1048    /// let snapshot = enc.as_bytes().to_vec();
1049    /// enc.write(&2_u64).unwrap();
1050    /// assert_eq!(snapshot, &[0x01]);
1051    /// assert_eq!(enc.as_bytes(), &[0x01, 0x02]);
1052    /// ```
1053    #[inline]
1054    #[must_use]
1055    pub fn as_bytes(&self) -> &[u8] {
1056        &self.out
1057    }
1058
1059    /// Consume the encoder and return its underlying buffer.
1060    ///
1061    /// The returned `Vec<u8>` is the exact bytes accumulated by every
1062    /// preceding `write` call.
1063    ///
1064    /// # Examples
1065    ///
1066    /// ```
1067    /// use pack_io::Encoder;
1068    ///
1069    /// let mut enc = Encoder::new();
1070    /// enc.write(&7_u64).unwrap();
1071    /// let bytes: Vec<u8> = enc.into_inner();
1072    /// assert_eq!(bytes, &[0x07]);
1073    /// ```
1074    #[inline]
1075    #[must_use]
1076    pub fn into_inner(self) -> Vec<u8> {
1077        self.out
1078    }
1079
1080    /// Swap the encoder's buffer with a fresh empty one, returning the bytes
1081    /// written so far. Useful for "encode then send" loops that want to
1082    /// re-use the encoder across many messages.
1083    ///
1084    /// After `take`, the encoder is empty and ready to encode the next
1085    /// message. The returned buffer is the previous contents.
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// use pack_io::Encoder;
1091    ///
1092    /// let mut enc = Encoder::new();
1093    /// enc.write(&1_u64).unwrap();
1094    /// let first = enc.take();
1095    /// enc.write(&2_u64).unwrap();
1096    /// let second = enc.take();
1097    /// assert_eq!(first, &[0x01]);
1098    /// assert_eq!(second, &[0x02]);
1099    /// assert!(enc.as_bytes().is_empty());
1100    /// ```
1101    #[must_use]
1102    pub fn take(&mut self) -> Vec<u8> {
1103        core::mem::take(&mut self.out)
1104    }
1105
1106    /// Encode `value`, appending its bytes to the internal buffer.
1107    ///
1108    /// This is the [`Serialize`]-aware sibling of [`Encode::write_bytes`].
1109    /// Prefer it for typed values; reserve `write_bytes` for raw byte
1110    /// passthrough.
1111    ///
1112    /// # Errors
1113    ///
1114    /// Propagates any error returned by the type's [`Serialize`]
1115    /// implementation. The built-in primitive and collection impls in this
1116    /// crate never error on an in-memory encoder.
1117    ///
1118    /// # Examples
1119    ///
1120    /// Writing several values in sequence:
1121    ///
1122    /// ```
1123    /// use pack_io::Encoder;
1124    ///
1125    /// let mut enc = Encoder::new();
1126    /// enc.write(&7_u64).unwrap();
1127    /// enc.write(&"hello").unwrap();
1128    /// enc.write(&vec![1u8, 2, 3]).unwrap();
1129    /// assert!(!enc.as_bytes().is_empty());
1130    /// ```
1131    ///
1132    /// Encoding a tuple in one call (anything that implements `Serialize`
1133    /// works):
1134    ///
1135    /// ```
1136    /// use pack_io::Encoder;
1137    ///
1138    /// let mut enc = Encoder::new();
1139    /// enc.write(&(7_u64, "hello", true)).unwrap();
1140    /// assert!(!enc.as_bytes().is_empty());
1141    /// ```
1142    #[inline]
1143    pub fn write<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1144        value.serialize(self)
1145    }
1146}
1147
1148impl Encode for Encoder {
1149    #[inline(always)]
1150    fn write_byte(&mut self, byte: u8) -> Result<()> {
1151        self.out.push(byte);
1152        Ok(())
1153    }
1154
1155    #[inline(always)]
1156    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
1157        self.out.extend_from_slice(bytes);
1158        Ok(())
1159    }
1160
1161    #[inline(always)]
1162    fn reserve(&mut self, additional: usize) {
1163        self.out.reserve(additional);
1164    }
1165
1166    /// Override of [`Encode::write_varint_u64`] specialised for the in-memory
1167    /// encoder. Pushes each varint byte directly onto the underlying `Vec`,
1168    /// reserving the full max-width up front so the loop never re-checks
1169    /// capacity. Avoids the stack-buffer + `extend_from_slice` round-trip
1170    /// the default impl would perform.
1171    #[inline]
1172    fn write_varint_u64(&mut self, value: u64) -> Result<()> {
1173        if value < 0x80 {
1174            self.out.push(value as u8);
1175            return Ok(());
1176        }
1177        // Up to 10 bytes for u64. Reserve once, then push without further
1178        // capacity checks.
1179        self.out.reserve(varint::MAX_VARINT_LEN_U64);
1180        let mut n = value;
1181        while n >= 0x80 {
1182            self.out.push((n as u8) | 0x80);
1183            n >>= 7;
1184        }
1185        self.out.push(n as u8);
1186        Ok(())
1187    }
1188
1189    /// Same specialisation as [`Encode::write_varint_u64`], widened to 128
1190    /// bits.
1191    #[inline]
1192    fn write_varint_u128(&mut self, value: u128) -> Result<()> {
1193        if value < 0x80 {
1194            self.out.push(value as u8);
1195            return Ok(());
1196        }
1197        self.out.reserve(varint::MAX_VARINT_LEN_U128);
1198        let mut n = value;
1199        while n >= 0x80 {
1200            self.out.push((n as u8) | 0x80);
1201            n >>= 7;
1202        }
1203        self.out.push(n as u8);
1204        Ok(())
1205    }
1206}
1207
1208// ---------------------------------------------------------------------------
1209// In-memory Decoder
1210// ---------------------------------------------------------------------------
1211
1212/// In-memory decoder. Borrows from an input slice and advances a position
1213/// pointer as values are read. Bounds-checked on every operation.
1214///
1215/// Implements [`Decode`], so [`Deserialize`] impls written generically over
1216/// `D: Decode` work directly through it.
1217///
1218/// # Examples
1219///
1220/// ```
1221/// use pack_io::{Encoder, Decoder};
1222///
1223/// let mut enc = Encoder::new();
1224/// enc.write(&7_u64).unwrap();
1225/// enc.write(&true).unwrap();
1226/// let bytes = enc.into_inner();
1227///
1228/// let mut dec = Decoder::new(&bytes);
1229/// let n: u64 = dec.read().unwrap();
1230/// let b: bool = dec.read().unwrap();
1231/// assert_eq!(n, 7);
1232/// assert!(b);
1233/// assert!(dec.is_empty());
1234/// ```
1235#[derive(Debug)]
1236pub struct Decoder<'a> {
1237    input: &'a [u8],
1238    pos: usize,
1239    config: Config,
1240    depth: usize,
1241    unbacked: usize,
1242}
1243
1244impl<'a> Decoder<'a> {
1245    /// Construct a decoder over `bytes` using the default [`Config`]
1246    /// (1 GiB `max_alloc`).
1247    ///
1248    /// For tighter allocation limits on untrusted input, use
1249    /// [`Decoder::with_config`] instead.
1250    ///
1251    /// # Examples
1252    ///
1253    /// ```
1254    /// use pack_io::Decoder;
1255    ///
1256    /// let bytes = pack_io::encode(&42_u64).unwrap();
1257    /// let mut dec = Decoder::new(&bytes);
1258    /// let n: u64 = dec.read().unwrap();
1259    /// assert_eq!(n, 42);
1260    /// ```
1261    #[inline]
1262    #[must_use]
1263    pub fn new(bytes: &'a [u8]) -> Self {
1264        Self {
1265            input: bytes,
1266            pos: 0,
1267            config: Config::new(),
1268            depth: 0,
1269            unbacked: 0,
1270        }
1271    }
1272
1273    /// Construct a decoder with the supplied configuration.
1274    ///
1275    /// Use this when the input comes from an untrusted producer and the
1276    /// caller wants to bound per-value allocations.
1277    ///
1278    /// # Errors
1279    ///
1280    /// [`SerialError::InvalidConfig`] if `config.max_alloc == 0` or
1281    /// `config.max_depth == 0`.
1282    ///
1283    /// # Examples
1284    ///
1285    /// ```
1286    /// use pack_io::{Config, Decoder};
1287    ///
1288    /// let cfg = Config::new().with_max_alloc(16 * 1024); // 16 KiB cap
1289    /// let bytes = pack_io::encode(&"hello").unwrap();
1290    /// let mut dec = Decoder::with_config(&bytes, cfg).unwrap();
1291    /// let s: String = dec.read().unwrap();
1292    /// assert_eq!(s, "hello");
1293    /// ```
1294    pub fn with_config(bytes: &'a [u8], config: Config) -> Result<Self> {
1295        Ok(Self {
1296            input: bytes,
1297            pos: 0,
1298            config: config.validate()?,
1299            depth: 0,
1300            unbacked: 0,
1301        })
1302    }
1303
1304    /// Decoder over a sub-slice that inherits `config`, the current nesting
1305    /// `depth` and the running [`Decode::unbacked`] total of the decoder it
1306    /// was carved out of. Used for the bodies of versioned structs, so a
1307    /// body is decoded under exactly the limits the caller asked for.
1308    #[inline]
1309    pub(crate) fn nested(bytes: &'a [u8], config: Config, depth: usize, unbacked: usize) -> Self {
1310        Self {
1311            input: bytes,
1312            pos: 0,
1313            config,
1314            depth,
1315            unbacked,
1316        }
1317    }
1318
1319    /// The configuration this decoder enforces.
1320    ///
1321    /// # Examples
1322    ///
1323    /// ```
1324    /// use pack_io::{Config, Decoder};
1325    ///
1326    /// let cfg = Config::new().with_max_depth(8);
1327    /// let dec = Decoder::with_config(&[], cfg).unwrap();
1328    /// assert_eq!(dec.config().max_depth, 8);
1329    /// ```
1330    #[inline]
1331    #[must_use]
1332    pub fn config(&self) -> Config {
1333        self.config
1334    }
1335
1336    /// Bytes consumed so far from the start of the input.
1337    ///
1338    /// # Examples
1339    ///
1340    /// ```
1341    /// use pack_io::Decoder;
1342    ///
1343    /// let bytes = pack_io::encode(&(1_u8, 2_u8)).unwrap();
1344    /// let mut dec = Decoder::new(&bytes);
1345    /// assert_eq!(dec.position(), 0);
1346    /// let _: u8 = dec.read().unwrap();
1347    /// assert_eq!(dec.position(), 1);
1348    /// ```
1349    #[inline]
1350    #[must_use]
1351    pub fn position(&self) -> usize {
1352        self.pos
1353    }
1354
1355    /// Number of bytes remaining in the input.
1356    ///
1357    /// # Examples
1358    ///
1359    /// ```
1360    /// use pack_io::Decoder;
1361    ///
1362    /// let bytes = pack_io::encode(&(1_u8, 2_u8, 3_u8)).unwrap();
1363    /// let mut dec = Decoder::new(&bytes);
1364    /// assert_eq!(dec.remaining(), 3);
1365    /// let _: u8 = dec.read().unwrap();
1366    /// assert_eq!(dec.remaining(), 2);
1367    /// ```
1368    #[inline]
1369    #[must_use]
1370    pub fn remaining(&self) -> usize {
1371        self.input.len().saturating_sub(self.pos)
1372    }
1373
1374    /// True when there are no more bytes to read.
1375    ///
1376    /// Useful as the loop condition for multi-value decode passes that
1377    /// don't have an explicit count up front.
1378    ///
1379    /// # Examples
1380    ///
1381    /// ```
1382    /// use pack_io::{Encoder, Decoder};
1383    ///
1384    /// let mut enc = Encoder::new();
1385    /// enc.write(&1_u64).unwrap();
1386    /// enc.write(&2_u64).unwrap();
1387    /// let bytes = enc.into_inner();
1388    ///
1389    /// let mut dec = Decoder::new(&bytes);
1390    /// let mut sum = 0_u64;
1391    /// while !dec.is_empty() {
1392    ///     sum += dec.read::<u64>().unwrap();
1393    /// }
1394    /// assert_eq!(sum, 3);
1395    /// ```
1396    #[inline]
1397    #[must_use]
1398    pub fn is_empty(&self) -> bool {
1399        self.remaining() == 0
1400    }
1401
1402    /// Decode a value of type `T` from the current position, advancing the
1403    /// cursor by the number of bytes the value consumed.
1404    ///
1405    /// # Errors
1406    ///
1407    /// Returns any [`SerialError`] surfaced by `T::deserialize`.
1408    ///
1409    /// # Examples
1410    ///
1411    /// Reading several values in sequence:
1412    ///
1413    /// ```
1414    /// use pack_io::{Encoder, Decoder};
1415    ///
1416    /// let mut enc = Encoder::new();
1417    /// enc.write(&7_u64).unwrap();
1418    /// enc.write(&"hello").unwrap();
1419    /// let bytes = enc.into_inner();
1420    ///
1421    /// let mut dec = Decoder::new(&bytes);
1422    /// let n: u64 = dec.read().unwrap();
1423    /// let s: String = dec.read().unwrap();
1424    /// assert_eq!((n, s.as_str()), (7, "hello"));
1425    /// ```
1426    ///
1427    /// Reading a tuple in a single call:
1428    ///
1429    /// ```
1430    /// use pack_io::Decoder;
1431    ///
1432    /// let bytes = pack_io::encode(&(7_u64, true)).unwrap();
1433    /// let mut dec = Decoder::new(&bytes);
1434    /// let pair: (u64, bool) = dec.read().unwrap();
1435    /// assert_eq!(pair, (7, true));
1436    /// ```
1437    #[inline]
1438    pub fn read<T: Deserialize>(&mut self) -> Result<T> {
1439        T::deserialize(self)
1440    }
1441
1442    /// Read a length-prefixed byte run as a **borrowed** slice of the
1443    /// underlying input — no allocation, no copy.
1444    ///
1445    /// The borrowed slice has the same lifetime `'a` as the decoder's
1446    /// input buffer, which lets caller-side `&'a str` / `&'a [u8]` decode
1447    /// paths return a borrow directly into that buffer. This is the seam
1448    /// the zero-copy [`crate::DeserializeView`] surface plugs into for
1449    /// `&'a str` and `&'a [u8]`.
1450    ///
1451    /// # Errors
1452    ///
1453    /// - [`SerialError::InvalidLength`] if the prefix exceeds the
1454    ///   configured `max_alloc`, OR exceeds the remaining input.
1455    /// - [`SerialError::UnexpectedEof`] is folded into `InvalidLength` for
1456    ///   this method, since the buffer length is known up front and a
1457    ///   declared length running off the end is logically a length-prefix
1458    ///   error, not a streaming EOF.
1459    #[inline]
1460    pub fn read_length_prefixed_borrowed(&mut self) -> Result<&'a [u8]> {
1461        let declared = <Self as Decode>::read_varint_u64(self)?;
1462        let remaining = self.remaining();
1463        let max = self.config.max_alloc as u64;
1464        if declared > max || declared > remaining as u64 {
1465            return Err(SerialError::InvalidLength {
1466                declared,
1467                remaining,
1468            });
1469        }
1470        // `declared <= remaining`, so the conversion is lossless.
1471        self.read_borrowed(declared as usize)
1472    }
1473
1474    /// Read exactly `len` bytes as a **borrowed** slice of the input — no
1475    /// length prefix, no allocation, no copy.
1476    ///
1477    /// Use it for fixed-size fields whose length is known from the type or
1478    /// from an earlier field.
1479    ///
1480    /// # Errors
1481    ///
1482    /// [`SerialError::UnexpectedEof`] if fewer than `len` bytes remain; the
1483    /// cursor does not move.
1484    ///
1485    /// # Examples
1486    ///
1487    /// ```
1488    /// use pack_io::Decoder;
1489    ///
1490    /// let mut dec = Decoder::new(&[1, 2, 3, 4]);
1491    /// let head: &[u8] = dec.read_borrowed(3).unwrap();
1492    /// assert_eq!(head, &[1, 2, 3]);
1493    /// assert_eq!(dec.remaining(), 1);
1494    /// ```
1495    #[inline]
1496    pub fn read_borrowed(&mut self, len: usize) -> Result<&'a [u8]> {
1497        let remaining = self.remaining();
1498        if len > remaining {
1499            return Err(SerialError::UnexpectedEof {
1500                needed: len,
1501                remaining,
1502            });
1503        }
1504        let start = self.pos;
1505        let end = start + len;
1506        let input: &'a [u8] = self.input;
1507        self.pos = end;
1508        Ok(&input[start..end])
1509    }
1510}
1511
1512impl Decode for Decoder<'_> {
1513    #[inline]
1514    fn read_byte(&mut self) -> Result<u8> {
1515        match self.input.get(self.pos) {
1516            Some(&b) => {
1517                self.pos += 1;
1518                Ok(b)
1519            }
1520            None => Err(SerialError::UnexpectedEof {
1521                needed: 1,
1522                remaining: 0,
1523            }),
1524        }
1525    }
1526
1527    #[inline]
1528    fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
1529        let n = out.len();
1530        let remaining = self.remaining();
1531        if n > remaining {
1532            return Err(SerialError::UnexpectedEof {
1533                needed: n,
1534                remaining,
1535            });
1536        }
1537        let start = self.pos;
1538        let end = start + n;
1539        out.copy_from_slice(&self.input[start..end]);
1540        self.pos = end;
1541        Ok(())
1542    }
1543
1544    #[inline]
1545    fn max_alloc(&self) -> usize {
1546        self.config.max_alloc
1547    }
1548
1549    #[inline]
1550    fn remaining_hint(&self) -> Option<usize> {
1551        Some(self.remaining())
1552    }
1553
1554    #[inline]
1555    fn config(&self) -> Config {
1556        self.config
1557    }
1558
1559    #[inline]
1560    fn depth(&self) -> usize {
1561        self.depth
1562    }
1563
1564    #[inline]
1565    fn enter_nested(&mut self) -> Result<()> {
1566        if self.depth >= self.config.max_depth {
1567            return Err(SerialError::DepthLimitExceeded {
1568                max_depth: self.config.max_depth,
1569            });
1570        }
1571        self.depth += 1;
1572        Ok(())
1573    }
1574
1575    #[inline]
1576    fn leave_nested(&mut self) {
1577        self.depth = self.depth.saturating_sub(1);
1578    }
1579
1580    #[inline]
1581    fn consumed(&self) -> Option<&[u8]> {
1582        self.input.get(..self.pos)
1583    }
1584
1585    #[inline]
1586    fn bytes_read(&self) -> Option<u64> {
1587        Some(self.pos as u64)
1588    }
1589
1590    #[inline]
1591    fn unbacked(&self) -> usize {
1592        self.unbacked
1593    }
1594
1595    #[inline]
1596    fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
1597        let total = self.unbacked.saturating_add(bytes);
1598        if total > self.config.max_alloc {
1599            return Err(unbacked_limit_error(total, Some(self.remaining())));
1600        }
1601        self.unbacked = total;
1602        Ok(())
1603    }
1604
1605    /// In-memory specialisation: a bounds check and a borrow of the input.
1606    #[inline]
1607    fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>> {
1608        self.read_borrowed(len).map(Cow::Borrowed)
1609    }
1610
1611    /// In-memory specialisation: validates the length against the actual
1612    /// buffer as well as `max_alloc`, so a truncated input is rejected
1613    /// without allocating, then copies exactly the declared bytes.
1614    #[inline]
1615    fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
1616        self.read_length_prefixed_borrowed().map(<[u8]>::to_vec)
1617    }
1618}
1619
1620// ---------------------------------------------------------------------------
1621// Tier-1 free functions
1622// ---------------------------------------------------------------------------
1623
1624/// Encode `value` into a freshly allocated `Vec<u8>`.
1625///
1626/// This is the **Tier-1** entry point — the one-line surface for the common
1627/// case. Allocates one buffer with room for 512 bytes up front (measured
1628/// faster than an exact-size pre-pass), which grows if the value is larger.
1629/// To allocate exactly once at the exact size, use
1630/// `Encoder::with_capacity(value.encoded_len()?)`.
1631///
1632/// # Examples
1633///
1634/// ```
1635/// let bytes = pack_io::encode(&42_u64).unwrap();
1636/// let back: u64 = pack_io::decode(&bytes).unwrap();
1637/// assert_eq!(back, 42);
1638/// ```
1639///
1640/// # Errors
1641///
1642/// Propagates any error returned by the type's [`Serialize`] implementation.
1643/// The built-in primitive and collection impls never error on an in-memory
1644/// encoder.
1645#[inline]
1646pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
1647    // Pre-reserve enough to hold a typical small-to-medium message in a
1648    // single allocation. A zero-capacity `Vec` doubles 8+ times before
1649    // hitting 512 bytes, with each doubling memcpy-ing the prior contents
1650    // — accounting for a large fraction of the encode-time gap vs codecs
1651    // that pre-size their output buffer. 512 bytes covers most network
1652    // messages without growth; larger payloads pay at most one or two
1653    // doublings instead of the eight-plus a fresh `Vec` would.
1654    let mut enc = Encoder::with_capacity(512);
1655    value.serialize(&mut enc)?;
1656    Ok(enc.into_inner())
1657}
1658
1659/// Peek the schema version of a payload produced by a `#[pack_io(version = N)]`
1660/// type without consuming the buffer.
1661///
1662/// Reads only the leading varint and returns it as `u32`, leaving the
1663/// caller free to dispatch decode to the right `T` based on what they find.
1664/// On a non-versioned payload (no `#[pack_io(version = N)]` on the type)
1665/// this returns whatever the first varint of the encoding happens to be —
1666/// callers should only use it on payloads they know are versioned. The
1667/// value is not validated: a leading `0` peeks as `Ok(0)`, although every
1668/// decoder rejects version `0` with [`SerialError::InvalidVersion`].
1669///
1670/// # Examples
1671///
1672/// ```
1673/// # #[cfg(feature = "derive")] {
1674/// use pack_io::{encode, peek_version, Serialize, Deserialize};
1675///
1676/// #[derive(Serialize, Deserialize)]
1677/// #[pack_io(version = 2)]
1678/// struct Msg { id: u64 }
1679///
1680/// let bytes = encode(&Msg { id: 7 }).unwrap();
1681/// assert_eq!(peek_version(&bytes).unwrap(), 2);
1682/// # }
1683/// ```
1684///
1685/// # Errors
1686///
1687/// - [`SerialError::UnexpectedEof`] if `bytes` is empty or the leading
1688///   varint is truncated.
1689/// - [`SerialError::VarintOverflow`] / [`SerialError::IntegerOutOfRange`]
1690///   if the leading varint does not fit in `u32`.
1691#[inline]
1692pub fn peek_version(bytes: &[u8]) -> Result<u32> {
1693    let mut dec = Decoder::new(bytes);
1694    let v = dec.read_varint_u64()?;
1695    u32::try_from(v).map_err(|_| SerialError::IntegerOutOfRange)
1696}
1697
1698/// Decode a value of type `T` from `bytes`, requiring the input to be fully
1699/// consumed.
1700///
1701/// This is the **Tier-1** entry point — the one-line surface for the common
1702/// case. After the value has been read, the decoder checks that no bytes
1703/// remain; trailing input is reported as [`SerialError::TrailingBytes`].
1704/// Callers that want to read several values from a single buffer should use
1705/// [`Decoder`] directly.
1706///
1707/// # Examples
1708///
1709/// ```
1710/// let bytes = pack_io::encode(&"hello").unwrap();
1711/// let back: String = pack_io::decode(&bytes).unwrap();
1712/// assert_eq!(back, "hello");
1713/// ```
1714///
1715/// # Errors
1716///
1717/// - Returns [`SerialError::TrailingBytes`] when extra bytes follow the value.
1718/// - Propagates any [`SerialError`] from the type's [`Deserialize`] impl.
1719#[inline]
1720pub fn decode<T: Deserialize>(bytes: &[u8]) -> Result<T> {
1721    let mut dec = Decoder::new(bytes);
1722    let value = T::deserialize(&mut dec)?;
1723    finish(&dec, value)
1724}
1725
1726/// [`decode`] under an explicit [`Config`]: decode a value of type `T` from
1727/// `bytes`, requiring the input to be fully consumed.
1728///
1729/// Use it to tighten [`Config::max_alloc`] / [`Config::max_depth`] for
1730/// untrusted input, or to turn on [`Config::canonical`] where the bytes are
1731/// hashed or signed.
1732///
1733/// # Examples
1734///
1735/// ```
1736/// use pack_io::{Config, SerialError, decode_with_config, encode};
1737///
1738/// let bytes = encode(&vec![0u8; 1024]).unwrap();
1739/// let tight = Config::new().with_max_alloc(256);
1740/// let err = decode_with_config::<Vec<u8>>(&bytes, tight).unwrap_err();
1741/// assert!(matches!(err, SerialError::InvalidLength { declared: 1024, .. }));
1742/// ```
1743///
1744/// # Errors
1745///
1746/// - Any error [`Decoder::with_config`] reports for an invalid `config`.
1747/// - [`SerialError::TrailingBytes`] when extra bytes follow the value.
1748/// - Any [`SerialError`] from the type's [`Deserialize`] impl.
1749#[inline]
1750pub fn decode_with_config<T: Deserialize>(bytes: &[u8], config: Config) -> Result<T> {
1751    let mut dec = Decoder::with_config(bytes, config)?;
1752    let value = T::deserialize(&mut dec)?;
1753    finish(&dec, value)
1754}
1755
1756/// Reject trailing input after a whole-buffer decode.
1757#[inline]
1758pub(crate) fn finish<T>(dec: &Decoder<'_>, value: T) -> Result<T> {
1759    let remaining = dec.remaining();
1760    if remaining != 0 {
1761        return Err(SerialError::TrailingBytes { remaining });
1762    }
1763    Ok(value)
1764}
1765
1766// ---------------------------------------------------------------------------
1767// Size counting
1768// ---------------------------------------------------------------------------
1769
1770/// Number of bytes the LEB128 varint encoding of `value` occupies (1–10).
1771///
1772/// Handy for hand-written [`Serialize::encoded_len`] overrides, which must
1773/// account for every length prefix exactly.
1774///
1775/// # Examples
1776///
1777/// ```
1778/// assert_eq!(pack_io::varint_len(0), 1);
1779/// assert_eq!(pack_io::varint_len(127), 1);
1780/// assert_eq!(pack_io::varint_len(128), 2);
1781/// assert_eq!(pack_io::varint_len(u64::MAX), 10);
1782/// assert_eq!(pack_io::varint_len(300), pack_io::encode(&300_u64).unwrap().len());
1783/// ```
1784#[inline]
1785#[must_use]
1786pub const fn varint_len(value: u64) -> usize {
1787    // 1 byte per started group of 7 significant bits; zero still takes 1.
1788    let bits = 64 - (value | 1).leading_zeros() as usize;
1789    bits.div_ceil(7)
1790}
1791
1792/// An [`Encode`] sink that discards bytes and only counts them. Backs the
1793/// default [`Serialize::encoded_len`].
1794#[derive(Debug, Default)]
1795pub struct SizeCounter {
1796    len: usize,
1797}
1798
1799impl SizeCounter {
1800    /// Bytes counted so far.
1801    #[inline]
1802    pub fn count(&self) -> usize {
1803        self.len
1804    }
1805}
1806
1807impl Encode for SizeCounter {
1808    #[inline]
1809    fn write_byte(&mut self, _byte: u8) -> Result<()> {
1810        self.len = self.len.saturating_add(1);
1811        Ok(())
1812    }
1813
1814    #[inline]
1815    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
1816        self.len = self.len.saturating_add(bytes.len());
1817        Ok(())
1818    }
1819
1820    #[inline]
1821    fn write_varint_u64(&mut self, value: u64) -> Result<()> {
1822        self.len = self.len.saturating_add(varint_len(value));
1823        Ok(())
1824    }
1825}
1826
1827#[cfg(test)]
1828mod tests {
1829    use super::*;
1830
1831    #[test]
1832    fn config_default_has_one_gib_cap() {
1833        let cfg = Config::default();
1834        assert_eq!(cfg.max_alloc, 1 << 30);
1835    }
1836
1837    #[test]
1838    fn decoder_with_zero_cap_is_rejected() {
1839        let cfg = Config::new().with_max_alloc(0);
1840        let err = Decoder::with_config(&[], cfg).expect_err("zero cap is invalid");
1841        assert!(matches!(err, SerialError::InvalidConfig { .. }));
1842    }
1843
1844    #[test]
1845    fn encoder_into_buffer_reuses_caller_vec() {
1846        let mut buf = Vec::with_capacity(64);
1847        buf.push(0xff);
1848        let mut enc = Encoder::into_buffer(buf);
1849        enc.write(&7_u64).unwrap();
1850        let out = enc.into_inner();
1851        assert_eq!(out[0], 0xff);
1852        assert!(out.len() > 1);
1853    }
1854
1855    #[test]
1856    fn encoder_take_returns_buffer_and_resets() {
1857        let mut enc = Encoder::new();
1858        enc.write(&1_u64).unwrap();
1859        let first = enc.take();
1860        assert!(!first.is_empty());
1861        assert!(enc.as_bytes().is_empty());
1862
1863        enc.write(&2_u64).unwrap();
1864        let second = enc.take();
1865        assert_eq!(second, [0x02]);
1866    }
1867
1868    #[test]
1869    fn decode_rejects_trailing_bytes() {
1870        let mut bytes = encode(&7_u8).unwrap();
1871        bytes.push(0xff);
1872        let err = decode::<u8>(&bytes).expect_err("trailing bytes should fail");
1873        assert!(matches!(err, SerialError::TrailingBytes { remaining: 1 }));
1874    }
1875
1876    #[test]
1877    fn decoder_read_past_end_returns_unexpected_eof() {
1878        let mut dec = Decoder::new(&[0x01]);
1879        let _: u8 = dec.read().unwrap();
1880        let err = dec.read::<u8>().expect_err("past end should fail");
1881        assert!(matches!(err, SerialError::UnexpectedEof { .. }));
1882    }
1883
1884    #[test]
1885    fn decoder_length_prefix_above_cap_is_rejected() {
1886        let cfg = Config::new().with_max_alloc(4);
1887        let bytes = [0x05, b'h', b'e', b'l', b'l', b'o'];
1888        let mut dec = Decoder::with_config(&bytes, cfg).expect("non-zero cap");
1889        let err = dec
1890            .read_length_prefixed()
1891            .expect_err("length > cap should fail");
1892        assert!(matches!(
1893            err,
1894            SerialError::InvalidLength { declared: 5, .. }
1895        ));
1896    }
1897
1898    #[test]
1899    fn decoder_length_prefix_overflowing_remaining_is_rejected() {
1900        let bytes = [0x10, b'a', b'b'];
1901        let mut dec = Decoder::new(&bytes);
1902        let err = dec
1903            .read_length_prefixed()
1904            .expect_err("length > remaining should fail");
1905        assert!(matches!(err, SerialError::InvalidLength { .. }));
1906    }
1907
1908    #[test]
1909    fn decoder_position_advances_with_reads() {
1910        let bytes = [0x01, 0x02, 0x03];
1911        let mut dec = Decoder::new(&bytes);
1912        assert_eq!(dec.position(), 0);
1913        let _ = dec.read_byte().unwrap();
1914        assert_eq!(dec.position(), 1);
1915        let mut buf = [0u8; 2];
1916        dec.read_into(&mut buf).unwrap();
1917        assert_eq!(dec.position(), 3);
1918        assert!(dec.is_empty());
1919    }
1920
1921    #[test]
1922    fn test_config_builders_and_validation() {
1923        let cfg = Config::new()
1924            .with_max_alloc(10)
1925            .with_max_depth(3)
1926            .with_canonical(true);
1927        assert_eq!((cfg.max_alloc, cfg.max_depth, cfg.canonical), (10, 3, true));
1928        assert_eq!(Config::default(), Config::new());
1929        assert!(matches!(
1930            Decoder::with_config(&[], Config::new().with_max_depth(0)),
1931            Err(SerialError::InvalidConfig { .. })
1932        ));
1933    }
1934
1935    #[test]
1936    fn test_varint_len_matches_the_encoder_at_every_boundary() {
1937        for shift in 0..64 {
1938            for v in [
1939                1u64 << shift,
1940                (1u64 << shift) - 1,
1941                (1u64 << shift).wrapping_add(1),
1942            ] {
1943                let mut enc = Encoder::new();
1944                enc.write_varint_u64(v).unwrap();
1945                assert_eq!(varint_len(v), enc.as_bytes().len(), "{v}");
1946            }
1947        }
1948        assert_eq!(varint_len(u64::MAX), 10);
1949    }
1950
1951    /// A minimal third-party decoder: only the three required methods.
1952    struct Minimal<'a> {
1953        bytes: &'a [u8],
1954        reads: usize,
1955    }
1956
1957    impl Decode for Minimal<'_> {
1958        fn read_byte(&mut self) -> Result<u8> {
1959            let (first, rest) = self.bytes.split_first().ok_or(SerialError::UnexpectedEof {
1960                needed: 1,
1961                remaining: 0,
1962            })?;
1963            self.bytes = rest;
1964            Ok(*first)
1965        }
1966
1967        fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
1968            if out.len() > self.bytes.len() {
1969                return Err(SerialError::UnexpectedEof {
1970                    needed: out.len(),
1971                    remaining: self.bytes.len(),
1972                });
1973            }
1974            self.reads += 1;
1975            let (head, rest) = self.bytes.split_at(out.len());
1976            out.copy_from_slice(head);
1977            self.bytes = rest;
1978            Ok(())
1979        }
1980
1981        fn max_alloc(&self) -> usize {
1982            1 << 30
1983        }
1984    }
1985
1986    #[test]
1987    fn test_provided_methods_work_for_a_minimal_decoder() {
1988        let big = alloc::vec![7u8; PREALLOC_BYTES * 3 + 5];
1989        let mut encoded = encode(&big).unwrap();
1990        encoded.extend(encode(&"tail").unwrap());
1991        let mut dec = Minimal {
1992            bytes: &encoded,
1993            reads: 0,
1994        };
1995        // The incremental reader fills in chunks (64 KiB, then doubling).
1996        let back: Vec<u8> = Deserialize::deserialize(&mut dec).unwrap();
1997        assert_eq!(back, big);
1998        assert!(dec.reads >= 2, "read in chunks, got {}", dec.reads);
1999        let tail: alloc::string::String = Deserialize::deserialize(&mut dec).unwrap();
2000        assert_eq!(tail, "tail");
2001        // Defaults: no depth tracking, no consumed bytes, default config.
2002        assert_eq!(dec.depth(), 0);
2003        assert!(dec.enter_nested().is_ok());
2004        dec.leave_nested();
2005        assert!(dec.consumed().is_none());
2006        assert_eq!(dec.remaining_hint(), None);
2007        assert_eq!(dec.config().max_alloc, 1 << 30);
2008    }
2009
2010    /// A decoder that counts how often its configuration is consulted.
2011    struct CountingConfig<'a> {
2012        inner: Decoder<'a>,
2013        config_calls: core::cell::Cell<usize>,
2014    }
2015
2016    impl Decode for CountingConfig<'_> {
2017        fn read_byte(&mut self) -> Result<u8> {
2018            self.inner.read_byte()
2019        }
2020
2021        fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
2022            self.inner.read_into(out)
2023        }
2024
2025        fn max_alloc(&self) -> usize {
2026            self.inner.max_alloc()
2027        }
2028
2029        fn config(&self) -> Config {
2030            self.config_calls.set(self.config_calls.get() + 1);
2031            self.inner.config()
2032        }
2033    }
2034
2035    /// PACK-R04: the varint hot path must not read the configuration.
2036    /// 2.0.0 checked `config().canonical` on every varint, which cost
2037    /// lenient decoding about 10 % on small-integer vectors.
2038    #[test]
2039    fn test_varint_decode_consults_config_only_for_overlong_encodings() {
2040        let mut bytes = Vec::new();
2041        for v in [0u64, 1, 127, 128, 300, 16_384, u32::MAX as u64, u64::MAX] {
2042            bytes.extend(encode(&v).unwrap());
2043        }
2044        for strict in [false, true] {
2045            let config = Config::new().with_canonical(strict);
2046            let mut dec = CountingConfig {
2047                inner: Decoder::with_config(&bytes, config).unwrap(),
2048                config_calls: core::cell::Cell::new(0),
2049            };
2050            for _ in 0..8 {
2051                let _ = dec.read_varint_u64().unwrap();
2052            }
2053            assert_eq!(dec.config_calls.get(), 0, "canonical = {strict}");
2054        }
2055        // Only a redundant zero final byte reaches the configuration.
2056        let overlong = [0x80, 0x00];
2057        for (strict, expected) in [
2058            (false, Ok(0)),
2059            (true, Err(SerialError::NonCanonical { reason: "varint" })),
2060        ] {
2061            let mut dec = CountingConfig {
2062                inner: Decoder::with_config(&overlong, Config::new().with_canonical(strict))
2063                    .unwrap(),
2064                config_calls: core::cell::Cell::new(0),
2065            };
2066            assert_eq!(dec.read_varint_u64(), expected);
2067            assert_eq!(dec.config_calls.get(), 1);
2068        }
2069    }
2070
2071    #[test]
2072    fn test_unbacked_charges_accumulate_and_stop_at_max_alloc() {
2073        let cfg = Config::new().with_max_alloc(10);
2074        let mut dec = Decoder::with_config(&[], cfg).unwrap();
2075        dec.charge_unbacked(4).unwrap();
2076        dec.charge_unbacked(6).unwrap();
2077        assert_eq!(dec.unbacked(), 10);
2078        assert!(matches!(
2079            dec.charge_unbacked(1),
2080            Err(SerialError::InvalidLength { declared: 11, .. })
2081        ));
2082        assert_eq!(dec.unbacked(), 10, "a refused charge is not recorded");
2083        // The provided default keeps no total: it refuses only a single
2084        // charge above `max_alloc`.
2085        let mut minimal = Minimal {
2086            bytes: &[],
2087            reads: 0,
2088        };
2089        minimal.charge_unbacked(1 << 30).unwrap();
2090        minimal.charge_unbacked(1 << 30).unwrap();
2091        assert!(minimal.charge_unbacked((1 << 30) + 1).is_err());
2092        assert_eq!(minimal.unbacked(), 0);
2093        assert_eq!(minimal.bytes_read(), None);
2094    }
2095
2096    #[test]
2097    fn test_canonical_mode_rejects_overlong_u128_varints() {
2098        let strict = Config::new().with_canonical(true);
2099        let mut dec = Decoder::with_config(&[0x80, 0x00], strict).unwrap();
2100        assert_eq!(
2101            dec.read_varint_u128(),
2102            Err(SerialError::NonCanonical { reason: "varint" })
2103        );
2104        let mut dec = Decoder::new(&[0x80, 0x00]);
2105        assert_eq!(dec.read_varint_u128(), Ok(0));
2106    }
2107
2108    #[test]
2109    fn test_read_borrowed_and_consumed() {
2110        let mut dec = Decoder::new(&[1, 2, 3]);
2111        assert_eq!(dec.read_borrowed(2).unwrap(), &[1, 2]);
2112        assert_eq!(dec.consumed(), Some(&[1u8, 2][..]));
2113        assert!(matches!(
2114            dec.read_borrowed(2),
2115            Err(SerialError::UnexpectedEof {
2116                needed: 2,
2117                remaining: 1
2118            })
2119        ));
2120        assert_eq!(dec.position(), 2, "a failed read does not move the cursor");
2121    }
2122
2123    #[test]
2124    fn test_size_counter_counts_without_storing() {
2125        let mut counter = SizeCounter::default();
2126        counter.write_bytes(&[0; 10]).unwrap();
2127        counter.write_byte(1).unwrap();
2128        counter.write_varint_u64(300).unwrap();
2129        assert_eq!(counter.count(), 13);
2130    }
2131
2132    #[test]
2133    fn read_into_short_read_is_rejected() {
2134        let mut dec = Decoder::new(&[0x01, 0x02]);
2135        let mut buf = [0u8; 4];
2136        let err = dec.read_into(&mut buf).expect_err("short read");
2137        assert!(matches!(err, SerialError::UnexpectedEof { .. }));
2138    }
2139}