Skip to main content

ic_wire/packed/
mod.rs

1//! Explicit fixed-width little-endian packed fields with optional element bounds.
2// Contract and minimal algorithm adapted from pinned IC Wire; see docs/design/packed.md.
3
4#[cfg(test)]
5mod tests;
6
7use crate::Error;
8use alloc::vec::Vec;
9use core::{fmt, marker::PhantomData};
10use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
11
12/// Qualified fixed-width packed words. Sealed; arbitrary-bit casts never admit
13/// booleans, nonzero integers or floating-point domain values.
14pub trait PackedElement: word::Word {}
15mod word {
16    pub trait Word: bytemuck::Pod + core::fmt::Debug + Eq {
17        const SCHEMA: &'static str;
18        fn extend_words(output: &mut alloc::vec::Vec<Self>, bytes: &[u8]);
19        fn append(self, bytes: &mut alloc::vec::Vec<u8>);
20    }
21    macro_rules! integer {
22        ($($ty:ty),+) => {$(
23            impl super::PackedElement for $ty {}
24            impl Word for $ty {
25                const SCHEMA: &'static str = stringify!($ty);
26                fn extend_words(output: &mut alloc::vec::Vec<Self>, bytes: &[u8]) {
27                    output.extend(bytes.as_chunks::<{ size_of::<Self>() }>().0.iter().copied().map(Self::from_le_bytes));
28                }
29                fn append(self, bytes: &mut alloc::vec::Vec<u8>) { bytes.extend_from_slice(&self.to_le_bytes()); }
30            }
31        )+};
32    }
33    integer!(i8, i16, u16, i32, u32, i64, u64);
34    macro_rules! opaque {
35        ($n:literal,$schema:literal) => {
36            impl super::PackedElement for [u8; $n] {}
37            impl Word for [u8; $n] {
38                const SCHEMA: &'static str = $schema;
39                fn extend_words(output: &mut alloc::vec::Vec<Self>, bytes: &[u8]) {
40                    output.extend_from_slice(bytes.as_chunks::<$n>().0);
41                }
42
43                fn append(self, bytes: &mut alloc::vec::Vec<u8>) {
44                    bytes.extend_from_slice(&self);
45                }
46            }
47        };
48    }
49    opaque!(16, "hash16");
50    opaque!(32, "hash32");
51}
52
53/// Explicit fixed-width little-endian byte buffer. Prefix counts bytes, not
54/// elements. Ordinary vectors retain their original Serde representation.
55/// N limits the number of words; the default is unbounded apart from codec limits.
56///
57/// ```compile_fail
58/// let value = ic_wire::Packed::<f32>::new(vec![1.0_f32]).unwrap();
59/// fn serializable(_: impl serde::Serialize) {}
60/// serializable(value);
61/// ```
62#[derive(Clone, Debug, Eq, PartialEq)]
63pub struct Packed<T, const N: usize = { usize::MAX }>(Vec<T>);
64impl<T, const N: usize> Packed<T, N> {
65    /// Admit owned words without copying; codec limits also apply on traversal.
66    /// # Errors
67    /// Returns [`Error::Limit`] when the element count exceeds N.
68    pub fn new(words: Vec<T>) -> Result<Self, Error> {
69        if words.len() > N {
70            Err(Error::Limit(crate::LimitKind::Field))
71        } else {
72            Ok(Self(words))
73        }
74    }
75
76    /// Borrow the words.
77    #[must_use]
78    pub fn as_slice(&self) -> &[T] {
79        &self.0
80    }
81
82    /// Recover storage without copying.
83    #[must_use]
84    pub fn into_vec(self) -> Vec<T> {
85        self.0
86    }
87}
88impl<T: PackedElement, const N: usize> Serialize for Packed<T, N> {
89    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
90        serialize_words(&self.0, serializer)
91    }
92}
93impl<'de, T: PackedElement, const N: usize> Deserialize<'de> for Packed<T, N> {
94    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
95        deserializer
96            .deserialize_bytes(PackedVisitor::<T> {
97                limit: N,
98                marker: PhantomData,
99            })
100            .map(Self)
101    }
102}
103
104pub(crate) fn serialize_words<T: PackedElement, S: Serializer>(
105    words: &[T],
106    serializer: S,
107) -> Result<S::Ok, S::Error> {
108    if cfg!(target_endian = "little") {
109        serializer.serialize_bytes(bytemuck::must_cast_slice(words))
110    } else {
111        let bytes = little_endian_bytes::<T, S::Error>(words)?;
112        serializer.serialize_bytes(&bytes)
113    }
114}
115
116// Compiled in native tests as well as on big-endian targets, so conversion is
117// exercised without claiming a native big-endian execution result.
118fn little_endian_bytes<T: PackedElement, E: serde::ser::Error>(words: &[T]) -> Result<Vec<u8>, E> {
119    let length = words
120        .len()
121        .checked_mul(size_of::<T>())
122        .ok_or_else(|| E::custom("length overflow"))?;
123    let mut bytes = Vec::new();
124    bytes
125        .try_reserve_exact(length)
126        .map_err(|_| E::custom("allocation"))?;
127    for word in words {
128        word.append(&mut bytes);
129    }
130    Ok(bytes)
131}
132
133// Returning Vec keeps traversal accounting independent of the wrapper. The runtime
134// bound keeps one allocation/copy body rather than duplicating it per N.
135struct PackedVisitor<T> {
136    limit: usize,
137    marker: PhantomData<T>,
138}
139
140impl<T: PackedElement> de::Visitor<'_> for PackedVisitor<T> {
141    type Value = Vec<T>;
142
143    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
144        formatter.write_str("packed little-endian words")
145    }
146
147    fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
148        let width = size_of::<T>();
149        if !bytes.len().is_multiple_of(width) || bytes.len() / width > self.limit {
150            return Err(E::custom("invalid packed length"));
151        }
152        let mut values = Vec::new();
153        values
154            .try_reserve_exact(bytes.len() / width)
155            .map_err(|_| E::custom("allocation"))?;
156        T::extend_words(&mut values, bytes);
157        Ok(values)
158    }
159}