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