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(Debug, 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_with<CB>(&mut self, mut cb:CB)
33    where CB: FnMut(V),
34          V: Default
35    {
36        let visible = &self.visible;
37        self.map.retain( | k, v | if visible.contains(&k){true}else
38        {
39            let mut v2 = V::default();
40            std::mem::swap(v, &mut v2);
41            cb(v2);
42            false
43        });
44        self.visible.clear();
45    } 
46
47    pub fn retain_visible_and<CB>(&mut self, cb:CB)
48    where CB: Fn(&K, &V)->bool
49    {
50        let visible = &self.visible;
51        self.map.retain( | k, v | visible.contains(&k) || cb(k,v));
52        self.visible.clear();
53    } 
54
55    pub fn get_or_insert<'a, CB>(&'a mut self, cx:&mut Cx, key:K, cb:CB)->&'a mut V
56    where CB: FnOnce(&mut Cx)->V{
57        self.visible.insert(key);
58        match self.map.entry(key){
59            Entry::Occupied(o) => o.into_mut(),
60            Entry::Vacant(v) => v.insert(cb(cx))
61        }
62    }
63
64    pub fn entry(&mut self, key: K) -> Entry<K, V> {
65        self.visible.insert(key);
66        self.map.entry(key)
67    }
68}
69 
70impl<K,V> Deref for ComponentMap<K,V> {
71    type Target = HashMap<K,V>;
72    fn deref(&self) -> &Self::Target {&self.map}
73}
74
75impl<K,V> DerefMut for ComponentMap<K,V> {
76    fn deref_mut(&mut self) -> &mut Self::Target {&mut self.map}
77}
78
79impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> Index<K> for ComponentMap<K,V>{
80    type Output = V;
81    fn index(&self, index:K)->&Self::Output{
82        self.map.get(&index).unwrap()
83    }
84}
85
86impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> IndexMut<K> for ComponentMap<K,V>{
87    fn index_mut(&mut self, index:K)->&mut Self::Output{
88        self.map.get_mut(&index).unwrap()
89    }
90}