cairo_lang_utils/
unordered_hash_set.rs1use core::borrow::Borrow;
2use core::hash::{BuildHasher, Hash};
3use core::ops::Sub;
4#[cfg(feature = "std")]
5use std::collections::HashSet;
6#[cfg(feature = "std")]
7use std::collections::hash_map::RandomState;
8
9#[cfg(not(feature = "std"))]
10use hashbrown::HashSet;
11
12#[cfg(feature = "std")]
17#[derive(Clone, Debug)]
18pub struct UnorderedHashSet<Key, BH = RandomState>(HashSet<Key, BH>);
19#[cfg(not(feature = "std"))]
20#[derive(Clone, Debug)]
21pub struct UnorderedHashSet<Key, BH = hashbrown::hash_map::DefaultHashBuilder>(HashSet<Key, BH>);
22
23impl<K, BH: Default> Default for UnorderedHashSet<K, BH> {
24 #[cfg(feature = "std")]
25 fn default() -> Self {
26 Self(Default::default())
27 }
28 #[cfg(not(feature = "std"))]
29 fn default() -> Self {
30 Self(HashSet::with_hasher(Default::default()))
31 }
32}
33
34impl<K, BH> PartialEq for UnorderedHashSet<K, BH>
35where
36 K: Eq + Hash,
37 BH: BuildHasher,
38{
39 fn eq(&self, other: &Self) -> bool {
40 self.0 == other.0
41 }
42}
43
44impl<K, BH> Eq for UnorderedHashSet<K, BH>
45where
46 K: Eq + Hash,
47 BH: BuildHasher,
48{
49}
50
51impl<Key, BH> UnorderedHashSet<Key, BH> {
52 pub fn len(&self) -> usize {
54 self.0.len()
55 }
56
57 pub fn is_empty(&self) -> bool {
59 self.0.is_empty()
60 }
61
62 pub fn clear(&mut self) {
64 self.0.clear()
65 }
66}
67
68impl<Key: Hash + Eq, BH: BuildHasher> UnorderedHashSet<Key, BH> {
69 pub fn insert(&mut self, key: Key) -> bool {
73 self.0.insert(key)
74 }
75
76 pub fn remove<Q: ?Sized + Hash + Eq>(&mut self, value: &Q) -> bool
78 where
79 Key: Borrow<Q>,
80 {
81 self.0.remove(value)
82 }
83
84 pub fn extend<I: IntoIterator<Item = Key>>(&mut self, iter: I) {
86 self.0.extend(iter)
87 }
88
89 pub fn extend_unordered(&mut self, other: Self) {
91 self.0.extend(other.0)
92 }
93
94 pub fn contains<Q: ?Sized + Hash + Eq>(&self, value: &Q) -> bool
96 where
97 Key: Borrow<Q>,
98 {
99 self.0.contains(value)
100 }
101}
102
103impl<Key: Hash + Eq, BH: BuildHasher + Default> FromIterator<Key> for UnorderedHashSet<Key, BH> {
104 fn from_iter<T: IntoIterator<Item = Key>>(iter: T) -> Self {
105 Self(iter.into_iter().collect())
106 }
107}
108
109impl<'a, Key, BH> Sub<&'a UnorderedHashSet<Key, BH>> for &'a UnorderedHashSet<Key, BH>
110where
111 &'a HashSet<Key, BH>: Sub<Output = HashSet<Key, BH>>,
112{
113 type Output = UnorderedHashSet<Key, BH>;
114
115 fn sub(self, rhs: Self) -> Self::Output {
116 UnorderedHashSet::<Key, BH>(&self.0 - &rhs.0)
117 }
118}