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