cairo_lang_utils/
ordered_hash_set.rs

1use core::hash::{BuildHasher, Hash};
2use core::ops::Sub;
3#[cfg(feature = "std")]
4use std::collections::hash_map::RandomState;
5
6use indexmap::{Equivalent, IndexSet};
7use itertools::zip_eq;
8
9#[cfg(feature = "std")]
10#[derive(Clone, Debug)]
11pub struct OrderedHashSet<Key, BH = RandomState>(IndexSet<Key, BH>);
12#[cfg(not(feature = "std"))]
13#[derive(Clone, Debug)]
14pub struct OrderedHashSet<Key, BH = hashbrown::hash_map::DefaultHashBuilder>(IndexSet<Key, BH>);
15
16pub type Iter<'a, Key> = indexmap::set::Iter<'a, Key>;
17
18impl<Key, BH: Default> Default for OrderedHashSet<Key, BH> {
19    #[cfg(feature = "std")]
20    fn default() -> Self {
21        Self(Default::default())
22    }
23    #[cfg(not(feature = "std"))]
24    fn default() -> Self {
25        Self(IndexSet::with_hasher(Default::default()))
26    }
27}
28
29impl<Key, BH> OrderedHashSet<Key, BH> {
30    /// Returns an iterator over the values of the set, in their order.
31    pub fn iter(&self) -> Iter<'_, Key> {
32        self.0.iter()
33    }
34}
35
36impl<Key: Hash + Eq, BH> OrderedHashSet<Key, BH> {
37    /// Returns the number of elements in the set.
38    pub fn len(&self) -> usize {
39        self.0.len()
40    }
41
42    /// Returns true if the set contains no elements.
43    pub fn is_empty(&self) -> bool {
44        self.0.is_empty()
45    }
46
47    /// Remove all elements in the set, while preserving its capacity.
48    ///
49    /// Computes in O(n) time.
50    pub fn clear(&mut self) {
51        self.0.clear()
52    }
53}
54
55impl<Key: Hash + Eq, BH: BuildHasher> OrderedHashSet<Key, BH> {
56    /// Inserts the value into the set.
57    ///
58    /// If an equivalent item already exists in the set, returns `false`. Otherwise, returns `true`.
59    pub fn insert(&mut self, key: Key) -> bool {
60        self.0.insert(key)
61    }
62
63    /// Extends the set with the content of the given iterator.
64    pub fn extend<I: IntoIterator<Item = Key>>(&mut self, iter: I) {
65        self.0.extend(iter)
66    }
67
68    /// Returns true if an equivalent to value exists in the set.
69    pub fn contains<Q: ?Sized + Hash + Equivalent<Key>>(&self, value: &Q) -> bool {
70        self.0.contains(value)
71    }
72
73    /// Removes the value from the set, preserving the order of elements.
74    ///
75    /// Returns true if the value was present in the set.
76    pub fn shift_remove<Q: ?Sized + Hash + Equivalent<Key>>(&mut self, value: &Q) -> bool {
77        self.0.shift_remove(value)
78    }
79
80    /// Removes the value by swapping it with the last element, thus the order of elements is not
81    /// preserved, but the resulting order is still deterministic.
82    ///
83    /// Returns true if the value was present in the set.
84    pub fn swap_remove<Q: ?Sized + Hash + Equivalent<Key>>(&mut self, value: &Q) -> bool {
85        self.0.swap_remove(value)
86    }
87
88    pub fn difference<'a, S2>(
89        &'a self,
90        other: &'a OrderedHashSet<Key, S2>,
91    ) -> indexmap::set::Difference<'a, Key, S2>
92    where
93        S2: core::hash::BuildHasher,
94    {
95        self.0.difference(&other.0)
96    }
97
98    /// Returns `true` if all elements of `self` are contained in `other`.
99    pub fn is_subset<S2: BuildHasher>(&self, other: &OrderedHashSet<Key, S2>) -> bool {
100        self.0.is_subset(&other.0)
101    }
102
103    /// Returns `true` if all elements of `other` are contained in `self`.
104    pub fn is_superset<S2: BuildHasher>(&self, other: &OrderedHashSet<Key, S2>) -> bool {
105        self.0.is_superset(&other.0)
106    }
107
108    /// Return an iterator over all values that are either in `self` or `other`.
109    ///
110    /// Values from `self` are produced in their original order, followed by
111    /// values that are unique to `other` in their original order.
112    pub fn union<'a, BH2: BuildHasher>(
113        &'a self,
114        other: &'a OrderedHashSet<Key, BH2>,
115    ) -> indexmap::set::Union<'a, Key, BH> {
116        self.0.union(&other.0)
117    }
118}
119
120impl<Key, BH> IntoIterator for OrderedHashSet<Key, BH> {
121    type Item = Key;
122    type IntoIter = <IndexSet<Key, BH> as IntoIterator>::IntoIter;
123
124    fn into_iter(self) -> Self::IntoIter {
125        self.0.into_iter()
126    }
127}
128
129impl<'a, Key, BH> IntoIterator for &'a OrderedHashSet<Key, BH> {
130    type Item = &'a Key;
131    type IntoIter = <&'a IndexSet<Key, BH> as IntoIterator>::IntoIter;
132
133    fn into_iter(self) -> Self::IntoIter {
134        self.iter()
135    }
136}
137
138impl<Key: Eq, BH> PartialEq for OrderedHashSet<Key, BH> {
139    fn eq(&self, other: &Self) -> bool {
140        if self.0.len() != other.0.len() {
141            return false;
142        };
143
144        zip_eq(self.0.iter(), other.0.iter()).all(|(a, b)| a == b)
145    }
146}
147
148impl<Key: Eq, BH> Eq for OrderedHashSet<Key, BH> {}
149
150impl<Key: Hash + Eq, BH: BuildHasher + Default> FromIterator<Key> for OrderedHashSet<Key, BH> {
151    fn from_iter<T: IntoIterator<Item = Key>>(iter: T) -> Self {
152        Self(iter.into_iter().collect())
153    }
154}
155
156impl<'a, Key, BH> Sub<&'a OrderedHashSet<Key, BH>> for &'a OrderedHashSet<Key, BH>
157where
158    &'a IndexSet<Key, BH>: Sub<Output = IndexSet<Key, BH>>,
159{
160    type Output = OrderedHashSet<Key, BH>;
161
162    fn sub(self, rhs: Self) -> Self::Output {
163        OrderedHashSet::<Key, BH>(&self.0 - &rhs.0)
164    }
165}
166
167#[cfg(feature = "serde")]
168mod impl_serde {
169    use serde::{Deserialize, Deserializer, Serialize, Serializer};
170
171    use super::*;
172
173    impl<K: Hash + Eq + Serialize, BH: BuildHasher> Serialize for OrderedHashSet<K, BH> {
174        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
175            self.0.serialize(serializer)
176        }
177    }
178
179    impl<'de, K: Hash + Eq + Deserialize<'de>, BH: BuildHasher + Default> Deserialize<'de>
180        for OrderedHashSet<K, BH>
181    {
182        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
183            IndexSet::<K, BH>::deserialize(deserializer).map(|s| OrderedHashSet(s))
184        }
185    }
186}