Skip to main content

icydb_core/db/data/
store.rs

1use crate::db::data::{DataKey, RawDataKey, RawRow};
2use canic_cdk::structures::{BTreeMap, DefaultMemoryImpl, memory::VirtualMemory};
3use derive_more::{Deref, DerefMut};
4
5///
6/// DataStore
7///
8
9#[derive(Deref, DerefMut)]
10pub struct DataStore(BTreeMap<RawDataKey, RawRow, VirtualMemory<DefaultMemoryImpl>>);
11
12impl DataStore {
13    #[must_use]
14    /// Initialize a data store with the provided backing memory.
15    pub fn init(memory: VirtualMemory<DefaultMemoryImpl>) -> Self {
16        Self(BTreeMap::init(memory))
17    }
18
19    /// Clear all stored rows from the data store.
20    pub fn clear(&mut self) {
21        self.0.clear();
22    }
23
24    /// Sum of bytes used by all stored rows.
25    pub fn memory_bytes(&self) -> u64 {
26        self.iter()
27            .map(|entry| DataKey::STORED_SIZE_BYTES + entry.value().len() as u64)
28            .sum()
29    }
30}