adana_db/
tree.rs

1use std::{
2    collections::BTreeMap,
3    ops::{Deref, DerefMut},
4};
5
6use serde::{Deserialize, Serialize};
7
8use super::{Key, Op, Value};
9
10type InnerMap<K, V> = BTreeMap<K, V>;
11#[derive(Debug, Deserialize, Serialize)]
12pub struct Tree<K: Key, V: Value>(InnerMap<K, V>);
13
14impl<K: Key, V: Value> Default for Tree<K, V> {
15    fn default() -> Tree<K, V> {
16        Tree(BTreeMap::new())
17    }
18}
19
20impl<K: Key, V: Value> Deref for Tree<K, V> {
21    type Target = InnerMap<K, V>;
22
23    fn deref(&self) -> &Self::Target {
24        &self.0
25    }
26}
27impl<K: Key, V: Value> DerefMut for Tree<K, V> {
28    fn deref_mut(&mut self) -> &mut Self::Target {
29        &mut self.0
30    }
31}
32
33impl<K: Key + Clone, V: Value> Op<K, V> for Tree<K, V> {
34    fn read(
35        &self,
36        k: impl Into<K>,
37        mapper: impl Fn(&V) -> Option<V>,
38    ) -> Option<V> {
39        let v = self.get(&k.into())?;
40        mapper(v)
41    }
42
43    fn insert(&mut self, k: impl Into<K>, v: impl Into<V>) -> Option<V> {
44        self.0.insert(k.into(), v.into())
45    }
46
47    fn remove(&mut self, k: impl Into<K>) -> Option<V> {
48        self.0.remove(&k.into())
49    }
50
51    fn clear(&mut self) {
52        self.0.clear();
53    }
54
55    fn contains(&self, k: &K) -> Option<bool> {
56        Some(self.contains_key(k))
57    }
58
59    fn len(&self) -> Option<usize> {
60        Some(self.0.len())
61    }
62
63    fn keys(&self) -> Vec<K> {
64        self.0.keys().cloned().collect()
65    }
66
67    fn list_all(&self) -> BTreeMap<K, V> {
68        self.0.clone()
69    }
70}