gistools/data_store/kv/
mod.rs

1use super::U64;
2/// File based reader that implements the KVStore trait
3#[cfg(feature = "std")]
4pub mod file;
5use alloc::collections::btree_map::BTreeMap;
6use s2json::Properties;
7use serde::{Serialize, de::DeserializeOwned};
8
9/// Represents a key-value store
10pub trait KVStore<K: U64 = u64, V: Serialize + DeserializeOwned + Clone = Properties>:
11    Clone
12{
13    /// New key-value store
14    fn new(name: Option<&str>) -> Self;
15    /// The length of the store
16    fn len(&self) -> u64;
17    /// Check if the store is empty
18    fn is_empty(&self) -> bool;
19    /// Get a value from the store
20    fn get(&self, key: K) -> Option<&V>;
21    /// Get a mutable value from the store
22    fn get_mut(&mut self, key: K) -> Option<&mut V>;
23    /// Set a value in the store
24    fn set(&mut self, key: K, value: V);
25    /// Check if a key exists
26    fn has(&self, key: K) -> bool;
27    /// Iterate over the store
28    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)>
29    where
30        K: 'a,
31        V: 'a;
32    /// Iterate mutably over the store
33    fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = (&'a K, &'a mut V)>
34    where
35        K: 'a,
36        V: 'a;
37    /// Cleanup the store
38    fn cleanup(&mut self) {}
39}
40
41/// A local key-value store
42#[derive(Debug, Clone, Default)]
43pub struct KV<K: U64 = u64, V: Serialize + DeserializeOwned + Clone = Properties> {
44    store: BTreeMap<K, V>,
45}
46impl<K: U64, V: Serialize + DeserializeOwned + Clone> KVStore<K, V> for KV<K, V> {
47    fn new(_name: Option<&str>) -> Self {
48        KV { store: BTreeMap::new() }
49    }
50    fn len(&self) -> u64 {
51        self.store.len() as u64
52    }
53    fn is_empty(&self) -> bool {
54        self.store.is_empty()
55    }
56    fn get(&self, key: K) -> Option<&V> {
57        self.store.get(&key)
58    }
59    fn get_mut(&mut self, key: K) -> Option<&mut V> {
60        self.store.get_mut(&key)
61    }
62    fn set(&mut self, key: K, value: V) {
63        self.store.insert(key, value);
64    }
65    fn has(&self, key: K) -> bool {
66        self.store.contains_key(&key)
67    }
68    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)>
69    where
70        V: 'a,
71    {
72        self.store.iter()
73    }
74    fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = (&'a K, &'a mut V)>
75    where
76        V: 'a,
77    {
78        self.store.iter_mut()
79    }
80    fn cleanup(&mut self) {
81        self.store.clear();
82    }
83}