Skip to main content

icydb_core/db/data/
store.rs

1//! Module: data::store
2//! Responsibility: stable BTreeMap-backed row persistence.
3//! Does not own: key/row validation policy beyond type boundaries.
4//! Boundary: commit/executor call into this layer after prevalidation.
5
6use crate::db::data::{CanonicalRow, DataKey, RawDataKey, RawRow};
7use canic_cdk::structures::{BTreeMap, DefaultMemoryImpl, memory::VirtualMemory};
8
9///
10/// DataStore
11///
12/// Thin persistence wrapper over one stable BTreeMap.
13///
14/// Invariant: callers provide already-validated `RawDataKey` and canonical row bytes.
15/// This type intentionally does not enforce commit-phase ordering.
16///
17
18pub struct DataStore {
19    map: BTreeMap<RawDataKey, RawRow, VirtualMemory<DefaultMemoryImpl>>,
20}
21
22impl DataStore {
23    /// Initialize a data store with the provided backing memory.
24    #[must_use]
25    pub fn init(memory: VirtualMemory<DefaultMemoryImpl>) -> Self {
26        Self {
27            map: BTreeMap::init(memory),
28        }
29    }
30
31    /// Insert or replace one row by raw key.
32    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    /// Insert one raw row directly for corruption-focused test setup only.
37    #[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    /// Remove one row by raw key.
43    pub fn remove(&mut self, key: &RawDataKey) -> Option<RawRow> {
44        self.map.remove(key)
45    }
46
47    /// Load one row by raw key.
48    pub fn get(&self, key: &RawDataKey) -> Option<RawRow> {
49        self.map.get(key)
50    }
51
52    /// Return whether one raw key exists without cloning the row payload.
53    #[must_use]
54    pub fn contains(&self, key: &RawDataKey) -> bool {
55        self.map.contains_key(key)
56    }
57
58    /// Clear all stored rows from the data store.
59    pub fn clear(&mut self) {
60        self.map.clear();
61    }
62
63    /// Sum of bytes used by all stored rows.
64    pub fn memory_bytes(&self) -> u64 {
65        // Report map footprint as key bytes + row bytes per entry.
66        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}