Skip to main content

weak_table/
ptr_weak_hash_set.rs

1//! A hash set where the elements are held by weak pointers and compared by pointer.
2
3use crate::common::*;
4use crate::compat::*;
5use crate::inner;
6
7use super::by_ptr::ByPtr;
8use super::ptr_weak_key_hash_map as base;
9use super::traits::*;
10
11pub use super::PtrWeakHashSet;
12
13universal_hashless_members! {
14    PtrWeakHashSet
15    ("`PtrWeakHashSet`", a "set")
16    super::PtrWeakKeyHashMap::with_capacity_and_hasher
17    {T}
18}
19
20impl<T: WeakElement, S: BuildHasher> PtrWeakHashSet<T, S>
21where
22    T::Strong: Deref,
23{
24    universal_key_independent_members! {"elements"}
25
26    /// Returns true if the set contains the specified key.
27    ///
28    /// expected *O*(1) time; worst-case *O*(*p*) time
29    pub fn contains(&self, key: &T::Strong) -> bool {
30        self.0.contains_key(key)
31    }
32
33    /// Unconditionally inserts `key` into this set,
34    /// replacing any previous entry with the same key.
35    ///
36    /// Returns true if the key was absent before, and false otherwise.
37    ///
38    /// (Note that unlike `HashSet::insert`, this insert method always replaces
39    /// the key.)
40    ///
41    /// expected *O*(1) time; worst-case *O*(*p*) time
42    pub fn insert(&mut self, key: T::Strong) -> bool {
43        self.0.insert(key, ()).is_some()
44    }
45
46    /// Removes the element matching the given key, if it exists.
47    ///
48    /// Returns true if an entry was removed.
49    ///
50    /// expected *O*(1) time; worst-case *O*(*p*) time
51    pub fn remove(&mut self, key: &T::Strong) -> bool {
52        self.0.remove(key).is_some()
53    }
54
55    /// Removes all elements not satisfying the given predicate.
56    ///
57    /// Also removes any expired elements.
58    ///
59    /// *O*(*n*) time
60    pub fn retain<F>(&mut self, mut f: F)
61    where
62        F: FnMut(T::Strong) -> bool,
63    {
64        self.0.retain(|k, _| f(k));
65    }
66
67    /// Is self a subset of other?
68    ///
69    /// expected *O*(*n*) time; worst-case *O*(*nq*) time (where *n* is
70    /// `self.capacity()` and *q* is the length of the probe sequences
71    /// in `other`)
72    pub fn is_subset<S1>(&self, other: &PtrWeakHashSet<T, S1>) -> bool
73    where
74        S1: BuildHasher,
75    {
76        self.0.domain_is_subset(&other.0)
77    }
78
79    /// Helper: return true if 'self' contains 'item'.
80    fn contains_strong(&self, item: &T::Strong) -> bool {
81        self.contains(item)
82    }
83
84    set_op_methods! {PtrWeakHashSet}
85    set_relationships! {PtrWeakHashSet}
86}
87
88/// An iterator over the elements of a set.
89pub struct Iter<'a, T: 'a>(base::Keys<'a, ByPtr<T>, ()>);
90
91impl<'a, T: WeakElement> Iterator for Iter<'a, T> {
92    type Item = T::Strong;
93
94    fn next(&mut self) -> Option<Self::Item> {
95        self.0.next()
96    }
97
98    fn size_hint(&self) -> (usize, Option<usize>) {
99        self.0.size_hint()
100    }
101}
102
103/// An iterator over the elements of a set.
104pub struct IntoIter<T>(base::IntoIter<ByPtr<T>, ()>);
105
106impl<T: WeakElement> Iterator for IntoIter<T> {
107    type Item = T::Strong;
108
109    fn next(&mut self) -> Option<Self::Item> {
110        self.0.next().map(|pair| pair.0)
111    }
112
113    fn size_hint(&self) -> (usize, Option<usize>) {
114        self.0.size_hint()
115    }
116}
117
118/// A draining iterator over the elements of a set.
119///
120/// Once this iterator is dropped, all elements are removed from the set,
121/// whether the iterator itself was drained or not.
122pub struct Drain<'a, T: 'a>(base::Drain<'a, ByPtr<T>, ()>);
123
124impl<'a, T: WeakElement> Iterator for Drain<'a, T> {
125    type Item = T::Strong;
126
127    fn next(&mut self) -> Option<Self::Item> {
128        self.0.next().map(|pair| pair.0)
129    }
130
131    fn size_hint(&self) -> (usize, Option<usize>) {
132        self.0.size_hint()
133    }
134}
135
136impl<T: WeakElement, S> PtrWeakHashSet<T, S> {
137    /// Gets an iterator over the elements of this set.
138    ///
139    /// *O*(1) time
140    pub fn iter(&self) -> Iter<'_, T> {
141        Iter(self.0.keys())
142    }
143
144    /// Gets a draining iterator, which removes all the elements but retains the storage.
145    ///
146    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
147    pub fn drain(&mut self) -> Drain<'_, T> {
148        Drain(self.0.drain())
149    }
150
151    /// Gets an iterator that removes and returns elements matching a given predicate.
152    ///
153    /// Expired elements are also removed.
154    ///
155    /// If this iterator is dropped before it is completed, then no further
156    /// elements are removed.
157    /// (This is in contrast to the behavior of [`drain`](Self::drain)).
158    ///
159    /// *O*(1) time
160    pub fn extract_if<'a, F>(&'a mut self, mut f: F) -> ExtractIf<'a, T, F>
161    where
162        F: FnMut(T::Strong) -> bool + 'a,
163    {
164        ExtractIf {
165            inner: self.0 .0 .0.extract_if(move |e| {
166                if let Some(k) = e.0.val.view() {
167                    f(k)
168                } else {
169                    true
170                }
171            }),
172            _phantom: PhantomData,
173        }
174    }
175}
176
177/// An iterator that removes members that match a given predicate.
178#[must_use = "iterators do nothing unless consumed; \
179    consider using `retain` instead"]
180pub struct ExtractIf<'a, T: WeakElement, F> {
181    /// The underlying iterator.
182    inner: inner::ExtractIf<'a, inner::WeakK<ByPtr<T>>, inner::Owned<()>>,
183    /// A marker so that F does not appear unused.
184    _phantom: PhantomData<F>,
185}
186
187impl<'a, T: WeakElement, F> Iterator for ExtractIf<'a, T, F> {
188    type Item = T::Strong;
189
190    fn next(&mut self) -> Option<Self::Item> {
191        self.inner.next().map(|(k, ())| k)
192    }
193
194    fn size_hint(&self) -> (usize, Option<usize>) {
195        self.inner.size_hint()
196    }
197}
198
199set_op_types! {PtrWeakHashSet where {T: WeakElement, T::Strong: Deref}}
200set_operators! {PtrWeakHashSet where {T: WeakElement, T::Strong: Deref}}
201
202impl<T, S, S1> PartialEq<PtrWeakHashSet<T, S1>> for PtrWeakHashSet<T, S>
203where
204    T: WeakElement,
205    T::Strong: Deref,
206    S: BuildHasher,
207    S1: BuildHasher,
208{
209    fn eq(&self, other: &PtrWeakHashSet<T, S1>) -> bool {
210        self.0 == other.0
211    }
212}
213
214impl<T: WeakElement, S: BuildHasher> Eq for PtrWeakHashSet<T, S> where T::Strong: Deref {}
215
216impl<T, S> FromIterator<T::Strong> for PtrWeakHashSet<T, S>
217where
218    T: WeakElement,
219    T::Strong: Deref,
220    S: BuildHasher + Default,
221{
222    fn from_iter<I: IntoIterator<Item = T::Strong>>(iter: I) -> Self {
223        PtrWeakHashSet(base::PtrWeakKeyHashMap::<T, (), S>::from_iter(
224            iter.into_iter().map(|k| (k, ())),
225        ))
226    }
227}
228
229#[cfg(any(test, feature = "std", feature = "ahash"))]
230impl<T, const N: usize> From<[T::Strong; N]> for PtrWeakHashSet<T, RandomState>
231where
232    T: WeakElement,
233    T::Strong: Deref,
234{
235    /// Converts an array of elements into a set.
236    ///
237    /// If any entries in the array are equal,
238    /// all but one of the corresponding values will be dropped.
239    fn from(value: [T::Strong; N]) -> Self {
240        Self::from_iter(value)
241    }
242}
243
244impl<T, S> Extend<T::Strong> for PtrWeakHashSet<T, S>
245where
246    T: WeakElement,
247    T::Strong: Deref,
248    S: BuildHasher,
249{
250    fn extend<I: IntoIterator<Item = T::Strong>>(&mut self, iter: I) {
251        self.0.extend(iter.into_iter().map(|k| (k, ())));
252    }
253}
254
255impl<T, S> Debug for PtrWeakHashSet<T, S>
256where
257    T: WeakElement,
258    T::Strong: Debug,
259{
260    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
261        f.debug_set().entries(self.iter()).finish()
262    }
263}
264
265impl<T: WeakElement, S> IntoIterator for PtrWeakHashSet<T, S> {
266    type Item = T::Strong;
267    type IntoIter = IntoIter<T>;
268
269    /// Creates an owning iterator from `self`.
270    ///
271    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
272    fn into_iter(self) -> Self::IntoIter {
273        IntoIter(self.0.into_iter())
274    }
275}
276
277impl<'a, T: WeakElement, S> IntoIterator for &'a PtrWeakHashSet<T, S>
278where
279    T::Strong: Deref,
280{
281    type Item = T::Strong;
282    type IntoIter = Iter<'a, T>;
283
284    /// Creates a borrowing iterator from `self`.
285    ///
286    /// *O*(1) time
287    fn into_iter(self) -> Self::IntoIter {
288        Iter(self.0.keys())
289    }
290}
291
292/// Helper: Given two references to sets, return them in ascending order of
293/// len().
294fn sort_by_size<'a, T: WeakElement, S: BuildHasher>(
295    a: &'a PtrWeakHashSet<T, S>,
296    b: &'a PtrWeakHashSet<T, S>,
297) -> (&'a PtrWeakHashSet<T, S>, &'a PtrWeakHashSet<T, S>)
298where
299    T::Strong: Deref,
300{
301    if a.len() < b.len() {
302        (a, b)
303    } else {
304        (b, a)
305    }
306}
307
308#[cfg(test)]
309mod test {
310    // TODO 050: remove.
311    #![cfg_attr(feature = "ahash", allow(deprecated))]
312
313    use super::PtrWeakHashSet;
314    use crate::{
315        compat::{
316            format,
317            rc::{Rc, Weak},
318        },
319        tests::util::VecDebugAsSet,
320    };
321
322    crate::tests::common::empty_constructor_tests! {PtrWeakHashSet<Weak<u8>>}
323    crate::tests::set_operations::set_operation_tests! {PtrWeakHashSet, 1}
324
325    #[test]
326    fn test_debug() {
327        let s = [Rc::new(1), Rc::new(2)];
328        let set: PtrWeakHashSet<Weak<u32>> = s.clone().into();
329        let v: VecDebugAsSet<_> = set.iter().collect();
330        assert_eq!(format!("{v:?}"), format!("{set:?}"));
331    }
332}