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
use ::std::{
    hash::{BuildHasher, Hash, Hasher},
    sync::Arc,
};

pub struct SetArc<T: Hash + Eq> {
    /// A `Set` is equivalent to a `Map` of dummy values.
    pub keys: ::hashbrown::HashMap<Arc<T>, ()>,
}

impl<T: Hash + Eq> Default for SetArc<T> {
    fn default() -> Self {
        Self {
            keys: <_>::default(),
        }
    }
}

impl<T: Hash + Eq> SetArc<T> {
    pub fn insert(&mut self, value: Arc<T>) {
        self.keys.insert(value, ());
    }

    /// The whole point of this API.
    ///
    /// Returns `true` iff a value was effectively removed
    pub fn remove(&mut self, value: &T) -> bool {
        let value_hash = {
            let hasher = &mut self.keys.hasher().build_hasher();
            value.hash(hasher);
            hasher.finish()
        };
        let removed = match self
            .keys
            .raw_entry_mut()
            .from_key_hashed_nocheck(value_hash, value)
        {
            ::hashbrown::hash_map::RawEntryMut::Occupied(entry) => {
                entry.remove();
                true
            }
            ::hashbrown::hash_map::RawEntryMut::Vacant(_) => false,
        };
        removed
    }

    pub fn contains(&self, value: &T) -> bool {
        self.keys.contains_key(value)
    }
}