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.
178pub struct ExtractIf<'a, T: WeakElement, F> {
179    /// The underlying iterator.
180    inner: inner::ExtractIf<'a, inner::WeakK<ByPtr<T>>, inner::Owned<()>>,
181    /// A marker so that F does not appear unused.
182    _phantom: PhantomData<F>,
183}
184
185impl<'a, T: WeakElement, F> Iterator for ExtractIf<'a, T, F> {
186    type Item = T::Strong;
187
188    fn next(&mut self) -> Option<Self::Item> {
189        self.inner.next().map(|(k, ())| k)
190    }
191
192    fn size_hint(&self) -> (usize, Option<usize>) {
193        self.inner.size_hint()
194    }
195}
196
197set_op_types! {PtrWeakHashSet where {T: WeakElement, T::Strong: Deref}}
198set_operators! {PtrWeakHashSet where {T: WeakElement, T::Strong: Deref}}
199
200impl<T, S, S1> PartialEq<PtrWeakHashSet<T, S1>> for PtrWeakHashSet<T, S>
201where
202    T: WeakElement,
203    T::Strong: Deref,
204    S: BuildHasher,
205    S1: BuildHasher,
206{
207    fn eq(&self, other: &PtrWeakHashSet<T, S1>) -> bool {
208        self.0 == other.0
209    }
210}
211
212impl<T: WeakElement, S: BuildHasher> Eq for PtrWeakHashSet<T, S> where T::Strong: Deref {}
213
214impl<T, S> FromIterator<T::Strong> for PtrWeakHashSet<T, S>
215where
216    T: WeakElement,
217    T::Strong: Deref,
218    S: BuildHasher + Default,
219{
220    fn from_iter<I: IntoIterator<Item = T::Strong>>(iter: I) -> Self {
221        PtrWeakHashSet(base::PtrWeakKeyHashMap::<T, (), S>::from_iter(
222            iter.into_iter().map(|k| (k, ())),
223        ))
224    }
225}
226
227impl<T, const N: usize> From<[T::Strong; N]> for PtrWeakHashSet<T, RandomState>
228where
229    T: WeakElement,
230    T::Strong: Deref,
231{
232    /// Converts an array of elements into a set.
233    ///
234    /// If any entries in the array are equal,
235    /// all but one of the corresponding values will be dropped.
236    fn from(value: [T::Strong; N]) -> Self {
237        Self::from_iter(value)
238    }
239}
240
241impl<T, S> Extend<T::Strong> for PtrWeakHashSet<T, S>
242where
243    T: WeakElement,
244    T::Strong: Deref,
245    S: BuildHasher,
246{
247    fn extend<I: IntoIterator<Item = T::Strong>>(&mut self, iter: I) {
248        self.0.extend(iter.into_iter().map(|k| (k, ())));
249    }
250}
251
252impl<T, S> Debug for PtrWeakHashSet<T, S>
253where
254    T: WeakElement,
255    T::Strong: Debug,
256{
257    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
258        f.debug_set().entries(self.iter()).finish()
259    }
260}
261
262impl<T: WeakElement, S> IntoIterator for PtrWeakHashSet<T, S> {
263    type Item = T::Strong;
264    type IntoIter = IntoIter<T>;
265
266    /// Creates an owning iterator from `self`.
267    ///
268    /// *O*(1) time (and *O*(*n*) time to dispose of the result)
269    fn into_iter(self) -> Self::IntoIter {
270        IntoIter(self.0.into_iter())
271    }
272}
273
274impl<'a, T: WeakElement, S> IntoIterator for &'a PtrWeakHashSet<T, S>
275where
276    T::Strong: Deref,
277{
278    type Item = T::Strong;
279    type IntoIter = Iter<'a, T>;
280
281    /// Creates a borrowing iterator from `self`.
282    ///
283    /// *O*(1) time
284    fn into_iter(self) -> Self::IntoIter {
285        Iter(self.0.keys())
286    }
287}
288
289/// Helper: Given two references to sets, return them in ascending order of
290/// len().
291fn sort_by_size<'a, T: WeakElement, S: BuildHasher>(
292    a: &'a PtrWeakHashSet<T, S>,
293    b: &'a PtrWeakHashSet<T, S>,
294) -> (&'a PtrWeakHashSet<T, S>, &'a PtrWeakHashSet<T, S>)
295where
296    T::Strong: Deref,
297{
298    if a.len() < b.len() {
299        (a, b)
300    } else {
301        (b, a)
302    }
303}
304
305#[cfg(test)]
306mod test {
307    use super::PtrWeakHashSet;
308    use crate::{
309        compat::{
310            format,
311            rc::{Rc, Weak},
312        },
313        tests::util::VecDebugAsSet,
314    };
315
316    crate::tests::common::empty_constructor_tests! {PtrWeakHashSet<Weak<u8>>}
317    crate::tests::set_operations::set_operation_tests! {PtrWeakHashSet, 1}
318
319    #[test]
320    fn test_debug() {
321        let s = [Rc::new(1), Rc::new(2)];
322        let set: PtrWeakHashSet<Weak<u32>> = s.clone().into();
323        let v: VecDebugAsSet<_> = set.iter().collect();
324        assert_eq!(format!("{v:?}"), format!("{set:?}"));
325    }
326}