1#[cfg(test)]
2mod tests {
3 #[test]
4 fn it_works() {
5 assert_eq!(2 + 2, 4);
6 }
7}
8
9use bimap::{BiMap, Overwritten};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone)]
13pub struct BiMapPlusMap<L, R, V>
14where
15 L: std::fmt::Debug + Eq + Hash,
16 R: std::fmt::Debug + Eq + Hash,
17{
18 bimap: BiMap<L, R>,
19 hashmap: HashMap<L, V>,
20}
21
22use std::hash::Hash;
23
24impl<L, R, V> BiMapPlusMap<L, R, V>
25where
26 L: std::fmt::Debug + Eq + Hash + Clone,
27 R: std::fmt::Debug + Eq + Hash,
28{
29 pub fn new() -> Self {
30 BiMapPlusMap {
31 bimap: BiMap::new(),
32 hashmap: HashMap::new(),
33 }
34 }
35 pub fn insert(&mut self, left: L, right: R, value: V) {
36 match self.bimap.insert(left.clone(), right) {
37 Overwritten::Neither | Overwritten::Left(_, _) | Overwritten::Pair(_, _) => {
38 self.hashmap.insert(left, value);
39 }
40 Overwritten::Right(l1, _) => {
41 self.hashmap.remove(&l1);
42 self.hashmap.insert(left, value);
43 }
44 Overwritten::Both((l1, _), (l2, _)) => {
45 self.hashmap.remove(&l1);
46 self.hashmap.remove(&l2);
47 self.hashmap.insert(left, value);
48 }
49 }
50 }
51
52 pub fn bimap_get_by_left(&self, left: &L) -> Option<&R> {
53 self.bimap.get_by_left(left)
54 }
55
56 pub fn bimap_get_by_right(&self, right: &R) -> Option<&L> {
57 self.bimap.get_by_right(right)
58 }
59
60 pub fn hashmap_get_by_left(&self, left: &L) -> Option<&V> {
61 self.hashmap.get(left)
62 }
63
64 pub fn hashmap_get_by_right(&self, right: &R) -> Option<&V> {
65 let left = self.bimap_get_by_right(right)?;
66 self.hashmap.get(left)
67 }
68}