Skip to main content

miden_base/types/
storage.rs

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