use std::{
    hash::{BuildHasher, Hash, Hasher},
    sync::Arc,
};

// We need to use `hashbrown` for its `.raw_entry_mut()` API (so as to be able
// to use `Arc<T>` with `&T`…)
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)
    }
}

impl<A: Hash + Eq> FromIterator<Arc<A>> for SetArc<A> {
    fn from_iter<T: IntoIterator<Item = Arc<A>>>(iter: T) -> Self {
        let mut set = Self::default();
        for value in iter {
            set.insert(value);
        }
        set
    }
}
