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::initial_capacity;
61use crate::codec::read_varint_u64_with;
62use crate::codec::{
63    Decode, Encode, Encoder, decode_elements_counted, guard_element_count, varint_len,
64};
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        // Dispatch to T's `deserialize_many` so byte-vec payloads
581        // (T = u8) take the memcpy fast path via the `u8` override.
582        T::deserialize_many(decoder, len)
583    }
584}
585
586impl<T: Deserialize> Deserialize for Box<[T]> {
587    #[inline]
588    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
589        Vec::<T>::deserialize(decoder).map(Vec::into_boxed_slice)
590    }
591}
592
593impl<T: Serialize> Serialize for VecDeque<T> {
594    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
595        encoder.write_varint_u64(self.len() as u64)?;
596        let (front, back) = self.as_slices();
597        T::serialize_slice(front, encoder)?;
598        T::serialize_slice(back, encoder)
599    }
600
601    fn encoded_len(&self) -> Result<usize> {
602        let (front, back) = self.as_slices();
603        Ok(varint_len(self.len() as u64)
604            .saturating_add(T::encoded_len_slice(front)?)
605            .saturating_add(T::encoded_len_slice(back)?))
606    }
607}
608
609impl<T: Deserialize> Deserialize for VecDeque<T> {
610    #[inline]
611    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
612        Vec::<T>::deserialize(decoder).map(VecDeque::from)
613    }
614}
615
616// ---------------------------------------------------------------------------
617// Fixed-size arrays — [T; N]
618// ---------------------------------------------------------------------------
619
620impl<T: Serialize, const N: usize> Serialize for [T; N] {
621    /// Routed through `T::serialize_slice`, so `[u8; N]` is one bulk write.
622    #[inline]
623    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
624        T::serialize_slice(self, encoder)
625    }
626
627    #[inline]
628    fn encoded_len(&self) -> Result<usize> {
629        T::encoded_len_slice(self)
630    }
631}
632
633impl<T: Deserialize, const N: usize> Deserialize for [T; N] {
634    /// Routed through `T::deserialize_array`, so `[u8; N]` is one read into
635    /// a stack array.
636    #[inline]
637    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
638        T::deserialize_array::<D, N>(decoder)
639    }
640}
641
642// ---------------------------------------------------------------------------
643// Tuples — arity 0..=12, PhantomData
644// ---------------------------------------------------------------------------
645
646impl Serialize for () {
647    #[inline]
648    fn serialize<E: Encode + ?Sized>(&self, _encoder: &mut E) -> Result<()> {
649        Ok(())
650    }
651
652    #[inline]
653    fn encoded_len(&self) -> Result<usize> {
654        Ok(0)
655    }
656}
657
658impl Deserialize for () {
659    #[inline]
660    fn deserialize<D: Decode + ?Sized>(_decoder: &mut D) -> Result<Self> {
661        Ok(())
662    }
663}
664
665impl<T: ?Sized> Serialize for PhantomData<T> {
666    #[inline]
667    fn serialize<E: Encode + ?Sized>(&self, _encoder: &mut E) -> Result<()> {
668        Ok(())
669    }
670
671    #[inline]
672    fn encoded_len(&self) -> Result<usize> {
673        Ok(0)
674    }
675}
676
677impl<T: ?Sized> Deserialize for PhantomData<T> {
678    #[inline]
679    fn deserialize<D: Decode + ?Sized>(_decoder: &mut D) -> Result<Self> {
680        Ok(PhantomData)
681    }
682}
683
684macro_rules! impl_tuple {
685    ($($name:ident: $idx:tt),+) => {
686        impl<$($name: Serialize),+> Serialize for ($($name,)+) {
687            #[inline]
688            fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
689                $( self.$idx.serialize(encoder)?; )+
690                Ok(())
691            }
692
693            #[inline]
694            fn encoded_len(&self) -> Result<usize> {
695                let mut total = 0usize;
696                $( total = total.saturating_add(self.$idx.encoded_len()?); )+
697                Ok(total)
698            }
699        }
700
701        impl<$($name: Deserialize),+> Deserialize for ($($name,)+) {
702            #[inline]
703            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
704                Ok(( $( $name::deserialize(decoder)?, )+ ))
705            }
706        }
707    };
708}
709
710impl_tuple!(T0: 0);
711impl_tuple!(T0: 0, T1: 1);
712impl_tuple!(T0: 0, T1: 1, T2: 2);
713impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3);
714impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
715impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
716impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
717impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
718impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
719impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
720impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
721impl_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);
722
723// ---------------------------------------------------------------------------
724// Option<T>
725// ---------------------------------------------------------------------------
726
727impl<T: Serialize> Serialize for Option<T> {
728    #[inline]
729    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
730        match self {
731            None => encoder.write_byte(0x00),
732            Some(value) => {
733                encoder.write_byte(0x01)?;
734                value.serialize(encoder)
735            }
736        }
737    }
738
739    #[inline]
740    fn encoded_len(&self) -> Result<usize> {
741        match self {
742            None => Ok(1),
743            Some(value) => Ok(value.encoded_len()?.saturating_add(1)),
744        }
745    }
746}
747
748impl<T: Deserialize> Deserialize for Option<T> {
749    #[inline]
750    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
751        match decoder.read_byte()? {
752            0x00 => Ok(None),
753            0x01 => Ok(Some(T::deserialize(decoder)?)),
754            tag => Err(SerialError::InvalidTag {
755                kind: "Option",
756                tag,
757            }),
758        }
759    }
760}
761
762// ---------------------------------------------------------------------------
763// Result<T, E>
764// ---------------------------------------------------------------------------
765
766impl<T: Serialize, E: Serialize> Serialize for core::result::Result<T, E> {
767    #[inline]
768    fn serialize<Enc: Encode + ?Sized>(&self, encoder: &mut Enc) -> Result<()> {
769        match self {
770            Ok(value) => {
771                encoder.write_byte(0x00)?;
772                value.serialize(encoder)
773            }
774            Err(err) => {
775                encoder.write_byte(0x01)?;
776                err.serialize(encoder)
777            }
778        }
779    }
780
781    #[inline]
782    fn encoded_len(&self) -> Result<usize> {
783        let inner = match self {
784            Ok(value) => value.encoded_len()?,
785            Err(err) => err.encoded_len()?,
786        };
787        Ok(inner.saturating_add(1))
788    }
789}
790
791impl<T: Deserialize, E: Deserialize> Deserialize for core::result::Result<T, E> {
792    #[inline]
793    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
794        match decoder.read_byte()? {
795            0x00 => Ok(Ok(T::deserialize(decoder)?)),
796            0x01 => Ok(Err(E::deserialize(decoder)?)),
797            tag => Err(SerialError::InvalidTag {
798                kind: "Result",
799                tag,
800            }),
801        }
802    }
803}
804
805// ---------------------------------------------------------------------------
806// Transparent wrappers: &T, Rc<T>, Arc<T>, Cow<'_, T>
807// ---------------------------------------------------------------------------
808
809impl<T: Serialize + ?Sized> Serialize for &T {
810    #[inline]
811    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
812        (**self).serialize(encoder)
813    }
814
815    #[inline]
816    fn encoded_len(&self) -> Result<usize> {
817        (**self).encoded_len()
818    }
819}
820
821impl<T: Serialize + ?Sized> Serialize for Box<T> {
822    #[inline]
823    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
824        (**self).serialize(encoder)
825    }
826
827    #[inline]
828    fn encoded_len(&self) -> Result<usize> {
829        (**self).encoded_len()
830    }
831}
832
833/// `Box<T>` encodes exactly like `T`, so a recursive type such as
834/// `struct List { next: Option<Box<List>> }` derives directly. Recursion
835/// through it is bounded by [`crate::Config::max_depth`] because the
836/// recursive type itself is derived.
837impl<T: Deserialize> Deserialize for Box<T> {
838    #[inline]
839    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
840        T::deserialize(decoder).map(Box::new)
841    }
842}
843
844/// Transparent `Serialize` plus owned `Deserialize` for a shared-ownership
845/// pointer. `Rc<T>` / `Arc<T>` encode exactly like `T`; decoding allocates
846/// a fresh pointer (sharing is not preserved across the wire).
847macro_rules! impl_shared_pointer {
848    ($ptr:ident) => {
849        impl<T: Serialize + ?Sized> Serialize for $ptr<T> {
850            #[inline]
851            fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
852                (**self).serialize(encoder)
853            }
854
855            #[inline]
856            fn encoded_len(&self) -> Result<usize> {
857                (**self).encoded_len()
858            }
859        }
860
861        impl<T: Deserialize> Deserialize for $ptr<T> {
862            #[inline]
863            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
864                T::deserialize(decoder).map($ptr::new)
865            }
866        }
867
868        impl Deserialize for $ptr<str> {
869            #[inline]
870            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
871                String::deserialize(decoder).map($ptr::from)
872            }
873        }
874
875        impl<T: Deserialize> Deserialize for $ptr<[T]> {
876            #[inline]
877            fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
878                Vec::<T>::deserialize(decoder).map($ptr::from)
879            }
880        }
881    };
882}
883
884impl_shared_pointer!(Rc);
885#[cfg(target_has_atomic = "ptr")]
886impl_shared_pointer!(Arc);
887
888impl<B> Serialize for Cow<'_, B>
889where
890    B: Serialize + ToOwned + ?Sized,
891{
892    #[inline]
893    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
894        (**self).serialize(encoder)
895    }
896
897    #[inline]
898    fn encoded_len(&self) -> Result<usize> {
899        (**self).encoded_len()
900    }
901}
902
903/// Owning decode always yields [`Cow::Owned`]. To borrow from the input
904/// buffer, decode `Cow<'a, str>` / `Cow<'a, [u8]>` through
905/// [`crate::DeserializeView`] instead, which yields [`Cow::Borrowed`].
906impl<B> Deserialize for Cow<'_, B>
907where
908    B: ToOwned + ?Sized,
909    B::Owned: Deserialize,
910{
911    #[inline]
912    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
913        B::Owned::deserialize(decoder).map(Cow::Owned)
914    }
915}
916
917// ---------------------------------------------------------------------------
918// NonZero integers — same bytes as the underlying integer, zero rejected
919// ---------------------------------------------------------------------------
920
921macro_rules! impl_non_zero {
922    ($($nz:ident => $prim:ty),+ $(,)?) => {
923        $(
924            impl Serialize for $nz {
925                #[inline]
926                fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
927                    self.get().serialize(encoder)
928                }
929
930                #[inline]
931                fn encoded_len(&self) -> Result<usize> {
932                    self.get().encoded_len()
933                }
934            }
935
936            impl Deserialize for $nz {
937                #[inline]
938                fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
939                    let raw = <$prim>::deserialize(decoder)?;
940                    $nz::new(raw).ok_or(SerialError::InvalidValue { kind: stringify!($nz) })
941                }
942            }
943        )+
944    };
945}
946
947impl_non_zero!(
948    NonZeroU8 => u8,
949    NonZeroU16 => u16,
950    NonZeroU32 => u32,
951    NonZeroU64 => u64,
952    NonZeroU128 => u128,
953    NonZeroUsize => usize,
954    NonZeroI8 => i8,
955    NonZeroI16 => i16,
956    NonZeroI32 => i32,
957    NonZeroI64 => i64,
958    NonZeroI128 => i128,
959    NonZeroIsize => isize,
960);
961
962// ---------------------------------------------------------------------------
963// Duration — varint(secs) ++ varint(subsec nanos)
964// ---------------------------------------------------------------------------
965
966impl Serialize for Duration {
967    #[inline]
968    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
969        encoder.write_varint_u64(self.as_secs())?;
970        encoder.write_varint_u64(u64::from(self.subsec_nanos()))
971    }
972
973    #[inline]
974    fn encoded_len(&self) -> Result<usize> {
975        Ok(varint_len(self.as_secs()).saturating_add(varint_len(u64::from(self.subsec_nanos()))))
976    }
977}
978
979impl Deserialize for Duration {
980    #[inline]
981    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
982        const NANOS_PER_SEC: u32 = 1_000_000_000;
983        let secs = decoder.read_varint_u64()?;
984        let nanos = u32::deserialize(decoder)?;
985        if nanos >= NANOS_PER_SEC {
986            return Err(SerialError::InvalidValue { kind: "Duration" });
987        }
988        Ok(Duration::new(secs, nanos))
989    }
990}
991
992// ---------------------------------------------------------------------------
993// Map and set collections
994// ---------------------------------------------------------------------------
995//
996// Encoding contract: `varint(count) ++ sorted_entries`, where entries are
997// sorted lexicographically by their **encoded key bytes**. This means a
998// `HashMap` and a `BTreeMap` holding the same logical data encode to the
999// same bytes. Hash-randomisation across runs and insertion order are both
1000// irrelevant to the output — the byte-determinism contract holds.
1001
1002/// Byte offsets of one encoded entry inside the shared scratch buffer:
1003/// the key occupies `start..key_end`, the whole entry `start..end`.
1004#[derive(Clone, Copy)]
1005struct EntrySpan {
1006    start: usize,
1007    key_end: usize,
1008    end: usize,
1009}
1010
1011/// Collects the encoded entries of a map or set so they can be written in
1012/// canonical (encoded-key-byte) order.
1013///
1014/// Every entry is encoded once into a single shared scratch buffer while
1015/// its byte span is recorded, so a whole map costs two growing allocations
1016/// (the scratch bytes and the span list) instead of one per entry. When the
1017/// entries already arrive in canonical order — the common case for a
1018/// `BTreeMap` whose `Ord` agrees with the encoded-byte order — the scratch
1019/// buffer is emitted in one write and the sort is skipped.
1020///
1021/// Ties on the key bytes (only possible for key types whose encoding is not
1022/// injective) are broken by the full entry bytes, so the output never
1023/// depends on iteration order.
1024///
1025/// Shared by the native map / set impls and the `serde` adapter, which is
1026/// how a serde map encodes to the same bytes as the native one.
1027pub(crate) struct SortedEntries {
1028    scratch: Encoder,
1029    spans: Vec<EntrySpan>,
1030    in_order: bool,
1031    start: usize,
1032    key_end: Option<usize>,
1033}
1034
1035impl SortedEntries {
1036    /// Room for `count` entries (the span list is bounded by the caller's
1037    /// already-materialised collection, never by untrusted input).
1038    pub(crate) fn with_capacity(count: usize) -> Self {
1039        Self {
1040            scratch: Encoder::new(),
1041            spans: Vec::with_capacity(count),
1042            in_order: true,
1043            start: 0,
1044            key_end: None,
1045        }
1046    }
1047
1048    /// The scratch encoder the next key / value must be written into.
1049    pub(crate) fn encoder(&mut self) -> &mut Encoder {
1050        &mut self.scratch
1051    }
1052
1053    /// Mark the start of a new entry.
1054    pub(crate) fn begin_entry(&mut self) {
1055        self.start = self.scratch.as_bytes().len();
1056        self.key_end = None;
1057    }
1058
1059    /// Mark the end of the current entry's key. Sets never call this: their
1060    /// whole entry is the key.
1061    pub(crate) fn end_key(&mut self) {
1062        self.key_end = Some(self.scratch.as_bytes().len());
1063    }
1064
1065    /// Finish the current entry.
1066    pub(crate) fn end_entry(&mut self) {
1067        let end = self.scratch.as_bytes().len();
1068        let span = EntrySpan {
1069            start: self.start,
1070            key_end: self.key_end.unwrap_or(end),
1071            end,
1072        };
1073        if let Some(prev) = self.spans.last() {
1074            let bytes = self.scratch.as_bytes();
1075            self.in_order &= bytes[prev.start..prev.key_end] < bytes[span.start..span.key_end];
1076        }
1077        self.spans.push(span);
1078    }
1079
1080    /// Write `varint(count) ++ entries in canonical order` into `encoder`.
1081    pub(crate) fn write_to<E: Encode + ?Sized>(mut self, encoder: &mut E) -> Result<()> {
1082        encoder.write_varint_u64(self.spans.len() as u64)?;
1083        let bytes = self.scratch.as_bytes();
1084        if self.in_order {
1085            return encoder.write_bytes(bytes);
1086        }
1087        self.spans.sort_unstable_by(|a, b| {
1088            bytes[a.start..a.key_end]
1089                .cmp(&bytes[b.start..b.key_end])
1090                .then_with(|| bytes[a.start..a.end].cmp(&bytes[b.start..b.end]))
1091        });
1092        for span in &self.spans {
1093            encoder.write_bytes(&bytes[span.start..span.end])?;
1094        }
1095        Ok(())
1096    }
1097}
1098
1099/// Encode `count` entries as `varint(count) ++ entries sorted by encoded
1100/// key bytes` (see [`SortedEntries`]).
1101fn encode_map_like<K, V, I, E>(count: usize, entries: I, encoder: &mut E) -> Result<()>
1102where
1103    K: Serialize,
1104    V: Serialize,
1105    I: IntoIterator<Item = (K, V)>,
1106    E: Encode + ?Sized,
1107{
1108    if count == 0 {
1109        return encoder.write_byte(0);
1110    }
1111    let mut sorted = SortedEntries::with_capacity(count);
1112    for (k, v) in entries {
1113        sorted.begin_entry();
1114        k.serialize(sorted.encoder())?;
1115        sorted.end_key();
1116        v.serialize(sorted.encoder())?;
1117        sorted.end_entry();
1118    }
1119    sorted.write_to(encoder)
1120}
1121
1122/// Encode `count` set elements as `varint(count) ++ sorted_elements`.
1123fn encode_set_like<T, I, E>(count: usize, items: I, encoder: &mut E) -> Result<()>
1124where
1125    T: Serialize,
1126    I: IntoIterator<Item = T>,
1127    E: Encode + ?Sized,
1128{
1129    if count == 0 {
1130        return encoder.write_byte(0);
1131    }
1132    let mut sorted = SortedEntries::with_capacity(count);
1133    for item in items {
1134        sorted.begin_entry();
1135        item.serialize(sorted.encoder())?;
1136        sorted.end_entry();
1137    }
1138    sorted.write_to(encoder)
1139}
1140
1141/// `encoded_len` of a map: the count prefix plus every entry. Order does
1142/// not change the length, so no sorting (and no allocation) is needed.
1143fn map_encoded_len<'a, K, V, I>(count: usize, entries: I) -> Result<usize>
1144where
1145    K: Serialize + 'a,
1146    V: Serialize + 'a,
1147    I: IntoIterator<Item = (&'a K, &'a V)>,
1148{
1149    entries
1150        .into_iter()
1151        .try_fold(varint_len(count as u64), |acc, (k, v)| {
1152            Ok(acc
1153                .saturating_add(k.encoded_len()?)
1154                .saturating_add(v.encoded_len()?))
1155        })
1156}
1157
1158/// `encoded_len` of a set: the count prefix plus every element.
1159fn set_encoded_len<'a, T, I>(count: usize, items: I) -> Result<usize>
1160where
1161    T: Serialize + 'a,
1162    I: IntoIterator<Item = &'a T>,
1163{
1164    items
1165        .into_iter()
1166        .try_fold(varint_len(count as u64), |acc, item| {
1167            Ok(acc.saturating_add(item.encoded_len()?))
1168        })
1169}
1170
1171/// Tracks the byte span of the previous key while a map or set decodes in
1172/// canonical mode, and rejects any key that does not sort strictly after
1173/// it.
1174///
1175/// The spans are offsets into [`Decode::consumed`], which only grows during
1176/// a decode, so the previous key's bytes stay addressable without copying.
1177pub(crate) struct KeyOrder {
1178    reason: &'static str,
1179    prev: Option<(usize, usize)>,
1180}
1181
1182impl KeyOrder {
1183    /// Start tracking; `reason` is reported in
1184    /// [`SerialError::NonCanonical`] (`"map key order"` / `"set element
1185    /// order"`).
1186    pub(crate) fn new(reason: &'static str) -> Self {
1187        Self { reason, prev: None }
1188    }
1189
1190    /// Offset at which the next key starts.
1191    ///
1192    /// # Errors
1193    ///
1194    /// [`SerialError::InvalidConfig`] if the decoder cannot expose its
1195    /// consumed input, so canonical order cannot be checked.
1196    pub(crate) fn mark<D: Decode + ?Sized>(&self, decoder: &D) -> Result<usize> {
1197        decoder
1198            .consumed()
1199            .map(<[u8]>::len)
1200            .ok_or(SerialError::InvalidConfig {
1201                reason: "canonical mode needs a decoder that exposes its consumed input",
1202            })
1203    }
1204
1205    /// Check the key that started at `start` and has just been decoded.
1206    ///
1207    /// # Errors
1208    ///
1209    /// [`SerialError::NonCanonical`] if the key is not strictly greater
1210    /// than the previous one.
1211    pub(crate) fn check<D: Decode + ?Sized>(&mut self, decoder: &D, start: usize) -> Result<()> {
1212        let consumed = decoder.consumed().unwrap_or_default();
1213        let end = consumed.len();
1214        if let Some((prev_start, prev_end)) = self.prev {
1215            let prev = consumed.get(prev_start..prev_end).unwrap_or_default();
1216            let current = consumed.get(start..end).unwrap_or_default();
1217            if current <= prev {
1218                return Err(SerialError::NonCanonical {
1219                    reason: self.reason,
1220                });
1221            }
1222        }
1223        self.prev = Some((start, end));
1224        Ok(())
1225    }
1226}
1227
1228/// Decode `len` `(K, V)` entries, handing each to `insert`. In canonical
1229/// mode the encoded keys must be strictly increasing. Entries that consume
1230/// no input are charged against `max_alloc` (see
1231/// [`decode_elements_counted`]).
1232fn decode_entries<K, V, D, F>(decoder: &mut D, len: usize, mut insert: F) -> Result<()>
1233where
1234    K: Deserialize,
1235    V: Deserialize,
1236    D: Decode + ?Sized,
1237    F: FnMut(K, V),
1238{
1239    if decoder.config().canonical {
1240        let mut order = KeyOrder::new("map key order");
1241        decode_elements_counted::<(K, V), D, _>(decoder, len, |decoder| {
1242            let start = order.mark(decoder)?;
1243            let k = K::deserialize(decoder)?;
1244            order.check(decoder, start)?;
1245            let v = V::deserialize(decoder)?;
1246            insert(k, v);
1247            Ok(())
1248        })
1249    } else {
1250        decode_elements_counted::<(K, V), D, _>(decoder, len, |decoder| {
1251            let k = K::deserialize(decoder)?;
1252            let v = V::deserialize(decoder)?;
1253            insert(k, v);
1254            Ok(())
1255        })
1256    }
1257}
1258
1259/// Decode `len` set elements, handing each to `insert`. In canonical mode
1260/// the encoded elements must be strictly increasing. Elements that consume
1261/// no input are charged against `max_alloc`.
1262fn decode_elements<T, D, F>(decoder: &mut D, len: usize, mut insert: F) -> Result<()>
1263where
1264    T: Deserialize,
1265    D: Decode + ?Sized,
1266    F: FnMut(T),
1267{
1268    if decoder.config().canonical {
1269        let mut order = KeyOrder::new("set element order");
1270        decode_elements_counted::<T, D, _>(decoder, len, |decoder| {
1271            let start = order.mark(decoder)?;
1272            let item = T::deserialize(decoder)?;
1273            order.check(decoder, start)?;
1274            insert(item);
1275            Ok(())
1276        })
1277    } else {
1278        decode_elements_counted::<T, D, _>(decoder, len, |decoder| {
1279            insert(T::deserialize(decoder)?);
1280            Ok(())
1281        })
1282    }
1283}
1284
1285impl<K, V> Serialize for BTreeMap<K, V>
1286where
1287    K: Serialize,
1288    V: Serialize,
1289{
1290    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1291        encode_map_like(self.len(), self.iter(), encoder)
1292    }
1293
1294    fn encoded_len(&self) -> Result<usize> {
1295        map_encoded_len(self.len(), self.iter())
1296    }
1297}
1298
1299impl<K, V> Deserialize for BTreeMap<K, V>
1300where
1301    K: Deserialize + Ord,
1302    V: Deserialize,
1303{
1304    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1305        let declared = decoder.read_varint_u64()?;
1306        let len = guard_element_count(declared, decoder)?;
1307        let mut out = BTreeMap::new();
1308        decode_entries(decoder, len, |k, v| {
1309            let _ = out.insert(k, v);
1310        })?;
1311        Ok(out)
1312    }
1313}
1314
1315impl<T> Serialize for BTreeSet<T>
1316where
1317    T: Serialize,
1318{
1319    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1320        encode_set_like(self.len(), self.iter(), encoder)
1321    }
1322
1323    fn encoded_len(&self) -> Result<usize> {
1324        set_encoded_len(self.len(), self.iter())
1325    }
1326}
1327
1328impl<T> Deserialize for BTreeSet<T>
1329where
1330    T: Deserialize + Ord,
1331{
1332    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1333        let declared = decoder.read_varint_u64()?;
1334        let len = guard_element_count(declared, decoder)?;
1335        let mut out = BTreeSet::new();
1336        decode_elements(decoder, len, |item| {
1337            let _ = out.insert(item);
1338        })?;
1339        Ok(out)
1340    }
1341}
1342
1343#[cfg(feature = "std")]
1344impl<K, V, S> Serialize for HashMap<K, V, S>
1345where
1346    K: Serialize,
1347    V: Serialize,
1348{
1349    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1350        encode_map_like(self.len(), self.iter(), encoder)
1351    }
1352
1353    fn encoded_len(&self) -> Result<usize> {
1354        map_encoded_len(self.len(), self.iter())
1355    }
1356}
1357
1358#[cfg(feature = "std")]
1359impl<K, V, S> Deserialize for HashMap<K, V, S>
1360where
1361    K: Deserialize + Hash + Eq,
1362    V: Deserialize,
1363    S: BuildHasher + Default,
1364{
1365    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1366        let declared = decoder.read_varint_u64()?;
1367        let len = guard_element_count(declared, decoder)?;
1368        let capacity = initial_capacity::<(K, V), D>(len, decoder);
1369        let mut out = HashMap::with_capacity_and_hasher(capacity, S::default());
1370        decode_entries(decoder, len, |k, v| {
1371            let _ = out.insert(k, v);
1372        })?;
1373        Ok(out)
1374    }
1375}
1376
1377#[cfg(feature = "std")]
1378impl<T, S> Serialize for HashSet<T, S>
1379where
1380    T: Serialize,
1381{
1382    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
1383        encode_set_like(self.len(), self.iter(), encoder)
1384    }
1385
1386    fn encoded_len(&self) -> Result<usize> {
1387        set_encoded_len(self.len(), self.iter())
1388    }
1389}
1390
1391#[cfg(feature = "std")]
1392impl<T, S> Deserialize for HashSet<T, S>
1393where
1394    T: Deserialize + Hash + Eq,
1395    S: BuildHasher + Default,
1396{
1397    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
1398        let declared = decoder.read_varint_u64()?;
1399        let len = guard_element_count(declared, decoder)?;
1400        let capacity = initial_capacity::<T, D>(len, decoder);
1401        let mut out = HashSet::with_capacity_and_hasher(capacity, S::default());
1402        decode_elements(decoder, len, |item| {
1403            let _ = out.insert(item);
1404        })?;
1405        Ok(out)
1406    }
1407}
1408
1409#[cfg(test)]
1410mod tests {
1411    use super::*;
1412    use crate::{decode, encode};
1413    use alloc::vec;
1414
1415    fn round_trip<T>(value: T)
1416    where
1417        T: Serialize + Deserialize + PartialEq + core::fmt::Debug,
1418    {
1419        let bytes = encode(&value).expect("encode");
1420        let back: T = decode(&bytes).expect("decode");
1421        assert_eq!(back, value);
1422    }
1423
1424    #[test]
1425    fn u8_round_trips() {
1426        for v in [0u8, 1, 127, 128, 255] {
1427            round_trip(v);
1428        }
1429    }
1430
1431    #[test]
1432    fn u64_round_trips() {
1433        for v in [0u64, 1, u32::MAX as u64, u64::MAX] {
1434            round_trip(v);
1435        }
1436    }
1437
1438    #[test]
1439    fn i64_round_trips() {
1440        for v in [0i64, -1, 1, i64::MIN, i64::MAX] {
1441            round_trip(v);
1442        }
1443    }
1444
1445    #[test]
1446    fn bool_round_trips() {
1447        round_trip(true);
1448        round_trip(false);
1449    }
1450
1451    #[test]
1452    fn string_round_trips() {
1453        for s in ["", "hello", "a longer string with some content"] {
1454            round_trip(String::from(s));
1455        }
1456    }
1457
1458    #[test]
1459    fn vec_u8_round_trips() {
1460        round_trip::<Vec<u8>>(vec![]);
1461        round_trip::<Vec<u8>>(vec![0u8, 1, 2, 3]);
1462        round_trip::<Vec<u8>>(vec![0xffu8; 1024]);
1463    }
1464
1465    #[test]
1466    fn vec_u32_round_trips() {
1467        round_trip::<Vec<u32>>(vec![]);
1468        round_trip::<Vec<u32>>(vec![1, 2, u32::MAX]);
1469    }
1470
1471    #[test]
1472    fn vec_string_round_trips() {
1473        round_trip(vec![
1474            String::from("hello"),
1475            String::from("world"),
1476            String::new(),
1477        ]);
1478    }
1479
1480    #[test]
1481    fn array_round_trips() {
1482        round_trip([1u32, 2, 3, 4]);
1483        round_trip([0u8; 0]);
1484    }
1485
1486    #[test]
1487    fn tuple_round_trips() {
1488        round_trip((1u8, 2u16, 3u32));
1489        round_trip((String::from("a"), 42u64, -3i32));
1490    }
1491
1492    #[test]
1493    fn option_round_trips() {
1494        round_trip::<Option<u64>>(None);
1495        round_trip::<Option<u64>>(Some(42));
1496        round_trip::<Option<String>>(Some(String::from("hi")));
1497    }
1498
1499    #[test]
1500    fn result_round_trips() {
1501        round_trip::<core::result::Result<u64, String>>(Ok(7));
1502        round_trip::<core::result::Result<u64, String>>(Err(String::from("nope")));
1503    }
1504
1505    #[test]
1506    fn invalid_bool_byte_is_rejected() {
1507        let err = decode::<bool>(&[0x7f]).expect_err("0x7f is not a bool");
1508        assert!(matches!(err, SerialError::InvalidBool { byte: 0x7f }));
1509    }
1510
1511    #[test]
1512    fn string_with_invalid_utf8_is_rejected() {
1513        let bytes = [0x02, 0xff, 0xff];
1514        let err = decode::<String>(&bytes).expect_err("invalid UTF-8 should fail");
1515        assert!(matches!(err, SerialError::InvalidUtf8));
1516    }
1517
1518    #[test]
1519    fn option_invalid_tag_is_rejected() {
1520        let err = decode::<Option<u8>>(&[0x02]).expect_err("0x02 is not a valid Option tag");
1521        assert!(matches!(
1522            err,
1523            SerialError::InvalidTag {
1524                kind: "Option",
1525                tag: 0x02
1526            }
1527        ));
1528    }
1529
1530    #[test]
1531    fn result_invalid_tag_is_rejected() {
1532        let err =
1533            decode::<core::result::Result<u8, u8>>(&[0x02]).expect_err("0x02 is not a Result tag");
1534        assert!(matches!(
1535            err,
1536            SerialError::InvalidTag {
1537                kind: "Result",
1538                tag: 0x02
1539            }
1540        ));
1541    }
1542
1543    #[test]
1544    fn f64_round_trips_including_inf() {
1545        for v in [
1546            0.0f64,
1547            -0.0,
1548            1.0,
1549            -1.0,
1550            f64::MIN,
1551            f64::MAX,
1552            f64::INFINITY,
1553            f64::NEG_INFINITY,
1554        ] {
1555            let bytes = encode(&v).unwrap();
1556            let back: f64 = decode(&bytes).unwrap();
1557            assert_eq!(back.to_bits(), v.to_bits());
1558        }
1559    }
1560
1561    #[test]
1562    fn f64_nan_round_trips_bit_for_bit() {
1563        let v = f64::NAN;
1564        let bytes = encode(&v).unwrap();
1565        let back: f64 = decode(&bytes).unwrap();
1566        assert_eq!(back.to_bits(), v.to_bits());
1567        assert!(back.is_nan());
1568    }
1569
1570    #[test]
1571    fn btreemap_round_trips() {
1572        let mut m = BTreeMap::new();
1573        let _ = m.insert(String::from("a"), 1u32);
1574        let _ = m.insert(String::from("b"), 2);
1575        let _ = m.insert(String::from("c"), 3);
1576        round_trip(m);
1577    }
1578
1579    #[test]
1580    fn btreemap_empty_round_trips() {
1581        round_trip(BTreeMap::<u32, u32>::new());
1582    }
1583
1584    #[test]
1585    fn btreeset_round_trips() {
1586        let mut s = BTreeSet::new();
1587        let _ = s.insert(1u32);
1588        let _ = s.insert(2);
1589        let _ = s.insert(3);
1590        round_trip(s);
1591    }
1592
1593    #[cfg(feature = "std")]
1594    #[test]
1595    fn hashmap_round_trips() {
1596        let mut m: HashMap<String, u32> = HashMap::new();
1597        let _ = m.insert(String::from("alpha"), 1);
1598        let _ = m.insert(String::from("beta"), 2);
1599        round_trip(m);
1600    }
1601
1602    #[cfg(feature = "std")]
1603    #[test]
1604    fn hashset_round_trips() {
1605        let mut s: HashSet<u32> = HashSet::new();
1606        let _ = s.insert(1);
1607        let _ = s.insert(7);
1608        let _ = s.insert(42);
1609        round_trip(s);
1610    }
1611
1612    #[cfg(feature = "std")]
1613    #[test]
1614    fn hashmap_and_btreemap_encode_identically_for_same_data() {
1615        let mut h: HashMap<String, u32> = HashMap::new();
1616        let mut b: BTreeMap<String, u32> = BTreeMap::new();
1617        for (k, v) in [("zeta", 5u32), ("alpha", 1), ("delta", 4), ("beta", 2)] {
1618            let _ = h.insert(k.into(), v);
1619            let _ = b.insert(k.into(), v);
1620        }
1621        assert_eq!(encode(&h).unwrap(), encode(&b).unwrap());
1622    }
1623
1624    #[cfg(feature = "std")]
1625    #[test]
1626    fn hashmap_insertion_order_independent() {
1627        let mut a: HashMap<u32, u32> = HashMap::new();
1628        let _ = a.insert(1, 10);
1629        let _ = a.insert(2, 20);
1630        let _ = a.insert(3, 30);
1631
1632        let mut b: HashMap<u32, u32> = HashMap::new();
1633        let _ = b.insert(3, 30);
1634        let _ = b.insert(1, 10);
1635        let _ = b.insert(2, 20);
1636
1637        assert_eq!(encode(&a).unwrap(), encode(&b).unwrap());
1638    }
1639
1640    #[test]
1641    fn collection_with_hostile_element_count_is_rejected() {
1642        // varint(u64::MAX) is 10 bytes of 0xff... 0x01.
1643        let bytes: [u8; 10] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01];
1644        let err = decode::<Vec<u32>>(&bytes).expect_err("hostile count");
1645        assert!(matches!(err, SerialError::InvalidLength { .. }));
1646    }
1647}