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