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