Skip to main content

pack_io/
traits.rs

1//! The [`Serialize`] and [`Deserialize`] traits.
2//!
3//! These are the seam between a Rust value and its wire-format bytes. They
4//! are generic over the [`Encode`] / [`Decode`] behaviour traits, so a single
5//! `impl Serialize` works through both the in-memory [`crate::Encoder`] and
6//! the streaming [`crate::IoEncoder`].
7//!
8//! The built-in primitive and collection implementations live in
9//! [`crate::impls`]. User-defined types either implement these traits
10//! directly or — with the `derive` feature on — derive them with
11//! `#[derive(pack_io::Serialize, pack_io::Deserialize)]`. The derive macro
12//! writes a sound, deterministic implementation for any struct or enum
13//! whose fields are themselves `Serialize` / `Deserialize`.
14
15use alloc::vec::Vec;
16
17use crate::codec::{Decode, Encode, SizeCounter, decode_elements_counted, initial_capacity};
18use crate::error::{Result, SerialError};
19
20/// Types that know how to write themselves into any [`Encode`] sink.
21///
22/// The contract is: `serialize` appends the type's wire-format bytes to the
23/// encoder. It does **not** clear the encoder first — encoders are
24/// stream-shaped, and may already hold bytes from prior writes.
25///
26/// Implementors MUST be deterministic: for any two equal values `a` and `b`
27/// (in the type's `Eq` / `PartialEq` sense, or its semantic equivalent for
28/// types like `f64`), the bytes appended by `a.serialize(&mut enc)` MUST
29/// equal the bytes appended by `b.serialize(&mut enc)`.
30///
31/// # Examples
32///
33/// ```
34/// use pack_io::{Encode, Encoder, Result, Serialize};
35///
36/// struct Point { x: i32, y: i32 }
37///
38/// impl Serialize for Point {
39///     fn serialize<E: Encode + ?Sized>(&self, enc: &mut E) -> Result<()> {
40///         self.x.serialize(enc)?;
41///         self.y.serialize(enc)
42///     }
43/// }
44///
45/// let mut enc = Encoder::new();
46/// Point { x: 3, y: -7 }.serialize(&mut enc).unwrap();
47/// assert!(!enc.as_bytes().is_empty());
48/// ```
49pub trait Serialize {
50    /// Append the encoded bytes of `self` to `encoder`.
51    ///
52    /// # Errors
53    ///
54    /// Primitive impls in this crate are infallible on the in-memory
55    /// [`crate::Encoder`]. Streaming encoders (`IoEncoder<W>`) may surface
56    /// a [`crate::SerialError`] when the underlying `Write` errors. User
57    /// impls may also surface custom errors via [`crate::SerialError`].
58    fn serialize<E: Encode + ?Sized>(&self, encoder: &mut E) -> Result<()>;
59
60    /// Append the encoded bytes of every element of `slice` to `encoder`.
61    ///
62    /// The default implementation calls [`Serialize::serialize`] once per
63    /// element. Types that can take advantage of a single bulk operation
64    /// — most importantly `u8`, which compiles down to a single
65    /// `extend_from_slice` / `Write::write_all` instead of N individual
66    /// pushes — override this to skip the per-element loop overhead.
67    ///
68    /// **This method is the seam that makes `Vec<u8>` encode at memcpy
69    /// speed without forcing `unsafe` or specialisation onto the public
70    /// trait surface.** The `[T]::serialize` impl calls
71    /// `T::serialize_slice(self, encoder)` rather than looping inline, so
72    /// any `Serialize` impl that overrides `serialize_slice` automatically
73    /// applies to every `&[T]`, `Vec<T>`, `[T; N]`, and `&[u8]`-shaped
74    /// payload that flows through it.
75    ///
76    /// # Errors
77    ///
78    /// Propagates any error returned by the per-element / bulk operation.
79    #[inline]
80    fn serialize_slice<E: Encode + ?Sized>(slice: &[Self], encoder: &mut E) -> Result<()>
81    where
82        Self: Sized,
83    {
84        for item in slice {
85            item.serialize(encoder)?;
86        }
87        Ok(())
88    }
89
90    /// Exact number of bytes [`Serialize::serialize`] appends for `self`.
91    ///
92    /// The default runs `serialize` against a counting sink that stores
93    /// nothing, so it is always correct but costs one encode pass. The
94    /// built-in impls and the derive macro override it with direct
95    /// arithmetic (a `String` is `varint_len(len) + len`, a map sums its
96    /// entries without sorting them, …).
97    ///
98    /// Use it to size a buffer exactly before encoding
99    /// (`Encoder::with_capacity(v.encoded_len()?)`), or to write a length
100    /// prefix without encoding the value twice. Versioned structs use it to
101    /// write their body length up front instead of buffering the body.
102    ///
103    /// **Overrides MUST return exactly the number of bytes `serialize`
104    /// writes.** A versioned struct that contains a value whose override
105    /// over- or under-counts produces a corrupt frame.
106    ///
107    /// # Errors
108    ///
109    /// Whatever [`Serialize::serialize`] would return for this value.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use pack_io::{Encoder, Serialize};
115    ///
116    /// let value = (7_u64, String::from("hello"), vec![1_u32, 2, 300]);
117    /// let len = value.encoded_len().unwrap();
118    ///
119    /// let mut enc = Encoder::with_capacity(len); // exactly one allocation
120    /// value.serialize(&mut enc).unwrap();
121    /// assert_eq!(enc.as_bytes().len(), len);
122    /// ```
123    #[inline]
124    fn encoded_len(&self) -> Result<usize> {
125        let mut counter = SizeCounter::default();
126        self.serialize(&mut counter)?;
127        Ok(counter.count())
128    }
129
130    /// Exact number of bytes [`Serialize::serialize_slice`] appends for
131    /// `slice` (no length prefix). Counterpart of
132    /// [`Serialize::encoded_len`]; `u8` overrides it to return
133    /// `slice.len()` without iterating.
134    ///
135    /// # Errors
136    ///
137    /// Whatever the per-element [`Serialize::encoded_len`] returns.
138    #[inline]
139    fn encoded_len_slice(slice: &[Self]) -> Result<usize>
140    where
141        Self: Sized,
142    {
143        slice.iter().try_fold(0usize, |acc, item| {
144            Ok(acc.saturating_add(item.encoded_len()?))
145        })
146    }
147}
148
149/// Types that know how to read themselves from any [`Decode`] source.
150///
151/// The contract is: `deserialize` consumes exactly the bytes that a
152/// corresponding `Serialize` would have produced for the returned value, no
153/// more and no fewer. On any malformed input it MUST return an error and
154/// MUST NOT panic, allocate unboundedly, or read past the decoder's
155/// underlying source.
156///
157/// Hand-written impls for **recursive** types should bracket their body
158/// with [`Decode::enter_nested`] / [`Decode::leave_nested`] so that
159/// [`crate::Config::max_depth`] bounds the recursion (derived impls do this
160/// automatically).
161///
162/// Round-trip invariant:
163/// `decode::<T>(&encode(&v)?)? == v` for every `v: T`.
164///
165/// # Examples
166///
167/// ```
168/// use pack_io::{Decode, Decoder, Deserialize, Result, encode};
169///
170/// struct Point { x: i32, y: i32 }
171///
172/// impl Deserialize for Point {
173///     fn deserialize<D: Decode + ?Sized>(dec: &mut D) -> Result<Self> {
174///         Ok(Point {
175///             x: i32::deserialize(dec)?,
176///             y: i32::deserialize(dec)?,
177///         })
178///     }
179/// }
180///
181/// # impl pack_io::Serialize for Point {
182/// #     fn serialize<E: pack_io::Encode + ?Sized>(&self, e: &mut E) -> Result<()> {
183/// #         self.x.serialize(e)?;
184/// #         self.y.serialize(e)
185/// #     }
186/// # }
187/// let bytes = encode(&Point { x: 3, y: -7 }).unwrap();
188/// let mut dec = Decoder::new(&bytes);
189/// let back = Point::deserialize(&mut dec).unwrap();
190/// assert_eq!((back.x, back.y), (3, -7));
191/// ```
192pub trait Deserialize: Sized {
193    /// Read a value of `Self` from the decoder, advancing its cursor.
194    ///
195    /// # Errors
196    ///
197    /// Any [`crate::SerialError`] the underlying byte reads surface
198    /// (truncated input, invalid length prefix, hostile varint, …).
199    fn deserialize<D: Decode + ?Sized>(decoder: &mut D) -> Result<Self>;
200
201    /// Read `count` consecutive `Self` values into a freshly-allocated `Vec`.
202    ///
203    /// The default implementation calls [`Deserialize::deserialize`] in a
204    /// loop. Types whose batch read can be done in a single bulk operation
205    /// — most importantly `u8`, which compiles down to a single
206    /// `Read::read_exact` instead of N individual byte reads — override
207    /// this for the memcpy-class fast path.
208    ///
209    /// **This method is the seam that makes `Vec<u8>` decode at memcpy
210    /// speed without forcing `unsafe` or specialisation onto the public
211    /// trait surface.** The `Vec<T>::deserialize` impl calls
212    /// `T::deserialize_many(decoder, len)` rather than looping inline.
213    ///
214    /// Implementations MUST NOT size an allocation from `count` alone. The
215    /// caller has validated `count` against [`crate::Config::max_alloc`],
216    /// but that is a per-value cap, not proof the input holds `count`
217    /// elements. The default pre-allocates at most the smaller of `count`,
218    /// the decoder's [`Decode::remaining_hint`], and 64 KiB worth of
219    /// `Self` (4 KiB when the remaining input is unknown), then grows as
220    /// elements actually decode. Elements that consume no input bytes are
221    /// charged `size_of::<Self>()` each (at least 1) through
222    /// [`Decode::charge_unbacked`], so a count of free elements is bounded
223    /// by `max_alloc` across the whole decode.
224    ///
225    /// # Errors
226    ///
227    /// Propagates any error returned by the per-element / bulk read, and
228    /// [`crate::SerialError::InvalidLength`] when free elements exceed the
229    /// budget.
230    fn deserialize_many<D: Decode + ?Sized>(decoder: &mut D, count: usize) -> Result<Vec<Self>> {
231        let mut out = Vec::with_capacity(initial_capacity::<Self, D>(count, decoder));
232        decode_elements_counted::<Self, D, _>(decoder, count, |decoder| {
233            out.push(Self::deserialize(decoder)?);
234            Ok(())
235        })?;
236        Ok(out)
237    }
238
239    /// Read `N` consecutive `Self` values into an array.
240    ///
241    /// The default decodes into a temporary `Vec` and converts it (building
242    /// an array of a generic `T` element by element needs either `unsafe`
243    /// or the unstable `core::array::try_from_fn`). The primitive impls
244    /// override it with a stack array: `u8` with a single read, so
245    /// `[u8; N]` (hashes, keys, fixed-width identifiers) is one copy, and
246    /// the other integers, floats, `bool` and `char` by filling a
247    /// zero-initialised array, so none of them touch the heap.
248    ///
249    /// # Errors
250    ///
251    /// Propagates any error returned by the per-element / bulk read.
252    fn deserialize_array<D: Decode + ?Sized, const N: usize>(decoder: &mut D) -> Result<[Self; N]> {
253        let mut out: Vec<Self> = Vec::with_capacity(N);
254        for _ in 0..N {
255            out.push(Self::deserialize(decoder)?);
256        }
257        // Exactly `N` elements were pushed above, so the conversion cannot
258        // fail; map the impossible case to an error rather than panicking.
259        out.try_into()
260            .map_err(|_| SerialError::custom("array length mismatch"))
261    }
262}