1use std::{borrow::Borrow, fmt, hash::Hash};
2
3use hashbrown::HashMap;
4
5#[derive(thiserror::Error)]
6pub enum InsertError<L, R> {
7 LhsClash(L, (L, R)),
8 RhsClash(R, (L, R)),
9}
10
11impl<L: fmt::Debug, R: fmt::Debug> fmt::Debug for InsertError<L, R> {
12 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13 match self {
14 InsertError::LhsClash(l1, (l2, r)) => {
15 write!(
16 f,
17 "Left-hand side of {l2:?} ⇔ {r:?} clashes with existing mapping {l1:?} ⇔ {r:?}"
18 )
19 },
20 InsertError::RhsClash(r1, (l, r2)) => {
21 write!(
22 f,
23 "Right-hand side of {l:?} ⇔ {r2:?} clashes with existing mapping {l:?} ⇔ \
24 {r1:?}"
25 )
26 },
27 }
28 }
29}
30
31impl<L: fmt::Display, R: fmt::Display> fmt::Display for InsertError<L, R> {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 match self {
34 InsertError::LhsClash(l1, (l2, r)) => {
35 write!(
36 f,
37 "Left-hand side of {l2} ⇔ {r} clashes with existing mapping {l1} ⇔ {r}"
38 )
39 },
40 InsertError::RhsClash(r1, (l, r2)) => {
41 write!(
42 f,
43 "Right-hand side of {l} ⇔ {r2} clashes with existing mapping {l} ⇔ {r1}"
44 )
45 },
46 }
47 }
48}
49
50#[derive(Clone)]
51pub struct Bijection<L, R> {
52 fwd: HashMap<L, R>,
53 bck: HashMap<R, L>,
54}
55
56impl<L: fmt::Debug, R: fmt::Debug> fmt::Debug for Bijection<L, R> {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 struct Pair<'a, L, R>(&'a L, &'a R);
59
60 impl<L: fmt::Debug, R: fmt::Debug> fmt::Debug for Pair<'_, L, R> {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 let Self(l, r) = self;
63 write!(f, "{l:?} ⇔ {r:?}")
64 }
65 }
66
67 f.debug_set()
68 .entries(self.fwd.iter().map(|(l, r)| Pair(l, r)))
69 .finish()
70 }
71}
72
73impl<L, R> Default for Bijection<L, R> {
74 #[inline]
75 fn default() -> Self { Self::new() }
76}
77
78impl<L, R> Bijection<L, R> {
79 #[inline]
80 #[must_use]
81 pub fn new() -> Self {
82 Self {
83 fwd: HashMap::new(),
84 bck: HashMap::new(),
85 }
86 }
87}
88
89impl<L: Eq + Hash, R: Eq + Hash> Bijection<L, R> {
90 #[inline]
91 pub fn image<Q: Eq + Hash>(&self, l: &Q) -> Option<&R>
92 where L: Borrow<Q> {
93 self.fwd.get(l)
94 }
95
96 #[inline]
97 pub fn preimage<Q: Eq + Hash>(&self, r: &Q) -> Option<&L>
98 where R: Borrow<Q> {
99 self.bck.get(r)
100 }
101}
102
103impl<L: Clone + Eq + Hash, R: Clone + Eq + Hash> Bijection<L, R> {
104 pub fn insert(&mut self, l: L, r: R) -> Result<bool, InsertError<L, R>> {
106 use hashbrown::hash_map::Entry;
107
108 let fwd_entry = self.fwd.entry(l.clone());
109 let bck_entry = self.bck.entry(r.clone());
110
111 match (fwd_entry, bck_entry) {
112 (Entry::Vacant(f), Entry::Vacant(b)) => {
113 f.insert(r);
114 b.insert(l);
115 Ok(true)
116 },
117 (Entry::Occupied(ol), Entry::Occupied(or)) if *ol.get() == r => {
118 debug_assert!(*or.get() == l);
119 Ok(false)
120 },
121 (Entry::Occupied(f), _) => Err(InsertError::RhsClash(f.get().clone(), (l, r))),
122 (Entry::Vacant(_), Entry::Occupied(b)) => {
123 Err(InsertError::LhsClash(b.get().clone(), (l, r)))
124 },
125 }
126 }
127}