summaryrefslogtreecommitdiffstats
path: root/vendor/gix-attributes/src/search/refmap.rs
blob: aa9dee84bf4e7de63ed3598b2f086400c9c34c26 (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, hash_map::DefaultHasher, BTreeMap},
    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)
    }
}