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