vertigo/computed/struct_mut/
btree_map_mut.rs

1use super::inner_value::InnerValue;
2use std::collections::BTreeMap;
3
4pub struct BTreeMapMut<K: Ord, V> {
5    data: InnerValue<BTreeMap<K, V>>,
6}
7
8impl<K: Ord, V> Default for BTreeMapMut<K, V> {
9    fn default() -> Self {
10        Self::new()
11    }
12}
13
14impl<K: Ord, V> BTreeMapMut<K, V> {
15    pub fn new() -> BTreeMapMut<K, V> {
16        BTreeMapMut {
17            data: InnerValue::new(BTreeMap::new()),
18        }
19    }
20
21    pub fn insert(&self, key: K, value: V) -> Option<V> {
22        let state = self.data.get_mut();
23        state.insert(key, value)
24    }
25
26    pub fn remove(&self, key: &K) -> Option<V> {
27        let state = self.data.get_mut();
28        state.remove(key)
29    }
30
31    pub fn contains_key(&self, key: &K) -> bool {
32        let state = self.data.get();
33        state.contains_key(key)
34    }
35
36    pub fn is_empty(&self) -> bool {
37        let state = self.data.get();
38        state.is_empty()
39    }
40
41    pub fn take(&self) -> BTreeMap<K, V> {
42        let state = self.data.get_mut();
43        std::mem::take(state)
44    }
45
46    pub fn map<R>(&self, map_f: impl FnOnce(&BTreeMap<K, V>) -> R) -> R {
47        let state = self.data.get();
48        map_f(state)
49    }
50
51    pub fn change(&self, change_f: impl FnOnce(&mut BTreeMap<K, V>)) {
52        let state = self.data.get_mut();
53        change_f(state)
54    }
55
56    pub fn map_and_change<R>(&self, change_f: impl FnOnce(&mut BTreeMap<K, V>) -> R) -> R {
57        let state = self.data.get_mut();
58        change_f(state)
59    }
60
61    pub fn get_mut<R, F: FnOnce(&mut V) -> R>(&self, key: &K, callback: F) -> Option<R> {
62        let state = self.data.get_mut();
63
64        let item = state.get_mut(key);
65
66        if let Some(elem) = item {
67            return Some(callback(elem));
68        }
69
70        None
71    }
72}
73
74impl<K: Ord, V: Clone> BTreeMapMut<K, V> {
75    pub fn get_and_clone(&self, key: &K) -> Option<V> {
76        let state = self.data.get();
77        state.get(key).cloned()
78    }
79}