canic_utils/macros/
storable.rs

1//! Derive `ic-stable-structures` storage traits using Mini CBOR serialization.
2//!
3//! The helper macros below wire types into the Canister Development Kit's
4//! `Storable` trait by delegating to Canic's MiniCBOR helpers. The bounded
5//! variant requires callers to specify a maximum serialized size and whether
6//! the size is fixed; the unbounded variant is suitable for archival data
7//! that can grow, at the cost of larger metadata cells.
8
9/// Implement [`Storable`](ic_stable_structures::storable::Storable) with a
10/// bounded size guarantee.
11#[macro_export]
12macro_rules! impl_storable_bounded {
13    ($ident:ident, $max_size:expr, $is_fixed_size:expr) => {
14        impl $crate::cdk::structures::storable::Storable for $ident {
15            const BOUND: $crate::cdk::structures::storable::Bound =
16                $crate::cdk::structures::storable::Bound::Bounded {
17                    max_size: $max_size,
18                    is_fixed_size: $is_fixed_size,
19                };
20
21            fn to_bytes(&self) -> ::std::borrow::Cow<'_, [u8]> {
22                ::std::borrow::Cow::Owned($crate::serialize::serialize(self).unwrap())
23            }
24
25            fn into_bytes(self) -> Vec<u8> {
26                $crate::serialize::serialize(&self).unwrap()
27            }
28
29            fn from_bytes(bytes: ::std::borrow::Cow<'_, [u8]>) -> Self {
30                $crate::serialize::deserialize(&bytes).unwrap()
31            }
32        }
33    };
34}
35
36/// Implement [`Storable`](ic_stable_structures::storable::Storable) without a
37/// size bound.
38#[macro_export]
39macro_rules! impl_storable_unbounded {
40    ($ident:ident) => {
41        impl $crate::cdk::structures::storable::Storable for $ident {
42            const BOUND: $crate::cdk::structures::storable::Bound =
43                $crate::cdk::structures::storable::Bound::Unbounded;
44
45            fn to_bytes(&self) -> ::std::borrow::Cow<'_, [u8]> {
46                ::std::borrow::Cow::Owned($crate::serialize::serialize(self).unwrap())
47            }
48
49            fn into_bytes(self) -> Vec<u8> {
50                $crate::serialize::serialize(&self).unwrap()
51            }
52
53            fn from_bytes(bytes: ::std::borrow::Cow<'_, [u8]>) -> Self {
54                $crate::serialize::deserialize(&bytes).unwrap()
55            }
56        }
57    };
58}