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