Skip to main content

ic_storage/
storable.rs

1//! Storage-owned record codec contract. Application records normally use IC Wire.
2use std::borrow::Cow;
3
4///
5/// Bound
6///
7/// Maximum encoded record size, with an optional exact-width requirement.
8///
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum Bound {
11    /// No type-level bound; collection resource limits still apply.
12    Unbounded,
13    /// A finite encoded-size limit.
14    Bounded {
15        /// Maximum encoded byte count.
16        max_size: u32,
17        /// Whether every encoding must have exactly the maximum length.
18        is_fixed_size: bool,
19    },
20}
21
22impl Bound {
23    pub(crate) const fn check(self, bytes: &[u8]) {
24        if let Self::Bounded {
25            max_size,
26            is_fixed_size,
27        } = self
28            && !(bytes.len() <= max_size as usize
29                && (!is_fixed_size || bytes.len() == max_size as usize))
30        {
31            panic!("record violates codec bound");
32        }
33    }
34}
35
36///
37/// Storable
38///
39/// Encode and decode a collection record. The caller owns its schema; Storage
40/// enforces its declared byte bound before writes and after reading bytes.
41/// Collection checks are independent of overrides of the convenience helpers.
42///
43pub trait Storable: Sized {
44    /// Record size contract.
45    const BOUND: Bound;
46    /// Borrow or allocate an encoding.
47    ///
48    fn to_bytes(&self) -> Cow<'_, [u8]>;
49    /// Consume a value into its encoding.
50    ///
51    fn into_bytes(self) -> Vec<u8> {
52        self.to_bytes().into_owned()
53    }
54    /// Decode application bytes, trapping on invalid encodings.
55    ///
56    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self;
57    /// Optional comparison of a typed key with a bound-checked stored encoding.
58    /// It must agree with decoded ordering and reject the same invalid records.
59    const CMP_ENCODED: Option<fn(&Self, &[u8]) -> std::cmp::Ordering> = None;
60    /// Enforce the declared maximum and exact width where applicable.
61    ///
62    fn check_bounds(bytes: &[u8]) {
63        Self::BOUND.check(bytes)
64    }
65    /// Encode and enforce the declared bound.
66    ///
67    fn to_bytes_checked(&self) -> Cow<'_, [u8]> {
68        let bytes = self.to_bytes();
69        Self::BOUND.check(&bytes);
70        bytes
71    }
72    /// Consume, encode and enforce the declared bound.
73    ///
74    fn into_bytes_checked(self) -> Vec<u8> {
75        let bytes = self.into_bytes();
76        Self::BOUND.check(&bytes);
77        bytes
78    }
79}
80
81macro_rules! integer {
82    ($($ty:ty),* $(,)?) => {$ (
83        impl Storable for $ty {
84            const BOUND: Bound = Bound::Bounded { max_size: size_of::<Self>() as u32, is_fixed_size: true };
85            fn to_bytes(&self) -> Cow<'_, [u8]> { Cow::Owned(self.to_le_bytes().to_vec()) }
86            fn from_bytes(bytes: Cow<'_, [u8]>) -> Self { Self::from_le_bytes(bytes.as_ref().try_into().expect("integer width")) }
87        }
88    )*};
89}
90integer!(u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64);
91impl Storable for u8 {
92    const BOUND: Bound = Bound::Bounded {
93        max_size: 1,
94        is_fixed_size: true,
95    };
96    fn to_bytes(&self) -> Cow<'_, [u8]> {
97        Cow::Borrowed(std::slice::from_ref(self))
98    }
99    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
100        Self::from_le_bytes(bytes.as_ref().try_into().expect("integer width"))
101    }
102}
103impl Storable for () {
104    const BOUND: Bound = Bound::Bounded {
105        max_size: 0,
106        is_fixed_size: true,
107    };
108    fn to_bytes(&self) -> Cow<'_, [u8]> {
109        Cow::Borrowed(&[])
110    }
111    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
112        Self::check_bounds(&bytes)
113    }
114}
115impl Storable for bool {
116    const BOUND: Bound = Bound::Bounded {
117        max_size: 1,
118        is_fixed_size: true,
119    };
120    fn to_bytes(&self) -> Cow<'_, [u8]> {
121        Cow::Borrowed(if *self { &[1] } else { &[0] })
122    }
123    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
124        match bytes.as_ref() {
125            [0] => false,
126            [1] => true,
127            _ => panic!("invalid boolean encoding"),
128        }
129    }
130}
131impl Storable for Vec<u8> {
132    const CMP_ENCODED: Option<fn(&Self, &[u8]) -> std::cmp::Ordering> =
133        Some(|key, stored| key.as_slice().cmp(stored));
134    const BOUND: Bound = Bound::Unbounded;
135    fn to_bytes(&self) -> Cow<'_, [u8]> {
136        Cow::Borrowed(self)
137    }
138    fn into_bytes(self) -> Vec<u8> {
139        self
140    }
141    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
142        bytes.into_owned()
143    }
144}
145impl Storable for String {
146    const CMP_ENCODED: Option<fn(&Self, &[u8]) -> std::cmp::Ordering> = Some(|key, stored| {
147        key.as_str()
148            .cmp(std::str::from_utf8(stored).expect("invalid UTF-8 record"))
149    });
150    const BOUND: Bound = Bound::Unbounded;
151    fn to_bytes(&self) -> Cow<'_, [u8]> {
152        Cow::Borrowed(self.as_bytes())
153    }
154    fn into_bytes(self) -> Vec<u8> {
155        self.into_bytes()
156    }
157    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
158        Self::from_utf8(bytes.into_owned()).expect("invalid UTF-8 record")
159    }
160}
161impl<const N: usize> Storable for [u8; N] {
162    const BOUND: Bound = Bound::Bounded {
163        max_size: {
164            assert!(N <= u32::MAX as usize);
165            N as u32
166        },
167        is_fixed_size: true,
168    };
169    fn to_bytes(&self) -> Cow<'_, [u8]> {
170        Cow::Borrowed(self)
171    }
172    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
173        bytes.as_ref().try_into().expect("invalid byte array width")
174    }
175}
176impl<T: Storable> Storable for Option<T> {
177    const BOUND: Bound = match T::BOUND {
178        Bound::Unbounded => Bound::Unbounded,
179        Bound::Bounded { max_size, .. } => Bound::Bounded {
180            max_size: max_size.checked_add(1).expect("optional bound overflow"),
181            is_fixed_size: false,
182        },
183    };
184    fn to_bytes(&self) -> Cow<'_, [u8]> {
185        let mut bytes = vec![u8::from(self.is_some())];
186        if let Some(value) = self {
187            bytes.extend_from_slice(&value.to_bytes_checked());
188        }
189        Cow::Owned(bytes)
190    }
191    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
192        match bytes.as_ref().split_first() {
193            Some((0, [])) => None,
194            Some((1, payload)) => {
195                T::check_bounds(payload);
196                Some(T::from_bytes(Cow::Borrowed(payload)))
197            }
198            _ => panic!("invalid optional record tag"),
199        }
200    }
201}
202
203const fn pair_bound(left: Bound, right: Bound) -> Bound {
204    match (left, right) {
205        (
206            Bound::Bounded {
207                max_size: a,
208                is_fixed_size: af,
209            },
210            Bound::Bounded {
211                max_size: b,
212                is_fixed_size: bf,
213            },
214        ) => {
215            let width = a as u64 + b as u64 + 4;
216            if width <= u32::MAX as u64 {
217                Bound::Bounded {
218                    max_size: width as u32,
219                    is_fixed_size: af && bf,
220                }
221            } else {
222                Bound::Unbounded
223            }
224        }
225        _ => Bound::Unbounded,
226    }
227}
228
229// All tuple components except the last carry a four-byte length.
230fn push_component(bytes: &mut Vec<u8>, component: &[u8]) {
231    let length = u32::try_from(component.len()).expect("tuple component exceeds u32");
232    bytes.extend_from_slice(&length.to_le_bytes());
233    bytes.extend_from_slice(component);
234}
235
236fn take_component<T: Storable>(bytes: &mut &[u8]) -> T {
237    let (prefix, payload) = bytes.split_at(4);
238    let length = u32::from_le_bytes(prefix.try_into().unwrap()) as usize;
239    let (component, rest) = payload.split_at(length);
240    *bytes = rest;
241    decode_component(component)
242}
243
244fn decode_component<T: Storable>(bytes: &[u8]) -> T {
245    T::BOUND.check(bytes);
246    T::from_bytes(Cow::Borrowed(bytes))
247}
248
249impl<A: Storable, B: Storable> Storable for (A, B) {
250    const BOUND: Bound = pair_bound(A::BOUND, B::BOUND);
251
252    fn to_bytes(&self) -> Cow<'_, [u8]> {
253        let left = self.0.to_bytes();
254        let right = self.1.to_bytes();
255        A::BOUND.check(&left);
256        B::BOUND.check(&right);
257        let mut bytes = Vec::with_capacity(4 + left.len() + right.len());
258        push_component(&mut bytes, &left);
259        bytes.extend_from_slice(&right);
260        Cow::Owned(bytes)
261    }
262
263    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
264        let mut payload = bytes.as_ref();
265        (take_component(&mut payload), decode_component(payload))
266    }
267}
268
269impl<A: Storable, B: Storable, C: Storable> Storable for (A, B, C) {
270    const BOUND: Bound = pair_bound(A::BOUND, pair_bound(B::BOUND, C::BOUND));
271
272    fn to_bytes(&self) -> Cow<'_, [u8]> {
273        let a = self.0.to_bytes();
274        let b = self.1.to_bytes();
275        let c = self.2.to_bytes();
276        A::BOUND.check(&a);
277        B::BOUND.check(&b);
278        C::BOUND.check(&c);
279        let mut bytes = Vec::with_capacity(8 + a.len() + b.len() + c.len());
280        push_component(&mut bytes, &a);
281        push_component(&mut bytes, &b);
282        bytes.extend_from_slice(&c);
283        Cow::Owned(bytes)
284    }
285
286    fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
287        let mut payload = bytes.as_ref();
288        (
289            take_component(&mut payload),
290            take_component(&mut payload),
291            decode_component(payload),
292        )
293    }
294}