oasis_contract_sdk_storage/
cell.rs

1//! Low-level storage primitive that holds one value.
2use std::marker::PhantomData;
3
4use oasis_contract_sdk::storage::{ConfidentialStore, PublicStore};
5
6macro_rules! declare_cell {
7    ($name:ident, $store:ident) => {
8        /// A storage cell identifies a storage key of a specific type.
9        pub struct $name<'key, T> {
10            key: &'key [u8],
11            _type: PhantomData<T>,
12        }
13
14        impl<'key, T> $name<'key, T> {
15            /// Create a new storage cell with the specified key and type.
16            pub const fn new(key: &'key [u8]) -> Self {
17                Self {
18                    key,
19                    _type: PhantomData,
20                }
21            }
22
23            /// Clear the value in the storage cell.
24            pub fn clear(&self, store: &mut dyn $store) {
25                store.remove(self.key);
26            }
27        }
28
29        impl<'key, T> $name<'key, T>
30        where
31            T: cbor::Decode,
32        {
33            /// Return the current value of the storage cell.
34            ///
35            /// # Panics
36            ///
37            /// The method will panic in case the raw cell value cannot be deserialized.
38            ///
39            pub fn get(&self, store: &dyn $store) -> Option<T> {
40                store
41                    .get(self.key)
42                    .map(|raw| cbor::from_slice(&raw).unwrap())
43            }
44        }
45
46        impl<'key, T> $name<'key, T>
47        where
48            T: cbor::Encode,
49        {
50            /// Set the value of the storage cell.
51            pub fn set(&self, store: &mut dyn $store, value: T) {
52                store.insert(self.key, &cbor::to_vec(value));
53            }
54        }
55    };
56}
57
58declare_cell!(PublicCell, PublicStore);
59declare_cell!(ConfidentialCell, ConfidentialStore);