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