Skip to main content

pack_io/
serde.rs

1//! `serde` adapter (feature `serde`): put any type that implements
2//! `serde::Serialize` / `serde::Deserialize` on the pack-io wire.
3//!
4//! The adapter maps serde's data model onto the formats in
5//! `docs/WIRE_FORMAT.md`, so a serde-derived type encodes to the same bytes
6//! as the equivalent `#[derive(pack_io::Serialize)]` type: structs and
7//! tuples are their fields concatenated, enums are
8//! `varint(variant_index) ++ fields`, sequences and strings are
9//! length-prefixed, and maps are written in canonical encoded-key order.
10//!
11//! **One exception: sets.** serde's data model has no set type, so a
12//! `BTreeSet` or `HashSet` reaches the adapter as a plain sequence and is
13//! written in iteration order: `Ord` order for a `BTreeSet` (deterministic,
14//! but not the native encoded-byte order), and an unspecified, per-process
15//! order for a `HashSet` (not deterministic). Annotate set fields with
16//! [`#[serde(with = "pack_io::serde::sorted_set")]`](sorted_set) to get the
17//! native bytes and canonical-mode order checks. With that, a producer can
18//! switch between the two derives without changing a byte.
19//!
20//! ```
21//! use serde::{Deserialize, Serialize};
22//!
23//! #[derive(Serialize, Deserialize, Debug, PartialEq)]
24//! enum Shape {
25//!     Circle { radius: u32 },
26//!     Rect(u32, u32),
27//! }
28//!
29//! let bytes = pack_io::serde::to_vec(&Shape::Rect(3, 4)).unwrap();
30//! assert_eq!(bytes, [1, 3, 4]); // varint(1) ++ varint(3) ++ varint(4)
31//! let back: Shape = pack_io::serde::from_slice(&bytes).unwrap();
32//! assert_eq!(back, Shape::Rect(3, 4));
33//! ```
34//!
35//! ## Entry points
36//!
37//! | Function | Use |
38//! |---|---|
39//! | [`to_vec`] | encode into a fresh `Vec<u8>` |
40//! | [`to_encoder`] | encode into any [`Encode`] sink (`Encoder`, `IoEncoder`, `BytesMut`, …) |
41//! | [`from_slice`] / [`from_slice_with_config`] | decode one value from a whole buffer; `&str` / `&[u8]` fields borrow from it |
42//! | [`from_decoder`] | decode the next value from an in-memory [`Decoder`] (borrowing) |
43//! | [`from_decode`] | decode the next value from any [`Decode`] source, e.g. an `IoDecoder` (owning) |
44//! | [`compat`] | `#[pack_io(with = "pack_io::serde::compat")]` for one serde-typed field in a pack-io-derived type |
45//! | [`sorted_set`] | `#[serde(with = "pack_io::serde::sorted_set")]` for a set field: native set bytes and canonical order checks |
46//! | [`Compat`] | wrapper that makes any serde type a pack-io `Serialize` / `Deserialize` / `DeserializeView` |
47//!
48//! ## Limits
49//!
50//! pack-io is not self-describing, so serde features that need the decoder
51//! to discover the shape of the data at run time are rejected with
52//! [`SerialError::Custom`]: `deserialize_any` (untagged and internally
53//! tagged enums, `#[serde(flatten)]`) and `deserialize_ignored_any`.
54//! Struct fields are positional; `#[serde(skip)]` works, but renaming or
55//! reordering fields changes the wire just like it does for the native
56//! derive.
57//!
58//! Sets without [`sorted_set`] are sequences (see above): their bytes
59//! follow iteration order, and canonical mode cannot check their order
60//! because nothing on the wire or in serde marks them as sets. Maps are
61//! always sorted and always checked.
62//!
63//! Decoding enforces the same [`Config`] limits as the native path:
64//! `max_alloc` on every length prefix and, across the whole decode, on
65//! sequence and map elements that occupy no input bytes; `max_depth` on
66//! nested sequences, maps, structs, enums and options; and canonical mode
67//! (non-canonical varints, unsorted or duplicate map keys, unsorted or
68//! duplicate [`sorted_set`] elements) when it is on.
69
70use alloc::borrow::Cow;
71use alloc::string::String;
72use alloc::vec::Vec;
73
74use serde::de::{self, DeserializeOwned, IntoDeserializer};
75use serde::ser;
76
77use crate::codec::{
78    Config, Decode, Decoder, Encode, Encoder, FreeElements, finish, guard_element_count,
79};
80use crate::error::{Result, SerialError};
81use crate::impls::{KeyOrder, SortedEntries};
82use crate::traits::{Deserialize, Serialize};
83use crate::view::DeserializeView;
84
85// ---------------------------------------------------------------------------
86// Public entry points
87// ---------------------------------------------------------------------------
88
89/// Encode a serde value into a freshly allocated `Vec<u8>`.
90///
91/// # Errors
92///
93/// Whatever the value's `serde::Serialize` impl reports (via
94/// [`SerialError::Custom`]), or [`SerialError::Custom`] if it emits a
95/// sequence whose length differs from the length it declared.
96///
97/// # Examples
98///
99/// ```
100/// let bytes = pack_io::serde::to_vec(&(7_u64, "hi")).unwrap();
101/// assert_eq!(bytes, pack_io::encode(&(7_u64, "hi")).unwrap());
102/// ```
103pub fn to_vec<T: ser::Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
104    let mut encoder = Encoder::with_capacity(128);
105    to_encoder(value, &mut encoder)?;
106    Ok(encoder.into_inner())
107}
108
109/// Encode a serde value into any [`Encode`] sink.
110///
111/// # Errors
112///
113/// As for [`to_vec`], plus any error the sink reports.
114///
115/// # Examples
116///
117/// ```
118/// use pack_io::Encoder;
119///
120/// let mut enc = Encoder::new();
121/// pack_io::serde::to_encoder(&[1_u16, 2, 3], &mut enc).unwrap();
122/// pack_io::serde::to_encoder(&"tail", &mut enc).unwrap();
123/// assert_eq!(enc.as_bytes(), &[1, 2, 3, 4, b't', b'a', b'i', b'l']);
124/// ```
125pub fn to_encoder<T, E>(value: &T, encoder: &mut E) -> Result<()>
126where
127    T: ser::Serialize + ?Sized,
128    E: Encode + ?Sized,
129{
130    value.serialize(&mut Serializer { encoder })
131}
132
133/// Decode one serde value from `bytes`, which must be fully consumed.
134/// Borrowed `&str` / `&[u8]` fields point into `bytes`.
135///
136/// # Errors
137///
138/// The same errors as [`crate::decode`], plus [`SerialError::Custom`] for
139/// the serde features this format cannot support (see the module docs) and
140/// for errors raised by the type's `serde::Deserialize` impl.
141///
142/// # Examples
143///
144/// ```
145/// #[derive(serde::Deserialize)]
146/// struct Msg<'a> { id: u32, text: &'a str }
147///
148/// let bytes = pack_io::encode(&(9_u32, "borrowed")).unwrap();
149/// let msg: Msg<'_> = pack_io::serde::from_slice(&bytes).unwrap();
150/// assert_eq!((msg.id, msg.text), (9, "borrowed"));
151/// ```
152pub fn from_slice<'de, T: de::Deserialize<'de>>(bytes: &'de [u8]) -> Result<T> {
153    let mut decoder = Decoder::new(bytes);
154    let value = from_decoder(&mut decoder)?;
155    finish(&decoder, value)
156}
157
158/// [`from_slice`] under an explicit [`Config`].
159///
160/// # Errors
161///
162/// As for [`from_slice`], plus any error [`Decoder::with_config`] reports
163/// for an invalid `config`.
164///
165/// # Examples
166///
167/// ```
168/// use pack_io::{Config, SerialError};
169///
170/// // `[0x80, 0x00]` is a non-canonical encoding of 0.
171/// let strict = Config::new().with_canonical(true);
172/// let err = pack_io::serde::from_slice_with_config::<u32>(&[0x80, 0x00], strict).unwrap_err();
173/// assert!(matches!(err, SerialError::NonCanonical { .. }));
174/// ```
175pub fn from_slice_with_config<'de, T: de::Deserialize<'de>>(
176    bytes: &'de [u8],
177    config: Config,
178) -> Result<T> {
179    let mut decoder = Decoder::with_config(bytes, config)?;
180    let value = from_decoder(&mut decoder)?;
181    finish(&decoder, value)
182}
183
184/// Decode the next serde value from an in-memory [`Decoder`], leaving the
185/// cursor after it. Borrowed fields point into the decoder's input.
186///
187/// # Errors
188///
189/// As for [`from_slice`], except that trailing input is not an error.
190///
191/// # Examples
192///
193/// ```
194/// use pack_io::{Decoder, Encoder};
195///
196/// let mut enc = Encoder::new();
197/// enc.write(&1_u8).unwrap();
198/// enc.write(&"two").unwrap();
199/// let bytes = enc.into_inner();
200///
201/// let mut dec = Decoder::new(&bytes);
202/// let a: u8 = pack_io::serde::from_decoder(&mut dec).unwrap();
203/// let b: &str = pack_io::serde::from_decoder(&mut dec).unwrap();
204/// assert_eq!((a, b), (1, "two"));
205/// ```
206pub fn from_decoder<'de, T: de::Deserialize<'de>>(decoder: &mut Decoder<'de>) -> Result<T> {
207    T::deserialize(&mut Deserializer::new(decoder))
208}
209
210/// Decode the next serde value from any [`Decode`] source, such as an
211/// `IoDecoder` (feature `std`). Strings and byte buffers are copied, so
212/// `T` must own its data.
213///
214/// # Errors
215///
216/// As for [`from_decoder`], plus any error the source reports.
217///
218/// # Examples
219///
220/// ```
221/// # #[cfg(feature = "std")] {
222/// use std::io::Cursor;
223/// use pack_io::IoDecoder;
224///
225/// let bytes = pack_io::encode(&vec![String::from("a"), String::from("b")]).unwrap();
226/// let mut dec = IoDecoder::new(Cursor::new(bytes));
227/// let v: Vec<String> = pack_io::serde::from_decode(&mut dec).unwrap();
228/// assert_eq!(v, ["a", "b"]);
229/// # }
230/// ```
231pub fn from_decode<T, D>(decoder: &mut D) -> Result<T>
232where
233    T: DeserializeOwned,
234    D: Decode + ?Sized,
235{
236    let mut owned = Owned(decoder);
237    T::deserialize(&mut Deserializer::new(&mut owned))
238}
239
240/// Helpers for one serde-typed field inside a pack-io-derived type:
241///
242/// ```
243/// # #[cfg(feature = "derive")] {
244/// use pack_io::{Deserialize, Serialize};
245///
246/// // Any type that only implements serde's traits.
247/// #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
248/// struct Point { x: i32, y: i32 }
249///
250/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
251/// struct Record {
252///     id: u64,
253///     #[pack_io(with = "pack_io::serde::compat")]
254///     at: Point,
255/// }
256///
257/// let rec = Record { id: 1, at: Point { x: -2, y: 5 } };
258/// let bytes = pack_io::encode(&rec).unwrap();
259/// assert_eq!(pack_io::decode::<Record>(&bytes).unwrap(), rec);
260/// # }
261/// ```
262pub mod compat {
263    use super::{Decode, Decoder, DeserializeOwned, Encode, Result, de, ser};
264
265    /// Encode `value` through serde. See [`super::to_encoder`].
266    ///
267    /// # Errors
268    ///
269    /// As for [`super::to_encoder`].
270    pub fn serialize<T, E>(value: &T, encoder: &mut E) -> Result<()>
271    where
272        T: ser::Serialize + ?Sized,
273        E: Encode + ?Sized,
274    {
275        super::to_encoder(value, encoder)
276    }
277
278    /// Decode an owned value through serde. See [`super::from_decode`].
279    ///
280    /// # Errors
281    ///
282    /// As for [`super::from_decode`].
283    pub fn deserialize<T, D>(decoder: &mut D) -> Result<T>
284    where
285        T: DeserializeOwned,
286        D: Decode + ?Sized,
287    {
288        super::from_decode(decoder)
289    }
290
291    /// Decode a possibly-borrowing value through serde, for
292    /// `#[derive(DeserializeView)]` types. See [`super::from_decoder`].
293    ///
294    /// # Errors
295    ///
296    /// As for [`super::from_decoder`].
297    pub fn deserialize_view<'de, T: de::Deserialize<'de>>(decoder: &mut Decoder<'de>) -> Result<T> {
298        super::from_decoder(decoder)
299    }
300}
301
302/// serde `with` helpers for a set field (`BTreeSet`, `HashSet`, or any
303/// collection that iterates as `&T` and deserializes from a sequence):
304/// `#[serde(with = "pack_io::serde::sorted_set")]`.
305///
306/// serde has no set type, so without this a set is an ordinary sequence in
307/// iteration order. With it:
308///
309/// - **Encoding** writes the elements sorted by their pack-io encoding,
310///   exactly like the native `BTreeSet` / `HashSet` impls, so the bytes are
311///   deterministic (also for a `HashSet`) and identical to a
312///   `#[derive(pack_io::Serialize)]` type with the same field.
313/// - **Decoding** in canonical mode ([`Config::with_canonical`]) rejects
314///   elements that are not in strictly increasing encoded order (which
315///   also rejects duplicates) with
316///   `SerialError::NonCanonical { reason: "set element order" }`.
317///
318/// Other serde formats see a newtype around an ordinary sequence: the
319/// elements are still sorted, so their output is deterministic too.
320///
321/// # Examples
322///
323/// ```
324/// # #[cfg(feature = "std")] {
325/// use std::collections::{BTreeSet, HashSet};
326///
327/// #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
328/// struct Tags {
329///     #[serde(with = "pack_io::serde::sorted_set")]
330///     names: BTreeSet<String>,
331///     #[serde(with = "pack_io::serde::sorted_set")]
332///     ids: HashSet<u32>,
333/// }
334///
335/// let tags = Tags {
336///     names: ["b", "aa", "ccc"].map(String::from).into(),
337///     ids: [300, 1, 129].into(),
338/// };
339/// let bytes = pack_io::serde::to_vec(&tags).unwrap();
340/// // Byte-identical to the native encoding of the same fields.
341/// assert_eq!(bytes, pack_io::encode(&(&tags.names, &tags.ids)).unwrap());
342/// assert_eq!(pack_io::serde::from_slice::<Tags>(&bytes).unwrap(), tags);
343/// # }
344/// ```
345pub mod sorted_set {
346    use alloc::vec::Vec;
347    use core::fmt;
348    use core::marker::PhantomData;
349
350    use serde::{de, ser};
351
352    /// The newtype name that tells the pack-io deserializer the sequence
353    /// inside is a set, so canonical mode checks its order.
354    pub(super) const NAME: &str = "$pack_io::serde::sorted_set";
355
356    /// Serialize `set` with its elements sorted by their pack-io encoding.
357    ///
358    /// # Errors
359    ///
360    /// Whatever the serializer or an element's `Serialize` impl reports.
361    pub fn serialize<'a, C, T, S>(set: &'a C, serializer: S) -> Result<S::Ok, S::Error>
362    where
363        &'a C: IntoIterator<Item = &'a T>,
364        T: ser::Serialize + 'a,
365        S: ser::Serializer,
366    {
367        let mut keyed: Vec<(Vec<u8>, &'a T)> = Vec::new();
368        for item in set {
369            let key = super::to_vec(item).map_err(ser::Error::custom)?;
370            keyed.push((key, item));
371        }
372        keyed.sort_by(|a, b| a.0.cmp(&b.0));
373        serializer.serialize_newtype_struct(NAME, &Sorted(keyed))
374    }
375
376    /// Deserialize a set written by [`serialize`] (or any sequence). In
377    /// canonical mode the pack-io deserializer checks the element order.
378    ///
379    /// # Errors
380    ///
381    /// Whatever the deserializer or the collection's `Deserialize` impl
382    /// reports.
383    pub fn deserialize<'de, C, D>(deserializer: D) -> Result<C, D::Error>
384    where
385        C: de::Deserialize<'de>,
386        D: de::Deserializer<'de>,
387    {
388        deserializer.deserialize_newtype_struct(NAME, SetVisitor(PhantomData))
389    }
390
391    /// The sorted elements, serialized as a sequence.
392    struct Sorted<'a, T>(Vec<(Vec<u8>, &'a T)>);
393
394    impl<T: ser::Serialize> ser::Serialize for Sorted<'_, T> {
395        fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
396            serializer.collect_seq(self.0.iter().map(|(_, item)| *item))
397        }
398    }
399
400    struct SetVisitor<C>(PhantomData<C>);
401
402    impl<'de, C: de::Deserialize<'de>> de::Visitor<'de> for SetVisitor<C> {
403        type Value = C;
404
405        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406            f.write_str("a set")
407        }
408
409        fn visit_newtype_struct<D: de::Deserializer<'de>>(
410            self,
411            deserializer: D,
412        ) -> Result<C, D::Error> {
413            C::deserialize(deserializer)
414        }
415
416        fn visit_seq<A: de::SeqAccess<'de>>(self, seq: A) -> Result<C, A::Error> {
417            C::deserialize(de::value::SeqAccessDeserializer::new(seq))
418        }
419    }
420}
421
422/// Wrapper that gives any serde type pack-io's [`Serialize`],
423/// [`Deserialize`] and [`DeserializeView`] impls, so it can sit anywhere a
424/// pack-io type can: inside a `Vec`, a map, a tuple, or a derived struct.
425///
426/// The wrapper adds no bytes: `Compat(v)` encodes exactly like
427/// `pack_io::serde::to_vec(&v)`. Sets inside `v` follow the adapter's rules
428/// (see the [module docs](self) and [`sorted_set`]).
429///
430/// # Examples
431///
432/// ```
433/// use pack_io::serde::Compat;
434///
435/// #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
436/// struct Tag { key: String, value: String }
437///
438/// let tags = vec![Compat(Tag { key: "env".into(), value: "prod".into() })];
439/// let bytes = pack_io::encode(&tags).unwrap();
440/// let back: Vec<Compat<Tag>> = pack_io::decode(&bytes).unwrap();
441/// assert_eq!(back[0].0.value, "prod");
442/// ```
443#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
444pub struct Compat<T>(pub T);
445
446impl<T: ser::Serialize> Serialize for Compat<T> {
447    #[inline]
448    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()> {
449        to_encoder(&self.0, encoder)
450    }
451}
452
453impl<T: DeserializeOwned> Deserialize for Compat<T> {
454    #[inline]
455    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self> {
456        from_decode(decoder).map(Compat)
457    }
458}
459
460impl<'de, T: de::Deserialize<'de>> DeserializeView<'de> for Compat<T> {
461    #[inline]
462    fn deserialize_view(decoder: &mut Decoder<'de>) -> Result<Self> {
463        from_decoder(decoder).map(Compat)
464    }
465}
466
467// ---------------------------------------------------------------------------
468// Serializer
469// ---------------------------------------------------------------------------
470
471/// serde `Serializer` writing pack-io wire bytes into an [`Encode`] sink.
472struct Serializer<'e, E: ?Sized> {
473    encoder: &'e mut E,
474}
475
476impl<E: Encode + ?Sized> Serializer<'_, E> {
477    #[inline]
478    fn write_len(&mut self, len: usize) -> Result<()> {
479        self.encoder.write_varint_u64(len as u64)
480    }
481
482    #[inline]
483    fn write_variant(&mut self, index: u32) -> Result<()> {
484        self.encoder.write_varint_u64(u64::from(index))
485    }
486}
487
488impl<'a, 'e, E: Encode + ?Sized> ser::Serializer for &'a mut Serializer<'e, E> {
489    type Ok = ();
490    type Error = SerialError;
491    type SerializeSeq = SeqSerializer<'a, 'e, E>;
492    type SerializeTuple = Self;
493    type SerializeTupleStruct = Self;
494    type SerializeTupleVariant = Self;
495    type SerializeMap = MapSerializer<'a, 'e, E>;
496    type SerializeStruct = Self;
497    type SerializeStructVariant = Self;
498
499    fn serialize_bool(self, v: bool) -> Result<()> {
500        v.serialize(self.encoder)
501    }
502
503    fn serialize_i8(self, v: i8) -> Result<()> {
504        v.serialize(self.encoder)
505    }
506
507    fn serialize_i16(self, v: i16) -> Result<()> {
508        v.serialize(self.encoder)
509    }
510
511    fn serialize_i32(self, v: i32) -> Result<()> {
512        v.serialize(self.encoder)
513    }
514
515    fn serialize_i64(self, v: i64) -> Result<()> {
516        v.serialize(self.encoder)
517    }
518
519    fn serialize_i128(self, v: i128) -> Result<()> {
520        v.serialize(self.encoder)
521    }
522
523    fn serialize_u8(self, v: u8) -> Result<()> {
524        v.serialize(self.encoder)
525    }
526
527    fn serialize_u16(self, v: u16) -> Result<()> {
528        v.serialize(self.encoder)
529    }
530
531    fn serialize_u32(self, v: u32) -> Result<()> {
532        v.serialize(self.encoder)
533    }
534
535    fn serialize_u64(self, v: u64) -> Result<()> {
536        v.serialize(self.encoder)
537    }
538
539    fn serialize_u128(self, v: u128) -> Result<()> {
540        v.serialize(self.encoder)
541    }
542
543    fn serialize_f32(self, v: f32) -> Result<()> {
544        v.serialize(self.encoder)
545    }
546
547    fn serialize_f64(self, v: f64) -> Result<()> {
548        v.serialize(self.encoder)
549    }
550
551    fn serialize_char(self, v: char) -> Result<()> {
552        v.serialize(self.encoder)
553    }
554
555    fn serialize_str(self, v: &str) -> Result<()> {
556        v.serialize(self.encoder)
557    }
558
559    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
560        v.serialize(self.encoder)
561    }
562
563    fn serialize_none(self) -> Result<()> {
564        self.encoder.write_byte(0x00)
565    }
566
567    fn serialize_some<T: ser::Serialize + ?Sized>(self, value: &T) -> Result<()> {
568        self.encoder.write_byte(0x01)?;
569        value.serialize(self)
570    }
571
572    fn serialize_unit(self) -> Result<()> {
573        Ok(())
574    }
575
576    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
577        Ok(())
578    }
579
580    fn serialize_unit_variant(
581        self,
582        _name: &'static str,
583        variant_index: u32,
584        _variant: &'static str,
585    ) -> Result<()> {
586        self.write_variant(variant_index)
587    }
588
589    fn serialize_newtype_struct<T: ser::Serialize + ?Sized>(
590        self,
591        _name: &'static str,
592        value: &T,
593    ) -> Result<()> {
594        value.serialize(self)
595    }
596
597    fn serialize_newtype_variant<T: ser::Serialize + ?Sized>(
598        self,
599        _name: &'static str,
600        variant_index: u32,
601        _variant: &'static str,
602        value: &T,
603    ) -> Result<()> {
604        self.write_variant(variant_index)?;
605        value.serialize(self)
606    }
607
608    fn serialize_seq(self, len: Option<usize>) -> Result<SeqSerializer<'a, 'e, E>> {
609        Ok(match len {
610            Some(expected) => {
611                self.write_len(expected)?;
612                SeqSerializer::Direct {
613                    ser: self,
614                    expected,
615                    written: 0,
616                }
617            }
618            None => SeqSerializer::Buffered {
619                ser: self,
620                scratch: Encoder::new(),
621                count: 0,
622            },
623        })
624    }
625
626    fn serialize_tuple(self, _len: usize) -> Result<Self> {
627        Ok(self)
628    }
629
630    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self> {
631        Ok(self)
632    }
633
634    fn serialize_tuple_variant(
635        self,
636        _name: &'static str,
637        variant_index: u32,
638        _variant: &'static str,
639        _len: usize,
640    ) -> Result<Self> {
641        self.write_variant(variant_index)?;
642        Ok(self)
643    }
644
645    fn serialize_map(self, len: Option<usize>) -> Result<MapSerializer<'a, 'e, E>> {
646        Ok(MapSerializer {
647            ser: self,
648            entries: SortedEntries::with_capacity(len.unwrap_or(0)),
649        })
650    }
651
652    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self> {
653        Ok(self)
654    }
655
656    fn serialize_struct_variant(
657        self,
658        _name: &'static str,
659        variant_index: u32,
660        _variant: &'static str,
661        _len: usize,
662    ) -> Result<Self> {
663        self.write_variant(variant_index)?;
664        Ok(self)
665    }
666
667    fn is_human_readable(&self) -> bool {
668        false
669    }
670}
671
672/// Sequence serializer. A known length is written up front and checked at
673/// the end; an unknown length buffers the elements and writes the count
674/// once it is known.
675enum SeqSerializer<'a, 'e, E: ?Sized> {
676    Direct {
677        ser: &'a mut Serializer<'e, E>,
678        expected: usize,
679        written: usize,
680    },
681    Buffered {
682        ser: &'a mut Serializer<'e, E>,
683        scratch: Encoder,
684        count: usize,
685    },
686}
687
688impl<E: Encode + ?Sized> ser::SerializeSeq for SeqSerializer<'_, '_, E> {
689    type Ok = ();
690    type Error = SerialError;
691
692    fn serialize_element<T: ser::Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
693        match self {
694            Self::Direct { ser, written, .. } => {
695                *written = written.saturating_add(1);
696                value.serialize(&mut **ser)
697            }
698            Self::Buffered { scratch, count, .. } => {
699                *count = count.saturating_add(1);
700                value.serialize(&mut Serializer { encoder: scratch })
701            }
702        }
703    }
704
705    fn end(self) -> Result<()> {
706        match self {
707            Self::Direct {
708                expected, written, ..
709            } => {
710                if expected != written {
711                    return Err(SerialError::custom(
712                        "serde sequence emitted a different number of elements than it declared",
713                    ));
714                }
715                Ok(())
716            }
717            Self::Buffered {
718                ser,
719                scratch,
720                count,
721            } => {
722                ser.write_len(count)?;
723                ser.encoder.write_bytes(scratch.as_bytes())
724            }
725        }
726    }
727}
728
729/// Map serializer: entries are buffered and written in canonical
730/// encoded-key order, exactly like the native map impls.
731struct MapSerializer<'a, 'e, E: ?Sized> {
732    ser: &'a mut Serializer<'e, E>,
733    entries: SortedEntries,
734}
735
736impl<E: Encode + ?Sized> ser::SerializeMap for MapSerializer<'_, '_, E> {
737    type Ok = ();
738    type Error = SerialError;
739
740    fn serialize_key<T: ser::Serialize + ?Sized>(&mut self, key: &T) -> Result<()> {
741        self.entries.begin_entry();
742        key.serialize(&mut Serializer {
743            encoder: self.entries.encoder(),
744        })?;
745        self.entries.end_key();
746        Ok(())
747    }
748
749    fn serialize_value<T: ser::Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
750        value.serialize(&mut Serializer {
751            encoder: self.entries.encoder(),
752        })?;
753        self.entries.end_entry();
754        Ok(())
755    }
756
757    fn end(self) -> Result<()> {
758        self.entries.write_to(self.ser.encoder)
759    }
760}
761
762/// Tuples, tuple structs, structs and their enum-variant forms: fields are
763/// written in order with no framing.
764macro_rules! impl_fields_serializer {
765    ($($trait:ident :: $method:ident $(, $key:ty)?);+ $(;)?) => {
766        $(
767            impl<E: Encode + ?Sized> ser::$trait for &mut Serializer<'_, E> {
768                type Ok = ();
769                type Error = SerialError;
770
771                fn $method<T: ser::Serialize + ?Sized>(
772                    &mut self,
773                    $(_key: $key,)?
774                    value: &T,
775                ) -> Result<()> {
776                    value.serialize(&mut **self)
777                }
778
779                fn end(self) -> Result<()> {
780                    Ok(())
781                }
782            }
783        )+
784    };
785}
786
787impl_fields_serializer! {
788    SerializeTuple::serialize_element;
789    SerializeTupleStruct::serialize_field;
790    SerializeTupleVariant::serialize_field;
791    SerializeStruct::serialize_field, &'static str;
792    SerializeStructVariant::serialize_field, &'static str;
793}
794
795// ---------------------------------------------------------------------------
796// Deserializer
797// ---------------------------------------------------------------------------
798
799/// Where the deserializer gets its bytes: borrowed from an in-memory
800/// [`Decoder`], or copied out of any other [`Decode`] via [`Owned`].
801trait Source<'de>: Decode {
802    /// Read `len` bytes of UTF-8 and hand them to `visitor`.
803    fn visit_str<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value>;
804
805    /// Read `len` raw bytes and hand them to `visitor`.
806    fn visit_bytes<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value>;
807}
808
809impl<'de> Source<'de> for Decoder<'de> {
810    fn visit_str<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value> {
811        let bytes = self.read_borrowed(len)?;
812        let text = core::str::from_utf8(bytes).map_err(|_| SerialError::InvalidUtf8)?;
813        visitor.visit_borrowed_str(text)
814    }
815
816    fn visit_bytes<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value> {
817        visitor.visit_borrowed_bytes(self.read_borrowed(len)?)
818    }
819}
820
821/// Adapts any [`Decode`] into a [`Source`] that copies strings and bytes.
822struct Owned<'d, D: ?Sized>(&'d mut D);
823
824impl<D: Decode + ?Sized> Decode for Owned<'_, D> {
825    #[inline]
826    fn read_byte(&mut self) -> Result<u8> {
827        self.0.read_byte()
828    }
829
830    #[inline]
831    fn read_into(&mut self, out: &mut [u8]) -> Result<()> {
832        self.0.read_into(out)
833    }
834
835    #[inline]
836    fn max_alloc(&self) -> usize {
837        self.0.max_alloc()
838    }
839
840    #[inline]
841    fn remaining_hint(&self) -> Option<usize> {
842        self.0.remaining_hint()
843    }
844
845    #[inline]
846    fn config(&self) -> Config {
847        self.0.config()
848    }
849
850    #[inline]
851    fn depth(&self) -> usize {
852        self.0.depth()
853    }
854
855    #[inline]
856    fn enter_nested(&mut self) -> Result<()> {
857        self.0.enter_nested()
858    }
859
860    #[inline]
861    fn leave_nested(&mut self) {
862        self.0.leave_nested();
863    }
864
865    #[inline]
866    fn consumed(&self) -> Option<&[u8]> {
867        self.0.consumed()
868    }
869
870    #[inline]
871    fn bytes_read(&self) -> Option<u64> {
872        self.0.bytes_read()
873    }
874
875    #[inline]
876    fn unbacked(&self) -> usize {
877        self.0.unbacked()
878    }
879
880    #[inline]
881    fn charge_unbacked(&mut self, bytes: usize) -> Result<()> {
882        self.0.charge_unbacked(bytes)
883    }
884
885    #[inline]
886    fn read_byte_cow(&mut self, len: usize) -> Result<Cow<'_, [u8]>> {
887        self.0.read_byte_cow(len)
888    }
889
890    #[inline]
891    fn read_varint_u64(&mut self) -> Result<u64> {
892        self.0.read_varint_u64()
893    }
894
895    #[inline]
896    fn read_varint_u128(&mut self) -> Result<u128> {
897        self.0.read_varint_u128()
898    }
899
900    #[inline]
901    fn read_length_prefixed(&mut self) -> Result<Vec<u8>> {
902        self.0.read_length_prefixed()
903    }
904}
905
906impl<'de, D: Decode + ?Sized> Source<'de> for Owned<'_, D> {
907    fn visit_str<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value> {
908        let bytes = self.0.read_byte_cow(len)?.into_owned();
909        let text = String::from_utf8(bytes).map_err(|_| SerialError::InvalidUtf8)?;
910        visitor.visit_string(text)
911    }
912
913    fn visit_bytes<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value> {
914        visitor.visit_byte_buf(self.0.read_byte_cow(len)?.into_owned())
915    }
916}
917
918/// serde `Deserializer` reading pack-io wire bytes from a [`Source`].
919struct Deserializer<'s, S: ?Sized> {
920    source: &'s mut S,
921    /// Set by a [`sorted_set`] newtype: the next sequence is a set whose
922    /// element order canonical mode checks.
923    set_next: bool,
924}
925
926impl<'s, S: ?Sized> Deserializer<'s, S> {
927    fn new(source: &'s mut S) -> Self {
928        Self {
929            source,
930            set_next: false,
931        }
932    }
933}
934
935impl<'de, S: Source<'de> + ?Sized> Deserializer<'_, S> {
936    /// Read and validate a length / count prefix.
937    fn read_len(&mut self) -> Result<usize> {
938        let declared = self.source.read_varint_u64()?;
939        guard_element_count(declared, &*self.source)
940    }
941
942    /// Run `body` one nesting level deeper.
943    fn nested<T>(&mut self, body: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
944        self.source.enter_nested()?;
945        let out = body(self);
946        self.source.leave_nested();
947        out
948    }
949}
950
951/// [`SerialError::Custom`] for a serde feature this format cannot support.
952fn unsupported<T>(what: &'static str) -> Result<T> {
953    Err(SerialError::Custom {
954        message: Cow::Borrowed(what),
955    })
956}
957
958/// Forward a primitive `deserialize_*` to pack-io's native impl and the
959/// matching `visit_*`.
960macro_rules! forward_primitive {
961    ($($method:ident => $ty:ty, $visit:ident;)+) => {
962        $(
963            fn $method<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
964                let value = <$ty as Deserialize>::deserialize(&mut *self.source)?;
965                visitor.$visit(value)
966            }
967        )+
968    };
969}
970
971impl<'de, S: Source<'de> + ?Sized> de::Deserializer<'de> for &mut Deserializer<'_, S> {
972    type Error = SerialError;
973
974    fn deserialize_any<V: de::Visitor<'de>>(self, _visitor: V) -> Result<V::Value> {
975        unsupported(
976            "pack-io is not self-describing: deserialize_any (untagged / internally tagged enums, \
977             #[serde(flatten)]) is not supported",
978        )
979    }
980
981    forward_primitive! {
982        deserialize_bool => bool, visit_bool;
983        deserialize_i8 => i8, visit_i8;
984        deserialize_i16 => i16, visit_i16;
985        deserialize_i32 => i32, visit_i32;
986        deserialize_i64 => i64, visit_i64;
987        deserialize_i128 => i128, visit_i128;
988        deserialize_u8 => u8, visit_u8;
989        deserialize_u16 => u16, visit_u16;
990        deserialize_u32 => u32, visit_u32;
991        deserialize_u64 => u64, visit_u64;
992        deserialize_u128 => u128, visit_u128;
993        deserialize_f32 => f32, visit_f32;
994        deserialize_f64 => f64, visit_f64;
995        deserialize_char => char, visit_char;
996    }
997
998    fn deserialize_str<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
999        let len = self.read_len()?;
1000        self.source.visit_str(len, visitor)
1001    }
1002
1003    fn deserialize_string<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1004        self.deserialize_str(visitor)
1005    }
1006
1007    fn deserialize_bytes<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1008        let len = self.read_len()?;
1009        self.source.visit_bytes(len, visitor)
1010    }
1011
1012    fn deserialize_byte_buf<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1013        self.deserialize_bytes(visitor)
1014    }
1015
1016    fn deserialize_option<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1017        match self.source.read_byte()? {
1018            0x00 => visitor.visit_none(),
1019            0x01 => self.nested(|de| visitor.visit_some(&mut *de)),
1020            tag => Err(SerialError::InvalidTag {
1021                kind: "Option",
1022                tag,
1023            }),
1024        }
1025    }
1026
1027    fn deserialize_unit<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1028        visitor.visit_unit()
1029    }
1030
1031    fn deserialize_unit_struct<V: de::Visitor<'de>>(
1032        self,
1033        _name: &'static str,
1034        visitor: V,
1035    ) -> Result<V::Value> {
1036        visitor.visit_unit()
1037    }
1038
1039    fn deserialize_newtype_struct<V: de::Visitor<'de>>(
1040        self,
1041        name: &'static str,
1042        visitor: V,
1043    ) -> Result<V::Value> {
1044        if name == sorted_set::NAME {
1045            // Transparent on the wire, like the native set impls (no extra
1046            // nesting level); the flag reaches the `deserialize_seq` the
1047            // set's own `Deserialize` makes next.
1048            self.set_next = true;
1049            let out = visitor.visit_newtype_struct(&mut *self);
1050            self.set_next = false;
1051            return out;
1052        }
1053        self.nested(|de| visitor.visit_newtype_struct(&mut *de))
1054    }
1055
1056    fn deserialize_seq<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1057        let is_set = core::mem::take(&mut self.set_next);
1058        let len = self.read_len()?;
1059        let order =
1060            (is_set && self.source.config().canonical).then(|| KeyOrder::new("set element order"));
1061        self.nested(|de| {
1062            let free = Some(FreeElements::new(&*de.source));
1063            let mut access = SeqAccess {
1064                de,
1065                remaining: len,
1066                free,
1067                order,
1068            };
1069            let value = visitor.visit_seq(&mut access)?;
1070            if access.remaining != 0 {
1071                return unsupported("serde visitor stopped before the end of the sequence");
1072            }
1073            Ok(value)
1074        })
1075    }
1076
1077    fn deserialize_tuple<V: de::Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value> {
1078        self.visit_exact_seq(len, visitor)
1079    }
1080
1081    fn deserialize_tuple_struct<V: de::Visitor<'de>>(
1082        self,
1083        _name: &'static str,
1084        len: usize,
1085        visitor: V,
1086    ) -> Result<V::Value> {
1087        self.visit_exact_seq(len, visitor)
1088    }
1089
1090    fn deserialize_map<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1091        let len = self.read_len()?;
1092        self.nested(|de| {
1093            let order = de
1094                .source
1095                .config()
1096                .canonical
1097                .then(|| KeyOrder::new("map key order"));
1098            let free = FreeElements::new(&*de.source);
1099            let mut access = MapAccess {
1100                de,
1101                remaining: len,
1102                order,
1103                free,
1104                key_size: 0,
1105            };
1106            let value = visitor.visit_map(&mut access)?;
1107            if access.remaining != 0 {
1108                return unsupported("serde visitor stopped before the end of the map");
1109            }
1110            Ok(value)
1111        })
1112    }
1113
1114    fn deserialize_struct<V: de::Visitor<'de>>(
1115        self,
1116        _name: &'static str,
1117        fields: &'static [&'static str],
1118        visitor: V,
1119    ) -> Result<V::Value> {
1120        self.visit_exact_seq(fields.len(), visitor)
1121    }
1122
1123    fn deserialize_enum<V: de::Visitor<'de>>(
1124        self,
1125        _name: &'static str,
1126        _variants: &'static [&'static str],
1127        visitor: V,
1128    ) -> Result<V::Value> {
1129        self.nested(|de| visitor.visit_enum(&mut *de))
1130    }
1131
1132    fn deserialize_identifier<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
1133        let index = <u32 as Deserialize>::deserialize(&mut *self.source)?;
1134        visitor.visit_u32(index)
1135    }
1136
1137    fn deserialize_ignored_any<V: de::Visitor<'de>>(self, _visitor: V) -> Result<V::Value> {
1138        unsupported("pack-io is not self-describing: values cannot be skipped without their type")
1139    }
1140
1141    fn is_human_readable(&self) -> bool {
1142        false
1143    }
1144}
1145
1146impl<'de, S: Source<'de> + ?Sized> Deserializer<'_, S> {
1147    /// Visit exactly `len` positional elements (a length-prefixed sequence,
1148    /// a tuple, or a struct's fields).
1149    fn visit_exact_seq<V: de::Visitor<'de>>(&mut self, len: usize, visitor: V) -> Result<V::Value> {
1150        self.nested(|de| {
1151            let mut access = SeqAccess {
1152                de,
1153                remaining: len,
1154                free: None,
1155                order: None,
1156            };
1157            let value = visitor.visit_seq(&mut access)?;
1158            if access.remaining != 0 {
1159                return unsupported("serde visitor stopped before the end of the sequence");
1160            }
1161            Ok(value)
1162        })
1163    }
1164}
1165
1166struct SeqAccess<'a, 's, S: ?Sized> {
1167    de: &'a mut Deserializer<'s, S>,
1168    remaining: usize,
1169    /// Charging of elements that occupy no input, for sequences whose
1170    /// length came off the wire (`None` for tuples and structs).
1171    free: Option<FreeElements>,
1172    /// Element order check for a [`sorted_set`] in canonical mode.
1173    order: Option<KeyOrder>,
1174}
1175
1176impl<'de, S: Source<'de> + ?Sized> de::SeqAccess<'de> for SeqAccess<'_, '_, S> {
1177    type Error = SerialError;
1178
1179    fn next_element_seed<T: de::DeserializeSeed<'de>>(
1180        &mut self,
1181        seed: T,
1182    ) -> Result<Option<T::Value>> {
1183        if self.remaining == 0 {
1184            return Ok(None);
1185        }
1186        self.remaining -= 1;
1187        let start = match self.order.as_ref() {
1188            Some(order) => Some(order.mark(&*self.de.source)?),
1189            None => None,
1190        };
1191        let value = seed.deserialize(&mut *self.de)?;
1192        if let (Some(order), Some(start)) = (self.order.as_mut(), start) {
1193            order.check(&*self.de.source, start)?;
1194        }
1195        if let Some(free) = self.free.as_mut() {
1196            free.after_element(&mut *self.de.source, core::mem::size_of::<T::Value>())?;
1197        }
1198        Ok(Some(value))
1199    }
1200
1201    fn size_hint(&self) -> Option<usize> {
1202        // Never let a hostile count drive a visitor's pre-allocation past
1203        // what the input can back.
1204        let by_input = self.de.source.remaining_hint().unwrap_or(4096);
1205        Some(self.remaining.min(by_input))
1206    }
1207}
1208
1209struct MapAccess<'a, 's, S: ?Sized> {
1210    de: &'a mut Deserializer<'s, S>,
1211    remaining: usize,
1212    order: Option<KeyOrder>,
1213    /// Charging of entries that occupy no input.
1214    free: FreeElements,
1215    /// In-memory size of the key just read, charged with its value.
1216    key_size: usize,
1217}
1218
1219impl<'de, S: Source<'de> + ?Sized> de::MapAccess<'de> for MapAccess<'_, '_, S> {
1220    type Error = SerialError;
1221
1222    fn next_key_seed<K: de::DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>> {
1223        if self.remaining == 0 {
1224            return Ok(None);
1225        }
1226        self.remaining -= 1;
1227        self.key_size = core::mem::size_of::<K::Value>();
1228        let Some(order) = self.order.as_mut() else {
1229            return seed.deserialize(&mut *self.de).map(Some);
1230        };
1231        let start = order.mark(&*self.de.source)?;
1232        let key = seed.deserialize(&mut *self.de)?;
1233        order.check(&*self.de.source, start)?;
1234        Ok(Some(key))
1235    }
1236
1237    fn next_value_seed<V: de::DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value> {
1238        let value = seed.deserialize(&mut *self.de)?;
1239        let entry = self
1240            .key_size
1241            .saturating_add(core::mem::size_of::<V::Value>());
1242        self.free.after_element(&mut *self.de.source, entry)?;
1243        Ok(value)
1244    }
1245
1246    fn size_hint(&self) -> Option<usize> {
1247        let by_input = self.de.source.remaining_hint().unwrap_or(4096);
1248        Some(self.remaining.min(by_input))
1249    }
1250}
1251
1252impl<'de, S: Source<'de> + ?Sized> de::EnumAccess<'de> for &mut Deserializer<'_, S> {
1253    type Error = SerialError;
1254    type Variant = Self;
1255
1256    fn variant_seed<V: de::DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self)> {
1257        let tag = self.source.read_varint_u64()?;
1258        let index = u32::try_from(tag).map_err(|_| SerialError::UnknownVariant {
1259            kind: "serde enum",
1260            index: tag,
1261        })?;
1262        let deserializer: de::value::U32Deserializer<SerialError> = index.into_deserializer();
1263        let value = seed.deserialize(deserializer)?;
1264        Ok((value, self))
1265    }
1266}
1267
1268impl<'de, S: Source<'de> + ?Sized> de::VariantAccess<'de> for &mut Deserializer<'_, S> {
1269    type Error = SerialError;
1270
1271    fn unit_variant(self) -> Result<()> {
1272        Ok(())
1273    }
1274
1275    fn newtype_variant_seed<T: de::DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value> {
1276        seed.deserialize(self)
1277    }
1278
1279    fn tuple_variant<V: de::Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value> {
1280        self.visit_exact_seq(len, visitor)
1281    }
1282
1283    fn struct_variant<V: de::Visitor<'de>>(
1284        self,
1285        fields: &'static [&'static str],
1286        visitor: V,
1287    ) -> Result<V::Value> {
1288        self.visit_exact_seq(fields.len(), visitor)
1289    }
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294    use super::*;
1295    use alloc::collections::BTreeMap;
1296    use alloc::string::ToString;
1297    use alloc::vec;
1298
1299    #[derive(::serde::Serialize, ::serde::Deserialize, Debug, PartialEq)]
1300    struct Inner {
1301        a: u8,
1302        b: Option<i64>,
1303    }
1304
1305    #[test]
1306    fn test_round_trip_struct_with_map_and_seq() {
1307        let mut map = BTreeMap::new();
1308        let _ = map.insert("k".to_string(), vec![1u32, 300]);
1309        let value = (Inner { a: 7, b: Some(-9) }, map, 'x');
1310        let bytes = to_vec(&value).unwrap();
1311        let back: (Inner, BTreeMap<String, Vec<u32>>, char) = from_slice(&bytes).unwrap();
1312        assert_eq!(back, value);
1313    }
1314
1315    #[test]
1316    fn test_any_is_rejected() {
1317        #[derive(Debug)]
1318        struct Any;
1319        impl<'de> de::Deserialize<'de> for Any {
1320            fn deserialize<D: de::Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
1321                d.deserialize_any(de::IgnoredAny).map(|_| Any)
1322            }
1323        }
1324        let err = from_slice::<Any>(&[0]).unwrap_err();
1325        assert!(matches!(err, SerialError::Custom { .. }));
1326    }
1327}