]> git.lizzy.rs Git - rust.git/blob - library/std/src/collections/hash/set.rs
Update set.rs
[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     /// Note: When an equal element is present in `self` and `other`
592     /// then the resulting `Intersection` may yield references to
593     /// one or the other, which will be visible in properties of `T`
594     /// not participating in the `Eq` implementation.
595     ///
596     /// # Examples
597     ///
598     /// ```
599     /// use std::collections::HashSet;
600     /// let a = HashSet::from([1, 2, 3]);
601     /// let b = HashSet::from([4, 2, 3, 4]);
602     ///
603     /// // Print 2, 3 in arbitrary order.
604     /// for x in a.intersection(&b) {
605     ///     println!("{x}");
606     /// }
607     ///
608     /// let intersection: HashSet<_> = a.intersection(&b).collect();
609     /// assert_eq!(intersection, [2, 3].iter().collect());
610     /// ```
611     #[inline]
612     #[rustc_lint_query_instability]
613     #[stable(feature = "rust1", since = "1.0.0")]
614     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
615         if self.len() <= other.len() {
616             Intersection { iter: self.iter(), other }
617         } else {
618             Intersection { iter: other.iter(), other: self }
619         }
620     }
621
622     /// Visits the values representing the union,
623     /// i.e., all the values in `self` or `other`, without duplicates.
624     ///
625     /// # Examples
626     ///
627     /// ```
628     /// use std::collections::HashSet;
629     /// let a = HashSet::from([1, 2, 3]);
630     /// let b = HashSet::from([4, 2, 3, 4]);
631     ///
632     /// // Print 1, 2, 3, 4 in arbitrary order.
633     /// for x in a.union(&b) {
634     ///     println!("{x}");
635     /// }
636     ///
637     /// let union: HashSet<_> = a.union(&b).collect();
638     /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
639     /// ```
640     #[inline]
641     #[rustc_lint_query_instability]
642     #[stable(feature = "rust1", since = "1.0.0")]
643     pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
644         if self.len() >= other.len() {
645             Union { iter: self.iter().chain(other.difference(self)) }
646         } else {
647             Union { iter: other.iter().chain(self.difference(other)) }
648         }
649     }
650
651     /// Returns `true` if the set contains a value.
652     ///
653     /// The value may be any borrowed form of the set's value type, but
654     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
655     /// the value type.
656     ///
657     /// # Examples
658     ///
659     /// ```
660     /// use std::collections::HashSet;
661     ///
662     /// let set = HashSet::from([1, 2, 3]);
663     /// assert_eq!(set.contains(&1), true);
664     /// assert_eq!(set.contains(&4), false);
665     /// ```
666     #[inline]
667     #[stable(feature = "rust1", since = "1.0.0")]
668     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
669     where
670         T: Borrow<Q>,
671         Q: Hash + Eq,
672     {
673         self.base.contains(value)
674     }
675
676     /// Returns a reference to the value in the set, if any, that is equal to the given value.
677     ///
678     /// The value may be any borrowed form of the set's value type, but
679     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
680     /// the value type.
681     ///
682     /// # Examples
683     ///
684     /// ```
685     /// use std::collections::HashSet;
686     ///
687     /// let set = HashSet::from([1, 2, 3]);
688     /// assert_eq!(set.get(&2), Some(&2));
689     /// assert_eq!(set.get(&4), None);
690     /// ```
691     #[inline]
692     #[stable(feature = "set_recovery", since = "1.9.0")]
693     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
694     where
695         T: Borrow<Q>,
696         Q: Hash + Eq,
697     {
698         self.base.get(value)
699     }
700
701     /// Inserts the given `value` into the set if it is not present, then
702     /// returns a reference to the value in the set.
703     ///
704     /// # Examples
705     ///
706     /// ```
707     /// #![feature(hash_set_entry)]
708     ///
709     /// use std::collections::HashSet;
710     ///
711     /// let mut set = HashSet::from([1, 2, 3]);
712     /// assert_eq!(set.len(), 3);
713     /// assert_eq!(set.get_or_insert(2), &2);
714     /// assert_eq!(set.get_or_insert(100), &100);
715     /// assert_eq!(set.len(), 4); // 100 was inserted
716     /// ```
717     #[inline]
718     #[unstable(feature = "hash_set_entry", issue = "60896")]
719     pub fn get_or_insert(&mut self, value: T) -> &T {
720         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
721         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
722         self.base.get_or_insert(value)
723     }
724
725     /// Inserts an owned copy of the given `value` into the set if it is not
726     /// present, then returns a reference to the value in the set.
727     ///
728     /// # Examples
729     ///
730     /// ```
731     /// #![feature(hash_set_entry)]
732     ///
733     /// use std::collections::HashSet;
734     ///
735     /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
736     ///     .iter().map(|&pet| pet.to_owned()).collect();
737     ///
738     /// assert_eq!(set.len(), 3);
739     /// for &pet in &["cat", "dog", "fish"] {
740     ///     let value = set.get_or_insert_owned(pet);
741     ///     assert_eq!(value, pet);
742     /// }
743     /// assert_eq!(set.len(), 4); // a new "fish" was inserted
744     /// ```
745     #[inline]
746     #[unstable(feature = "hash_set_entry", issue = "60896")]
747     pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
748     where
749         T: Borrow<Q>,
750         Q: Hash + Eq + ToOwned<Owned = T>,
751     {
752         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
753         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
754         self.base.get_or_insert_owned(value)
755     }
756
757     /// Inserts a value computed from `f` into the set if the given `value` is
758     /// not present, then returns a reference to the value in the set.
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// #![feature(hash_set_entry)]
764     ///
765     /// use std::collections::HashSet;
766     ///
767     /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
768     ///     .iter().map(|&pet| pet.to_owned()).collect();
769     ///
770     /// assert_eq!(set.len(), 3);
771     /// for &pet in &["cat", "dog", "fish"] {
772     ///     let value = set.get_or_insert_with(pet, str::to_owned);
773     ///     assert_eq!(value, pet);
774     /// }
775     /// assert_eq!(set.len(), 4); // a new "fish" was inserted
776     /// ```
777     #[inline]
778     #[unstable(feature = "hash_set_entry", issue = "60896")]
779     pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
780     where
781         T: Borrow<Q>,
782         Q: Hash + Eq,
783         F: FnOnce(&Q) -> T,
784     {
785         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
786         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
787         self.base.get_or_insert_with(value, f)
788     }
789
790     /// Returns `true` if `self` has no elements in common with `other`.
791     /// This is equivalent to checking for an empty intersection.
792     ///
793     /// # Examples
794     ///
795     /// ```
796     /// use std::collections::HashSet;
797     ///
798     /// let a = HashSet::from([1, 2, 3]);
799     /// let mut b = HashSet::new();
800     ///
801     /// assert_eq!(a.is_disjoint(&b), true);
802     /// b.insert(4);
803     /// assert_eq!(a.is_disjoint(&b), true);
804     /// b.insert(1);
805     /// assert_eq!(a.is_disjoint(&b), false);
806     /// ```
807     #[stable(feature = "rust1", since = "1.0.0")]
808     pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
809         if self.len() <= other.len() {
810             self.iter().all(|v| !other.contains(v))
811         } else {
812             other.iter().all(|v| !self.contains(v))
813         }
814     }
815
816     /// Returns `true` if the set is a subset of another,
817     /// i.e., `other` contains at least all the values in `self`.
818     ///
819     /// # Examples
820     ///
821     /// ```
822     /// use std::collections::HashSet;
823     ///
824     /// let sup = HashSet::from([1, 2, 3]);
825     /// let mut set = HashSet::new();
826     ///
827     /// assert_eq!(set.is_subset(&sup), true);
828     /// set.insert(2);
829     /// assert_eq!(set.is_subset(&sup), true);
830     /// set.insert(4);
831     /// assert_eq!(set.is_subset(&sup), false);
832     /// ```
833     #[stable(feature = "rust1", since = "1.0.0")]
834     pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
835         if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
836     }
837
838     /// Returns `true` if the set is a superset of another,
839     /// i.e., `self` contains at least all the values in `other`.
840     ///
841     /// # Examples
842     ///
843     /// ```
844     /// use std::collections::HashSet;
845     ///
846     /// let sub = HashSet::from([1, 2]);
847     /// let mut set = HashSet::new();
848     ///
849     /// assert_eq!(set.is_superset(&sub), false);
850     ///
851     /// set.insert(0);
852     /// set.insert(1);
853     /// assert_eq!(set.is_superset(&sub), false);
854     ///
855     /// set.insert(2);
856     /// assert_eq!(set.is_superset(&sub), true);
857     /// ```
858     #[inline]
859     #[stable(feature = "rust1", since = "1.0.0")]
860     pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
861         other.is_subset(self)
862     }
863
864     /// Adds a value to the set.
865     ///
866     /// Returns whether the value was newly inserted. That is:
867     ///
868     /// - If the set did not previously contain this value, `true` is returned.
869     /// - If the set already contained this value, `false` is returned.
870     ///
871     /// # Examples
872     ///
873     /// ```
874     /// use std::collections::HashSet;
875     ///
876     /// let mut set = HashSet::new();
877     ///
878     /// assert_eq!(set.insert(2), true);
879     /// assert_eq!(set.insert(2), false);
880     /// assert_eq!(set.len(), 1);
881     /// ```
882     #[inline]
883     #[stable(feature = "rust1", since = "1.0.0")]
884     pub fn insert(&mut self, value: T) -> bool {
885         self.base.insert(value)
886     }
887
888     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
889     /// one. Returns the replaced value.
890     ///
891     /// # Examples
892     ///
893     /// ```
894     /// use std::collections::HashSet;
895     ///
896     /// let mut set = HashSet::new();
897     /// set.insert(Vec::<i32>::new());
898     ///
899     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
900     /// set.replace(Vec::with_capacity(10));
901     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
902     /// ```
903     #[inline]
904     #[stable(feature = "set_recovery", since = "1.9.0")]
905     pub fn replace(&mut self, value: T) -> Option<T> {
906         self.base.replace(value)
907     }
908
909     /// Removes a value from the set. Returns whether the value was
910     /// present in the set.
911     ///
912     /// The value may be any borrowed form of the set's value type, but
913     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
914     /// the value type.
915     ///
916     /// # Examples
917     ///
918     /// ```
919     /// use std::collections::HashSet;
920     ///
921     /// let mut set = HashSet::new();
922     ///
923     /// set.insert(2);
924     /// assert_eq!(set.remove(&2), true);
925     /// assert_eq!(set.remove(&2), false);
926     /// ```
927     #[inline]
928     #[stable(feature = "rust1", since = "1.0.0")]
929     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
930     where
931         T: Borrow<Q>,
932         Q: Hash + Eq,
933     {
934         self.base.remove(value)
935     }
936
937     /// Removes and returns the value in the set, if any, that is equal to the given one.
938     ///
939     /// The value may be any borrowed form of the set's value type, but
940     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
941     /// the value type.
942     ///
943     /// # Examples
944     ///
945     /// ```
946     /// use std::collections::HashSet;
947     ///
948     /// let mut set = HashSet::from([1, 2, 3]);
949     /// assert_eq!(set.take(&2), Some(2));
950     /// assert_eq!(set.take(&2), None);
951     /// ```
952     #[inline]
953     #[stable(feature = "set_recovery", since = "1.9.0")]
954     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
955     where
956         T: Borrow<Q>,
957         Q: Hash + Eq,
958     {
959         self.base.take(value)
960     }
961 }
962
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<T, S> Clone for HashSet<T, S>
965 where
966     T: Clone,
967     S: Clone,
968 {
969     #[inline]
970     fn clone(&self) -> Self {
971         Self { base: self.base.clone() }
972     }
973
974     #[inline]
975     fn clone_from(&mut self, other: &Self) {
976         self.base.clone_from(&other.base);
977     }
978 }
979
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<T, S> PartialEq for HashSet<T, S>
982 where
983     T: Eq + Hash,
984     S: BuildHasher,
985 {
986     fn eq(&self, other: &HashSet<T, S>) -> bool {
987         if self.len() != other.len() {
988             return false;
989         }
990
991         self.iter().all(|key| other.contains(key))
992     }
993 }
994
995 #[stable(feature = "rust1", since = "1.0.0")]
996 impl<T, S> Eq for HashSet<T, S>
997 where
998     T: Eq + Hash,
999     S: BuildHasher,
1000 {
1001 }
1002
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 impl<T, S> fmt::Debug for HashSet<T, S>
1005 where
1006     T: fmt::Debug,
1007 {
1008     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009         f.debug_set().entries(self.iter()).finish()
1010     }
1011 }
1012
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl<T, S> FromIterator<T> for HashSet<T, S>
1015 where
1016     T: Eq + Hash,
1017     S: BuildHasher + Default,
1018 {
1019     #[inline]
1020     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
1021         let mut set = HashSet::with_hasher(Default::default());
1022         set.extend(iter);
1023         set
1024     }
1025 }
1026
1027 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1028 // Note: as what is currently the most convenient built-in way to construct
1029 // a HashSet, a simple usage of this function must not *require* the user
1030 // to provide a type annotation in order to infer the third type parameter
1031 // (the hasher parameter, conventionally "S").
1032 // To that end, this impl is defined using RandomState as the concrete
1033 // type of S, rather than being generic over `S: BuildHasher + Default`.
1034 // It is expected that users who want to specify a hasher will manually use
1035 // `with_capacity_and_hasher`.
1036 // If type parameter defaults worked on impls, and if type parameter
1037 // defaults could be mixed with const generics, then perhaps
1038 // this could be generalized.
1039 // See also the equivalent impl on HashMap.
1040 impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
1041 where
1042     T: Eq + Hash,
1043 {
1044     /// # Examples
1045     ///
1046     /// ```
1047     /// use std::collections::HashSet;
1048     ///
1049     /// let set1 = HashSet::from([1, 2, 3, 4]);
1050     /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1051     /// assert_eq!(set1, set2);
1052     /// ```
1053     fn from(arr: [T; N]) -> Self {
1054         Self::from_iter(arr)
1055     }
1056 }
1057
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<T, S> Extend<T> for HashSet<T, S>
1060 where
1061     T: Eq + Hash,
1062     S: BuildHasher,
1063 {
1064     #[inline]
1065     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1066         self.base.extend(iter);
1067     }
1068
1069     #[inline]
1070     fn extend_one(&mut self, item: T) {
1071         self.base.insert(item);
1072     }
1073
1074     #[inline]
1075     fn extend_reserve(&mut self, additional: usize) {
1076         self.base.extend_reserve(additional);
1077     }
1078 }
1079
1080 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1081 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1082 where
1083     T: 'a + Eq + Hash + Copy,
1084     S: BuildHasher,
1085 {
1086     #[inline]
1087     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1088         self.extend(iter.into_iter().cloned());
1089     }
1090
1091     #[inline]
1092     fn extend_one(&mut self, &item: &'a T) {
1093         self.base.insert(item);
1094     }
1095
1096     #[inline]
1097     fn extend_reserve(&mut self, additional: usize) {
1098         Extend::<T>::extend_reserve(self, additional)
1099     }
1100 }
1101
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 impl<T, S> Default for HashSet<T, S>
1104 where
1105     S: Default,
1106 {
1107     /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1108     #[inline]
1109     fn default() -> HashSet<T, S> {
1110         HashSet { base: Default::default() }
1111     }
1112 }
1113
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1116 where
1117     T: Eq + Hash + Clone,
1118     S: BuildHasher + Default,
1119 {
1120     type Output = HashSet<T, S>;
1121
1122     /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1123     ///
1124     /// # Examples
1125     ///
1126     /// ```
1127     /// use std::collections::HashSet;
1128     ///
1129     /// let a = HashSet::from([1, 2, 3]);
1130     /// let b = HashSet::from([3, 4, 5]);
1131     ///
1132     /// let set = &a | &b;
1133     ///
1134     /// let mut i = 0;
1135     /// let expected = [1, 2, 3, 4, 5];
1136     /// for x in &set {
1137     ///     assert!(expected.contains(x));
1138     ///     i += 1;
1139     /// }
1140     /// assert_eq!(i, expected.len());
1141     /// ```
1142     fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1143         self.union(rhs).cloned().collect()
1144     }
1145 }
1146
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1149 where
1150     T: Eq + Hash + Clone,
1151     S: BuildHasher + Default,
1152 {
1153     type Output = HashSet<T, S>;
1154
1155     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1156     ///
1157     /// # Examples
1158     ///
1159     /// ```
1160     /// use std::collections::HashSet;
1161     ///
1162     /// let a = HashSet::from([1, 2, 3]);
1163     /// let b = HashSet::from([2, 3, 4]);
1164     ///
1165     /// let set = &a & &b;
1166     ///
1167     /// let mut i = 0;
1168     /// let expected = [2, 3];
1169     /// for x in &set {
1170     ///     assert!(expected.contains(x));
1171     ///     i += 1;
1172     /// }
1173     /// assert_eq!(i, expected.len());
1174     /// ```
1175     fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1176         self.intersection(rhs).cloned().collect()
1177     }
1178 }
1179
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1182 where
1183     T: Eq + Hash + Clone,
1184     S: BuildHasher + Default,
1185 {
1186     type Output = HashSet<T, S>;
1187
1188     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1189     ///
1190     /// # Examples
1191     ///
1192     /// ```
1193     /// use std::collections::HashSet;
1194     ///
1195     /// let a = HashSet::from([1, 2, 3]);
1196     /// let b = HashSet::from([3, 4, 5]);
1197     ///
1198     /// let set = &a ^ &b;
1199     ///
1200     /// let mut i = 0;
1201     /// let expected = [1, 2, 4, 5];
1202     /// for x in &set {
1203     ///     assert!(expected.contains(x));
1204     ///     i += 1;
1205     /// }
1206     /// assert_eq!(i, expected.len());
1207     /// ```
1208     fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1209         self.symmetric_difference(rhs).cloned().collect()
1210     }
1211 }
1212
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1215 where
1216     T: Eq + Hash + Clone,
1217     S: BuildHasher + Default,
1218 {
1219     type Output = HashSet<T, S>;
1220
1221     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1222     ///
1223     /// # Examples
1224     ///
1225     /// ```
1226     /// use std::collections::HashSet;
1227     ///
1228     /// let a = HashSet::from([1, 2, 3]);
1229     /// let b = HashSet::from([3, 4, 5]);
1230     ///
1231     /// let set = &a - &b;
1232     ///
1233     /// let mut i = 0;
1234     /// let expected = [1, 2];
1235     /// for x in &set {
1236     ///     assert!(expected.contains(x));
1237     ///     i += 1;
1238     /// }
1239     /// assert_eq!(i, expected.len());
1240     /// ```
1241     fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1242         self.difference(rhs).cloned().collect()
1243     }
1244 }
1245
1246 /// An iterator over the items of a `HashSet`.
1247 ///
1248 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1249 /// See its documentation for more.
1250 ///
1251 /// [`iter`]: HashSet::iter
1252 ///
1253 /// # Examples
1254 ///
1255 /// ```
1256 /// use std::collections::HashSet;
1257 ///
1258 /// let a = HashSet::from([1, 2, 3]);
1259 ///
1260 /// let mut iter = a.iter();
1261 /// ```
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 pub struct Iter<'a, K: 'a> {
1264     base: base::Iter<'a, K>,
1265 }
1266
1267 /// An owning iterator over the items of a `HashSet`.
1268 ///
1269 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1270 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1271 ///
1272 /// [`into_iter`]: IntoIterator::into_iter
1273 /// [`IntoIterator`]: crate::iter::IntoIterator
1274 ///
1275 /// # Examples
1276 ///
1277 /// ```
1278 /// use std::collections::HashSet;
1279 ///
1280 /// let a = HashSet::from([1, 2, 3]);
1281 ///
1282 /// let mut iter = a.into_iter();
1283 /// ```
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 pub struct IntoIter<K> {
1286     base: base::IntoIter<K>,
1287 }
1288
1289 /// A draining iterator over the items of a `HashSet`.
1290 ///
1291 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1292 /// See its documentation for more.
1293 ///
1294 /// [`drain`]: HashSet::drain
1295 ///
1296 /// # Examples
1297 ///
1298 /// ```
1299 /// use std::collections::HashSet;
1300 ///
1301 /// let mut a = HashSet::from([1, 2, 3]);
1302 ///
1303 /// let mut drain = a.drain();
1304 /// ```
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub struct Drain<'a, K: 'a> {
1307     base: base::Drain<'a, K>,
1308 }
1309
1310 /// A draining, filtering iterator over the items of a `HashSet`.
1311 ///
1312 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1313 ///
1314 /// [`drain_filter`]: HashSet::drain_filter
1315 ///
1316 /// # Examples
1317 ///
1318 /// ```
1319 /// #![feature(hash_drain_filter)]
1320 ///
1321 /// use std::collections::HashSet;
1322 ///
1323 /// let mut a = HashSet::from([1, 2, 3]);
1324 ///
1325 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1326 /// ```
1327 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1328 pub struct DrainFilter<'a, K, F>
1329 where
1330     F: FnMut(&K) -> bool,
1331 {
1332     base: base::DrainFilter<'a, K, F>,
1333 }
1334
1335 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1336 ///
1337 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1338 /// See its documentation for more.
1339 ///
1340 /// [`intersection`]: HashSet::intersection
1341 ///
1342 /// # Examples
1343 ///
1344 /// ```
1345 /// use std::collections::HashSet;
1346 ///
1347 /// let a = HashSet::from([1, 2, 3]);
1348 /// let b = HashSet::from([4, 2, 3, 4]);
1349 ///
1350 /// let mut intersection = a.intersection(&b);
1351 /// ```
1352 #[must_use = "this returns the intersection as an iterator, \
1353               without modifying either input set"]
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 pub struct Intersection<'a, T: 'a, S: 'a> {
1356     // iterator of the first set
1357     iter: Iter<'a, T>,
1358     // the second set
1359     other: &'a HashSet<T, S>,
1360 }
1361
1362 /// A lazy iterator producing elements in the difference of `HashSet`s.
1363 ///
1364 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1365 /// See its documentation for more.
1366 ///
1367 /// [`difference`]: HashSet::difference
1368 ///
1369 /// # Examples
1370 ///
1371 /// ```
1372 /// use std::collections::HashSet;
1373 ///
1374 /// let a = HashSet::from([1, 2, 3]);
1375 /// let b = HashSet::from([4, 2, 3, 4]);
1376 ///
1377 /// let mut difference = a.difference(&b);
1378 /// ```
1379 #[must_use = "this returns the difference as an iterator, \
1380               without modifying either input set"]
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub struct Difference<'a, T: 'a, S: 'a> {
1383     // iterator of the first set
1384     iter: Iter<'a, T>,
1385     // the second set
1386     other: &'a HashSet<T, S>,
1387 }
1388
1389 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1390 ///
1391 /// This `struct` is created by the [`symmetric_difference`] method on
1392 /// [`HashSet`]. See its documentation for more.
1393 ///
1394 /// [`symmetric_difference`]: HashSet::symmetric_difference
1395 ///
1396 /// # Examples
1397 ///
1398 /// ```
1399 /// use std::collections::HashSet;
1400 ///
1401 /// let a = HashSet::from([1, 2, 3]);
1402 /// let b = HashSet::from([4, 2, 3, 4]);
1403 ///
1404 /// let mut intersection = a.symmetric_difference(&b);
1405 /// ```
1406 #[must_use = "this returns the difference as an iterator, \
1407               without modifying either input set"]
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1410     iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1411 }
1412
1413 /// A lazy iterator producing elements in the union of `HashSet`s.
1414 ///
1415 /// This `struct` is created by the [`union`] method on [`HashSet`].
1416 /// See its documentation for more.
1417 ///
1418 /// [`union`]: HashSet::union
1419 ///
1420 /// # Examples
1421 ///
1422 /// ```
1423 /// use std::collections::HashSet;
1424 ///
1425 /// let a = HashSet::from([1, 2, 3]);
1426 /// let b = HashSet::from([4, 2, 3, 4]);
1427 ///
1428 /// let mut union_iter = a.union(&b);
1429 /// ```
1430 #[must_use = "this returns the union as an iterator, \
1431               without modifying either input set"]
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 pub struct Union<'a, T: 'a, S: 'a> {
1434     iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1435 }
1436
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1439     type Item = &'a T;
1440     type IntoIter = Iter<'a, T>;
1441
1442     #[inline]
1443     #[rustc_lint_query_instability]
1444     fn into_iter(self) -> Iter<'a, T> {
1445         self.iter()
1446     }
1447 }
1448
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 impl<T, S> IntoIterator for HashSet<T, S> {
1451     type Item = T;
1452     type IntoIter = IntoIter<T>;
1453
1454     /// Creates a consuming iterator, that is, one that moves each value out
1455     /// of the set in arbitrary order. The set cannot be used after calling
1456     /// this.
1457     ///
1458     /// # Examples
1459     ///
1460     /// ```
1461     /// use std::collections::HashSet;
1462     /// let mut set = HashSet::new();
1463     /// set.insert("a".to_string());
1464     /// set.insert("b".to_string());
1465     ///
1466     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1467     /// let v: Vec<String> = set.into_iter().collect();
1468     ///
1469     /// // Will print in an arbitrary order.
1470     /// for x in &v {
1471     ///     println!("{x}");
1472     /// }
1473     /// ```
1474     #[inline]
1475     #[rustc_lint_query_instability]
1476     fn into_iter(self) -> IntoIter<T> {
1477         IntoIter { base: self.base.into_iter() }
1478     }
1479 }
1480
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<K> Clone for Iter<'_, K> {
1483     #[inline]
1484     fn clone(&self) -> Self {
1485         Iter { base: self.base.clone() }
1486     }
1487 }
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<'a, K> Iterator for Iter<'a, K> {
1490     type Item = &'a K;
1491
1492     #[inline]
1493     fn next(&mut self) -> Option<&'a K> {
1494         self.base.next()
1495     }
1496     #[inline]
1497     fn size_hint(&self) -> (usize, Option<usize>) {
1498         self.base.size_hint()
1499     }
1500 }
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl<K> ExactSizeIterator for Iter<'_, K> {
1503     #[inline]
1504     fn len(&self) -> usize {
1505         self.base.len()
1506     }
1507 }
1508 #[stable(feature = "fused", since = "1.26.0")]
1509 impl<K> FusedIterator for Iter<'_, K> {}
1510
1511 #[stable(feature = "std_debug", since = "1.16.0")]
1512 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1513     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514         f.debug_list().entries(self.clone()).finish()
1515     }
1516 }
1517
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl<K> Iterator for IntoIter<K> {
1520     type Item = K;
1521
1522     #[inline]
1523     fn next(&mut self) -> Option<K> {
1524         self.base.next()
1525     }
1526     #[inline]
1527     fn size_hint(&self) -> (usize, Option<usize>) {
1528         self.base.size_hint()
1529     }
1530 }
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl<K> ExactSizeIterator for IntoIter<K> {
1533     #[inline]
1534     fn len(&self) -> usize {
1535         self.base.len()
1536     }
1537 }
1538 #[stable(feature = "fused", since = "1.26.0")]
1539 impl<K> FusedIterator for IntoIter<K> {}
1540
1541 #[stable(feature = "std_debug", since = "1.16.0")]
1542 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1543     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1544         fmt::Debug::fmt(&self.base, f)
1545     }
1546 }
1547
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<'a, K> Iterator for Drain<'a, K> {
1550     type Item = K;
1551
1552     #[inline]
1553     fn next(&mut self) -> Option<K> {
1554         self.base.next()
1555     }
1556     #[inline]
1557     fn size_hint(&self) -> (usize, Option<usize>) {
1558         self.base.size_hint()
1559     }
1560 }
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<K> ExactSizeIterator for Drain<'_, K> {
1563     #[inline]
1564     fn len(&self) -> usize {
1565         self.base.len()
1566     }
1567 }
1568 #[stable(feature = "fused", since = "1.26.0")]
1569 impl<K> FusedIterator for Drain<'_, K> {}
1570
1571 #[stable(feature = "std_debug", since = "1.16.0")]
1572 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1573     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574         fmt::Debug::fmt(&self.base, f)
1575     }
1576 }
1577
1578 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1579 impl<K, F> Iterator for DrainFilter<'_, K, F>
1580 where
1581     F: FnMut(&K) -> bool,
1582 {
1583     type Item = K;
1584
1585     #[inline]
1586     fn next(&mut self) -> Option<K> {
1587         self.base.next()
1588     }
1589     #[inline]
1590     fn size_hint(&self) -> (usize, Option<usize>) {
1591         self.base.size_hint()
1592     }
1593 }
1594
1595 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1596 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1597
1598 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1599 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1600 where
1601     F: FnMut(&K) -> bool,
1602 {
1603     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1604         f.debug_struct("DrainFilter").finish_non_exhaustive()
1605     }
1606 }
1607
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl<T, S> Clone for Intersection<'_, T, S> {
1610     #[inline]
1611     fn clone(&self) -> Self {
1612         Intersection { iter: self.iter.clone(), ..*self }
1613     }
1614 }
1615
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1618 where
1619     T: Eq + Hash,
1620     S: BuildHasher,
1621 {
1622     type Item = &'a T;
1623
1624     #[inline]
1625     fn next(&mut self) -> Option<&'a T> {
1626         loop {
1627             let elt = self.iter.next()?;
1628             if self.other.contains(elt) {
1629                 return Some(elt);
1630             }
1631         }
1632     }
1633
1634     #[inline]
1635     fn size_hint(&self) -> (usize, Option<usize>) {
1636         let (_, upper) = self.iter.size_hint();
1637         (0, upper)
1638     }
1639 }
1640
1641 #[stable(feature = "std_debug", since = "1.16.0")]
1642 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1643 where
1644     T: fmt::Debug + Eq + Hash,
1645     S: BuildHasher,
1646 {
1647     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648         f.debug_list().entries(self.clone()).finish()
1649     }
1650 }
1651
1652 #[stable(feature = "fused", since = "1.26.0")]
1653 impl<T, S> FusedIterator for Intersection<'_, T, S>
1654 where
1655     T: Eq + Hash,
1656     S: BuildHasher,
1657 {
1658 }
1659
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<T, S> Clone for Difference<'_, T, S> {
1662     #[inline]
1663     fn clone(&self) -> Self {
1664         Difference { iter: self.iter.clone(), ..*self }
1665     }
1666 }
1667
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<'a, T, S> Iterator for Difference<'a, T, S>
1670 where
1671     T: Eq + Hash,
1672     S: BuildHasher,
1673 {
1674     type Item = &'a T;
1675
1676     #[inline]
1677     fn next(&mut self) -> Option<&'a T> {
1678         loop {
1679             let elt = self.iter.next()?;
1680             if !self.other.contains(elt) {
1681                 return Some(elt);
1682             }
1683         }
1684     }
1685
1686     #[inline]
1687     fn size_hint(&self) -> (usize, Option<usize>) {
1688         let (_, upper) = self.iter.size_hint();
1689         (0, upper)
1690     }
1691 }
1692
1693 #[stable(feature = "fused", since = "1.26.0")]
1694 impl<T, S> FusedIterator for Difference<'_, T, S>
1695 where
1696     T: Eq + Hash,
1697     S: BuildHasher,
1698 {
1699 }
1700
1701 #[stable(feature = "std_debug", since = "1.16.0")]
1702 impl<T, S> fmt::Debug for Difference<'_, T, S>
1703 where
1704     T: fmt::Debug + Eq + Hash,
1705     S: BuildHasher,
1706 {
1707     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1708         f.debug_list().entries(self.clone()).finish()
1709     }
1710 }
1711
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1714     #[inline]
1715     fn clone(&self) -> Self {
1716         SymmetricDifference { iter: self.iter.clone() }
1717     }
1718 }
1719
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1722 where
1723     T: Eq + Hash,
1724     S: BuildHasher,
1725 {
1726     type Item = &'a T;
1727
1728     #[inline]
1729     fn next(&mut self) -> Option<&'a T> {
1730         self.iter.next()
1731     }
1732     #[inline]
1733     fn size_hint(&self) -> (usize, Option<usize>) {
1734         self.iter.size_hint()
1735     }
1736 }
1737
1738 #[stable(feature = "fused", since = "1.26.0")]
1739 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1740 where
1741     T: Eq + Hash,
1742     S: BuildHasher,
1743 {
1744 }
1745
1746 #[stable(feature = "std_debug", since = "1.16.0")]
1747 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1748 where
1749     T: fmt::Debug + Eq + Hash,
1750     S: BuildHasher,
1751 {
1752     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1753         f.debug_list().entries(self.clone()).finish()
1754     }
1755 }
1756
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<T, S> Clone for Union<'_, T, S> {
1759     #[inline]
1760     fn clone(&self) -> Self {
1761         Union { iter: self.iter.clone() }
1762     }
1763 }
1764
1765 #[stable(feature = "fused", since = "1.26.0")]
1766 impl<T, S> FusedIterator for Union<'_, T, S>
1767 where
1768     T: Eq + Hash,
1769     S: BuildHasher,
1770 {
1771 }
1772
1773 #[stable(feature = "std_debug", since = "1.16.0")]
1774 impl<T, S> fmt::Debug for Union<'_, T, S>
1775 where
1776     T: fmt::Debug + Eq + Hash,
1777     S: BuildHasher,
1778 {
1779     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1780         f.debug_list().entries(self.clone()).finish()
1781     }
1782 }
1783
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<'a, T, S> Iterator for Union<'a, T, S>
1786 where
1787     T: Eq + Hash,
1788     S: BuildHasher,
1789 {
1790     type Item = &'a T;
1791
1792     #[inline]
1793     fn next(&mut self) -> Option<&'a T> {
1794         self.iter.next()
1795     }
1796     #[inline]
1797     fn size_hint(&self) -> (usize, Option<usize>) {
1798         self.iter.size_hint()
1799     }
1800 }
1801
1802 #[allow(dead_code)]
1803 fn assert_covariance() {
1804     fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1805         v
1806     }
1807     fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1808         v
1809     }
1810     fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1811         v
1812     }
1813     fn difference<'a, 'new>(
1814         v: Difference<'a, &'static str, RandomState>,
1815     ) -> Difference<'a, &'new str, RandomState> {
1816         v
1817     }
1818     fn symmetric_difference<'a, 'new>(
1819         v: SymmetricDifference<'a, &'static str, RandomState>,
1820     ) -> SymmetricDifference<'a, &'new str, RandomState> {
1821         v
1822     }
1823     fn intersection<'a, 'new>(
1824         v: Intersection<'a, &'static str, RandomState>,
1825     ) -> Intersection<'a, &'new str, RandomState> {
1826         v
1827     }
1828     fn union<'a, 'new>(
1829         v: Union<'a, &'static str, RandomState>,
1830     ) -> Union<'a, &'new str, RandomState> {
1831         v
1832     }
1833     fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1834         d
1835     }
1836 }