1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}

use bimap::{BiMap, Overwritten};
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub struct BiMapPlusMap<L, R, V>
where
    L: std::fmt::Debug + Eq + Hash,
    R: std::fmt::Debug + Eq + Hash,
{
    bimap: BiMap<L, R>,
    hashmap: HashMap<L, V>,
}

use std::hash::Hash;

impl<L, R, V> BiMapPlusMap<L, R, V>
where
    L: std::fmt::Debug + Eq + Hash + Clone,
    R: std::fmt::Debug + Eq + Hash,
{
    pub fn new() -> Self {
        BiMapPlusMap {
            bimap: BiMap::new(),
            hashmap: HashMap::new(),
        }
    }
    pub fn insert(&mut self, left: L, right: R, value: V) {
        match self.bimap.insert(left.clone(), right) {
            Overwritten::Neither | Overwritten::Left(_, _) | Overwritten::Pair(_, _) => {
                self.hashmap.insert(left, value);
            }
            Overwritten::Right(l1, _) => {
                self.hashmap.remove(&l1);
                self.hashmap.insert(left, value);
            }
            Overwritten::Both((l1, _), (l2, _)) => {
                self.hashmap.remove(&l1);
                self.hashmap.remove(&l2);
                self.hashmap.insert(left, value);
            }
        }
    }

    pub fn bimap_get_by_left(&self, left: &L) -> Option<&R> {
        self.bimap.get_by_left(left)
    }

    pub fn bimap_get_by_right(&self, right: &R) -> Option<&L> {
        self.bimap.get_by_right(right)
    }

    pub fn hashmap_get_by_left(&self, left: &L) -> Option<&V> {
        self.hashmap.get(left)
    }

    pub fn hashmap_get_by_right(&self, right: &R) -> Option<&V> {
        let left = self.bimap_get_by_right(right)?;
        self.hashmap.get(left)
    }
}