summaryrefslogtreecommitdiffstats
path: root/vendor/gix-attributes/src/search/refmap.rs
blob: 3dc51265c834306cd39d6fda9d9e555d9ebbe215 (plain)
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
//! A utility to store objects by identity, which deduplicates them while avoiding lifetimes.
//!
//! We chose to use hashing/identity over pointers as it's possible that different objects end up in the same memory location,
//! which would create obscure bugs. The same could happen with hash collisions, but they these are designed to be less likely.
use std::collections::btree_map::Entry;
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};

pub(crate) type RefMapKey = u64;
pub(crate) struct RefMap<T>(BTreeMap<RefMapKey, T>);

impl<T> Default for RefMap<T> {
    fn default() -> Self {
        RefMap(Default::default())
    }
}

impl<T> RefMap<T>
where
    T: Hash + Clone,
{
    pub(crate) fn insert(&mut self, value: &T) -> RefMapKey {
        let mut s = DefaultHasher::new();
        value.hash(&mut s);
        let key = s.finish();
        match self.0.entry(key) {
            Entry::Vacant(e) => {
                e.insert(value.clone());
                key
            }
            Entry::Occupied(_) => key,
        }
    }

    pub(crate) fn insert_owned(&mut self, value: T) -> RefMapKey {
        let mut s = DefaultHasher::new();
        value.hash(&mut s);
        let key = s.finish();
        match self.0.entry(key) {
            Entry::Vacant(e) => {
                e.insert(value);
                key
            }
            Entry::Occupied(_) => key,
        }
    }

    pub(crate) fn resolve(&self, key: RefMapKey) -> Option<&T> {
        self.0.get(&key)
    }
}