Skip to main content

calimero_runtime/
store.rs

1use core::fmt::Debug;
2use std::collections::btree_map::IntoIter;
3use std::collections::BTreeMap;
4
5use tracing::debug;
6
7use calimero_primitives::reflect::Reflect;
8
9pub type Key = Vec<u8>;
10pub type Value = Vec<u8>;
11
12pub trait Storage: Reflect {
13    fn get(&self, key: &Key) -> Option<Value>;
14    fn set(&mut self, key: Key, value: Value) -> Option<Value>;
15    fn remove(&mut self, key: &Key) -> Option<Vec<u8>>;
16    fn has(&self, key: &Key) -> bool;
17}
18
19#[derive(Debug, Default)]
20pub struct InMemoryStorage {
21    inner: BTreeMap<Key, Value>,
22}
23
24impl Storage for InMemoryStorage {
25    fn get(&self, key: &Key) -> Option<Value> {
26        debug!(target: "runtime::storage::memory", key_len = key.len(), "InMemoryStorage::get");
27        self.inner.get(key).cloned()
28    }
29
30    fn set(&mut self, key: Key, value: Value) -> Option<Value> {
31        debug!(
32            target: "runtime::storage::memory",
33            key_len = key.len(),
34            value_len = value.len(),
35            "InMemoryStorage::set"
36        );
37        self.inner.insert(key, value)
38    }
39
40    // todo! revisit this, should we return the value by default?
41    fn remove(&mut self, key: &Key) -> Option<Vec<u8>> {
42        debug!(target: "runtime::storage::memory", key_len = key.len(), "InMemoryStorage::remove");
43        self.inner.remove(key)
44    }
45
46    fn has(&self, key: &Key) -> bool {
47        debug!(target: "runtime::storage::memory", key_len = key.len(), "InMemoryStorage::has");
48        self.inner.contains_key(key)
49    }
50}
51
52impl IntoIterator for InMemoryStorage {
53    type Item = (Key, Value);
54
55    type IntoIter = IntoIter<Key, Value>;
56
57    fn into_iter(self) -> Self::IntoIter {
58        self.inner.into_iter()
59    }
60}