Skip to main content

pack_io/
impls.rs

1//! `Serialize` / `Deserialize` implementations for primitive, container, and
2//! collection types.
3//!
4//! ## Wire format (full reference: [`docs/WIRE_FORMAT.md`])
5//!
6//! - `u8` / `i8` — one byte each (fixed). `i8` is two's-complement.
7//! - `u16` / `u32` / `u64` / `u128` / `usize` — LEB128 varint. `usize` is
8//!   encoded through `u64`; on a 32-bit target a decoded value outside
9//!   `usize::MAX` is rejected with [`SerialError::IntegerOutOfRange`].
10//! - `i16` / `i32` / `i64` / `i128` / `isize` — ZigZag mapping followed by
11//!   LEB128 varint.
12//! - `bool` — one byte (`0x00` / `0x01`); any other byte is rejected.
13//! - `f32` / `f64` — IEEE 754 bit pattern, little-endian. NaN, ±Inf,
14//!   subnormals, and signed zeros all round-trip bit-for-bit.
15//! - `char` — the Unicode scalar value as a `u32` varint; surrogates and
16//!   values above `0x10FFFF` are rejected.
17//! - `String` / `&str` — varint length prefix, then UTF-8 bytes.
18//! - `[T; N]` — `N` consecutive `T` encodings, no length prefix (the length
19//!   is in the type).
20//! - `Vec<T>` / `&[T]` / `VecDeque<T>` — varint length prefix, then `len`
21//!   consecutive `T` encodings.
22//! - tuples (arity 1..=12) — fields concatenated in declaration order.
23//! - `Option<T>` — one tag byte (`0x00` = `None`, `0x01` = `Some`) followed
24//!   by the inner value when present.
25//! - `Result<T, E>` — one tag byte (`0x00` = `Ok`, `0x01` = `Err`) followed
26//!   by the inner value.
27//! - `()` and `PhantomData<T>` — zero bytes.
28//! - `NonZero*` — the same bytes as the underlying integer; zero is rejected.
29//! - `Duration` — `varint(secs: u64) ++ varint(nanos: u32)`, nanos `< 10^9`.
30//! - `Box<T>` (including `Box<str>`, `Box<[T]>`), `Rc<T>`, `Arc<T>`,
31//!   `Cow<'_, T>` — transparent:
32//!   the same bytes as the value they hold.
33//! - `BTreeMap` / `BTreeSet` / `HashMap` / `HashSet` — varint count followed
34//!   by the entries sorted lexicographically by their **encoded key bytes**.
35//!   This canonical ordering means a `HashMap` and a `BTreeMap` holding the
36//!   same logical data encode to the same bytes, regardless of insertion
37//!   order or build-flag-dependent hash randomisation.
38//!
39//! [`docs/WIRE_FORMAT.md`]: https://github.com/jamesgober/pack-io/blob/main/docs/WIRE_FORMAT.md
40
41use alloc::borrow::{Cow, ToOwned};
42use alloc::boxed::Box;
43use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
44use alloc::rc::Rc;
45use alloc::string::String;
46#[cfg(target_has_atomic = "ptr")]
47use alloc::sync::Arc;
48use alloc::vec::Vec;
49use core::marker::PhantomData;
50use core::num::{
51    NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
52    NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
53};
54use core::time::Duration;
55#[cfg(feature = "std")]
56use std::collections::{HashMap, HashSet};
57#[cfg(feature = "std")]
58use std::hash::{BuildHasher, Hash};
59
60use crate::codec::read_varint_u64_with;
61use crate::codec::{
62    Decode, Encode, Encoder, decode_elements_counted, guard_element_count, varint_len,
63};
64use crate::codec::{charge_boxed, charge_elements, initial_capacity};
65use crate::error::{Result, SerialError};
66use crate::traits::{Deserialize, Serialize};
67use crate::varint;
68
69/// `Deserialize::deserialize_many` for an integer encoded as a `u64`
70/// varint and converted with `$convert`.
71///
72/// The canonical flag is read once per collection and the element loop
73/// calls a varint reader specialised for it, so a lenient decode of an
74/// integer array runs the plain 1.0 varint loop with no per-element check
75/// (re-audit PACK-R04). Every element consumes at least one input byte, so
76/// the loop needs no accounting for free elements either.
77macro_rules! varint_many {
78    ($convert:expr) => {
79        #[inline]
80        fn deserialize_many<D: Decode + ?Sized>(
81            decoder: &mut D,
82            count: usize,
83        ) -> Result<Vec<Self>> {
84            let mut out = Vec::with_capacity(initial_capacity::<Self, D>(count, decoder));
85            if decoder.config().canonical {
86                for _ in 0..count {
87                    out.push($convert(read_varint_u64_with::<D, true>(decoder)?)?);
88                }
89            } else {
90                for _ in 0..count {
91                    out.push($convert(read_varint_u64_with::<D, false>(decoder)?)?);
92                }
93            }
94            Ok(out)
95        }
96    };
97}
98
99/// `Deserialize::deserialize_array` for a `Copy` primitive: fill a
100/// stack array initialised with `$zero`, so `[T; N]` decodes without a
101/// temporary heap `Vec`.
102macro_rules! stack_array {
103    ($zero:expr) => {
104        #[inline]
105        fn deserialize_array<D: Decode + ?Sized, const N: usize>(
106            decoder: &mut D,
107        ) -> Result<[Self; N]> {
108            let mut out = [$zero; N];
109            for slot in &mut out {
110                *slot = Self::deserialize(decoder)?;
111            }
112            Ok(out)
113        }
114    };
115}
116
117// ---------------------------------------------------------------------------
118// Unsigned integers
119// ---------------------------------------------------------------------------
120
121impl Serialize for u8 {
122    #[inline]
123    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
124        encoder.write_byte(*self)
125    }
126
127    /// Single bulk write — bypasses the per-element loop the default impl
128    /// would emit. For an in-memory [`crate::Encoder`] this compiles to a
129    /// single `Vec::extend_from_slice`; for `IoEncoder` it is one
130    /// `Write::write_all`. Either way it replaces N per-byte calls with a
131    /// memcpy.
132    #[inline]
133    fn serialize_slice<E: Encode + ?Sized>(slice: &[u8], encoder: &mut E) -> Result<()> {
134        encoder.write_bytes(slice)
135    }
136
137    #[inline]
138    fn encoded_len(&self) -> Result<usize> {
139        Ok(1)
140    }
141
142    #[inline]
143    fn encoded_len_slice(slice: &[u8]) -> Result<usize> {
144        Ok(slice.len())
145    }
146}
147
148impl Deserialize for u8 {
149    #[inline]
150    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
151        decoder.read_byte()
152    }
153
154    /// Single bulk read. For an in-memory [`crate::Decoder`] this is a
155    /// bounds check plus one copy of exactly `count` bytes; a `count` the
156    /// input cannot back is refused before anything is allocated. For
157    /// `IoDecoder` the buffer grows in bounded chunks as bytes
158    /// arrive, so a hostile count over a short stream costs one chunk.
159    #[inline]
160    fn deserialize_many<D: Decode + ?Sized>(decoder: &mut D, count: usize) -> Result<Vec<u8>> {
161        decoder.read_byte_cow(count).map(Cow::into_owned)
162    }
163
164    /// `[u8; N]` decodes with one read into a stack array — no heap.
165    #[inline]
166    fn deserialize_array<D: Decode + ?Sized, const N: usize>(decoder: &mut D) -> Result<[u8; N]> {
167        let mut out = [0u8; N];
168        decoder.read_into(&mut out)?;
169        Ok(out)
170    }
171}
172
173impl Serialize for u16 {
174    #[inline]
175    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
176        encoder.write_varint_u64(u64::from(*self))
177    }
178
179    #[inline]
180    fn encoded_len(&self) -> Result<usize> {
181        Ok(varint_len(u64::from(*self)))
182    }
183}
184
185impl Deserialize for u16 {
186    #[inline]
187    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
188        let value = decoder.read_varint_u64()?;
189        u16::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
190    }
191
192    stack_array!(0);
193
194    varint_many!(|v: u64| u16::try_from(v).map_err(|_| SerialError::IntegerOutOfRange));
195}
196
197impl Serialize for u32 {
198    #[inline]
199    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
200        encoder.write_varint_u64(u64::from(*self))
201    }
202
203    #[inline]
204    fn encoded_len(&self) -> Result<usize> {
205        Ok(varint_len(u64::from(*self)))
206    }
207}
208
209impl Deserialize for u32 {
210    #[inline]
211    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
212        let value = decoder.read_varint_u64()?;
213        u32::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
214    }
215
216    stack_array!(0);
217
218    varint_many!(|v: u64| u32::try_from(v).map_err(|_| SerialError::IntegerOutOfRange));
219}
220
221impl Serialize for u64 {
222    #[inline]
223    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
224        encoder.write_varint_u64(*self)
225    }
226
227    #[inline]
228    fn encoded_len(&self) -> Result<usize> {
229        Ok(varint_len(*self))
230    }
231}
232
233impl Deserialize for u64 {
234    #[inline]
235    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
236        decoder.read_varint_u64()
237    }
238
239    stack_array!(0);
240
241    varint_many!(|v: u64| -> Result<u64> { Ok(v) });
242}
243
244impl Serialize for u128 {
245    #[inline]
246    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
247        encoder.write_varint_u128(*self)
248    }
249
250    #[inline]
251    fn encoded_len(&self) -> Result<usize> {
252        Ok(varint::len_u128(*self))
253    }
254}
255
256impl Deserialize for u128 {
257    #[inline]
258    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
259        decoder.read_varint_u128()
260    }
261
262    stack_array!(0);
263}
264
265impl Serialize for usize {
266    #[inline]
267    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
268        encoder.write_varint_u64(*self as u64)
269    }
270
271    #[inline]
272    fn encoded_len(&self) -> Result<usize> {
273        Ok(varint_len(*self as u64))
274    }
275}
276
277impl Deserialize for usize {
278    #[inline]
279    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
280        let value = decoder.read_varint_u64()?;
281        usize::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
282    }
283
284    stack_array!(0);
285
286    varint_many!(|v: u64| usize::try_from(v).map_err(|_| SerialError::IntegerOutOfRange));
287}
288
289// ---------------------------------------------------------------------------
290// Signed integers — ZigZag + varint
291// ---------------------------------------------------------------------------
292
293impl Serialize for i8 {
294    #[inline]
295    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
296        encoder.write_byte(*self as u8)
297    }
298
299    #[inline]
300    fn encoded_len(&self) -> Result<usize> {
301        Ok(1)
302    }
303}
304
305impl Deserialize for i8 {
306    #[inline]
307    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
308        Ok(decoder.read_byte()? as i8)
309    }
310
311    stack_array!(0);
312}
313
314/// `Serialize` / `Deserialize` for a signed integer narrower than 64 bits
315/// (or pointer-sized): ZigZag through `i64`, then a `u64` varint.
316macro_rules! impl_signed_varint {
317    ($($t:ty),+ $(,)?) => {
318        $(
319            impl Serialize for $t {
320                #[inline]
321                fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
322                    encoder.write_varint_u64(varint::zigzag_encode_i64(*self as i64))
323                }
324
325                #[inline]
326                fn encoded_len(&self) -> Result<usize> {
327                    Ok(varint_len(varint::zigzag_encode_i64(*self as i64)))
328                }
329            }
330
331            impl Deserialize for $t {
332                #[inline]
333                fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
334                    let value = varint::zigzag_decode_i64(decoder.read_varint_u64()?);
335                    <$t>::try_from(value).map_err(|_| SerialError::IntegerOutOfRange)
336                }
337
338                varint_many!(|v: u64| {
339                    <$t>::try_from(varint::zigzag_decode_i64(v))
340                        .map_err(|_| SerialError::IntegerOutOfRange)
341                });
342
343                stack_array!(0);
344            }
345        )+
346    };
347}
348
349impl_signed_varint!(i16, i32, isize);
350
351impl Serialize for i64 {
352    #[inline]
353    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
354        encoder.write_varint_u64(varint::zigzag_encode_i64(*self))
355    }
356
357    #[inline]
358    fn encoded_len(&self) -> Result<usize> {
359        Ok(varint_len(varint::zigzag_encode_i64(*self)))
360    }
361}
362
363impl Deserialize for i64 {
364    #[inline]
365    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
366        Ok(varint::zigzag_decode_i64(decoder.read_varint_u64()?))
367    }
368
369    stack_array!(0);
370
371    varint_many!(|v: u64| -> Result<i64> { Ok(varint::zigzag_decode_i64(v)) });
372}
373
374impl Serialize for i128 {
375    #[inline]
376    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
377        encoder.write_varint_u128(varint::zigzag_encode_i128(*self))
378    }
379
380    #[inline]
381    fn encoded_len(&self) -> Result<usize> {
382        Ok(varint::len_u128(varint::zigzag_encode_i128(*self)))
383    }
384}
385
386impl Deserialize for i128 {
387    #[inline]
388    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
389        Ok(varint::zigzag_decode_i128(decoder.read_varint_u128()?))
390    }
391
392    stack_array!(0);
393}
394
395// ---------------------------------------------------------------------------
396// Bool
397// ---------------------------------------------------------------------------
398
399impl Serialize for bool {
400    #[inline]
401    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
402        encoder.write_byte(u8::from(*self))
403    }
404
405    #[inline]
406    fn encoded_len(&self) -> Result<usize> {
407        Ok(1)
408    }
409}
410
411impl Deserialize for bool {
412    #[inline]
413    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
414        match decoder.read_byte()? {
415            0x00 => Ok(false),
416            0x01 => Ok(true),
417            other => Err(SerialError::InvalidBool { byte: other }),
418        }
419    }
420
421    stack_array!(false);
422}
423
424// ---------------------------------------------------------------------------
425// char — Unicode scalar value as a u32 varint
426// ---------------------------------------------------------------------------
427
428impl Serialize for char {
429    #[inline]
430    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
431        encoder.write_varint_u64(u64::from(u32::from(*self)))
432    }
433
434    #[inline]
435    fn encoded_len(&self) -> Result<usize> {
436        Ok(varint_len(u64::from(u32::from(*self))))
437    }
438}
439
440impl Deserialize for char {
441    #[inline]
442    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
443        let scalar = u32::deserialize(decoder)?;
444        char::from_u32(scalar).ok_or(SerialError::InvalidValue { kind: "char" })
445    }
446
447    stack_array!('\0');
448}
449
450// ---------------------------------------------------------------------------
451// Floats — IEEE 754 bit pattern, little-endian
452// ---------------------------------------------------------------------------
453
454impl Serialize for f32 {
455    #[inline]
456    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
457        encoder.write_bytes(&self.to_bits().to_le_bytes())
458    }
459
460    #[inline]
461    fn encoded_len(&self) -> Result<usize> {
462        Ok(4)
463    }
464}
465
466impl Deserialize for f32 {
467    #[inline]
468    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
469        let mut buf = [0u8; 4];
470        decoder.read_into(&mut buf)?;
471        Ok(f32::from_bits(u32::from_le_bytes(buf)))
472    }
473
474    stack_array!(0.0);
475}
476
477impl Serialize for f64 {
478    #[inline]
479    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
480        encoder.write_bytes(&self.to_bits().to_le_bytes())
481    }
482
483    #[inline]
484    fn encoded_len(&self) -> Result<usize> {
485        Ok(8)
486    }
487}
488
489impl Deserialize for f64 {
490    #[inline]
491    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
492        let mut buf = [0u8; 8];
493        decoder.read_into(&mut buf)?;
494        Ok(f64::from_bits(u64::from_le_bytes(buf)))
495    }
496
497    stack_array!(0.0);
498}
499
500// ---------------------------------------------------------------------------
501// String / &str / Box<str>
502// ---------------------------------------------------------------------------
503
504impl Serialize for str {
505    #[inline]
506    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
507        let bytes = self.as_bytes();
508        encoder.write_varint_u64(bytes.len() as u64)?;
509        encoder.write_bytes(bytes)
510    }
511
512    #[inline]
513    fn encoded_len(&self) -> Result<usize> {
514        Ok(varint_len(self.len() as u64).saturating_add(self.len()))
515    }
516}
517
518impl Serialize for String {
519    #[inline]
520    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
521        Serialize::serialize(self.as_str(), encoder)
522    }
523
524    #[inline]
525    fn encoded_len(&self) -> Result<usize> {
526        self.as_str().encoded_len()
527    }
528}
529
530impl Deserialize for String {
531    #[inline]
532    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
533        let bytes = decoder.read_length_prefixed()?;
534        String::from_utf8(bytes).map_err(|_| SerialError::InvalidUtf8)
535    }
536}
537
538impl Deserialize for Box<str> {
539    #[inline]
540    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
541        String::deserialize(decoder).map(String::into_boxed_str)
542    }
543}
544
545// ---------------------------------------------------------------------------
546// Slices, Vec<T>, Box<[T]>, VecDeque<T>
547// ---------------------------------------------------------------------------
548
549impl<T: Serialize> Serialize for [T] {
550    #[inline]
551    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
552        encoder.write_varint_u64(self.len() as u64)?;
553        // Dispatch to T's `serialize_slice` so byte-slice payloads
554        // (T = u8) take the memcpy fast path via the `u8` override.
555        T::serialize_slice(self, encoder)
556    }
557
558    #[inline]
559    fn encoded_len(&self) -> Result<usize> {
560        Ok(varint_len(self.len() as u64).saturating_add(T::encoded_len_slice(self)?))
561    }
562}
563
564impl<T: Serialize> Serialize for Vec<T> {
565    #[inline]
566    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
567        Serialize::serialize(self.as_slice(), encoder)
568    }
569
570    #[inline]
571    fn encoded_len(&self) -> Result<usize> {
572        self.as_slice().encoded_len()
573    }
574}
575
576impl<T: Deserialize> Deserialize for Vec<T> {
577    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
578        let declared = decoder.read_varint_u64()?;
579        let len = guard_element_count(declared, decoder)?;
580        // Every slot is charged against the total budget up front, whatever
581        // its encoding costs: `Option<[u8; 4096]>` is one byte on the wire
582        // and 4097 in the `Vec`.
583        charge_elements::<T, D>(decoder, len)?;
584        // Dispatch to T's `deserialize_many` so byte-vec payloads
585        // (T = u8) take the memcpy fast path via the `u8` override.
586        T::deserialize_many(decoder, len)
587    }
588}
589
590impl<T: Deserialize> Deserialize for Box<[T]> {
591    #[inline]
592    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
593        Vec::<T>::deserialize(decoder).map(Vec::into_boxed_slice)
594    }
595}
596
597impl<T: Serialize> Serialize for VecDeque<T> {
598    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
599        encoder.write_varint_u64(self.len() as u64)?;
600        let (front, back) = self.as_slices();
601        T::serialize_slice(front, encoder)?;
602        T::serialize_slice(back, encoder)
603    }
604
605    fn encoded_len(&self) -> Result<usize> {
606        let (front, back) = self.as_slices();
607        Ok(varint_len(self.len() as u64)
608            .saturating_add(T::encoded_len_slice(front)?)
609            .saturating_add(T::encoded_len_slice(back)?))
610    }
611}
612
613impl<T: Deserialize> Deserialize for VecDeque<T> {
614    #[inline]
615    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
616        Vec::<T>::deserialize(decoder).map(VecDeque::from)
617    }
618}
619
620// ---------------------------------------------------------------------------
621// Fixed-size arrays — [T; N]
622// ---------------------------------------------------------------------------
623
624impl<T: Serialize, const N: usize> Serialize for [T; N] {
625    /// Routed through `T::serialize_slice`, so `[u8; N]` is one bulk write.
626    #[inline]
627    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
628        T::serialize_slice(self, encoder)
629    }
630
631    #[inline]
632    fn encoded_len(&self) -> Result<usize> {
633        T::encoded_len_slice(self)
634    }
635}
636
637impl<T: Deserialize, const N: usize> Deserialize for [T; N] {
638    /// Routed through `T::deserialize_array`, so `[u8; N]` is one read into
639    /// a stack array.
640    #[inline]
641    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
642        T::deserialize_array::<D, N>(decoder)
643    }
644}
645
646// ---------------------------------------------------------------------------
647// Tuples — arity 0..=12, PhantomData
648// ---------------------------------------------------------------------------
649
650impl Serialize for () {
651    #[inline]
652    fn serialize<E: Encode + ?Sized>(&self, _encoder: &mut E) -> Result<()> {
653        Ok(())
654    }
655
656    #[inline]
657    fn encoded_len(&self) -> Result<usize> {
658        Ok(0)
659    }
660}
661
662impl Deserialize for () {
663    #[inline]
664    fn deserialize<D: Decode + ?Sized>(_decoder: &mut D) -> Result<Self> {
665        Ok(())
666    }
667}
668
669impl<T: ?Sized> Serialize for PhantomData<T> {
670    #[inline]
671    fn serialize<E: Encode + ?Sized>(&self, _encoder: &mut E) -> Result<()> {
672        Ok(())
673    }
674
675    #[inline]
676    fn encoded_len(&self) -> Result<usize> {
677        Ok(0)
678    }
679}
680
681impl<T: ?Sized> Deserialize for PhantomData<T> {
682    #[inline]
683    fn deserialize<D: Decode + ?Sized>(_decoder: &mut D) -> Result<Self> {
684        Ok(PhantomData)
685    }
686}
687
688macro_rules! impl_tuple {
689    ($($name:ident: $idx:tt),+) => {
690        impl<$($name: Serialize),+> Serialize for ($($name,)+) {
691            #[inline]
692            fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
693                $( self.$idx.serialize(encoder)?; )+
694                Ok(())
695            }
696
697            #[inline]
698            fn encoded_len(&self) -> Result<usize> {
699                let mut total = 0usize;
700                $( total = total.saturating_add(self.$idx.encoded_len()?); )+
701                Ok(total)
702            }
703        }
704
705        impl<$($name: Deserialize),+> Deserialize for ($($name,)+) {
706            #[inline]
707            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
708                Ok(( $( $name::deserialize(decoder)?, )+ ))
709            }
710        }
711    };
712}
713
714impl_tuple!(T0: 0);
715impl_tuple!(T0: 0, T1: 1);
716impl_tuple!(T0: 0, T1: 1, T2: 2);
717impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3);
718impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
719impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
720impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
721impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
722impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
723impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
724impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
725impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11);
726
727// ---------------------------------------------------------------------------
728// Option<T>
729// ---------------------------------------------------------------------------
730
731impl<T: Serialize> Serialize for Option<T> {
732    #[inline]
733    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
734        match self {
735            None => encoder.write_byte(0x00),
736            Some(value) => {
737                encoder.write_byte(0x01)?;
738                value.serialize(encoder)
739            }
740        }
741    }
742
743    #[inline]
744    fn encoded_len(&self) -> Result<usize> {
745        match self {
746            None => Ok(1),
747            Some(value) => Ok(value.encoded_len()?.saturating_add(1)),
748        }
749    }
750}
751
752impl<T: Deserialize> Deserialize for Option<T> {
753    #[inline]
754    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
755        match decoder.read_byte()? {
756            0x00 => Ok(None),
757            0x01 => Ok(Some(T::deserialize(decoder)?)),
758            tag => Err(SerialError::InvalidTag {
759                kind: "Option",
760                tag,
761            }),
762        }
763    }
764}
765
766// ---------------------------------------------------------------------------
767// Result<T, E>
768// ---------------------------------------------------------------------------
769
770impl<T: Serialize, E: Serialize> Serialize for core::result::Result<T, E> {
771    #[inline]
772    fn serialize<Enc: Encode + ?Sized>(&self, encoder: &mut Enc) -> Result<()> {
773        match self {
774            Ok(value) => {
775                encoder.write_byte(0x00)?;
776                value.serialize(encoder)
777            }
778            Err(err) => {
779                encoder.write_byte(0x01)?;
780                err.serialize(encoder)
781            }
782        }
783    }
784
785    #[inline]
786    fn encoded_len(&self) -> Result<usize> {
787        let inner = match self {
788            Ok(value) => value.encoded_len()?,
789            Err(err) => err.encoded_len()?,
790        };
791        Ok(inner.saturating_add(1))
792    }
793}
794
795impl<T: Deserialize, E: Deserialize> Deserialize for core::result::Result<T, E> {
796    #[inline]
797    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
798        match decoder.read_byte()? {
799            0x00 => Ok(Ok(T::deserialize(decoder)?)),
800            0x01 => Ok(Err(E::deserialize(decoder)?)),
801            tag => Err(SerialError::InvalidTag {
802                kind: "Result",
803                tag,
804            }),
805        }
806    }
807}
808
809// ---------------------------------------------------------------------------
810// Transparent wrappers: &T, Rc<T>, Arc<T>, Cow<'_, T>
811// ---------------------------------------------------------------------------
812
813impl<T: Serialize + ?Sized> Serialize for &T {
814    #[inline]
815    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
816        (**self).serialize(encoder)
817    }
818
819    #[inline]
820    fn encoded_len(&self) -> Result<usize> {
821        (**self).encoded_len()
822    }
823}
824
825impl<T: Serialize + ?Sized> Serialize for Box<T> {
826    #[inline]
827    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
828        (**self).serialize(encoder)
829    }
830
831    #[inline]
832    fn encoded_len(&self) -> Result<usize> {
833        (**self).encoded_len()
834    }
835}
836
837/// `Box<T>` encodes exactly like `T`, so a recursive type such as
838/// `struct List { next: Option<Box<List>> }` derives directly. Recursion
839/// through it is bounded by [`crate::Config::max_depth`] because the
840/// recursive type itself is derived.
841impl<T: Deserialize> Deserialize for Box<T> {
842    /// The heap block (`size_of::<T>()`) is charged against the total
843    /// budget, so `Box<Option<[u8; 4096]>>` cannot turn one input byte into
844    /// four kilobytes uncounted.
845    #[inline]
846    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
847        charge_boxed::<T, D>(decoder, 0)?;
848        T::deserialize(decoder).map(Box::new)
849    }
850}
851
852/// Transparent `Serialize` plus owned `Deserialize` for a shared-ownership
853/// pointer. `Rc<T>` / `Arc<T>` encode exactly like `T`; decoding allocates
854/// a fresh pointer (sharing is not preserved across the wire).
855macro_rules! impl_shared_pointer {
856    ($ptr:ident) => {
857        impl<T: Serialize + ?Sized> Serialize for $ptr<T> {
858            #[inline]
859            fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
860                (**self).serialize(encoder)
861            }
862
863            #[inline]
864            fn encoded_len(&self) -> Result<usize> {
865                (**self).encoded_len()
866            }
867        }
868
869        impl<T: Deserialize> Deserialize for $ptr<T> {
870            /// The heap block (`size_of::<T>()` plus the two reference
871            /// counts) is charged against the total budget.
872            #[inline]
873            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
874                charge_boxed::<T, D>(decoder, 2 * core::mem::size_of::<usize>())?;
875                T::deserialize(decoder).map($ptr::new)
876            }
877        }
878
879        impl Deserialize for $ptr<str> {
880            #[inline]
881            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
882                String::deserialize(decoder).map($ptr::from)
883            }
884        }
885
886        impl<T: Deserialize> Deserialize for $ptr<[T]> {
887            #[inline]
888            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
889                Vec::<T>::deserialize(decoder).map($ptr::from)
890            }
891        }
892    };
893}
894
895impl_shared_pointer!(Rc);
896#[cfg(target_has_atomic = "ptr")]
897impl_shared_pointer!(Arc);
898
899impl<B> Serialize for Cow<'_, B>
900where
901    B: Serialize + ToOwned + ?Sized,
902{
903    #[inline]
904    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
905        (**self).serialize(encoder)
906    }
907
908    #[inline]
909    fn encoded_len(&self) -> Result<usize> {
910        (**self).encoded_len()
911    }
912}
913
914/// Owning decode always yields [`Cow::Owned`]. To borrow from the input
915/// buffer, decode `Cow<'a, str>` / `Cow<'a, [u8]>` through
916/// [`crate::DeserializeView`] instead, which yields [`Cow::Borrowed`].
917impl<B> Deserialize for Cow<'_, B>
918where
919    B: ToOwned + ?Sized,
920    B::Owned: Deserialize,
921{
922    #[inline]
923    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
924        B::Owned::deserialize(decoder).map(Cow::Owned)
925    }
926}
927
928// ---------------------------------------------------------------------------
929// NonZero integers — same bytes as the underlying integer, zero rejected
930// ---------------------------------------------------------------------------
931
932macro_rules! impl_non_zero {
933    ($($nz:ident => $prim:ty),+ $(,)?) => {
934        $(
935            impl Serialize for $nz {
936                #[inline]
937                fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
938                    self.get().serialize(encoder)
939                }
940
941                #[inline]
942                fn encoded_len(&self) -> Result<usize> {
943                    self.get().encoded_len()
944                }
945            }
946
947            impl Deserialize for $nz {
948                #[inline]
949                fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
950                    let raw = <$prim>::deserialize(decoder)?;
951                    $nz::new(raw).ok_or(SerialError::InvalidValue { kind: stringify!($nz) })
952                }
953            }
954        )+
955    };
956}
957
958impl_non_zero!(
959    NonZeroU8 => u8,
960    NonZeroU16 => u16,
961    NonZeroU32 => u32,
962    NonZeroU64 => u64,
963    NonZeroU128 => u128,
964    NonZeroUsize => usize,
965    NonZeroI8 => i8,
966    NonZeroI16 => i16,
967    NonZeroI32 => i32,
968    NonZeroI64 => i64,
969    NonZeroI128 => i128,
970    NonZeroIsize => isize,
971);
972
973// ---------------------------------------------------------------------------
974// Duration — varint(secs) ++ varint(subsec nanos)
975// ---------------------------------------------------------------------------
976
977impl Serialize for Duration {
978    #[inline]
979    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
980        encoder.write_varint_u64(self.as_secs())?;
981        encoder.write_varint_u64(u64::from(self.subsec_nanos()))
982    }
983
984    #[inline]
985    fn encoded_len(&self) -> Result<usize> {
986        Ok(varint_len(self.as_secs()).saturating_add(varint_len(u64::from(self.subsec_nanos()))))
987    }
988}
989
990impl Deserialize for Duration {
991    #[inline]
992    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
993        const NANOS_PER_SEC: u32 = 1_000_000_000;
994        let secs = decoder.read_varint_u64()?;
995        let nanos = u32::deserialize(decoder)?;
996        if nanos >= NANOS_PER_SEC {
997            return Err(SerialError::InvalidValue { kind: "Duration" });
998        }
999        Ok(Duration::new(secs, nanos))
1000    }
1001}
1002
1003// ---------------------------------------------------------------------------
1004// Map and set collections
1005// ---------------------------------------------------------------------------
1006//
1007// Encoding contract: `varint(count) ++ sorted_entries`, where entries are
1008// sorted lexicographically by their **encoded key bytes**. This means a
1009// `HashMap` and a `BTreeMap` holding the same logical data encode to the
1010// same bytes. Hash-randomisation across runs and insertion order are both
1011// irrelevant to the output — the byte-determinism contract holds.
1012
1013/// Byte offsets of one encoded entry inside the shared scratch buffer:
1014/// the key occupies `start..key_end`, the whole entry `start..end`.
1015#[derive(Clone, Copy)]
1016struct EntrySpan {
1017    start: usize,
1018    key_end: usize,
1019    end: usize,
1020}
1021
1022/// Collects the encoded entries of a map or set so they can be written in
1023/// canonical (encoded-key-byte) order.
1024///
1025/// Every entry is encoded once into a single shared scratch buffer while
1026/// its byte span is recorded, so a whole map costs two growing allocations
1027/// (the scratch bytes and the span list) instead of one per entry. When the
1028/// entries already arrive in canonical order — the common case for a
1029/// `BTreeMap` whose `Ord` agrees with the encoded-byte order — the scratch
1030/// buffer is emitted in one write and the sort is skipped.
1031///
1032/// Ties on the key bytes (only possible for key types whose encoding is not
1033/// injective) are broken by the full entry bytes, so the output never
1034/// depends on iteration order.
1035///
1036/// Shared by the native map / set impls and the `serde` adapter, which is
1037/// how a serde map encodes to the same bytes as the native one.
1038pub(crate) struct SortedEntries {
1039    scratch: Encoder,
1040    spans: Vec<EntrySpan>,
1041    in_order: bool,
1042    start: usize,
1043    key_end: Option<usize>,
1044    /// Where the entries start in `scratch`: `0` for a private scratch
1045    /// buffer, the caller's length when encoding in place.
1046    base: usize,
1047}
1048
1049impl SortedEntries {
1050    /// Room for `count` entries (the span list is bounded by the caller's
1051    /// already-materialised collection, never by untrusted input).
1052    pub(crate) fn with_capacity(count: usize) -> Self {
1053        Self {
1054            scratch: Encoder::new(),
1055            spans: Vec::with_capacity(count),
1056            in_order: true,
1057            start: 0,
1058            key_end: None,
1059            base: 0,
1060        }
1061    }
1062
1063    /// Encode `count` entries straight into `buffer`, after its current
1064    /// contents and the count prefix: the in-memory encoder's path, which
1065    /// needs no scratch buffer and, when the entries arrive in order, no
1066    /// copy at all. Finish with [`SortedEntries::finish_in_buffer`].
1067    fn in_buffer(buffer: Vec<u8>, count: usize) -> Self {
1068        let mut scratch = Encoder::into_buffer(buffer);
1069        // Never fails on an in-memory encoder.
1070        let _ = scratch.write_varint_u64(count as u64);
1071        let base = scratch.as_bytes().len();
1072        Self {
1073            scratch,
1074            spans: Vec::with_capacity(count),
1075            in_order: true,
1076            start: base,
1077            key_end: None,
1078            base,
1079        }
1080    }
1081
1082    /// Put the entries written by [`SortedEntries::in_buffer`] in
1083    /// canonical order and hand the buffer back. Entries already in order
1084    /// stay where they are; otherwise the entry region is copied once and
1085    /// written back sorted.
1086    fn finish_in_buffer(mut self) -> Vec<u8> {
1087        let mut buffer = self.scratch.into_inner();
1088        if self.in_order {
1089            return buffer;
1090        }
1091        let region = buffer.split_off(self.base);
1092        let base = self.base;
1093        self.spans.sort_unstable_by(|a, b| {
1094            region[a.start - base..a.key_end - base]
1095                .cmp(&region[b.start - base..b.key_end - base])
1096                .then_with(|| {
1097                    region[a.start - base..a.end - base].cmp(&region[b.start - base..b.end - base])
1098                })
1099        });
1100        for span in &self.spans {
1101            buffer.extend_from_slice(&region[span.start - base..span.end - base]);
1102        }
1103        buffer
1104    }
1105
1106    /// Run `fill` over a [`SortedEntries`] that writes into `buffer` in
1107    /// place, then order the entries. On error `buffer` is restored to its
1108    /// original length, as if nothing had been written.
1109    fn encode_in_buffer<F>(buffer: &mut Vec<u8>, count: usize, fill: F) -> Result<()>
1110    where
1111        F: FnOnce(&mut Self) -> Result<()>,
1112    {
1113        let original = buffer.len();
1114        let mut sorted = Self::in_buffer(core::mem::take(buffer), count);
1115        let outcome = fill(&mut sorted);
1116        let mut out = sorted.finish_in_buffer();
1117        if outcome.is_err() {
1118            out.truncate(original);
1119        }
1120        *buffer = out;
1121        outcome
1122    }
1123
1124    /// The scratch encoder the next key / value must be written into.
1125    pub(crate) fn encoder(&mut self) -> &mut Encoder {
1126        &mut self.scratch
1127    }
1128
1129    /// Mark the start of a new entry.
1130    pub(crate) fn begin_entry(&mut self) {
1131        self.start = self.scratch.as_bytes().len();
1132        self.key_end = None;
1133    }
1134
1135    /// Mark the end of the current entry's key. Sets never call this: their
1136    /// whole entry is the key.
1137    pub(crate) fn end_key(&mut self) {
1138        self.key_end = Some(self.scratch.as_bytes().len());
1139    }
1140
1141    /// Finish the current entry.
1142    pub(crate) fn end_entry(&mut self) {
1143        let end = self.scratch.as_bytes().len();
1144        let span = EntrySpan {
1145            start: self.start,
1146            key_end: self.key_end.unwrap_or(end),
1147            end,
1148        };
1149        if let Some(prev) = self.spans.last() {
1150            let bytes = self.scratch.as_bytes();
1151            self.in_order &= bytes[prev.start..prev.key_end] < bytes[span.start..span.key_end];
1152        }
1153        self.spans.push(span);
1154    }
1155
1156    /// Write `varint(count) ++ entries in canonical order` into `encoder`.
1157    pub(crate) fn write_to<E: Encode + ?Sized>(mut self, encoder: &mut E) -> Result<()> {
1158        encoder.write_varint_u64(self.spans.len() as u64)?;
1159        let bytes = self.scratch.as_bytes();
1160        if self.in_order {
1161            return encoder.write_bytes(bytes);
1162        }
1163        self.spans.sort_unstable_by(|a, b| {
1164            bytes[a.start..a.key_end]
1165                .cmp(&bytes[b.start..b.key_end])
1166                .then_with(|| bytes[a.start..a.end].cmp(&bytes[b.start..b.end]))
1167        });
1168        for span in &self.spans {
1169            encoder.write_bytes(&bytes[span.start..span.end])?;
1170        }
1171        Ok(())
1172    }
1173}
1174
1175/// Encode `count` entries as `varint(count) ++ entries sorted by encoded
1176/// key bytes` (see [`SortedEntries`]).
1177fn encode_map_like<K, V, I, E>(count: usize, entries: I, encoder: &mut E) -> Result<()>
1178where
1179    K: Serialize,
1180    V: Serialize,
1181    I: IntoIterator<Item = (K, V)>,
1182    E: Encode + ?Sized,
1183{
1184    if count == 0 {
1185        return encoder.write_byte(0);
1186    }
1187    let fill = |sorted: &mut SortedEntries| -> Result<()> {
1188        for (k, v) in entries {
1189            sorted.begin_entry();
1190            k.serialize(sorted.encoder())?;
1191            sorted.end_key();
1192            v.serialize(sorted.encoder())?;
1193            sorted.end_entry();
1194        }
1195        Ok(())
1196    };
1197    if let Some(buffer) = encoder.in_memory_buffer() {
1198        return SortedEntries::encode_in_buffer(buffer, count, fill);
1199    }
1200    let mut sorted = SortedEntries::with_capacity(count);
1201    fill(&mut sorted)?;
1202    sorted.write_to(encoder)
1203}
1204
1205/// Encode `count` set elements as `varint(count) ++ sorted_elements`.
1206fn encode_set_like<T, I, E>(count: usize, items: I, encoder: &mut E) -> Result<()>
1207where
1208    T: Serialize,
1209    I: IntoIterator<Item = T>,
1210    E: Encode + ?Sized,
1211{
1212    if count == 0 {
1213        return encoder.write_byte(0);
1214    }
1215    let fill = |sorted: &mut SortedEntries| -> Result<()> {
1216        for item in items {
1217            sorted.begin_entry();
1218            item.serialize(sorted.encoder())?;
1219            sorted.end_entry();
1220        }
1221        Ok(())
1222    };
1223    if let Some(buffer) = encoder.in_memory_buffer() {
1224        return SortedEntries::encode_in_buffer(buffer, count, fill);
1225    }
1226    let mut sorted = SortedEntries::with_capacity(count);
1227    fill(&mut sorted)?;
1228    sorted.write_to(encoder)
1229}
1230
1231/// `encoded_len` of a map: the count prefix plus every entry. Order does
1232/// not change the length, so no sorting (and no allocation) is needed.
1233fn map_encoded_len<'a, K, V, I>(count: usize, entries: I) -> Result<usize>
1234where
1235    K: Serialize + 'a,
1236    V: Serialize + 'a,
1237    I: IntoIterator<Item = (&'a K, &'a V)>,
1238{
1239    entries
1240        .into_iter()
1241        .try_fold(varint_len(count as u64), |acc, (k, v)| {
1242            Ok(acc
1243                .saturating_add(k.encoded_len()?)
1244                .saturating_add(v.encoded_len()?))
1245        })
1246}
1247
1248/// `encoded_len` of a set: the count prefix plus every element.
1249fn set_encoded_len<'a, T, I>(count: usize, items: I) -> Result<usize>
1250where
1251    T: Serialize + 'a,
1252    I: IntoIterator<Item = &'a T>,
1253{
1254    items
1255        .into_iter()
1256        .try_fold(varint_len(count as u64), |acc, item| {
1257            Ok(acc.saturating_add(item.encoded_len()?))
1258        })
1259}
1260
1261/// Tracks the byte span of the previous key while a map or set decodes in
1262/// canonical mode, and rejects any key that does not sort strictly after
1263/// it.
1264///
1265/// The spans are offsets into [`Decode::consumed`], which only grows during
1266/// a decode, so the previous key's bytes stay addressable without copying.
1267pub(crate) struct KeyOrder {
1268    reason: &'static str,
1269    prev: Option<(usize, usize)>,
1270}
1271
1272impl KeyOrder {
1273    /// Start tracking; `reason` is reported in
1274    /// [`SerialError::NonCanonical`] (`"map key order"` / `"set element
1275    /// order"`).
1276    pub(crate) fn new(reason: &'static str) -> Self {
1277        Self { reason, prev: None }
1278    }
1279
1280    /// Offset at which the next key starts.
1281    ///
1282    /// # Errors
1283    ///
1284    /// [`SerialError::InvalidConfig`] if the decoder cannot expose its
1285    /// consumed input, so canonical order cannot be checked.
1286    pub(crate) fn mark<D: Decode + ?Sized>(&self, decoder: &D) -> Result<usize> {
1287        decoder
1288            .consumed()
1289            .map(<[u8]>::len)
1290            .ok_or(SerialError::InvalidConfig {
1291                reason: "canonical mode needs a decoder that exposes its consumed input",
1292            })
1293    }
1294
1295    /// Check the key that started at `start` and has just been decoded.
1296    ///
1297    /// # Errors
1298    ///
1299    /// [`SerialError::NonCanonical`] if the key is not strictly greater
1300    /// than the previous one.
1301    pub(crate) fn check<D: Decode + ?Sized>(&mut self, decoder: &D, start: usize) -> Result<()> {
1302        let consumed = decoder.consumed().unwrap_or_default();
1303        let end = consumed.len();
1304        if let Some((prev_start, prev_end)) = self.prev {
1305            let prev = consumed.get(prev_start..prev_end).unwrap_or_default();
1306            let current = consumed.get(start..end).unwrap_or_default();
1307            if current <= prev {
1308                return Err(SerialError::NonCanonical {
1309                    reason: self.reason,
1310                });
1311            }
1312        }
1313        self.prev = Some((start, end));
1314        Ok(())
1315    }
1316}
1317
1318/// Decode `len` `(K, V)` entries, handing each to `insert`. In canonical
1319/// mode the encoded keys must be strictly increasing. Entries that consume
1320/// no input are charged against the total budget (see
1321/// [`decode_elements_counted`]).
1322fn decode_entries<K, V, D, F>(decoder: &mut D, len: usize, mut insert: F) -> Result<()>
1323where
1324    K: Deserialize,
1325    V: Deserialize,
1326    D: Decode + ?Sized,
1327    F: FnMut(K, V),
1328{
1329    if decoder.config().canonical {
1330        let mut order = KeyOrder::new("map key order");
1331        decode_elements_counted::<(K, V), D, _>(decoder, len, |decoder| {
1332            let start = order.mark(decoder)?;
1333            let k = K::deserialize(decoder)?;
1334            order.check(decoder, start)?;
1335            let v = V::deserialize(decoder)?;
1336            insert(k, v);
1337            Ok(())
1338        })
1339    } else {
1340        decode_elements_counted::<(K, V), D, _>(decoder, len, |decoder| {
1341            let k = K::deserialize(decoder)?;
1342            let v = V::deserialize(decoder)?;
1343            insert(k, v);
1344            Ok(())
1345        })
1346    }
1347}
1348
1349/// Decode `len` set elements, handing each to `insert`. In canonical mode
1350/// the encoded elements must be strictly increasing. Elements that consume
1351/// no input are charged against the total budget.
1352fn decode_elements<T, D, F>(decoder: &mut D, len: usize, mut insert: F) -> Result<()>
1353where
1354    T: Deserialize,
1355    D: Decode + ?Sized,
1356    F: FnMut(T),
1357{
1358    if decoder.config().canonical {
1359        let mut order = KeyOrder::new("set element order");
1360        decode_elements_counted::<T, D, _>(decoder, len, |decoder| {
1361            let start = order.mark(decoder)?;
1362            let item = T::deserialize(decoder)?;
1363            order.check(decoder, start)?;
1364            insert(item);
1365            Ok(())
1366        })
1367    } else {
1368        decode_elements_counted::<T, D, _>(decoder, len, |decoder| {
1369            insert(T::deserialize(decoder)?);
1370            Ok(())
1371        })
1372    }
1373}
1374
1375impl<K, V> Serialize for BTreeMap<K, V>
1376where
1377    K: Serialize,
1378    V: Serialize,
1379{
1380    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1381        encode_map_like(self.len(), self.iter(), encoder)
1382    }
1383
1384    fn encoded_len(&self) -> Result<usize> {
1385        map_encoded_len(self.len(), self.iter())
1386    }
1387}
1388
1389impl<K, V> Deserialize for BTreeMap<K, V>
1390where
1391    K: Deserialize + Ord,
1392    V: Deserialize,
1393{
1394    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1395        let declared = decoder.read_varint_u64()?;
1396        let len = guard_element_count(declared, decoder)?;
1397        charge_elements::<(K, V), D>(decoder, len)?;
1398        let mut out = BTreeMap::new();
1399        decode_entries(decoder, len, |k, v| {
1400            let _ = out.insert(k, v);
1401        })?;
1402        Ok(out)
1403    }
1404}
1405
1406impl<T> Serialize for BTreeSet<T>
1407where
1408    T: Serialize,
1409{
1410    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1411        encode_set_like(self.len(), self.iter(), encoder)
1412    }
1413
1414    fn encoded_len(&self) -> Result<usize> {
1415        set_encoded_len(self.len(), self.iter())
1416    }
1417}
1418
1419impl<T> Deserialize for BTreeSet<T>
1420where
1421    T: Deserialize + Ord,
1422{
1423    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1424        let declared = decoder.read_varint_u64()?;
1425        let len = guard_element_count(declared, decoder)?;
1426        charge_elements::<T, D>(decoder, len)?;
1427        let mut out = BTreeSet::new();
1428        decode_elements(decoder, len, |item| {
1429            let _ = out.insert(item);
1430        })?;
1431        Ok(out)
1432    }
1433}
1434
1435#[cfg(feature = "std")]
1436impl<K, V, S> Serialize for HashMap<K, V, S>
1437where
1438    K: Serialize,
1439    V: Serialize,
1440{
1441    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1442        encode_map_like(self.len(), self.iter(), encoder)
1443    }
1444
1445    fn encoded_len(&self) -> Result<usize> {
1446        map_encoded_len(self.len(), self.iter())
1447    }
1448}
1449
1450#[cfg(feature = "std")]
1451impl<K, V, S> Deserialize for HashMap<K, V, S>
1452where
1453    K: Deserialize + Hash + Eq,
1454    V: Deserialize,
1455    S: BuildHasher + Default,
1456{
1457    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1458        let declared = decoder.read_varint_u64()?;
1459        let len = guard_element_count(declared, decoder)?;
1460        charge_elements::<(K, V), D>(decoder, len)?;
1461        let capacity = initial_capacity::<(K, V), D>(len, decoder);
1462        let mut out = HashMap::with_capacity_and_hasher(capacity, S::default());
1463        decode_entries(decoder, len, |k, v| {
1464            let _ = out.insert(k, v);
1465        })?;
1466        Ok(out)
1467    }
1468}
1469
1470#[cfg(feature = "std")]
1471impl<T, S> Serialize for HashSet<T, S>
1472where
1473    T: Serialize,
1474{
1475    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1476        encode_set_like(self.len(), self.iter(), encoder)
1477    }
1478
1479    fn encoded_len(&self) -> Result<usize> {
1480        set_encoded_len(self.len(), self.iter())
1481    }
1482}
1483
1484#[cfg(feature = "std")]
1485impl<T, S> Deserialize for HashSet<T, S>
1486where
1487    T: Deserialize + Hash + Eq,
1488    S: BuildHasher + Default,
1489{
1490    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1491        let declared = decoder.read_varint_u64()?;
1492        let len = guard_element_count(declared, decoder)?;
1493        charge_elements::<T, D>(decoder, len)?;
1494        let capacity = initial_capacity::<T, D>(len, decoder);
1495        let mut out = HashSet::with_capacity_and_hasher(capacity, S::default());
1496        decode_elements(decoder, len, |item| {
1497            let _ = out.insert(item);
1498        })?;
1499        Ok(out)
1500    }
1501}
1502
1503#[cfg(test)]
1504mod tests {
1505    use super::*;
1506    use crate::{decode, encode};
1507    use alloc::vec;
1508
1509    fn round_trip<T>(value: T)
1510    where
1511        T: Serialize + Deserialize + PartialEq + core::fmt::Debug,
1512    {
1513        let bytes = encode(&value).expect("encode");
1514        let back: T = decode(&bytes).expect("decode");
1515        assert_eq!(back, value);
1516    }
1517
1518    #[test]
1519    fn u8_round_trips() {
1520        for v in [0u8, 1, 127, 128, 255] {
1521            round_trip(v);
1522        }
1523    }
1524
1525    #[test]
1526    fn u64_round_trips() {
1527        for v in [0u64, 1, u32::MAX as u64, u64::MAX] {
1528            round_trip(v);
1529        }
1530    }
1531
1532    #[test]
1533    fn i64_round_trips() {
1534        for v in [0i64, -1, 1, i64::MIN, i64::MAX] {
1535            round_trip(v);
1536        }
1537    }
1538
1539    #[test]
1540    fn bool_round_trips() {
1541        round_trip(true);
1542        round_trip(false);
1543    }
1544
1545    #[test]
1546    fn string_round_trips() {
1547        for s in ["", "hello", "a longer string with some content"] {
1548            round_trip(String::from(s));
1549        }
1550    }
1551
1552    #[test]
1553    fn vec_u8_round_trips() {
1554        round_trip::<Vec<u8>>(vec![]);
1555        round_trip::<Vec<u8>>(vec![0u8, 1, 2, 3]);
1556        round_trip::<Vec<u8>>(vec![0xffu8; 1024]);
1557    }
1558
1559    #[test]
1560    fn vec_u32_round_trips() {
1561        round_trip::<Vec<u32>>(vec![]);
1562        round_trip::<Vec<u32>>(vec![1, 2, u32::MAX]);
1563    }
1564
1565    #[test]
1566    fn vec_string_round_trips() {
1567        round_trip(vec![
1568            String::from("hello"),
1569            String::from("world"),
1570            String::new(),
1571        ]);
1572    }
1573
1574    #[test]
1575    fn array_round_trips() {
1576        round_trip([1u32, 2, 3, 4]);
1577        round_trip([0u8; 0]);
1578    }
1579
1580    #[test]
1581    fn tuple_round_trips() {
1582        round_trip((1u8, 2u16, 3u32));
1583        round_trip((String::from("a"), 42u64, -3i32));
1584    }
1585
1586    #[test]
1587    fn option_round_trips() {
1588        round_trip::<Option<u64>>(None);
1589        round_trip::<Option<u64>>(Some(42));
1590        round_trip::<Option<String>>(Some(String::from("hi")));
1591    }
1592
1593    #[test]
1594    fn result_round_trips() {
1595        round_trip::<core::result::Result<u64, String>>(Ok(7));
1596        round_trip::<core::result::Result<u64, String>>(Err(String::from("nope")));
1597    }
1598
1599    #[test]
1600    fn invalid_bool_byte_is_rejected() {
1601        let err = decode::<bool>(&[0x7f]).expect_err("0x7f is not a bool");
1602        assert!(matches!(err, SerialError::InvalidBool { byte: 0x7f }));
1603    }
1604
1605    #[test]
1606    fn string_with_invalid_utf8_is_rejected() {
1607        let bytes = [0x02, 0xff, 0xff];
1608        let err = decode::<String>(&bytes).expect_err("invalid UTF-8 should fail");
1609        assert!(matches!(err, SerialError::InvalidUtf8));
1610    }
1611
1612    #[test]
1613    fn option_invalid_tag_is_rejected() {
1614        let err = decode::<Option<u8>>(&[0x02]).expect_err("0x02 is not a valid Option tag");
1615        assert!(matches!(
1616            err,
1617            SerialError::InvalidTag {
1618                kind: "Option",
1619                tag: 0x02
1620            }
1621        ));
1622    }
1623
1624    #[test]
1625    fn result_invalid_tag_is_rejected() {
1626        let err =
1627            decode::<core::result::Result<u8, u8>>(&[0x02]).expect_err("0x02 is not a Result tag");
1628        assert!(matches!(
1629            err,
1630            SerialError::InvalidTag {
1631                kind: "Result",
1632                tag: 0x02
1633            }
1634        ));
1635    }
1636
1637    #[test]
1638    fn f64_round_trips_including_inf() {
1639        for v in [
1640            0.0f64,
1641            -0.0,
1642            1.0,
1643            -1.0,
1644            f64::MIN,
1645            f64::MAX,
1646            f64::INFINITY,
1647            f64::NEG_INFINITY,
1648        ] {
1649            let bytes = encode(&v).unwrap();
1650            let back: f64 = decode(&bytes).unwrap();
1651            assert_eq!(back.to_bits(), v.to_bits());
1652        }
1653    }
1654
1655    #[test]
1656    fn f64_nan_round_trips_bit_for_bit() {
1657        let v = f64::NAN;
1658        let bytes = encode(&v).unwrap();
1659        let back: f64 = decode(&bytes).unwrap();
1660        assert_eq!(back.to_bits(), v.to_bits());
1661        assert!(back.is_nan());
1662    }
1663
1664    #[test]
1665    fn btreemap_round_trips() {
1666        let mut m = BTreeMap::new();
1667        let _ = m.insert(String::from("a"), 1u32);
1668        let _ = m.insert(String::from("b"), 2);
1669        let _ = m.insert(String::from("c"), 3);
1670        round_trip(m);
1671    }
1672
1673    #[test]
1674    fn btreemap_empty_round_trips() {
1675        round_trip(BTreeMap::<u32, u32>::new());
1676    }
1677
1678    #[test]
1679    fn btreeset_round_trips() {
1680        let mut s = BTreeSet::new();
1681        let _ = s.insert(1u32);
1682        let _ = s.insert(2);
1683        let _ = s.insert(3);
1684        round_trip(s);
1685    }
1686
1687    #[cfg(feature = "std")]
1688    #[test]
1689    fn hashmap_round_trips() {
1690        let mut m: HashMap<String, u32> = HashMap::new();
1691        let _ = m.insert(String::from("alpha"), 1);
1692        let _ = m.insert(String::from("beta"), 2);
1693        round_trip(m);
1694    }
1695
1696    #[cfg(feature = "std")]
1697    #[test]
1698    fn hashset_round_trips() {
1699        let mut s: HashSet<u32> = HashSet::new();
1700        let _ = s.insert(1);
1701        let _ = s.insert(7);
1702        let _ = s.insert(42);
1703        round_trip(s);
1704    }
1705
1706    #[cfg(feature = "std")]
1707    #[test]
1708    fn hashmap_and_btreemap_encode_identically_for_same_data() {
1709        let mut h: HashMap<String, u32> = HashMap::new();
1710        let mut b: BTreeMap<String, u32> = BTreeMap::new();
1711        for (k, v) in [("zeta", 5u32), ("alpha", 1), ("delta", 4), ("beta", 2)] {
1712            let _ = h.insert(k.into(), v);
1713            let _ = b.insert(k.into(), v);
1714        }
1715        assert_eq!(encode(&h).unwrap(), encode(&b).unwrap());
1716    }
1717
1718    #[cfg(feature = "std")]
1719    #[test]
1720    fn hashmap_insertion_order_independent() {
1721        let mut a: HashMap<u32, u32> = HashMap::new();
1722        let _ = a.insert(1, 10);
1723        let _ = a.insert(2, 20);
1724        let _ = a.insert(3, 30);
1725
1726        let mut b: HashMap<u32, u32> = HashMap::new();
1727        let _ = b.insert(3, 30);
1728        let _ = b.insert(1, 10);
1729        let _ = b.insert(2, 20);
1730
1731        assert_eq!(encode(&a).unwrap(), encode(&b).unwrap());
1732    }
1733
1734    #[test]
1735    fn collection_with_hostile_element_count_is_rejected() {
1736        // varint(u64::MAX) is 10 bytes of 0xff... 0x01.
1737        let bytes: [u8; 10] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01];
1738        let err = decode::<Vec<u32>>(&bytes).expect_err("hostile count");
1739        assert!(matches!(err, SerialError::InvalidLength { .. }));
1740    }
1741}