makepad_platform/
component_map.rs

1use {
2    std::{
3        ops::{Index, IndexMut, Deref, DerefMut},
4        collections::{HashSet, HashMap,},
5        collections::hash_map::Entry
6    },
7    crate::cx::Cx
8};
9
10#[derive(Clone)]
11pub struct ComponentMap<K,V>{
12    map: HashMap<K,V>,
13    visible: HashSet<K>
14}
15
16impl<K,V> Default for ComponentMap<K,V>{
17    fn default()->Self{
18        Self{
19            map: HashMap::new(),
20            visible: HashSet::new()
21        }
22    }
23}
24
25impl<K: std::cmp::Eq + std::hash::Hash + Copy,V> ComponentMap<K,V>{
26    pub fn retain_visible(&mut self) {
27        let visible = &self.visible;
28        self.map.retain( | k, _ | visible.contains(&k));
29        self.visible.clear();
30    }
31    
32    pub fn retain_visible_and<CB>(&mut self, cb:CB)
33    where CB: Fn(&K, &V)->bool
34    {
35        let visible = &self.visible;
36        self.map.retain( | k, v | visible.contains(&k) || cb(k,v));
37        self.visible.clear();
38    } 
39
40    pub fn get_or_insert<'a, CB>(&'a mut self, cx:&mut Cx, key:K, cb:CB)->&'a mut V
41    where CB: FnOnce(&mut Cx)->V{
42        self.visible.insert(key);
43        match self.map.entry(key){
44            Entry::Occupied(o) => o.into_mut(),
45            Entry::Vacant(v) => v.insert(cb(cx))
46        }
47    }
48}
49 
50impl<K,V> Deref for ComponentMap<K,V> {
51    type Target = HashMap<K,V>;
52    fn deref(&self) -> &Self::Target {&self.map}
53}
54
55impl<K,V> DerefMut for ComponentMap<K,V> {
56    fn deref_mut(&mut self) -> &mut Self::Target {&mut self.map}
57}
58
59impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> Index<K> for ComponentMap<K,V>{
60    type Output = V;
61    fn index(&self, index:K)->&Self::Output{
62        self.map.get(&index).unwrap()
63    }
64}
65
66impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> IndexMut<K> for ComponentMap<K,V>{
67    fn index_mut(&mut self, index:K)->&mut Self::Output{
68        self.map.get_mut(&index).unwrap()
69    }
70}