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::{
        ops::{Index, IndexMut, Deref, DerefMut},
        collections::{HashSet, HashMap,},
        collections::hash_map::Entry
    },
    crate::cx::Cx
};

#[derive(Clone)]
pub struct ComponentMap<K,V>{
    map: HashMap<K,V>,
    visible: HashSet<K>
}

impl<K,V> Default for ComponentMap<K,V>{
    fn default()->Self{
        Self{
            map: HashMap::new(),
            visible: HashSet::new()
        }
    }
}

impl<K: std::cmp::Eq + std::hash::Hash + Copy,V> ComponentMap<K,V>{
    pub fn retain_visible(&mut self) {
        let visible = &self.visible;
        self.map.retain( | k, _ | visible.contains(&k));
        self.visible.clear();
    }
    
    pub fn retain_visible_and<CB>(&mut self, cb:CB)
    where CB: Fn(&K, &V)->bool
    {
        let visible = &self.visible;
        self.map.retain( | k, v | visible.contains(&k) || cb(k,v));
        self.visible.clear();
    } 

    pub fn get_or_insert<'a, CB>(&'a mut self, cx:&mut Cx, key:K, cb:CB)->&'a mut V
    where CB: FnOnce(&mut Cx)->V{
        self.visible.insert(key);
        match self.map.entry(key){
            Entry::Occupied(o) => o.into_mut(),
            Entry::Vacant(v) => v.insert(cb(cx))
        }
    }
}
 
impl<K,V> Deref for ComponentMap<K,V> {
    type Target = HashMap<K,V>;
    fn deref(&self) -> &Self::Target {&self.map}
}

impl<K,V> DerefMut for ComponentMap<K,V> {
    fn deref_mut(&mut self) -> &mut Self::Target {&mut self.map}
}

impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> Index<K> for ComponentMap<K,V>{
    type Output = V;
    fn index(&self, index:K)->&Self::Output{
        self.map.get(&index).unwrap()
    }
}

impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> IndexMut<K> for ComponentMap<K,V>{
    fn index_mut(&mut self, index:K)->&mut Self::Output{
        self.map.get_mut(&index).unwrap()
    }
}