Skip to main content

primitives/utils/codec/
mod.rs

1//! Fast, architecture-independent fixed-size (de)serialization.
2//!
3//! [`InPlaceCodec`] encodes a value to (and decodes it from) a fixed-size byte window directly,
4//! bypassing the per-element `serde` dispatch. The encoding is deliberately *not*
5//! required to match any external format (`serde`/`bincode`); it only has to be
6//! architecture-independent (fixed-width little-endian) and fast.
7
8use std::mem::MaybeUninit;
9
10use crate::errors::PrimitiveError;
11
12pub mod bincode_io;
13pub mod containers;
14pub mod legacy;
15pub mod prims;
16
17/// A type that can be (de)serialized to/from a fixed-size byte window directly.
18///
19/// The encoding must be *architecture-independent* (same bytes on any target — in practice
20/// fixed-width little-endian) but is otherwise this codec's own format: it need **not** match the
21/// type's `serde::Serialize`/`Deserialize` nor its `bincode` encoding.
22///
23/// # Safety
24/// Implementors must guarantee:
25/// - `write_le_bytes` initializes every one of the `ENCODED_SIZE` bytes of `out`, without reading
26///   `out` (it may be uninitialized memory).
27/// - `read_le_bytes` is unbiased: given `bytes.len() == ENCODED_SIZE`, if `write_le_bytes` could
28///   have produced `bytes`, `read_le_bytes` must return the same value.
29pub unsafe trait InPlaceCodec: Sized {
30    /// Encoded width in bytes.
31    const ENCODED_SIZE: usize;
32
33    /// Write `self`'s canonical encoding into `out`, initializing every byte.
34    /// `out.len() == Self::ENCODED_SIZE`.
35    fn write_le_bytes(&self, out: &mut [MaybeUninit<u8>]);
36
37    /// Parse `self` from `bytes`, validating it. `bytes.len() == Self::ENCODED_SIZE`.
38    /// Returns an error on an invalid (e.g. non-canonical) encoding.
39    fn read_le_bytes(bytes: &[u8]) -> Result<Self, PrimitiveError>;
40
41    /// Number of consecutive elements that encode together as a "pack". `1` (the default) means no
42    /// grouping — each element is encoded independently via [`Self::write_le_bytes`]. Must be `>=
43    /// 1`.
44    ///
45    /// Container codecs (e.g. `HeapArray<_, N>`) split a run of elements into `N / PACK` full packs
46    /// plus an `N % PACK` per-element tail. Types with `PACK > 1` must be `Copy` (see
47    /// [`Self::read_pack`]).
48    const PACK: usize = 1;
49
50    /// Bytes a full `PACK`-element pack occupies. Defaults to `PACK * ENCODED_SIZE` (the packed
51    /// bytes are exactly the per-element bytes laid out back-to-back — the case for a pure
52    /// vectorization like `Mersenne107`). Override with a smaller value for a sub-byte packing
53    /// (e.g. `Gf2`: `PACK = 8`, `PACK_BYTES = 1`).
54    const PACK_BYTES: usize = Self::PACK * Self::ENCODED_SIZE;
55
56    /// Encode exactly [`Self::PACK`] elements (`items.len() == PACK`) into `out`
57    /// (`out.len() == PACK_BYTES`), initializing every byte.
58    ///
59    /// The default encodes the group element-by-element (valid whenever
60    /// `PACK_BYTES == PACK * ENCODED_SIZE`); override it for a vectorized or sub-byte-packed
61    /// encoding.
62    fn write_pack(items: &[Self], out: &mut [MaybeUninit<u8>]) {
63        for (chunk, item) in out.chunks_exact_mut(Self::ENCODED_SIZE).zip(items) {
64            item.write_le_bytes(chunk);
65        }
66    }
67
68    /// Decode a full pack: read [`Self::PACK`] elements from `bytes` (`bytes.len() == PACK_BYTES`)
69    /// into `out` (`out.len() == PACK`), returning an error on an invalid encoding.
70    ///
71    /// The default decodes element-by-element (valid whenever `PACK_BYTES == PACK * ENCODED_SIZE`).
72    /// On an error it may leave some of `out` written; the container caller drops only *completed*
73    /// packs, so any type with `PACK > 1` must be `Copy` (partially-written packs are not dropped).
74    fn read_pack(bytes: &[u8], out: &mut [MaybeUninit<Self>]) -> Result<(), PrimitiveError> {
75        for (chunk, slot) in bytes.chunks_exact(Self::ENCODED_SIZE).zip(out.iter_mut()) {
76            slot.write(Self::read_le_bytes(chunk)?);
77        }
78        Ok(())
79    }
80
81    /// Serialize `self` into a freshly-allocated buffer of exactly `Self::ENCODED_SIZE` bytes,
82    /// bypassing per-element `serde` dispatch.
83    fn to_inplace_bytes(&self) -> Vec<u8> {
84        let mut out = Vec::with_capacity(Self::ENCODED_SIZE);
85        let spare = &mut out.spare_capacity_mut()[..Self::ENCODED_SIZE];
86        self.write_le_bytes(spare);
87        // SAFETY: `write_le_bytes` initializes every byte of `spare` above.
88        unsafe { out.set_len(Self::ENCODED_SIZE) };
89        out
90    }
91
92    /// Deserialize `Self` from exactly `Self::ENCODED_SIZE` bytes.
93    fn from_inplace_bytes(bytes: &[u8]) -> Result<Self, PrimitiveError> {
94        if bytes.len() != Self::ENCODED_SIZE {
95            return Err(PrimitiveError::InvalidSize(Self::ENCODED_SIZE, bytes.len()));
96        }
97        Self::read_le_bytes(bytes)
98    }
99}
100
101/// Whether a trailing partial group of `rem` (`0 < rem < PACK`) elements is smaller encoded
102/// individually (`rem * ENCODED_SIZE` bytes) than padded up to a full pack (`PACK_BYTES` bytes).
103/// `rem` is a plain count, never the elements' values, so the encoder and decoder always agree on
104/// this without any extra tag on the wire — see [`write_packed_le_bytes`]/[`read_packed_le_bytes`].
105const fn tail_is_unpacked<T: InPlaceCodec>(rem: usize) -> bool {
106    rem * T::ENCODED_SIZE < T::PACK_BYTES
107}
108
109/// Bytes needed for a trailing partial group of `rem` (`0 <= rem < PACK`) elements: whichever of
110/// padding to a full pack or encoding `rem` elements individually is smaller (see
111/// [`tail_is_unpacked`]).
112const fn tail_size<T: InPlaceCodec>(rem: usize) -> usize {
113    if rem == 0 {
114        0
115    } else if tail_is_unpacked::<T>(rem) {
116        rem * T::ENCODED_SIZE
117    } else {
118        T::PACK_BYTES
119    }
120}
121
122/// Shared by `HeapArray<T, M>`, `hybrid_array::Array<T, N>` and `[T; N]`'s `InPlaceCodec` impls:
123/// the `PACK`-aware encoded size, `(len / PACK) * PACK_BYTES + tail_size(len % PACK)` — see
124/// [`tail_size`]. For `PACK == 1` this reduces to `T::ENCODED_SIZE * len`.
125pub(crate) const fn packed_size<T: InPlaceCodec>(len: usize) -> usize {
126    (len / T::PACK) * T::PACK_BYTES + tail_size::<T>(len % T::PACK)
127}
128
129/// Shared by `HeapArray<T, M>`, `hybrid_array::Array<T, N>` and `[T; N]`'s `InPlaceCodec` impls:
130/// write `items` as `items.len() / PACK` full packs (each `PACK_BYTES`), plus a trailing
131/// `items.len() % PACK`-element tail encoded however [`tail_size`] says is smaller — padded up to
132/// one more full pack, or element-by-element. `out.len()` must equal
133/// `packed_size::<T>(items.len())`.
134///
135/// `T::PACK` is a constant, so the `PACK == 1` branch is compile-time-folded to a single flat loop
136/// with no per-element `write_pack` call / iterator setup — the common case (field elements,
137/// points, ...).
138pub(crate) fn write_packed_le_bytes<T: InPlaceCodec>(items: &[T], out: &mut [MaybeUninit<u8>]) {
139    if T::PACK == 1 {
140        for (chunk, elem) in out.chunks_exact_mut(T::ENCODED_SIZE).zip(items) {
141            elem.write_le_bytes(chunk);
142        }
143        return;
144    }
145    let n_full = items.len() / T::PACK;
146    let rem = items.len() % T::PACK;
147    let (packed, last) = out.split_at_mut(n_full * T::PACK_BYTES);
148    for (chunk, group) in packed
149        .chunks_exact_mut(T::PACK_BYTES)
150        .zip(items.chunks_exact(T::PACK))
151    {
152        T::write_pack(group, chunk);
153    }
154    if rem == 0 {
155        return;
156    }
157    let tail_items = &items[n_full * T::PACK..];
158    if tail_is_unpacked::<T>(rem) {
159        // Encoding the tail element-by-element is smaller than padding it to a full pack.
160        for (chunk, item) in last.chunks_exact_mut(T::ENCODED_SIZE).zip(tail_items) {
161            item.write_le_bytes(chunk);
162        }
163        return;
164    }
165    // A trailing partial group is padded with duplicates of its last element up to a full
166    // `PACK`-element pack, so `write_pack` — whose bit-packed layout depends on every
167    // element's value, not just the count — can encode it directly. The dummy values are
168    // never read back: `read_packed_le_bytes` decodes the padded pack and keeps only its
169    // first `rem` elements.
170    //
171    // SAFETY: `T::PACK > 1` requires `T: Copy` (see `read_pack`'s doc), so duplicating an
172    // element's bytes via `ptr::read` and letting the duplicate drop normally alongside the
173    // original (still owned by `items`) is exactly `Copy` semantics — no double-free.
174    let mut padded: Vec<T> = tail_items
175        .iter()
176        .map(|item| unsafe { std::ptr::read(item) })
177        .collect();
178    padded.resize_with(T::PACK, || unsafe { std::ptr::read(&tail_items[rem - 1]) });
179    T::write_pack(&padded, last);
180}
181
182/// Shared by `HeapArray<T, M>` and `hybrid_array::Array<T, N>`'s `InPlaceCodec` impls: the
183/// decoding counterpart of [`write_packed_le_bytes`]. Fills every one of `data`'s `data.len()`
184/// slots from `bytes` (`bytes.len()` must equal `packed_size::<T>(data.len())`).
185///
186/// `T` need not be `Copy`, so a partially-filled `data` on an early error return would leak (or
187/// double-free) the already-written prefix; an internal drop guard drops exactly the completed
188/// prefix and nothing else. (Types with `PACK > 1` are `Copy`, so a mid-pack failure that leaves
189/// part of a pack written has nothing to drop — see `read_pack`.)
190pub(crate) fn read_packed_le_bytes<T: InPlaceCodec>(
191    bytes: &[u8],
192    data: &mut [MaybeUninit<T>],
193) -> Result<(), PrimitiveError> {
194    let mut guard = SliceDropGuard::<T>::new(data.as_mut_ptr());
195    if T::PACK == 1 {
196        for (chunk, slot) in bytes.chunks_exact(T::ENCODED_SIZE).zip(data.iter_mut()) {
197            slot.write(T::read_le_bytes(chunk)?);
198            guard.inc_len();
199        }
200    } else {
201        let n_full = data.len() / T::PACK;
202        let rem = data.len() % T::PACK;
203        let (packed, last) = bytes.split_at(n_full * T::PACK_BYTES);
204        let mut written = 0usize;
205        for chunk in packed.chunks_exact(T::PACK_BYTES) {
206            T::read_pack(chunk, &mut data[written..written + T::PACK])?;
207            written += T::PACK;
208            guard.add_len(T::PACK);
209        }
210        if rem > 0 {
211            if tail_is_unpacked::<T>(rem) {
212                // Tail was encoded element-by-element, not padded (see `write_packed_le_bytes`).
213                for chunk in last.chunks_exact(T::ENCODED_SIZE) {
214                    data[written].write(T::read_le_bytes(chunk)?);
215                    written += 1;
216                    guard.inc_len();
217                }
218            } else {
219                // The trailing pack was padded with dummy elements up to a full `PACK`-element
220                // group on encode (see `write_packed_le_bytes`): decode it whole, then keep only
221                // the first `rem` real elements and let the owned `Vec`'s iterator drop the dummy
222                // padding.
223                let mut padded = Box::<[T]>::new_uninit_slice(T::PACK);
224                T::read_pack(last, &mut padded)?;
225                // SAFETY: `read_pack` above succeeded, so it initialized every one of the
226                // `T::PACK` slots.
227                let padded = unsafe { padded.assume_init() };
228                for item in Vec::from(padded).into_iter().take(rem) {
229                    data[written].write(item);
230                    written += 1;
231                    guard.inc_len();
232                }
233            }
234        }
235    }
236    // SAFETY: every slot of `data` was just written above (every `return`/`?` above this point is
237    // an error path, so reaching here means the loops ran to completion); forgetting the guard
238    // hands the now-fully-initialized `data` back to the caller instead of dropping it as empty.
239    std::mem::forget(guard);
240    Ok(())
241}
242
243/// Drops the initialized prefix of a `*mut MaybeUninit<T>` slice on unwind / early return.
244///
245/// Used by [`InPlaceCodec`] decoders that fill an uninitialized buffer element by element: if a
246/// mid-way decode fails, the already-written prefix must be dropped (and nothing else) to avoid
247/// leaks / double-frees for non-`Copy` `T`.
248struct SliceDropGuard<T> {
249    ptr: *mut MaybeUninit<T>,
250    initialized_len: usize,
251}
252
253impl<T> SliceDropGuard<T> {
254    fn new(ptr: *mut MaybeUninit<T>) -> Self {
255        Self {
256            ptr,
257            initialized_len: 0,
258        }
259    }
260
261    #[inline(always)]
262    #[allow(clippy::arithmetic_side_effects)]
263    fn inc_len(&mut self) {
264        self.initialized_len += 1;
265    }
266
267    #[inline(always)]
268    #[allow(clippy::arithmetic_side_effects)]
269    fn add_len(&mut self, n: usize) {
270        self.initialized_len += n;
271    }
272}
273
274impl<T> Drop for SliceDropGuard<T> {
275    #[inline(always)]
276    fn drop(&mut self) {
277        unsafe {
278            std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(
279                self.ptr.cast::<T>(),
280                self.initialized_len,
281            ));
282        }
283    }
284}