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::{DataKey, RawDataKey, RawRow};
7use canic_cdk::structures::{BTreeMap, DefaultMemoryImpl, memory::VirtualMemory};
8use derive_more::Deref;
9
10///
11/// DataStore
12///
13/// Thin persistence wrapper over one stable BTreeMap.
14///
15/// Invariant: callers provide already-validated `RawDataKey` and `RawRow`.
16/// This type intentionally does not enforce commit-phase ordering.
17///
18
19#[derive(Deref)]
20pub struct DataStore(BTreeMap<RawDataKey, RawRow, VirtualMemory<DefaultMemoryImpl>>);
21
22impl DataStore {
23    #[must_use]
24    /// Initialize a data store with the provided backing memory.
25    pub fn init(memory: VirtualMemory<DefaultMemoryImpl>) -> Self {
26        Self(BTreeMap::init(memory))
27    }
28
29    /// Insert or replace one row by raw key.
30    pub fn insert(&mut self, key: RawDataKey, row: RawRow) -> Option<RawRow> {
31        self.0.insert(key, row)
32    }
33
34    /// Remove one row by raw key.
35    pub fn remove(&mut self, key: &RawDataKey) -> Option<RawRow> {
36        self.0.remove(key)
37    }
38
39    /// Load one row by raw key.
40    pub fn get(&self, key: &RawDataKey) -> Option<RawRow> {
41        self.0.get(key)
42    }
43
44    /// Clear all stored rows from the data store.
45    pub fn clear(&mut self) {
46        self.0.clear();
47    }
48
49    /// Sum of bytes used by all stored rows.
50    pub fn memory_bytes(&self) -> u64 {
51        // Report map footprint as key bytes + row bytes per entry.
52        self.iter()
53            .map(|entry| DataKey::STORED_SIZE_BYTES + entry.value().len() as u64)
54            .sum()
55    }
56}