Skip to main content

fixed_map/set/storage/
hashbrown.rs

1use core::hash::Hash;
2use core::iter;
3
4use crate::set::SetStorage;
5
6/// [`SetStorage`] for dynamically stored types, using [`hashbrown::HashSet`].
7///
8/// This allows for dynamic types such as `&'static str` or `u32` to be used as
9/// a [`Key`][crate::Key].
10///
11/// # Examples
12///
13/// ```
14/// use fixed_map::{Key, Set};
15///
16/// #[derive(Clone, Copy, Key)]
17/// enum MyKey {
18///     First(u32),
19///     Second,
20/// }
21///
22/// let mut map = Set::new();
23/// map.insert(MyKey::First(1));
24/// assert_eq!(map.contains(MyKey::First(1)), true);
25/// assert_eq!(map.contains(MyKey::First(2)), false);
26/// assert_eq!(map.contains(MyKey::Second), false);
27/// ```
28#[repr(transparent)]
29pub struct HashbrownSetStorage<T> {
30    inner: ::hashbrown::HashSet<T>,
31}
32
33impl<T> Clone for HashbrownSetStorage<T>
34where
35    T: Clone,
36{
37    #[inline]
38    fn clone(&self) -> Self {
39        HashbrownSetStorage {
40            inner: self.inner.clone(),
41        }
42    }
43}
44
45impl<T> PartialEq for HashbrownSetStorage<T>
46where
47    T: Eq + Hash,
48{
49    #[inline]
50    fn eq(&self, other: &Self) -> bool {
51        self.inner.eq(&other.inner)
52    }
53}
54
55impl<T> Eq for HashbrownSetStorage<T> where T: Eq + Hash {}
56
57impl<T> SetStorage<T> for HashbrownSetStorage<T>
58where
59    T: Copy + Eq + Hash,
60{
61    type Iter<'this>
62        = iter::Copied<::hashbrown::hash_set::Iter<'this, T>>
63    where
64        T: 'this;
65    type IntoIter = ::hashbrown::hash_set::IntoIter<T>;
66
67    #[inline]
68    fn empty() -> Self {
69        Self {
70            inner: ::hashbrown::HashSet::new(),
71        }
72    }
73
74    #[inline]
75    fn len(&self) -> usize {
76        self.inner.len()
77    }
78
79    #[inline]
80    fn is_empty(&self) -> bool {
81        self.inner.is_empty()
82    }
83
84    #[inline]
85    fn insert(&mut self, value: T) -> bool {
86        self.inner.insert(value)
87    }
88
89    #[inline]
90    fn contains(&self, value: T) -> bool {
91        self.inner.contains(&value)
92    }
93
94    #[inline]
95    fn remove(&mut self, value: T) -> bool {
96        self.inner.remove(&value)
97    }
98
99    #[inline]
100    fn retain<F>(&mut self, mut func: F)
101    where
102        F: FnMut(T) -> bool,
103    {
104        self.inner.retain(|&value| func(value));
105    }
106
107    #[inline]
108    fn clear(&mut self) {
109        self.inner.clear();
110    }
111
112    #[inline]
113    fn iter(&self) -> Self::Iter<'_> {
114        self.inner.iter().copied()
115    }
116
117    #[inline]
118    fn into_iter(self) -> Self::IntoIter {
119        self.inner.into_iter()
120    }
121}