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