icydb_core/db/data/
store.rs1use crate::db::data::{CanonicalRow, DataKey, RawDataKey, RawRow};
7use canic_cdk::structures::{BTreeMap, DefaultMemoryImpl, memory::VirtualMemory};
8
9pub struct DataStore {
19 map: BTreeMap<RawDataKey, RawRow, VirtualMemory<DefaultMemoryImpl>>,
20}
21
22impl DataStore {
23 #[must_use]
25 pub fn init(memory: VirtualMemory<DefaultMemoryImpl>) -> Self {
26 Self {
27 map: BTreeMap::init(memory),
28 }
29 }
30
31 pub(in crate::db) fn insert(&mut self, key: RawDataKey, row: CanonicalRow) -> Option<RawRow> {
33 self.map.insert(key, row.into_raw_row())
34 }
35
36 #[cfg(test)]
38 pub(crate) fn insert_raw_for_test(&mut self, key: RawDataKey, row: RawRow) -> Option<RawRow> {
39 self.map.insert(key, row)
40 }
41
42 pub fn remove(&mut self, key: &RawDataKey) -> Option<RawRow> {
44 self.map.remove(key)
45 }
46
47 pub fn get(&self, key: &RawDataKey) -> Option<RawRow> {
49 self.map.get(key)
50 }
51
52 #[must_use]
54 pub fn contains(&self, key: &RawDataKey) -> bool {
55 self.map.contains_key(key)
56 }
57
58 pub fn clear(&mut self) {
60 self.map.clear();
61 }
62
63 pub fn memory_bytes(&self) -> u64 {
65 self.iter()
67 .map(|entry| DataKey::STORED_SIZE_BYTES + entry.value().len() as u64)
68 .sum()
69 }
70}
71
72impl std::ops::Deref for DataStore {
73 type Target = BTreeMap<RawDataKey, RawRow, VirtualMemory<DefaultMemoryImpl>>;
74
75 fn deref(&self) -> &Self::Target {
76 &self.map
77 }
78}