standing_relations/core/
count_map.rs

1use std::{
2    collections::{btree_map, hash_map, BTreeMap, HashMap},
3    hash::Hash,
4};
5
6pub trait CountMap<K>: Default + Sized {
7    fn add(&mut self, k: K, count: isize);
8    fn empty() -> Self {
9        Self::default()
10    }
11    fn singleton(k: K, count: isize) -> Self {
12        let mut result: Self = Self::empty();
13        result.add(k, count);
14        result
15    }
16}
17
18pub trait Observable {
19    fn is_empty(&self) -> bool;
20}
21
22impl<K1: Eq + Hash, K2, M: CountMap<K2> + Observable> CountMap<(K1, K2)> for HashMap<K1, M> {
23    fn add(&mut self, k: (K1, K2), count: isize) {
24        if count == 0 {
25            return;
26        }
27        let e = self.entry(k.0);
28        match e {
29            hash_map::Entry::Vacant(v) => {
30                v.insert(CountMap::singleton(k.1, count));
31            }
32            hash_map::Entry::Occupied(mut o) => {
33                let m = o.get_mut();
34                m.add(k.1, count);
35                if m.is_empty() {
36                    o.remove();
37                }
38            }
39        }
40    }
41}
42
43impl<K, V> Observable for HashMap<K, V> {
44    fn is_empty(&self) -> bool {
45        HashMap::is_empty(self)
46    }
47}
48
49impl<K1: Eq + Ord, K2, M: CountMap<K2> + Observable> CountMap<(K1, K2)> for BTreeMap<K1, M> {
50    fn add(&mut self, k: (K1, K2), count: isize) {
51        if count == 0 {
52            return;
53        }
54        let e = self.entry(k.0);
55        match e {
56            btree_map::Entry::Vacant(v) => {
57                v.insert(CountMap::singleton(k.1, count));
58            }
59            btree_map::Entry::Occupied(mut o) => {
60                let m = o.get_mut();
61                m.add(k.1, count);
62                if m.is_empty() {
63                    o.remove();
64                }
65            }
66        }
67    }
68}
69
70impl<K, V> Observable for BTreeMap<K, V> {
71    fn is_empty(&self) -> bool {
72        BTreeMap::is_empty(self)
73    }
74}
75
76impl CountMap<()> for isize {
77    fn add(&mut self, (): (), count: isize) {
78        *self += count
79    }
80}
81
82impl Observable for isize {
83    fn is_empty(&self) -> bool {
84        *self == 0
85    }
86}
87
88impl<K: Eq + Hash> CountMap<K> for HashMap<K, isize> {
89    fn add(&mut self, k: K, count: isize) {
90        CountMap::<(K, ())>::add(self, (k, ()), count)
91    }
92}
93
94impl<K: Ord> CountMap<K> for BTreeMap<K, isize> {
95    fn add(&mut self, k: K, count: isize) {
96        CountMap::<(K, ())>::add(self, (k, ()), count)
97    }
98}