1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::{
    collections::BTreeMap,
    ops::{Deref, DerefMut},
};

use serde::{Deserialize, Serialize};

use super::{Key, Op, Value};

type InnerMap<K, V> = BTreeMap<K, V>;
#[derive(Debug, Deserialize, Serialize)]
pub struct Tree<K: Key, V: Value>(InnerMap<K, V>);

impl<K: Key, V: Value> Default for Tree<K, V> {
    fn default() -> Tree<K, V> {
        Tree(BTreeMap::new())
    }
}

impl<K: Key, V: Value> Deref for Tree<K, V> {
    type Target = InnerMap<K, V>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<K: Key, V: Value> DerefMut for Tree<K, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<K: Key + Clone, V: Value> Op<K, V> for Tree<K, V> {
    fn read(
        &self,
        k: impl Into<K>,
        mapper: impl Fn(&V) -> Option<V>,
    ) -> Option<V> {
        let v = self.get(&k.into())?;
        mapper(v)
    }

    fn insert(&mut self, k: impl Into<K>, v: impl Into<V>) -> Option<V> {
        self.0.insert(k.into(), v.into())
    }

    fn remove(&mut self, k: impl Into<K>) -> Option<V> {
        self.0.remove(&k.into())
    }

    fn clear(&mut self) {
        self.0.clear();
    }

    fn contains(&self, k: &K) -> Option<bool> {
        Some(self.contains_key(k))
    }

    fn len(&self) -> Option<usize> {
        Some(self.0.len())
    }

    fn keys(&self) -> Vec<K> {
        self.0.keys().cloned().collect()
    }

    fn list_all(&self) -> BTreeMap<K, V> {
        self.0.clone()
    }
}