vertigo/computed/struct_mut/
hash_map_mut.rs

1use std::collections::HashMap;
2use std::hash::Hash;
3
4use super::inner_value::InnerValue;
5
6pub struct HashMapMut<K, V> {
7    data: InnerValue<HashMap<K, V>>,
8}
9
10impl<K: Eq + Hash, V> Default for HashMapMut<K, V> {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl<K: Eq + Hash, V> HashMapMut<K, V> {
17    pub fn new() -> HashMapMut<K, V> {
18        HashMapMut {
19            data: InnerValue::new(HashMap::new()),
20        }
21    }
22
23    pub fn insert(&self, key: K, value: V) -> Option<V> {
24        let state = self.data.get_mut();
25        state.insert(key, value)
26    }
27
28    pub fn get_and_map<R, F: FnOnce(&V) -> R>(&self, key: &K, callback: F) -> Option<R> {
29        let state = self.data.get();
30
31        let item = state.get(key);
32
33        if let Some(elem) = item {
34            return Some(callback(elem));
35        }
36
37        None
38    }
39
40    pub fn must_change<R, F: FnOnce(&mut V) -> R>(&self, key: &K, callback: F) -> Option<R> {
41        let state = self.data.get_mut();
42
43        let item = state.get_mut(key);
44
45        if let Some(elem) = item {
46            return Some(callback(elem));
47        }
48
49        None
50    }
51
52    pub fn remove(&self, key: &K) -> Option<V> {
53        let state = self.data.get_mut();
54        state.remove(key)
55    }
56
57    pub fn mem_replace(&self, new_map: HashMap<K, V>) -> HashMap<K, V> {
58        let state = self.data.get_mut();
59        std::mem::replace(state, new_map)
60    }
61
62    pub fn retain<F: FnMut(&K, &mut V) -> bool>(&self, f: F) {
63        let state = self.data.get_mut();
64        state.retain(f)
65    }
66
67    pub fn filter_and_map<R>(&self, map: fn(&V) -> Option<R>) -> Vec<R> {
68        let state = self.data.get();
69        let mut list = Vec::new();
70        for (_, value) in (*state).iter() {
71            if let Some(mapped) = map(value) {
72                list.push(mapped);
73            }
74        }
75
76        list
77    }
78}
79
80impl<K: Eq + Hash, V: Clone> HashMapMut<K, V> {
81    pub fn get_all_values(&self) -> Vec<V> {
82        let state = self.data.get();
83
84        let mut out = Vec::new();
85
86        for (_, callback) in state.iter() {
87            out.push((*callback).clone());
88        }
89
90        out
91    }
92
93    pub fn get(&self, key: &K) -> Option<V> {
94        let state = self.data.get();
95        state.get(key).map(|value| (*value).clone())
96    }
97}
98
99impl<K: Eq + Hash, V: PartialEq> HashMapMut<K, V> {
100    pub fn insert_and_check(&self, key: K, value: V) -> bool {
101        let state = self.data.get_mut();
102        let is_change = state.get(&key) != Some(&value);
103        state.insert(key, value);
104        is_change
105    }
106}