miden_base/types/
storage.rs

1use miden_base_sys::bindings::{StorageCommitmentRoot, storage};
2use miden_stdlib_sys::Word;
3
4pub trait ValueAccess<V> {
5    fn read(&self) -> V;
6    fn write(&mut self, value: V) -> (StorageCommitmentRoot, V);
7}
8
9pub struct Value {
10    pub slot: u8,
11}
12
13impl<V: Into<Word> + From<Word>> ValueAccess<V> for Value {
14    /// Returns an item value from the account storage.
15    #[inline(always)]
16    fn read(&self) -> V {
17        storage::get_item(self.slot).into()
18    }
19
20    /// Sets an item `value` in the account storage and returns (new_root, old_value)
21    /// Where:
22    /// - new_root is the new storage commitment.
23    /// - old_value is the previous value of the item.
24    #[inline(always)]
25    fn write(&mut self, value: V) -> (StorageCommitmentRoot, V) {
26        let (root, old_word) = storage::set_item(self.slot, value.into());
27        (root, old_word.into())
28    }
29}
30
31pub trait StorageMapAccess<K, V> {
32    /// Returns a map item value for `key` from the account storage.
33    fn get(&self, key: &K) -> V;
34    /// Sets a map item `value` for `key` in the account storage and returns (old_root, old_value)
35    fn set(&mut self, key: K, value: V) -> (StorageCommitmentRoot, V);
36}
37
38pub struct StorageMap {
39    pub slot: u8,
40}
41
42impl<K: Into<Word> + AsRef<Word>, V: From<Word> + Into<Word>> StorageMapAccess<K, V>
43    for StorageMap
44{
45    /// Returns a map item value from the account storage.
46    #[inline(always)]
47    fn get(&self, key: &K) -> V {
48        storage::get_map_item(self.slot, key.as_ref()).into()
49    }
50
51    /// Sets a map item `value` in the account storage and returns (old_root, old_value)
52    /// Where:
53    /// - old_root is the old map root.
54    /// - old_value is the previous value of the item.
55    #[inline(always)]
56    fn set(&mut self, key: K, value: V) -> (StorageCommitmentRoot, V) {
57        let (root, old_word) = storage::set_map_item(self.slot, key.into(), value.into());
58        (root, old_word.into())
59    }
60}