griddle/
set.rs

1use crate::TryReserveError;
2use alloc::borrow::ToOwned;
3use core::borrow::Borrow;
4use core::fmt;
5use core::hash::{BuildHasher, Hash};
6use core::iter::{Chain, FromIterator, FusedIterator};
7use core::mem;
8use core::ops::{BitAnd, BitOr, BitXor, Sub};
9
10use super::map::{self, ConsumeAllOnDrop, DefaultHashBuilder, DrainFilterInner, HashMap, Keys};
11
12// Future Optimization (FIXME!)
13// =============================
14//
15// Iteration over zero sized values is a noop. There is no need
16// for `bucket.val` in the case of HashSet. I suppose we would need HKT
17// to get rid of it properly.
18
19/// A hash set implemented as a `HashMap` where the value is `()`.
20///
21/// As with the [`HashMap`] type, a `HashSet` requires that the elements
22/// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
23/// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
24/// it is important that the following property holds:
25///
26/// ```text
27/// k1 == k2 -> hash(k1) == hash(k2)
28/// ```
29///
30/// In other words, if two keys are equal, their hashes must be equal.
31///
32///
33/// It is a logic error for an item to be modified in such a way that the
34/// item's hash, as determined by the [`Hash`] trait, or its equality, as
35/// determined by the [`Eq`] trait, changes while it is in the set. This is
36/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
37/// unsafe code.
38///
39/// It is also a logic error for the [`Hash`] implementation of a key to panic.
40/// This is generally only possible if the trait is implemented manually. If a
41/// panic does occur then the contents of the `HashSet` may become corrupted and
42/// some items may be dropped from the table.
43///
44/// # Examples
45///
46/// ```
47/// use griddle::HashSet;
48/// // Type inference lets us omit an explicit type signature (which
49/// // would be `HashSet<String>` in this example).
50/// let mut books = HashSet::new();
51///
52/// // Add some books.
53/// books.insert("A Dance With Dragons".to_string());
54/// books.insert("To Kill a Mockingbird".to_string());
55/// books.insert("The Odyssey".to_string());
56/// books.insert("The Great Gatsby".to_string());
57///
58/// // Check for a specific one.
59/// if !books.contains("The Winds of Winter") {
60///     println!("We have {} books, but The Winds of Winter ain't one.",
61///              books.len());
62/// }
63///
64/// // Remove a book.
65/// books.remove("The Odyssey");
66///
67/// // Iterate over everything.
68/// for book in &books {
69///     println!("{}", book);
70/// }
71/// ```
72///
73/// The easiest way to use `HashSet` with a custom type is to derive
74/// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
75/// future be implied by [`Eq`].
76///
77/// ```
78/// use griddle::HashSet;
79/// #[derive(Hash, Eq, PartialEq, Debug)]
80/// struct Viking {
81///     name: String,
82///     power: usize,
83/// }
84///
85/// let mut vikings = HashSet::new();
86///
87/// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
88/// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
89/// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
90/// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
91///
92/// // Use derived implementation to print the vikings.
93/// for x in &vikings {
94///     println!("{:?}", x);
95/// }
96/// ```
97///
98/// A `HashSet` with fixed list of elements can be initialized from an array:
99///
100/// ```
101/// use griddle::HashSet;
102///
103/// let viking_names: HashSet<&'static str> =
104///     [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
105/// // use the values stored in the set
106/// ```
107///
108/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
109/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
110/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
111/// [`HashMap`]: struct.HashMap.html
112/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
113/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
114pub struct HashSet<T, S = DefaultHashBuilder> {
115    pub(crate) map: HashMap<T, (), S>,
116}
117
118impl<T: Clone + Hash, S: Clone + BuildHasher> Clone for HashSet<T, S> {
119    fn clone(&self) -> Self {
120        HashSet {
121            map: self.map.clone(),
122        }
123    }
124
125    fn clone_from(&mut self, source: &Self) {
126        self.map.clone_from(&source.map);
127    }
128}
129
130#[cfg(feature = "ahash")]
131impl<T> HashSet<T, DefaultHashBuilder> {
132    /// Creates an empty `HashSet`.
133    ///
134    /// The hash set is initially created with a capacity of 0, so it will not allocate until it
135    /// is first inserted into.
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// use griddle::HashSet;
141    /// let set: HashSet<i32> = HashSet::new();
142    /// ```
143    #[cfg_attr(feature = "inline-more", inline)]
144    pub fn new() -> Self {
145        Self {
146            map: HashMap::new(),
147        }
148    }
149
150    /// Creates an empty `HashSet` with the specified capacity.
151    ///
152    /// The hash set will be able to hold at least `capacity` elements without
153    /// reallocating. If `capacity` is 0, the hash set will not allocate.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use griddle::HashSet;
159    /// let set: HashSet<i32> = HashSet::with_capacity(10);
160    /// assert!(set.capacity() >= 10);
161    /// ```
162    #[cfg_attr(feature = "inline-more", inline)]
163    pub fn with_capacity(capacity: usize) -> Self {
164        Self {
165            map: HashMap::with_capacity(capacity),
166        }
167    }
168}
169
170impl<T, S> HashSet<T, S> {
171    /// Returns the number of elements the set can hold without reallocating.
172    ///
173    /// # Examples
174    ///
175    /// ```
176    /// use griddle::HashSet;
177    /// let set: HashSet<i32> = HashSet::with_capacity(100);
178    /// assert!(set.capacity() >= 100);
179    /// ```
180    #[cfg_attr(feature = "inline-more", inline)]
181    pub fn capacity(&self) -> usize {
182        self.map.capacity()
183    }
184
185    /// An iterator visiting all elements in arbitrary order.
186    /// The iterator element type is `&'a T`.
187    ///
188    /// # Examples
189    ///
190    /// ```
191    /// use griddle::HashSet;
192    /// let mut set = HashSet::new();
193    /// set.insert("a");
194    /// set.insert("b");
195    ///
196    /// // Will print in an arbitrary order.
197    /// for x in set.iter() {
198    ///     println!("{}", x);
199    /// }
200    /// ```
201    #[cfg_attr(feature = "inline-more", inline)]
202    pub fn iter(&self) -> Iter<'_, T> {
203        Iter {
204            iter: self.map.keys(),
205        }
206    }
207
208    #[cfg(test)]
209    fn is_split(&self) -> bool {
210        self.map.table.is_split()
211    }
212
213    /// Returns the number of elements in the set.
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use griddle::HashSet;
219    ///
220    /// let mut v = HashSet::new();
221    /// assert_eq!(v.len(), 0);
222    /// v.insert(1);
223    /// assert_eq!(v.len(), 1);
224    /// ```
225    #[cfg_attr(feature = "inline-more", inline)]
226    pub fn len(&self) -> usize {
227        self.map.len()
228    }
229
230    /// Returns `true` if the set contains no elements.
231    ///
232    /// # Examples
233    ///
234    /// ```
235    /// use griddle::HashSet;
236    ///
237    /// let mut v = HashSet::new();
238    /// assert!(v.is_empty());
239    /// v.insert(1);
240    /// assert!(!v.is_empty());
241    /// ```
242    #[cfg_attr(feature = "inline-more", inline)]
243    pub fn is_empty(&self) -> bool {
244        self.map.is_empty()
245    }
246
247    /// Clears the set, returning all elements in an iterator.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// use griddle::HashSet;
253    ///
254    /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
255    /// assert!(!set.is_empty());
256    ///
257    /// // print 1, 2, 3 in an arbitrary order
258    /// for i in set.drain() {
259    ///     println!("{}", i);
260    /// }
261    ///
262    /// assert!(set.is_empty());
263    /// ```
264    #[cfg_attr(feature = "inline-more", inline)]
265    pub fn drain(&mut self) -> Drain<'_, T> {
266        Drain {
267            iter: self.map.drain(),
268        }
269    }
270
271    /// Retains only the elements specified by the predicate.
272    ///
273    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
274    ///
275    /// # Examples
276    ///
277    /// ```
278    /// use griddle::HashSet;
279    ///
280    /// let xs = [1,2,3,4,5,6];
281    /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
282    /// set.retain(|&k| k % 2 == 0);
283    /// assert_eq!(set.len(), 3);
284    /// ```
285    pub fn retain<F>(&mut self, mut f: F)
286    where
287        F: FnMut(&T) -> bool,
288    {
289        self.map.retain(|k, _| f(k));
290    }
291
292    /// Drains elements which are true under the given predicate,
293    /// and returns an iterator over the removed items.
294    ///
295    /// In other words, move all elements `e` such that `f(&e)` returns `true` out
296    /// into another iterator.
297    ///
298    /// When the returned DrainedFilter is dropped, any remaining elements that satisfy
299    /// the predicate are dropped from the set.
300    ///
301    /// # Examples
302    ///
303    /// ```
304    /// use griddle::HashSet;
305    ///
306    /// let mut set: HashSet<i32> = (0..8).collect();
307    /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
308    ///
309    /// let mut evens = drained.into_iter().collect::<Vec<_>>();
310    /// let mut odds = set.into_iter().collect::<Vec<_>>();
311    /// evens.sort();
312    /// odds.sort();
313    ///
314    /// assert_eq!(evens, vec![0, 2, 4, 6]);
315    /// assert_eq!(odds, vec![1, 3, 5, 7]);
316    /// ```
317    #[cfg_attr(feature = "inline-more", inline)]
318    pub fn drain_filter<F>(&mut self, f: F) -> DrainFilter<'_, T, F>
319    where
320        F: FnMut(&T) -> bool,
321    {
322        DrainFilter {
323            f,
324            inner: DrainFilterInner {
325                iter: unsafe { self.map.table.iter() },
326                table: &mut self.map.table,
327            },
328        }
329    }
330
331    /// Clears the set, removing all values.
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// use griddle::HashSet;
337    ///
338    /// let mut v = HashSet::new();
339    /// v.insert(1);
340    /// v.clear();
341    /// assert!(v.is_empty());
342    /// ```
343    #[cfg_attr(feature = "inline-more", inline)]
344    pub fn clear(&mut self) {
345        self.map.clear()
346    }
347}
348
349impl<T, S> HashSet<T, S> {
350    /// Creates a new empty hash set which will use the given hasher to hash
351    /// keys.
352    ///
353    /// The hash set is also created with the default initial capacity.
354    ///
355    /// Warning: `hasher` is normally randomly generated, and
356    /// is designed to allow `HashSet`s to be resistant to attacks that
357    /// cause many collisions and very poor performance. Setting it
358    /// manually using this function can expose a DoS attack vector.
359    ///
360    /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
361    /// the HashMap to be useful, see its documentation for details.
362    ///
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use griddle::HashSet;
368    /// use griddle::hash_map::DefaultHashBuilder;
369    ///
370    /// let s = DefaultHashBuilder::default();
371    /// let mut set = HashSet::with_hasher(s);
372    /// set.insert(2);
373    /// ```
374    ///
375    /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
376    #[cfg_attr(feature = "inline-more", inline)]
377    pub const fn with_hasher(hasher: S) -> Self {
378        Self {
379            map: HashMap::with_hasher(hasher),
380        }
381    }
382
383    /// Creates an empty `HashSet` with the specified capacity, using
384    /// `hasher` to hash the keys.
385    ///
386    /// The hash set will be able to hold at least `capacity` elements without
387    /// reallocating. If `capacity` is 0, the hash set will not allocate.
388    ///
389    /// Warning: `hasher` is normally randomly generated, and
390    /// is designed to allow `HashSet`s to be resistant to attacks that
391    /// cause many collisions and very poor performance. Setting it
392    /// manually using this function can expose a DoS attack vector.
393    ///
394    /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
395    /// the HashMap to be useful, see its documentation for details.
396    ///
397    /// # Examples
398    ///
399    /// ```
400    /// use griddle::HashSet;
401    /// use griddle::hash_map::DefaultHashBuilder;
402    ///
403    /// let s = DefaultHashBuilder::default();
404    /// let mut set = HashSet::with_capacity_and_hasher(10, s);
405    /// set.insert(1);
406    /// ```
407    ///
408    /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
409    #[cfg_attr(feature = "inline-more", inline)]
410    pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
411        Self {
412            map: HashMap::with_capacity_and_hasher(capacity, hasher),
413        }
414    }
415}
416
417impl<T, S> HashSet<T, S>
418where
419    T: Eq + Hash,
420    S: BuildHasher,
421{
422    /// Returns a reference to the set's [`BuildHasher`].
423    ///
424    /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
425    ///
426    /// # Examples
427    ///
428    /// ```
429    /// use griddle::HashSet;
430    /// use griddle::hash_map::DefaultHashBuilder;
431    ///
432    /// let hasher = DefaultHashBuilder::default();
433    /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
434    /// let hasher: &DefaultHashBuilder = set.hasher();
435    /// ```
436    #[cfg_attr(feature = "inline-more", inline)]
437    pub fn hasher(&self) -> &S {
438        self.map.hasher()
439    }
440}
441
442impl<T, S> HashSet<T, S>
443where
444    T: Eq + Hash,
445    S: BuildHasher,
446{
447    /// Reserves capacity for at least `additional` more elements to be inserted
448    /// in the `HashSet`. The collection may reserve more space to avoid
449    /// frequent reallocations.
450    ///
451    /// # Panics
452    ///
453    /// Panics if the new allocation size overflows `usize`.
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// use griddle::HashSet;
459    /// let mut set: HashSet<i32> = HashSet::new();
460    /// set.reserve(10);
461    /// assert!(set.capacity() >= 10);
462    /// ```
463    #[cfg_attr(feature = "inline-more", inline)]
464    pub fn reserve(&mut self, additional: usize) {
465        self.map.reserve(additional)
466    }
467
468    /// Tries to reserve capacity for at least `additional` more elements to be inserted
469    /// in the given `HashSet<K,V>`. The collection may reserve more space to avoid
470    /// frequent reallocations.
471    ///
472    /// # Errors
473    ///
474    /// If the capacity overflows, or the allocator reports a failure, then an error
475    /// is returned.
476    ///
477    /// # Examples
478    ///
479    /// ```
480    /// use griddle::HashSet;
481    /// let mut set: HashSet<i32> = HashSet::new();
482    /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
483    /// ```
484    #[cfg_attr(feature = "inline-more", inline)]
485    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
486        self.map.try_reserve(additional)
487    }
488
489    /// Shrinks the capacity of the set as much as possible. It will drop
490    /// down as much as possible while maintaining the internal rules
491    /// and possibly leaving some space in accordance with the resize policy.
492    ///
493    /// # Examples
494    ///
495    /// ```
496    /// use griddle::HashSet;
497    ///
498    /// let mut set = HashSet::with_capacity(100);
499    /// set.insert(1);
500    /// set.insert(2);
501    /// assert!(set.capacity() >= 100);
502    /// set.shrink_to_fit();
503    /// assert!(set.capacity() >= 2);
504    /// ```
505    #[cfg_attr(feature = "inline-more", inline)]
506    pub fn shrink_to_fit(&mut self) {
507        self.map.shrink_to_fit()
508    }
509
510    /// Shrinks the capacity of the set with a lower limit. It will drop
511    /// down no lower than the supplied limit while maintaining the internal rules
512    /// and possibly leaving some space in accordance with the resize policy.
513    ///
514    /// Panics if the current capacity is smaller than the supplied
515    /// minimum capacity.
516    ///
517    /// # Examples
518    ///
519    /// ```
520    /// use griddle::HashSet;
521    ///
522    /// let mut set = HashSet::with_capacity(100);
523    /// set.insert(1);
524    /// set.insert(2);
525    /// assert!(set.capacity() >= 100);
526    /// set.shrink_to(10);
527    /// assert!(set.capacity() >= 10);
528    /// set.shrink_to(0);
529    /// assert!(set.capacity() >= 2);
530    /// ```
531    #[cfg_attr(feature = "inline-more", inline)]
532    pub fn shrink_to(&mut self, min_capacity: usize) {
533        self.map.shrink_to(min_capacity)
534    }
535
536    /// Visits the values representing the difference,
537    /// i.e., the values that are in `self` but not in `other`.
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// use griddle::HashSet;
543    /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
544    /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
545    ///
546    /// // Can be seen as `a - b`.
547    /// for x in a.difference(&b) {
548    ///     println!("{}", x); // Print 1
549    /// }
550    ///
551    /// let diff: HashSet<_> = a.difference(&b).collect();
552    /// assert_eq!(diff, [1].iter().collect());
553    ///
554    /// // Note that difference is not symmetric,
555    /// // and `b - a` means something else:
556    /// let diff: HashSet<_> = b.difference(&a).collect();
557    /// assert_eq!(diff, [4].iter().collect());
558    /// ```
559    #[cfg_attr(feature = "inline-more", inline)]
560    pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T, S> {
561        Difference {
562            iter: self.iter(),
563            other,
564        }
565    }
566
567    /// Visits the values representing the symmetric difference,
568    /// i.e., the values that are in `self` or in `other` but not in both.
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// use griddle::HashSet;
574    /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
575    /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
576    ///
577    /// // Print 1, 4 in arbitrary order.
578    /// for x in a.symmetric_difference(&b) {
579    ///     println!("{}", x);
580    /// }
581    ///
582    /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
583    /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
584    ///
585    /// assert_eq!(diff1, diff2);
586    /// assert_eq!(diff1, [1, 4].iter().collect());
587    /// ```
588    #[cfg_attr(feature = "inline-more", inline)]
589    pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, T, S> {
590        SymmetricDifference {
591            iter: self.difference(other).chain(other.difference(self)),
592        }
593    }
594
595    /// Visits the values representing the intersection,
596    /// i.e., the values that are both in `self` and `other`.
597    ///
598    /// # Examples
599    ///
600    /// ```
601    /// use griddle::HashSet;
602    /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
603    /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
604    ///
605    /// // Print 2, 3 in arbitrary order.
606    /// for x in a.intersection(&b) {
607    ///     println!("{}", x);
608    /// }
609    ///
610    /// let intersection: HashSet<_> = a.intersection(&b).collect();
611    /// assert_eq!(intersection, [2, 3].iter().collect());
612    /// ```
613    #[cfg_attr(feature = "inline-more", inline)]
614    pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T, S> {
615        let (smaller, larger) = if self.len() <= other.len() {
616            (self, other)
617        } else {
618            (other, self)
619        };
620        Intersection {
621            iter: smaller.iter(),
622            other: larger,
623        }
624    }
625
626    /// Visits the values representing the union,
627    /// i.e., all the values in `self` or `other`, without duplicates.
628    ///
629    /// # Examples
630    ///
631    /// ```
632    /// use griddle::HashSet;
633    /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
634    /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
635    ///
636    /// // Print 1, 2, 3, 4 in arbitrary order.
637    /// for x in a.union(&b) {
638    ///     println!("{}", x);
639    /// }
640    ///
641    /// let union: HashSet<_> = a.union(&b).collect();
642    /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
643    /// ```
644    #[cfg_attr(feature = "inline-more", inline)]
645    pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T, S> {
646        let (smaller, larger) = if self.len() >= other.len() {
647            (self, other)
648        } else {
649            (other, self)
650        };
651        Union {
652            iter: larger.iter().chain(smaller.difference(larger)),
653        }
654    }
655
656    /// Returns `true` if the set contains a value.
657    ///
658    /// The value may be any borrowed form of the set's value type, but
659    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
660    /// the value type.
661    ///
662    /// # Examples
663    ///
664    /// ```
665    /// use griddle::HashSet;
666    ///
667    /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
668    /// assert_eq!(set.contains(&1), true);
669    /// assert_eq!(set.contains(&4), false);
670    /// ```
671    ///
672    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
673    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
674    #[cfg_attr(feature = "inline-more", inline)]
675    pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
676    where
677        T: Borrow<Q>,
678        Q: Hash + Eq,
679    {
680        self.map.contains_key(value)
681    }
682
683    /// Returns a reference to the value in the set, if any, that is equal to the given value.
684    ///
685    /// The value may be any borrowed form of the set's value type, but
686    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
687    /// the value type.
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// use griddle::HashSet;
693    ///
694    /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
695    /// assert_eq!(set.get(&2), Some(&2));
696    /// assert_eq!(set.get(&4), None);
697    /// ```
698    ///
699    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
700    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
701    #[cfg_attr(feature = "inline-more", inline)]
702    pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
703    where
704        T: Borrow<Q>,
705        Q: Hash + Eq,
706    {
707        // Avoid `Option::map` because it bloats LLVM IR.
708        match self.map.get_key_value(value) {
709            Some((k, _)) => Some(k),
710            None => None,
711        }
712    }
713
714    /// Inserts the given `value` into the set if it is not present, then
715    /// returns a reference to the value in the set.
716    ///
717    /// # Examples
718    ///
719    /// ```
720    /// use griddle::HashSet;
721    ///
722    /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
723    /// assert_eq!(set.len(), 3);
724    /// assert_eq!(set.get_or_insert(2), &2);
725    /// assert_eq!(set.get_or_insert(100), &100);
726    /// assert_eq!(set.len(), 4); // 100 was inserted
727    /// ```
728    #[cfg_attr(feature = "inline-more", inline)]
729    pub fn get_or_insert(&mut self, value: T) -> &T {
730        // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
731        // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
732        self.map
733            .raw_entry_mut()
734            .from_key(&value)
735            .or_insert(value, ())
736            .0
737    }
738
739    /// Inserts an owned copy of the given `value` into the set if it is not
740    /// present, then returns a reference to the value in the set.
741    ///
742    /// # Examples
743    ///
744    /// ```
745    /// use griddle::HashSet;
746    ///
747    /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
748    ///     .iter().map(|&pet| pet.to_owned()).collect();
749    ///
750    /// assert_eq!(set.len(), 3);
751    /// for &pet in &["cat", "dog", "fish"] {
752    ///     let value = set.get_or_insert_owned(pet);
753    ///     assert_eq!(value, pet);
754    /// }
755    /// assert_eq!(set.len(), 4); // a new "fish" was inserted
756    /// ```
757    #[inline]
758    pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
759    where
760        T: Borrow<Q>,
761        Q: Hash + Eq + ToOwned<Owned = T>,
762    {
763        // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
764        // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
765        self.map
766            .raw_entry_mut()
767            .from_key(value)
768            .or_insert_with(|| (value.to_owned(), ()))
769            .0
770    }
771
772    /// Inserts a value computed from `f` into the set if the given `value` is
773    /// not present, then returns a reference to the value in the set.
774    ///
775    /// # Examples
776    ///
777    /// ```
778    /// use griddle::HashSet;
779    ///
780    /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
781    ///     .iter().map(|&pet| pet.to_owned()).collect();
782    ///
783    /// assert_eq!(set.len(), 3);
784    /// for &pet in &["cat", "dog", "fish"] {
785    ///     let value = set.get_or_insert_with(pet, str::to_owned);
786    ///     assert_eq!(value, pet);
787    /// }
788    /// assert_eq!(set.len(), 4); // a new "fish" was inserted
789    /// ```
790    #[cfg_attr(feature = "inline-more", inline)]
791    pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
792    where
793        T: Borrow<Q>,
794        Q: Hash + Eq,
795        F: FnOnce(&Q) -> T,
796    {
797        // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
798        // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
799        self.map
800            .raw_entry_mut()
801            .from_key(value)
802            .or_insert_with(|| (f(value), ()))
803            .0
804    }
805
806    /// Returns `true` if `self` has no elements in common with `other`.
807    /// This is equivalent to checking for an empty intersection.
808    ///
809    /// # Examples
810    ///
811    /// ```
812    /// use griddle::HashSet;
813    ///
814    /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
815    /// let mut b = HashSet::new();
816    ///
817    /// assert_eq!(a.is_disjoint(&b), true);
818    /// b.insert(4);
819    /// assert_eq!(a.is_disjoint(&b), true);
820    /// b.insert(1);
821    /// assert_eq!(a.is_disjoint(&b), false);
822    /// ```
823    pub fn is_disjoint(&self, other: &Self) -> bool {
824        self.iter().all(|v| !other.contains(v))
825    }
826
827    /// Returns `true` if the set is a subset of another,
828    /// i.e., `other` contains at least all the values in `self`.
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// use griddle::HashSet;
834    ///
835    /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
836    /// let mut set = HashSet::new();
837    ///
838    /// assert_eq!(set.is_subset(&sup), true);
839    /// set.insert(2);
840    /// assert_eq!(set.is_subset(&sup), true);
841    /// set.insert(4);
842    /// assert_eq!(set.is_subset(&sup), false);
843    /// ```
844    pub fn is_subset(&self, other: &Self) -> bool {
845        self.len() <= other.len() && self.iter().all(|v| other.contains(v))
846    }
847
848    /// Returns `true` if the set is a superset of another,
849    /// i.e., `self` contains at least all the values in `other`.
850    ///
851    /// # Examples
852    ///
853    /// ```
854    /// use griddle::HashSet;
855    ///
856    /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
857    /// let mut set = HashSet::new();
858    ///
859    /// assert_eq!(set.is_superset(&sub), false);
860    ///
861    /// set.insert(0);
862    /// set.insert(1);
863    /// assert_eq!(set.is_superset(&sub), false);
864    ///
865    /// set.insert(2);
866    /// assert_eq!(set.is_superset(&sub), true);
867    /// ```
868    #[cfg_attr(feature = "inline-more", inline)]
869    pub fn is_superset(&self, other: &Self) -> bool {
870        other.is_subset(self)
871    }
872
873    /// Adds a value to the set.
874    ///
875    /// If the set did not have this value present, `true` is returned.
876    ///
877    /// If the set did have this value present, `false` is returned.
878    ///
879    /// # Examples
880    ///
881    /// ```
882    /// use griddle::HashSet;
883    ///
884    /// let mut set = HashSet::new();
885    ///
886    /// assert_eq!(set.insert(2), true);
887    /// assert_eq!(set.insert(2), false);
888    /// assert_eq!(set.len(), 1);
889    /// ```
890    #[cfg_attr(feature = "inline-more", inline)]
891    pub fn insert(&mut self, value: T) -> bool {
892        self.map.insert(value, ()).is_none()
893    }
894
895    /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
896    /// one. Returns the replaced value.
897    ///
898    /// # Examples
899    ///
900    /// ```
901    /// use griddle::HashSet;
902    ///
903    /// let mut set = HashSet::new();
904    /// set.insert(Vec::<i32>::new());
905    ///
906    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
907    /// set.replace(Vec::with_capacity(10));
908    /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
909    /// ```
910    #[cfg_attr(feature = "inline-more", inline)]
911    pub fn replace(&mut self, value: T) -> Option<T> {
912        match self.map.entry(value) {
913            map::Entry::Occupied(occupied) => Some(occupied.replace_key()),
914            map::Entry::Vacant(vacant) => {
915                vacant.insert(());
916                None
917            }
918        }
919    }
920
921    /// Removes a value from the set. Returns whether the value was
922    /// present in the set.
923    ///
924    /// The value may be any borrowed form of the set's value type, but
925    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
926    /// the value type.
927    ///
928    /// # Examples
929    ///
930    /// ```
931    /// use griddle::HashSet;
932    ///
933    /// let mut set = HashSet::new();
934    ///
935    /// set.insert(2);
936    /// assert_eq!(set.remove(&2), true);
937    /// assert_eq!(set.remove(&2), false);
938    /// ```
939    ///
940    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
941    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
942    #[cfg_attr(feature = "inline-more", inline)]
943    pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
944    where
945        T: Borrow<Q>,
946        Q: Hash + Eq,
947    {
948        self.map.remove(value).is_some()
949    }
950
951    /// Removes and returns the value in the set, if any, that is equal to the given one.
952    ///
953    /// The value may be any borrowed form of the set's value type, but
954    /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
955    /// the value type.
956    ///
957    /// # Examples
958    ///
959    /// ```
960    /// use griddle::HashSet;
961    ///
962    /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
963    /// assert_eq!(set.take(&2), Some(2));
964    /// assert_eq!(set.take(&2), None);
965    /// ```
966    ///
967    /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
968    /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
969    #[cfg_attr(feature = "inline-more", inline)]
970    pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
971    where
972        T: Borrow<Q>,
973        Q: Hash + Eq,
974    {
975        // Avoid `Option::map` because it bloats LLVM IR.
976        match self.map.remove_entry(value) {
977            Some((k, _)) => Some(k),
978            None => None,
979        }
980    }
981}
982
983impl<T, S> PartialEq for HashSet<T, S>
984where
985    T: Eq + Hash,
986    S: BuildHasher,
987{
988    fn eq(&self, other: &Self) -> bool {
989        if self.len() != other.len() {
990            return false;
991        }
992
993        self.iter().all(|key| other.contains(key))
994    }
995}
996
997impl<T, S> Eq for HashSet<T, S>
998where
999    T: Eq + Hash,
1000    S: BuildHasher,
1001{
1002}
1003
1004impl<T, S> fmt::Debug for HashSet<T, S>
1005where
1006    T: Eq + Hash + fmt::Debug,
1007    S: BuildHasher,
1008{
1009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010        f.debug_set().entries(self.iter()).finish()
1011    }
1012}
1013
1014impl<T, S> FromIterator<T> for HashSet<T, S>
1015where
1016    T: Eq + Hash,
1017    S: BuildHasher + Default,
1018{
1019    #[cfg_attr(feature = "inline-more", inline)]
1020    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1021        let mut set = Self::with_hasher(Default::default());
1022        set.extend(iter);
1023        set
1024    }
1025}
1026
1027impl<T, S> Extend<T> for HashSet<T, S>
1028where
1029    T: Eq + Hash,
1030    S: BuildHasher,
1031{
1032    #[cfg_attr(feature = "inline-more", inline)]
1033    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1034        self.map.extend(iter.into_iter().map(|k| (k, ())));
1035    }
1036}
1037
1038impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1039where
1040    T: 'a + Eq + Hash + Copy,
1041    S: BuildHasher,
1042{
1043    #[cfg_attr(feature = "inline-more", inline)]
1044    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1045        self.extend(iter.into_iter().cloned());
1046    }
1047}
1048
1049impl<T, S> Default for HashSet<T, S>
1050where
1051    S: Default,
1052{
1053    /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1054    #[cfg_attr(feature = "inline-more", inline)]
1055    fn default() -> Self {
1056        Self {
1057            map: HashMap::default(),
1058        }
1059    }
1060}
1061
1062impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1063where
1064    T: Eq + Hash + Clone,
1065    S: BuildHasher + Default,
1066{
1067    type Output = HashSet<T, S>;
1068
1069    /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1070    ///
1071    /// # Examples
1072    ///
1073    /// ```
1074    /// use griddle::HashSet;
1075    ///
1076    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1077    /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1078    ///
1079    /// let set = &a | &b;
1080    ///
1081    /// let mut i = 0;
1082    /// let expected = [1, 2, 3, 4, 5];
1083    /// for x in &set {
1084    ///     assert!(expected.contains(x));
1085    ///     i += 1;
1086    /// }
1087    /// assert_eq!(i, expected.len());
1088    /// ```
1089    fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1090        self.union(rhs).cloned().collect()
1091    }
1092}
1093
1094impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1095where
1096    T: Eq + Hash + Clone,
1097    S: BuildHasher + Default,
1098{
1099    type Output = HashSet<T, S>;
1100
1101    /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1102    ///
1103    /// # Examples
1104    ///
1105    /// ```
1106    /// use griddle::HashSet;
1107    ///
1108    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1109    /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1110    ///
1111    /// let set = &a & &b;
1112    ///
1113    /// let mut i = 0;
1114    /// let expected = [2, 3];
1115    /// for x in &set {
1116    ///     assert!(expected.contains(x));
1117    ///     i += 1;
1118    /// }
1119    /// assert_eq!(i, expected.len());
1120    /// ```
1121    fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1122        self.intersection(rhs).cloned().collect()
1123    }
1124}
1125
1126impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1127where
1128    T: Eq + Hash + Clone,
1129    S: BuildHasher + Default,
1130{
1131    type Output = HashSet<T, S>;
1132
1133    /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1134    ///
1135    /// # Examples
1136    ///
1137    /// ```
1138    /// use griddle::HashSet;
1139    ///
1140    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1141    /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1142    ///
1143    /// let set = &a ^ &b;
1144    ///
1145    /// let mut i = 0;
1146    /// let expected = [1, 2, 4, 5];
1147    /// for x in &set {
1148    ///     assert!(expected.contains(x));
1149    ///     i += 1;
1150    /// }
1151    /// assert_eq!(i, expected.len());
1152    /// ```
1153    fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1154        self.symmetric_difference(rhs).cloned().collect()
1155    }
1156}
1157
1158impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1159where
1160    T: Eq + Hash + Clone,
1161    S: BuildHasher + Default,
1162{
1163    type Output = HashSet<T, S>;
1164
1165    /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1166    ///
1167    /// # Examples
1168    ///
1169    /// ```
1170    /// use griddle::HashSet;
1171    ///
1172    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1173    /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1174    ///
1175    /// let set = &a - &b;
1176    ///
1177    /// let mut i = 0;
1178    /// let expected = [1, 2];
1179    /// for x in &set {
1180    ///     assert!(expected.contains(x));
1181    ///     i += 1;
1182    /// }
1183    /// assert_eq!(i, expected.len());
1184    /// ```
1185    fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1186        self.difference(rhs).cloned().collect()
1187    }
1188}
1189
1190/// An iterator over the items of a `HashSet`.
1191///
1192/// This `struct` is created by the [`iter`] method on [`HashSet`].
1193/// See its documentation for more.
1194///
1195/// [`HashSet`]: struct.HashSet.html
1196/// [`iter`]: struct.HashSet.html#method.iter
1197pub struct Iter<'a, K> {
1198    iter: Keys<'a, K, ()>,
1199}
1200
1201/// An owning iterator over the items of a `HashSet`.
1202///
1203/// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1204/// (provided by the `IntoIterator` trait). See its documentation for more.
1205///
1206/// [`HashSet`]: struct.HashSet.html
1207/// [`into_iter`]: struct.HashSet.html#method.into_iter
1208pub struct IntoIter<K> {
1209    iter: map::IntoIter<K, ()>,
1210}
1211
1212/// A draining iterator over the items of a `HashSet`.
1213///
1214/// This `struct` is created by the [`drain`] method on [`HashSet`].
1215/// See its documentation for more.
1216///
1217/// [`HashSet`]: struct.HashSet.html
1218/// [`drain`]: struct.HashSet.html#method.drain
1219pub struct Drain<'a, K> {
1220    iter: map::Drain<'a, K, ()>,
1221}
1222
1223/// A draining iterator over entries of a `HashSet` which don't satisfy the predicate `f`.
1224///
1225/// This `struct` is created by the [`drain_filter`] method on [`HashSet`]. See its
1226/// documentation for more.
1227///
1228/// [`drain_filter`]: struct.HashSet.html#method.drain_filter
1229/// [`HashSet`]: struct.HashSet.html
1230pub struct DrainFilter<'a, K, F>
1231where
1232    F: FnMut(&K) -> bool,
1233{
1234    f: F,
1235    inner: DrainFilterInner<'a, K, ()>,
1236}
1237
1238/// A lazy iterator producing elements in the intersection of `HashSet`s.
1239///
1240/// This `struct` is created by the [`intersection`] method on [`HashSet`].
1241/// See its documentation for more.
1242///
1243/// [`HashSet`]: struct.HashSet.html
1244/// [`intersection`]: struct.HashSet.html#method.intersection
1245pub struct Intersection<'a, T, S> {
1246    // iterator of the first set
1247    iter: Iter<'a, T>,
1248    // the second set
1249    other: &'a HashSet<T, S>,
1250}
1251
1252/// A lazy iterator producing elements in the difference of `HashSet`s.
1253///
1254/// This `struct` is created by the [`difference`] method on [`HashSet`].
1255/// See its documentation for more.
1256///
1257/// [`HashSet`]: struct.HashSet.html
1258/// [`difference`]: struct.HashSet.html#method.difference
1259pub struct Difference<'a, T, S> {
1260    // iterator of the first set
1261    iter: Iter<'a, T>,
1262    // the second set
1263    other: &'a HashSet<T, S>,
1264}
1265
1266/// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1267///
1268/// This `struct` is created by the [`symmetric_difference`] method on
1269/// [`HashSet`]. See its documentation for more.
1270///
1271/// [`HashSet`]: struct.HashSet.html
1272/// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1273pub struct SymmetricDifference<'a, T, S> {
1274    iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1275}
1276
1277/// A lazy iterator producing elements in the union of `HashSet`s.
1278///
1279/// This `struct` is created by the [`union`] method on [`HashSet`].
1280/// See its documentation for more.
1281///
1282/// [`HashSet`]: struct.HashSet.html
1283/// [`union`]: struct.HashSet.html#method.union
1284pub struct Union<'a, T, S> {
1285    iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1286}
1287
1288impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1289    type Item = &'a T;
1290    type IntoIter = Iter<'a, T>;
1291
1292    #[cfg_attr(feature = "inline-more", inline)]
1293    fn into_iter(self) -> Iter<'a, T> {
1294        self.iter()
1295    }
1296}
1297
1298impl<T, S> IntoIterator for HashSet<T, S> {
1299    type Item = T;
1300    type IntoIter = IntoIter<T>;
1301
1302    /// Creates a consuming iterator, that is, one that moves each value out
1303    /// of the set in arbitrary order. The set cannot be used after calling
1304    /// this.
1305    ///
1306    /// # Examples
1307    ///
1308    /// ```
1309    /// use griddle::HashSet;
1310    /// let mut set = HashSet::new();
1311    /// set.insert("a".to_string());
1312    /// set.insert("b".to_string());
1313    ///
1314    /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1315    /// let v: Vec<String> = set.into_iter().collect();
1316    ///
1317    /// // Will print in an arbitrary order.
1318    /// for x in &v {
1319    ///     println!("{}", x);
1320    /// }
1321    /// ```
1322    #[cfg_attr(feature = "inline-more", inline)]
1323    fn into_iter(self) -> IntoIter<T> {
1324        IntoIter {
1325            iter: self.map.into_iter(),
1326        }
1327    }
1328}
1329
1330impl<K> Clone for Iter<'_, K> {
1331    #[cfg_attr(feature = "inline-more", inline)]
1332    fn clone(&self) -> Self {
1333        Iter {
1334            iter: self.iter.clone(),
1335        }
1336    }
1337}
1338impl<'a, K> Iterator for Iter<'a, K> {
1339    type Item = &'a K;
1340
1341    #[cfg_attr(feature = "inline-more", inline)]
1342    fn next(&mut self) -> Option<&'a K> {
1343        self.iter.next()
1344    }
1345    #[cfg_attr(feature = "inline-more", inline)]
1346    fn size_hint(&self) -> (usize, Option<usize>) {
1347        self.iter.size_hint()
1348    }
1349}
1350impl<'a, K> ExactSizeIterator for Iter<'a, K> {
1351    #[cfg_attr(feature = "inline-more", inline)]
1352    fn len(&self) -> usize {
1353        self.iter.len()
1354    }
1355}
1356impl<K> FusedIterator for Iter<'_, K> {}
1357
1358impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1360        f.debug_list().entries(self.clone()).finish()
1361    }
1362}
1363
1364impl<K> Iterator for IntoIter<K> {
1365    type Item = K;
1366
1367    #[cfg_attr(feature = "inline-more", inline)]
1368    fn next(&mut self) -> Option<K> {
1369        // Avoid `Option::map` because it bloats LLVM IR.
1370        match self.iter.next() {
1371            Some((k, _)) => Some(k),
1372            None => None,
1373        }
1374    }
1375    #[cfg_attr(feature = "inline-more", inline)]
1376    fn size_hint(&self) -> (usize, Option<usize>) {
1377        self.iter.size_hint()
1378    }
1379}
1380impl<K> ExactSizeIterator for IntoIter<K> {
1381    #[cfg_attr(feature = "inline-more", inline)]
1382    fn len(&self) -> usize {
1383        self.iter.len()
1384    }
1385}
1386impl<K> FusedIterator for IntoIter<K> {}
1387
1388impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1390        let entries_iter = self.iter.iter().map(|(k, _)| k);
1391        f.debug_list().entries(entries_iter).finish()
1392    }
1393}
1394
1395impl<K> Iterator for Drain<'_, K> {
1396    type Item = K;
1397
1398    #[cfg_attr(feature = "inline-more", inline)]
1399    fn next(&mut self) -> Option<K> {
1400        // Avoid `Option::map` because it bloats LLVM IR.
1401        match self.iter.next() {
1402            Some((k, _)) => Some(k),
1403            None => None,
1404        }
1405    }
1406    #[cfg_attr(feature = "inline-more", inline)]
1407    fn size_hint(&self) -> (usize, Option<usize>) {
1408        self.iter.size_hint()
1409    }
1410}
1411
1412impl<K> ExactSizeIterator for Drain<'_, K> {
1413    #[cfg_attr(feature = "inline-more", inline)]
1414    fn len(&self) -> usize {
1415        self.iter.len()
1416    }
1417}
1418
1419impl<K> FusedIterator for Drain<'_, K> {}
1420
1421impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1423        let entries_iter = self.iter.iter().map(|(k, _)| k);
1424        f.debug_list().entries(entries_iter).finish()
1425    }
1426}
1427
1428impl<'a, K, F> Drop for DrainFilter<'a, K, F>
1429where
1430    F: FnMut(&K) -> bool,
1431{
1432    #[cfg_attr(feature = "inline-more", inline)]
1433    fn drop(&mut self) {
1434        while let Some(item) = self.next() {
1435            let guard = ConsumeAllOnDrop(self);
1436            drop(item);
1437            mem::forget(guard);
1438        }
1439    }
1440}
1441
1442impl<K, F> Iterator for DrainFilter<'_, K, F>
1443where
1444    F: FnMut(&K) -> bool,
1445{
1446    type Item = K;
1447
1448    #[cfg_attr(feature = "inline-more", inline)]
1449    fn next(&mut self) -> Option<Self::Item> {
1450        let f = &mut self.f;
1451        let (k, _) = self.inner.next(&mut |k, _| f(k))?;
1452        Some(k)
1453    }
1454
1455    #[inline]
1456    fn size_hint(&self) -> (usize, Option<usize>) {
1457        (0, self.inner.iter.size_hint().1)
1458    }
1459}
1460
1461impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1462
1463impl<T, S> Clone for Intersection<'_, T, S> {
1464    #[cfg_attr(feature = "inline-more", inline)]
1465    fn clone(&self) -> Self {
1466        Intersection {
1467            iter: self.iter.clone(),
1468            ..*self
1469        }
1470    }
1471}
1472
1473impl<'a, T, S> Iterator for Intersection<'a, T, S>
1474where
1475    T: Eq + Hash,
1476    S: BuildHasher,
1477{
1478    type Item = &'a T;
1479
1480    #[cfg_attr(feature = "inline-more", inline)]
1481    fn next(&mut self) -> Option<&'a T> {
1482        loop {
1483            let elt = self.iter.next()?;
1484            if self.other.contains(elt) {
1485                return Some(elt);
1486            }
1487        }
1488    }
1489
1490    #[cfg_attr(feature = "inline-more", inline)]
1491    fn size_hint(&self) -> (usize, Option<usize>) {
1492        let (_, upper) = self.iter.size_hint();
1493        (0, upper)
1494    }
1495}
1496
1497impl<T, S> fmt::Debug for Intersection<'_, T, S>
1498where
1499    T: fmt::Debug + Eq + Hash,
1500    S: BuildHasher,
1501{
1502    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1503        f.debug_list().entries(self.clone()).finish()
1504    }
1505}
1506
1507impl<T, S> FusedIterator for Intersection<'_, T, S>
1508where
1509    T: Eq + Hash,
1510    S: BuildHasher,
1511{
1512}
1513
1514impl<T, S> Clone for Difference<'_, T, S> {
1515    #[cfg_attr(feature = "inline-more", inline)]
1516    fn clone(&self) -> Self {
1517        Difference {
1518            iter: self.iter.clone(),
1519            ..*self
1520        }
1521    }
1522}
1523
1524impl<'a, T, S> Iterator for Difference<'a, T, S>
1525where
1526    T: Eq + Hash,
1527    S: BuildHasher,
1528{
1529    type Item = &'a T;
1530
1531    #[cfg_attr(feature = "inline-more", inline)]
1532    fn next(&mut self) -> Option<&'a T> {
1533        loop {
1534            let elt = self.iter.next()?;
1535            if !self.other.contains(elt) {
1536                return Some(elt);
1537            }
1538        }
1539    }
1540
1541    #[cfg_attr(feature = "inline-more", inline)]
1542    fn size_hint(&self) -> (usize, Option<usize>) {
1543        let (_, upper) = self.iter.size_hint();
1544        (0, upper)
1545    }
1546}
1547
1548impl<T, S> FusedIterator for Difference<'_, T, S>
1549where
1550    T: Eq + Hash,
1551    S: BuildHasher,
1552{
1553}
1554
1555impl<T, S> fmt::Debug for Difference<'_, T, S>
1556where
1557    T: fmt::Debug + Eq + Hash,
1558    S: BuildHasher,
1559{
1560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1561        f.debug_list().entries(self.clone()).finish()
1562    }
1563}
1564
1565impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1566    #[cfg_attr(feature = "inline-more", inline)]
1567    fn clone(&self) -> Self {
1568        SymmetricDifference {
1569            iter: self.iter.clone(),
1570        }
1571    }
1572}
1573
1574impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1575where
1576    T: Eq + Hash,
1577    S: BuildHasher,
1578{
1579    type Item = &'a T;
1580
1581    #[cfg_attr(feature = "inline-more", inline)]
1582    fn next(&mut self) -> Option<&'a T> {
1583        self.iter.next()
1584    }
1585    #[cfg_attr(feature = "inline-more", inline)]
1586    fn size_hint(&self) -> (usize, Option<usize>) {
1587        self.iter.size_hint()
1588    }
1589}
1590
1591impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1592where
1593    T: Eq + Hash,
1594    S: BuildHasher,
1595{
1596}
1597
1598impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1599where
1600    T: fmt::Debug + Eq + Hash,
1601    S: BuildHasher,
1602{
1603    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1604        f.debug_list().entries(self.clone()).finish()
1605    }
1606}
1607
1608impl<T, S> Clone for Union<'_, T, S> {
1609    #[cfg_attr(feature = "inline-more", inline)]
1610    fn clone(&self) -> Self {
1611        Union {
1612            iter: self.iter.clone(),
1613        }
1614    }
1615}
1616
1617impl<T, S> FusedIterator for Union<'_, T, S>
1618where
1619    T: Eq + Hash,
1620    S: BuildHasher,
1621{
1622}
1623
1624impl<T, S> fmt::Debug for Union<'_, T, S>
1625where
1626    T: fmt::Debug + Eq + Hash,
1627    S: BuildHasher,
1628{
1629    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1630        f.debug_list().entries(self.clone()).finish()
1631    }
1632}
1633
1634impl<'a, T, S> Iterator for Union<'a, T, S>
1635where
1636    T: Eq + Hash,
1637    S: BuildHasher,
1638{
1639    type Item = &'a T;
1640
1641    #[cfg_attr(feature = "inline-more", inline)]
1642    fn next(&mut self) -> Option<&'a T> {
1643        self.iter.next()
1644    }
1645    #[cfg_attr(feature = "inline-more", inline)]
1646    fn size_hint(&self) -> (usize, Option<usize>) {
1647        self.iter.size_hint()
1648    }
1649}
1650
1651#[allow(dead_code)]
1652fn assert_covariance() {
1653    fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1654        v
1655    }
1656    fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1657        v
1658    }
1659    fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1660        v
1661    }
1662    fn difference<'a, 'new>(
1663        v: Difference<'a, &'static str, DefaultHashBuilder>,
1664    ) -> Difference<'a, &'new str, DefaultHashBuilder> {
1665        v
1666    }
1667    fn symmetric_difference<'a, 'new>(
1668        v: SymmetricDifference<'a, &'static str, DefaultHashBuilder>,
1669    ) -> SymmetricDifference<'a, &'new str, DefaultHashBuilder> {
1670        v
1671    }
1672    fn intersection<'a, 'new>(
1673        v: Intersection<'a, &'static str, DefaultHashBuilder>,
1674    ) -> Intersection<'a, &'new str, DefaultHashBuilder> {
1675        v
1676    }
1677    fn union<'a, 'new>(
1678        v: Union<'a, &'static str, DefaultHashBuilder>,
1679    ) -> Union<'a, &'new str, DefaultHashBuilder> {
1680        v
1681    }
1682    fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1683        d
1684    }
1685}
1686
1687#[cfg(test)]
1688mod test_set {
1689    use super::super::map::DefaultHashBuilder;
1690    use super::HashSet;
1691    use std::vec::Vec;
1692
1693    #[test]
1694    fn test_zero_capacities() {
1695        type HS = HashSet<i32>;
1696
1697        let s = HS::new();
1698        assert_eq!(s.capacity(), 0);
1699
1700        let s = HS::default();
1701        assert_eq!(s.capacity(), 0);
1702
1703        let s = HS::with_hasher(DefaultHashBuilder::default());
1704        assert_eq!(s.capacity(), 0);
1705
1706        let s = HS::with_capacity(0);
1707        assert_eq!(s.capacity(), 0);
1708
1709        let s = HS::with_capacity_and_hasher(0, DefaultHashBuilder::default());
1710        assert_eq!(s.capacity(), 0);
1711
1712        let mut s = HS::new();
1713        s.insert(1);
1714        s.insert(2);
1715        s.remove(&1);
1716        s.remove(&2);
1717        s.shrink_to_fit();
1718        assert_eq!(s.capacity(), 0);
1719
1720        let mut s = HS::new();
1721        s.reserve(0);
1722        assert_eq!(s.capacity(), 0);
1723    }
1724
1725    #[test]
1726    fn test_disjoint() {
1727        let mut xs = HashSet::new();
1728        let mut ys = HashSet::new();
1729        assert!(xs.is_disjoint(&ys));
1730        assert!(ys.is_disjoint(&xs));
1731        assert!(xs.insert(5));
1732        assert!(ys.insert(11));
1733        assert!(xs.is_disjoint(&ys));
1734        assert!(ys.is_disjoint(&xs));
1735        assert!(xs.insert(7));
1736        assert!(xs.insert(19));
1737        assert!(xs.insert(4));
1738        assert!(ys.insert(2));
1739        assert!(ys.insert(-11));
1740        assert!(xs.is_disjoint(&ys));
1741        assert!(ys.is_disjoint(&xs));
1742        assert!(ys.insert(7));
1743        assert!(!xs.is_disjoint(&ys));
1744        assert!(!ys.is_disjoint(&xs));
1745    }
1746
1747    #[test]
1748    fn test_subset_and_superset() {
1749        let mut a = HashSet::new();
1750        assert!(a.insert(0));
1751        assert!(a.insert(5));
1752        assert!(a.insert(11));
1753        assert!(a.insert(7));
1754
1755        let mut b = HashSet::new();
1756        assert!(b.insert(0));
1757        assert!(b.insert(7));
1758        assert!(b.insert(19));
1759        assert!(b.insert(250));
1760        assert!(b.insert(11));
1761        assert!(b.insert(200));
1762
1763        assert!(!a.is_subset(&b));
1764        assert!(!a.is_superset(&b));
1765        assert!(!b.is_subset(&a));
1766        assert!(!b.is_superset(&a));
1767
1768        assert!(b.insert(5));
1769
1770        assert!(a.is_subset(&b));
1771        assert!(!a.is_superset(&b));
1772        assert!(!b.is_subset(&a));
1773        assert!(b.is_superset(&a));
1774    }
1775
1776    #[test]
1777    fn test_iterate() {
1778        let mut a = HashSet::new();
1779        for i in 0..32 {
1780            assert!(a.insert(i));
1781        }
1782        let mut observed: u32 = 0;
1783        for k in &a {
1784            observed |= 1 << *k;
1785        }
1786        assert_eq!(observed, 0xFFFF_FFFF);
1787    }
1788
1789    #[test]
1790    fn test_intersection() {
1791        let mut a = HashSet::new();
1792        let mut b = HashSet::new();
1793
1794        assert!(a.insert(11));
1795        assert!(a.insert(1));
1796        assert!(a.insert(3));
1797        assert!(a.insert(77));
1798        assert!(a.insert(103));
1799        assert!(a.insert(5));
1800        assert!(a.insert(-5));
1801
1802        assert!(b.insert(2));
1803        assert!(b.insert(11));
1804        assert!(b.insert(77));
1805        assert!(b.insert(-9));
1806        assert!(b.insert(-42));
1807        assert!(b.insert(5));
1808        assert!(b.insert(3));
1809
1810        let mut i = 0;
1811        let expected = [3, 5, 11, 77];
1812        for x in a.intersection(&b) {
1813            assert!(expected.contains(x));
1814            i += 1
1815        }
1816        assert_eq!(i, expected.len());
1817    }
1818
1819    #[test]
1820    fn test_difference() {
1821        let mut a = HashSet::new();
1822        let mut b = HashSet::new();
1823
1824        assert!(a.insert(1));
1825        assert!(a.insert(3));
1826        assert!(a.insert(5));
1827        assert!(a.insert(9));
1828        assert!(a.insert(11));
1829
1830        assert!(b.insert(3));
1831        assert!(b.insert(9));
1832
1833        let mut i = 0;
1834        let expected = [1, 5, 11];
1835        for x in a.difference(&b) {
1836            assert!(expected.contains(x));
1837            i += 1
1838        }
1839        assert_eq!(i, expected.len());
1840    }
1841
1842    #[test]
1843    fn test_symmetric_difference() {
1844        let mut a = HashSet::new();
1845        let mut b = HashSet::new();
1846
1847        assert!(a.insert(1));
1848        assert!(a.insert(3));
1849        assert!(a.insert(5));
1850        assert!(a.insert(9));
1851        assert!(a.insert(11));
1852
1853        assert!(b.insert(-2));
1854        assert!(b.insert(3));
1855        assert!(b.insert(9));
1856        assert!(b.insert(14));
1857        assert!(b.insert(22));
1858
1859        let mut i = 0;
1860        let expected = [-2, 1, 5, 11, 14, 22];
1861        for x in a.symmetric_difference(&b) {
1862            assert!(expected.contains(x));
1863            i += 1
1864        }
1865        assert_eq!(i, expected.len());
1866    }
1867
1868    #[test]
1869    fn test_union() {
1870        let mut a = HashSet::new();
1871        let mut b = HashSet::new();
1872
1873        assert!(a.insert(1));
1874        assert!(a.insert(3));
1875        assert!(a.insert(5));
1876        assert!(a.insert(9));
1877        assert!(a.insert(11));
1878        assert!(a.insert(16));
1879        assert!(a.insert(19));
1880        assert!(a.insert(24));
1881
1882        assert!(b.insert(-2));
1883        assert!(b.insert(1));
1884        assert!(b.insert(5));
1885        assert!(b.insert(9));
1886        assert!(b.insert(13));
1887        assert!(b.insert(19));
1888
1889        let mut i = 0;
1890        let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1891        for x in a.union(&b) {
1892            assert!(expected.contains(x));
1893            i += 1
1894        }
1895        assert_eq!(i, expected.len());
1896    }
1897
1898    #[test]
1899    fn test_from_iter() {
1900        let xs = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9];
1901
1902        let set: HashSet<_> = xs.iter().cloned().collect();
1903
1904        for x in &xs {
1905            assert!(set.contains(x));
1906        }
1907
1908        assert_eq!(set.iter().len(), xs.len() - 1);
1909    }
1910
1911    #[test]
1912    fn test_move_iter() {
1913        let hs = {
1914            let mut hs = HashSet::new();
1915
1916            hs.insert('a');
1917            hs.insert('b');
1918
1919            hs
1920        };
1921
1922        let v = hs.into_iter().collect::<Vec<char>>();
1923        assert!(v == ['a', 'b'] || v == ['b', 'a']);
1924    }
1925
1926    #[test]
1927    fn test_eq() {
1928        // These constants once happened to expose a bug in insert().
1929        // I'm keeping them around to prevent a regression.
1930        let mut s1 = HashSet::new();
1931
1932        s1.insert(1);
1933        s1.insert(2);
1934        s1.insert(3);
1935
1936        let mut s2 = HashSet::new();
1937
1938        s2.insert(1);
1939        s2.insert(2);
1940
1941        assert!(s1 != s2);
1942
1943        s2.insert(3);
1944
1945        assert_eq!(s1, s2);
1946    }
1947
1948    #[test]
1949    fn test_show() {
1950        let mut set = HashSet::new();
1951        let empty = HashSet::<i32>::new();
1952
1953        set.insert(1);
1954        set.insert(2);
1955
1956        let set_str = format!("{:?}", set);
1957
1958        assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1959        assert_eq!(format!("{:?}", empty), "{}");
1960    }
1961
1962    #[test]
1963    fn test_trivial_drain() {
1964        let mut s = HashSet::<i32>::new();
1965        for _ in s.drain() {}
1966        assert!(s.is_empty());
1967        drop(s);
1968
1969        let mut s = HashSet::<i32>::new();
1970        drop(s.drain());
1971        assert!(s.is_empty());
1972    }
1973
1974    #[test]
1975    fn test_drain() {
1976        let mut s: HashSet<_> = (1..100).collect();
1977
1978        // try this a bunch of times to make sure we don't screw up internal state.
1979        for _ in 0..20 {
1980            assert_eq!(s.len(), 99);
1981
1982            {
1983                let mut last_i = 0;
1984                let mut d = s.drain();
1985                for (i, x) in d.by_ref().take(50).enumerate() {
1986                    last_i = i;
1987                    assert!(x != 0);
1988                }
1989                assert_eq!(last_i, 49);
1990            }
1991
1992            for _ in &s {
1993                panic!("s should be empty!");
1994            }
1995
1996            // reset to try again.
1997            s.extend(1..100);
1998        }
1999    }
2000
2001    #[test]
2002    fn test_replace() {
2003        use core::hash;
2004
2005        #[derive(Debug)]
2006        #[allow(dead_code)]
2007        struct Foo(&'static str, i32);
2008
2009        impl PartialEq for Foo {
2010            fn eq(&self, other: &Self) -> bool {
2011                self.0 == other.0
2012            }
2013        }
2014
2015        impl Eq for Foo {}
2016
2017        impl hash::Hash for Foo {
2018            fn hash<H: hash::Hasher>(&self, h: &mut H) {
2019                self.0.hash(h);
2020            }
2021        }
2022
2023        let mut s = HashSet::new();
2024        assert_eq!(s.replace(Foo("a", 1)), None);
2025        assert_eq!(s.len(), 1);
2026        assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
2027        assert_eq!(s.len(), 1);
2028
2029        let mut it = s.iter();
2030        assert_eq!(it.next(), Some(&Foo("a", 2)));
2031        assert_eq!(it.next(), None);
2032    }
2033
2034    #[test]
2035    fn test_extend_ref() {
2036        let mut a = HashSet::new();
2037        a.insert(1);
2038
2039        a.extend(&[2, 3, 4]);
2040
2041        assert_eq!(a.len(), 4);
2042        assert!(a.contains(&1));
2043        assert!(a.contains(&2));
2044        assert!(a.contains(&3));
2045        assert!(a.contains(&4));
2046
2047        let mut b = HashSet::new();
2048        b.insert(5);
2049        b.insert(6);
2050
2051        a.extend(&b);
2052
2053        assert_eq!(a.len(), 6);
2054        assert!(a.contains(&1));
2055        assert!(a.contains(&2));
2056        assert!(a.contains(&3));
2057        assert!(a.contains(&4));
2058        assert!(a.contains(&5));
2059        assert!(a.contains(&6));
2060    }
2061
2062    #[test]
2063    fn test_retain() {
2064        let xs = [1, 2, 3, 4, 5, 6];
2065        let mut set: HashSet<i32> = xs.iter().cloned().collect();
2066        set.retain(|&k| k % 2 == 0);
2067        assert_eq!(set.len(), 3);
2068        assert!(set.contains(&2));
2069        assert!(set.contains(&4));
2070        assert!(set.contains(&6));
2071    }
2072
2073    #[test]
2074    fn test_drain_filter() {
2075        {
2076            let mut set: HashSet<i32> = HashSet::new();
2077            for x in 0..8 {
2078                set.insert(x);
2079            }
2080            assert!(set.is_split());
2081            let drained = set.drain_filter(|&k| k % 2 == 0);
2082            let mut out = drained.collect::<Vec<_>>();
2083            out.sort_unstable();
2084            assert_eq!(vec![0, 2, 4, 6], out);
2085            assert_eq!(set.len(), 4);
2086        }
2087        {
2088            let mut set: HashSet<i32> = HashSet::new();
2089            for x in 0..8 {
2090                set.insert(x);
2091            }
2092            assert!(set.is_split());
2093            drop(set.drain_filter(|&k| k % 2 == 0));
2094            assert_eq!(set.len(), 4, "Removes non-matching items on drop");
2095        }
2096        {
2097            let mut set: HashSet<i32> = HashSet::new();
2098            for x in 0..8 {
2099                set.insert(x);
2100            }
2101            assert!(set.is_split());
2102            let mut drain = set.drain_filter(|&k| k % 2 == 0);
2103            drain.next();
2104            std::mem::forget(drain);
2105            assert_eq!(
2106                set.len(),
2107                7,
2108                "Must only remove remaining items when (and if) dropped"
2109            );
2110        }
2111    }
2112
2113    #[test]
2114    fn test_const_with_hasher() {
2115        use core::hash::BuildHasher;
2116        use std::collections::hash_map::DefaultHasher;
2117
2118        #[derive(Clone)]
2119        struct MyHasher;
2120        impl BuildHasher for MyHasher {
2121            type Hasher = DefaultHasher;
2122
2123            fn build_hasher(&self) -> DefaultHasher {
2124                DefaultHasher::new()
2125            }
2126        }
2127
2128        const EMPTY_SET: HashSet<u32, MyHasher> = HashSet::with_hasher(MyHasher);
2129
2130        let mut set = EMPTY_SET.clone();
2131        set.insert(19);
2132        assert!(set.contains(&19));
2133    }
2134}