architect_api/utils/
bimap.rs1use std::collections::BTreeMap;
2
3#[derive(Debug, Clone)]
4pub struct Bimap<U: Clone + Ord, V: Clone + Ord> {
5 map: BTreeMap<U, V>,
6 rev: BTreeMap<V, U>,
7}
8
9impl<U: Clone + Ord, V: Clone + Ord> Bimap<U, V> {
10 pub fn new() -> Self {
11 Self { map: BTreeMap::new(), rev: BTreeMap::new() }
12 }
13
14 pub fn insert(&mut self, u: U, v: V) {
15 self.map.insert(u.clone(), v.clone());
16 self.rev.insert(v, u);
17 }
18
19 pub fn get(&self, u: &U) -> Option<&V> {
20 self.map.get(u)
21 }
22
23 pub fn get_rev(&self, v: &V) -> Option<&U> {
24 self.rev.get(v)
25 }
26
27 pub fn get_mut(&mut self, u: &U) -> Option<&mut V> {
28 self.map.get_mut(u)
29 }
30
31 pub fn get_rev_mut(&mut self, v: &V) -> Option<&mut U> {
32 self.rev.get_mut(v)
33 }
34
35 pub fn contains(&self, u: &U) -> bool {
36 self.map.contains_key(u)
37 }
38
39 pub fn contains_rev(&self, v: &V) -> bool {
40 self.rev.contains_key(v)
41 }
42
43 pub fn len(&self) -> usize {
44 self.map.len()
45 }
46
47 pub fn is_empty(&self) -> bool {
48 self.map.is_empty()
49 }
50
51 pub fn remove(&mut self, u: &U) -> Option<V> {
52 let v = self.map.remove(u)?;
53 self.rev.remove(&v);
54 Some(v)
55 }
56
57 pub fn remove_rev(&mut self, v: &V) -> Option<U> {
58 let u = self.rev.remove(v)?;
59 self.map.remove(&u);
60 Some(u)
61 }
62
63 pub fn clear(&mut self) {
64 self.map.clear();
65 self.rev.clear();
66 }
67
68 pub fn retain(&mut self, mut f: impl FnMut(&U, &V) -> bool) {
69 self.map.retain(|u, v| f(u, v));
70 self.rev.retain(|v, u| f(u, v));
71 }
72
73 pub fn iter(&self) -> impl Iterator<Item = (&U, &V)> {
74 self.map.iter()
75 }
76}
77
78impl<U: Clone + Ord, V: Clone + Ord> Default for Bimap<U, V> {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84impl<U: Clone + Ord, V: Clone + Ord> FromIterator<(U, V)> for Bimap<U, V> {
85 fn from_iter<I: IntoIterator<Item = (U, V)>>(iter: I) -> Self {
86 let mut bimap = Bimap::new();
87 for (u, v) in iter {
88 bimap.insert(u, v);
89 }
90 bimap
91 }
92}
93
94impl<U: Clone + Ord, V: Clone + Ord> IntoIterator for Bimap<U, V> {
95 type Item = (U, V);
96 type IntoIter = std::collections::btree_map::IntoIter<U, V>;
97
98 fn into_iter(self) -> Self::IntoIter {
99 self.map.into_iter()
100 }
101}