]> git.lizzy.rs Git - rust.git/blob - library/std/src/collections/hash/set.rs
Auto merge of #81635 - michaelwoerister:structured_def_path_hash, r=pnkfelix
[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 fixed list of elements can be initialized from an array:
99 ///
100 /// ```
101 /// use std::collections::HashSet;
102 ///
103 /// let viking_names: HashSet<&'static str> =
104 ///     [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
105 /// // use the values stored in the set
106 /// ```
107 ///
108 /// [`HashMap`]: crate::collections::HashMap
109 /// [`RefCell`]: crate::cell::RefCell
110 /// [`Cell`]: crate::cell::Cell
111 #[cfg_attr(not(test), rustc_diagnostic_item = "hashset_type")]
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct HashSet<T, S = RandomState> {
114     base: base::HashSet<T, S>,
115 }
116
117 impl<T> HashSet<T, RandomState> {
118     /// Creates an empty `HashSet`.
119     ///
120     /// The hash set is initially created with a capacity of 0, so it will not allocate until it
121     /// is first inserted into.
122     ///
123     /// # Examples
124     ///
125     /// ```
126     /// use std::collections::HashSet;
127     /// let set: HashSet<i32> = HashSet::new();
128     /// ```
129     #[inline]
130     #[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     #[stable(feature = "rust1", since = "1.0.0")]
149     pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
150         HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
151     }
152 }
153
154 impl<T, S> HashSet<T, S> {
155     /// Returns the number of elements the set can hold without reallocating.
156     ///
157     /// # Examples
158     ///
159     /// ```
160     /// use std::collections::HashSet;
161     /// let set: HashSet<i32> = HashSet::with_capacity(100);
162     /// assert!(set.capacity() >= 100);
163     /// ```
164     #[inline]
165     #[stable(feature = "rust1", since = "1.0.0")]
166     pub fn capacity(&self) -> usize {
167         self.base.capacity()
168     }
169
170     /// An iterator visiting all elements in arbitrary order.
171     /// The iterator element type is `&'a T`.
172     ///
173     /// # Examples
174     ///
175     /// ```
176     /// use std::collections::HashSet;
177     /// let mut set = HashSet::new();
178     /// set.insert("a");
179     /// set.insert("b");
180     ///
181     /// // Will print in an arbitrary order.
182     /// for x in set.iter() {
183     ///     println!("{}", x);
184     /// }
185     /// ```
186     #[inline]
187     #[stable(feature = "rust1", since = "1.0.0")]
188     pub fn iter(&self) -> Iter<'_, T> {
189         Iter { base: self.base.iter() }
190     }
191
192     /// Returns the number of elements in the set.
193     ///
194     /// # Examples
195     ///
196     /// ```
197     /// use std::collections::HashSet;
198     ///
199     /// let mut v = HashSet::new();
200     /// assert_eq!(v.len(), 0);
201     /// v.insert(1);
202     /// assert_eq!(v.len(), 1);
203     /// ```
204     #[doc(alias = "length")]
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     /// #![feature(try_reserve)]
429     /// use std::collections::HashSet;
430     /// let mut set: HashSet<i32> = HashSet::new();
431     /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
432     /// ```
433     #[inline]
434     #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
435     pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
436         self.base.try_reserve(additional).map_err(map_try_reserve_error)
437     }
438
439     /// Shrinks the capacity of the set as much as possible. It will drop
440     /// down as much as possible while maintaining the internal rules
441     /// and possibly leaving some space in accordance with the resize policy.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// use std::collections::HashSet;
447     ///
448     /// let mut set = HashSet::with_capacity(100);
449     /// set.insert(1);
450     /// set.insert(2);
451     /// assert!(set.capacity() >= 100);
452     /// set.shrink_to_fit();
453     /// assert!(set.capacity() >= 2);
454     /// ```
455     #[inline]
456     #[stable(feature = "rust1", since = "1.0.0")]
457     pub fn shrink_to_fit(&mut self) {
458         self.base.shrink_to_fit()
459     }
460
461     /// Shrinks the capacity of the set with a lower limit. It will drop
462     /// down no lower than the supplied limit while maintaining the internal rules
463     /// and possibly leaving some space in accordance with the resize policy.
464     ///
465     /// If the current capacity is less than the lower limit, this is a no-op.
466     /// # Examples
467     ///
468     /// ```
469     /// #![feature(shrink_to)]
470     /// use std::collections::HashSet;
471     ///
472     /// let mut set = HashSet::with_capacity(100);
473     /// set.insert(1);
474     /// set.insert(2);
475     /// assert!(set.capacity() >= 100);
476     /// set.shrink_to(10);
477     /// assert!(set.capacity() >= 10);
478     /// set.shrink_to(0);
479     /// assert!(set.capacity() >= 2);
480     /// ```
481     #[inline]
482     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
483     pub fn shrink_to(&mut self, min_capacity: usize) {
484         self.base.shrink_to(min_capacity)
485     }
486
487     /// Visits the values representing the difference,
488     /// i.e., the values that are in `self` but not in `other`.
489     ///
490     /// # Examples
491     ///
492     /// ```
493     /// use std::collections::HashSet;
494     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
495     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
496     ///
497     /// // Can be seen as `a - b`.
498     /// for x in a.difference(&b) {
499     ///     println!("{}", x); // Print 1
500     /// }
501     ///
502     /// let diff: HashSet<_> = a.difference(&b).collect();
503     /// assert_eq!(diff, [1].iter().collect());
504     ///
505     /// // Note that difference is not symmetric,
506     /// // and `b - a` means something else:
507     /// let diff: HashSet<_> = b.difference(&a).collect();
508     /// assert_eq!(diff, [4].iter().collect());
509     /// ```
510     #[inline]
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
513         Difference { iter: self.iter(), other }
514     }
515
516     /// Visits the values representing the symmetric difference,
517     /// i.e., the values that are in `self` or in `other` but not in both.
518     ///
519     /// # Examples
520     ///
521     /// ```
522     /// use std::collections::HashSet;
523     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
524     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
525     ///
526     /// // Print 1, 4 in arbitrary order.
527     /// for x in a.symmetric_difference(&b) {
528     ///     println!("{}", x);
529     /// }
530     ///
531     /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
532     /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
533     ///
534     /// assert_eq!(diff1, diff2);
535     /// assert_eq!(diff1, [1, 4].iter().collect());
536     /// ```
537     #[inline]
538     #[stable(feature = "rust1", since = "1.0.0")]
539     pub fn symmetric_difference<'a>(
540         &'a self,
541         other: &'a HashSet<T, S>,
542     ) -> SymmetricDifference<'a, T, S> {
543         SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
544     }
545
546     /// Visits the values representing the intersection,
547     /// i.e., the values that are both in `self` and `other`.
548     ///
549     /// # Examples
550     ///
551     /// ```
552     /// use std::collections::HashSet;
553     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
554     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
555     ///
556     /// // Print 2, 3 in arbitrary order.
557     /// for x in a.intersection(&b) {
558     ///     println!("{}", x);
559     /// }
560     ///
561     /// let intersection: HashSet<_> = a.intersection(&b).collect();
562     /// assert_eq!(intersection, [2, 3].iter().collect());
563     /// ```
564     #[inline]
565     #[stable(feature = "rust1", since = "1.0.0")]
566     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
567         if self.len() <= other.len() {
568             Intersection { iter: self.iter(), other }
569         } else {
570             Intersection { iter: other.iter(), other: self }
571         }
572     }
573
574     /// Visits the values representing the union,
575     /// i.e., all the values in `self` or `other`, without duplicates.
576     ///
577     /// # Examples
578     ///
579     /// ```
580     /// use std::collections::HashSet;
581     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
582     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
583     ///
584     /// // Print 1, 2, 3, 4 in arbitrary order.
585     /// for x in a.union(&b) {
586     ///     println!("{}", x);
587     /// }
588     ///
589     /// let union: HashSet<_> = a.union(&b).collect();
590     /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
591     /// ```
592     #[inline]
593     #[stable(feature = "rust1", since = "1.0.0")]
594     pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
595         if self.len() >= other.len() {
596             Union { iter: self.iter().chain(other.difference(self)) }
597         } else {
598             Union { iter: other.iter().chain(self.difference(other)) }
599         }
600     }
601
602     /// Returns `true` if the set contains a value.
603     ///
604     /// The value may be any borrowed form of the set's value type, but
605     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
606     /// the value type.
607     ///
608     /// # Examples
609     ///
610     /// ```
611     /// use std::collections::HashSet;
612     ///
613     /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
614     /// assert_eq!(set.contains(&1), true);
615     /// assert_eq!(set.contains(&4), false);
616     /// ```
617     #[inline]
618     #[stable(feature = "rust1", since = "1.0.0")]
619     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
620     where
621         T: Borrow<Q>,
622         Q: Hash + Eq,
623     {
624         self.base.contains(value)
625     }
626
627     /// Returns a reference to the value in the set, if any, that is equal to the given value.
628     ///
629     /// The value may be any borrowed form of the set's value type, but
630     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
631     /// the value type.
632     ///
633     /// # Examples
634     ///
635     /// ```
636     /// use std::collections::HashSet;
637     ///
638     /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
639     /// assert_eq!(set.get(&2), Some(&2));
640     /// assert_eq!(set.get(&4), None);
641     /// ```
642     #[inline]
643     #[stable(feature = "set_recovery", since = "1.9.0")]
644     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
645     where
646         T: Borrow<Q>,
647         Q: Hash + Eq,
648     {
649         self.base.get(value)
650     }
651
652     /// Inserts the given `value` into the set if it is not present, then
653     /// returns a reference to the value in the set.
654     ///
655     /// # Examples
656     ///
657     /// ```
658     /// #![feature(hash_set_entry)]
659     ///
660     /// use std::collections::HashSet;
661     ///
662     /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
663     /// assert_eq!(set.len(), 3);
664     /// assert_eq!(set.get_or_insert(2), &2);
665     /// assert_eq!(set.get_or_insert(100), &100);
666     /// assert_eq!(set.len(), 4); // 100 was inserted
667     /// ```
668     #[inline]
669     #[unstable(feature = "hash_set_entry", issue = "60896")]
670     pub fn get_or_insert(&mut self, value: T) -> &T {
671         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
672         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
673         self.base.get_or_insert(value)
674     }
675
676     /// Inserts an owned copy of the given `value` into the set if it is not
677     /// present, then returns a reference to the value in the set.
678     ///
679     /// # Examples
680     ///
681     /// ```
682     /// #![feature(hash_set_entry)]
683     ///
684     /// use std::collections::HashSet;
685     ///
686     /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
687     ///     .iter().map(|&pet| pet.to_owned()).collect();
688     ///
689     /// assert_eq!(set.len(), 3);
690     /// for &pet in &["cat", "dog", "fish"] {
691     ///     let value = set.get_or_insert_owned(pet);
692     ///     assert_eq!(value, pet);
693     /// }
694     /// assert_eq!(set.len(), 4); // a new "fish" was inserted
695     /// ```
696     #[inline]
697     #[unstable(feature = "hash_set_entry", issue = "60896")]
698     pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
699     where
700         T: Borrow<Q>,
701         Q: Hash + Eq + ToOwned<Owned = T>,
702     {
703         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
704         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
705         self.base.get_or_insert_owned(value)
706     }
707
708     /// Inserts a value computed from `f` into the set if the given `value` is
709     /// not present, then returns a reference to the value in the set.
710     ///
711     /// # Examples
712     ///
713     /// ```
714     /// #![feature(hash_set_entry)]
715     ///
716     /// use std::collections::HashSet;
717     ///
718     /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
719     ///     .iter().map(|&pet| pet.to_owned()).collect();
720     ///
721     /// assert_eq!(set.len(), 3);
722     /// for &pet in &["cat", "dog", "fish"] {
723     ///     let value = set.get_or_insert_with(pet, str::to_owned);
724     ///     assert_eq!(value, pet);
725     /// }
726     /// assert_eq!(set.len(), 4); // a new "fish" was inserted
727     /// ```
728     #[inline]
729     #[unstable(feature = "hash_set_entry", issue = "60896")]
730     pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
731     where
732         T: Borrow<Q>,
733         Q: Hash + Eq,
734         F: FnOnce(&Q) -> T,
735     {
736         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
737         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
738         self.base.get_or_insert_with(value, f)
739     }
740
741     /// Returns `true` if `self` has no elements in common with `other`.
742     /// This is equivalent to checking for an empty intersection.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// use std::collections::HashSet;
748     ///
749     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
750     /// let mut b = HashSet::new();
751     ///
752     /// assert_eq!(a.is_disjoint(&b), true);
753     /// b.insert(4);
754     /// assert_eq!(a.is_disjoint(&b), true);
755     /// b.insert(1);
756     /// assert_eq!(a.is_disjoint(&b), false);
757     /// ```
758     #[stable(feature = "rust1", since = "1.0.0")]
759     pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
760         if self.len() <= other.len() {
761             self.iter().all(|v| !other.contains(v))
762         } else {
763             other.iter().all(|v| !self.contains(v))
764         }
765     }
766
767     /// Returns `true` if the set is a subset of another,
768     /// i.e., `other` contains at least all the values in `self`.
769     ///
770     /// # Examples
771     ///
772     /// ```
773     /// use std::collections::HashSet;
774     ///
775     /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
776     /// let mut set = HashSet::new();
777     ///
778     /// assert_eq!(set.is_subset(&sup), true);
779     /// set.insert(2);
780     /// assert_eq!(set.is_subset(&sup), true);
781     /// set.insert(4);
782     /// assert_eq!(set.is_subset(&sup), false);
783     /// ```
784     #[stable(feature = "rust1", since = "1.0.0")]
785     pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
786         if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
787     }
788
789     /// Returns `true` if the set is a superset of another,
790     /// i.e., `self` contains at least all the values in `other`.
791     ///
792     /// # Examples
793     ///
794     /// ```
795     /// use std::collections::HashSet;
796     ///
797     /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
798     /// let mut set = HashSet::new();
799     ///
800     /// assert_eq!(set.is_superset(&sub), false);
801     ///
802     /// set.insert(0);
803     /// set.insert(1);
804     /// assert_eq!(set.is_superset(&sub), false);
805     ///
806     /// set.insert(2);
807     /// assert_eq!(set.is_superset(&sub), true);
808     /// ```
809     #[inline]
810     #[stable(feature = "rust1", since = "1.0.0")]
811     pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
812         other.is_subset(self)
813     }
814
815     /// Adds a value to the set.
816     ///
817     /// If the set did not have this value present, `true` is returned.
818     ///
819     /// If the set did have this value present, `false` is returned.
820     ///
821     /// # Examples
822     ///
823     /// ```
824     /// use std::collections::HashSet;
825     ///
826     /// let mut set = HashSet::new();
827     ///
828     /// assert_eq!(set.insert(2), true);
829     /// assert_eq!(set.insert(2), false);
830     /// assert_eq!(set.len(), 1);
831     /// ```
832     #[inline]
833     #[stable(feature = "rust1", since = "1.0.0")]
834     pub fn insert(&mut self, value: T) -> bool {
835         self.base.insert(value)
836     }
837
838     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
839     /// one. Returns the replaced value.
840     ///
841     /// # Examples
842     ///
843     /// ```
844     /// use std::collections::HashSet;
845     ///
846     /// let mut set = HashSet::new();
847     /// set.insert(Vec::<i32>::new());
848     ///
849     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
850     /// set.replace(Vec::with_capacity(10));
851     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
852     /// ```
853     #[inline]
854     #[stable(feature = "set_recovery", since = "1.9.0")]
855     pub fn replace(&mut self, value: T) -> Option<T> {
856         self.base.replace(value)
857     }
858
859     /// Removes a value from the set. Returns whether the value was
860     /// present in the set.
861     ///
862     /// The value may be any borrowed form of the set's value type, but
863     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
864     /// the value type.
865     ///
866     /// # Examples
867     ///
868     /// ```
869     /// use std::collections::HashSet;
870     ///
871     /// let mut set = HashSet::new();
872     ///
873     /// set.insert(2);
874     /// assert_eq!(set.remove(&2), true);
875     /// assert_eq!(set.remove(&2), false);
876     /// ```
877     #[doc(alias = "delete")]
878     #[inline]
879     #[stable(feature = "rust1", since = "1.0.0")]
880     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
881     where
882         T: Borrow<Q>,
883         Q: Hash + Eq,
884     {
885         self.base.remove(value)
886     }
887
888     /// Removes and returns the value in the set, if any, that is equal to the given one.
889     ///
890     /// The value may be any borrowed form of the set's value type, but
891     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
892     /// the value type.
893     ///
894     /// # Examples
895     ///
896     /// ```
897     /// use std::collections::HashSet;
898     ///
899     /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
900     /// assert_eq!(set.take(&2), Some(2));
901     /// assert_eq!(set.take(&2), None);
902     /// ```
903     #[inline]
904     #[stable(feature = "set_recovery", since = "1.9.0")]
905     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
906     where
907         T: Borrow<Q>,
908         Q: Hash + Eq,
909     {
910         self.base.take(value)
911     }
912
913     /// Retains only the elements specified by the predicate.
914     ///
915     /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
916     ///
917     /// # Examples
918     ///
919     /// ```
920     /// use std::collections::HashSet;
921     ///
922     /// let xs = [1, 2, 3, 4, 5, 6];
923     /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
924     /// set.retain(|&k| k % 2 == 0);
925     /// assert_eq!(set.len(), 3);
926     /// ```
927     #[stable(feature = "retain_hash_collection", since = "1.18.0")]
928     pub fn retain<F>(&mut self, f: F)
929     where
930         F: FnMut(&T) -> bool,
931     {
932         self.base.retain(f)
933     }
934 }
935
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<T, S> Clone for HashSet<T, S>
938 where
939     T: Clone,
940     S: Clone,
941 {
942     #[inline]
943     fn clone(&self) -> Self {
944         Self { base: self.base.clone() }
945     }
946
947     #[inline]
948     fn clone_from(&mut self, other: &Self) {
949         self.base.clone_from(&other.base);
950     }
951 }
952
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<T, S> PartialEq for HashSet<T, S>
955 where
956     T: Eq + Hash,
957     S: BuildHasher,
958 {
959     fn eq(&self, other: &HashSet<T, S>) -> bool {
960         if self.len() != other.len() {
961             return false;
962         }
963
964         self.iter().all(|key| other.contains(key))
965     }
966 }
967
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<T, S> Eq for HashSet<T, S>
970 where
971     T: Eq + Hash,
972     S: BuildHasher,
973 {
974 }
975
976 #[stable(feature = "rust1", since = "1.0.0")]
977 impl<T, S> fmt::Debug for HashSet<T, S>
978 where
979     T: fmt::Debug,
980 {
981     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982         f.debug_set().entries(self.iter()).finish()
983     }
984 }
985
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<T, S> FromIterator<T> for HashSet<T, S>
988 where
989     T: Eq + Hash,
990     S: BuildHasher + Default,
991 {
992     #[inline]
993     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
994         let mut set = HashSet::with_hasher(Default::default());
995         set.extend(iter);
996         set
997     }
998 }
999
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 impl<T, S> Extend<T> for HashSet<T, S>
1002 where
1003     T: Eq + Hash,
1004     S: BuildHasher,
1005 {
1006     #[inline]
1007     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1008         self.base.extend(iter);
1009     }
1010
1011     #[inline]
1012     fn extend_one(&mut self, item: T) {
1013         self.base.insert(item);
1014     }
1015
1016     #[inline]
1017     fn extend_reserve(&mut self, additional: usize) {
1018         self.base.extend_reserve(additional);
1019     }
1020 }
1021
1022 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1023 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1024 where
1025     T: 'a + Eq + Hash + Copy,
1026     S: BuildHasher,
1027 {
1028     #[inline]
1029     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1030         self.extend(iter.into_iter().cloned());
1031     }
1032
1033     #[inline]
1034     fn extend_one(&mut self, &item: &'a T) {
1035         self.base.insert(item);
1036     }
1037
1038     #[inline]
1039     fn extend_reserve(&mut self, additional: usize) {
1040         Extend::<T>::extend_reserve(self, additional)
1041     }
1042 }
1043
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 impl<T, S> Default for HashSet<T, S>
1046 where
1047     S: Default,
1048 {
1049     /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1050     #[inline]
1051     fn default() -> HashSet<T, S> {
1052         HashSet { base: Default::default() }
1053     }
1054 }
1055
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1058 where
1059     T: Eq + Hash + Clone,
1060     S: BuildHasher + Default,
1061 {
1062     type Output = HashSet<T, S>;
1063
1064     /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1065     ///
1066     /// # Examples
1067     ///
1068     /// ```
1069     /// use std::collections::HashSet;
1070     ///
1071     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1072     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1073     ///
1074     /// let set = &a | &b;
1075     ///
1076     /// let mut i = 0;
1077     /// let expected = [1, 2, 3, 4, 5];
1078     /// for x in &set {
1079     ///     assert!(expected.contains(x));
1080     ///     i += 1;
1081     /// }
1082     /// assert_eq!(i, expected.len());
1083     /// ```
1084     fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1085         self.union(rhs).cloned().collect()
1086     }
1087 }
1088
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1091 where
1092     T: Eq + Hash + Clone,
1093     S: BuildHasher + Default,
1094 {
1095     type Output = HashSet<T, S>;
1096
1097     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1098     ///
1099     /// # Examples
1100     ///
1101     /// ```
1102     /// use std::collections::HashSet;
1103     ///
1104     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1105     /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1106     ///
1107     /// let set = &a & &b;
1108     ///
1109     /// let mut i = 0;
1110     /// let expected = [2, 3];
1111     /// for x in &set {
1112     ///     assert!(expected.contains(x));
1113     ///     i += 1;
1114     /// }
1115     /// assert_eq!(i, expected.len());
1116     /// ```
1117     fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1118         self.intersection(rhs).cloned().collect()
1119     }
1120 }
1121
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1124 where
1125     T: Eq + Hash + Clone,
1126     S: BuildHasher + Default,
1127 {
1128     type Output = HashSet<T, S>;
1129
1130     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1131     ///
1132     /// # Examples
1133     ///
1134     /// ```
1135     /// use std::collections::HashSet;
1136     ///
1137     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1138     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1139     ///
1140     /// let set = &a ^ &b;
1141     ///
1142     /// let mut i = 0;
1143     /// let expected = [1, 2, 4, 5];
1144     /// for x in &set {
1145     ///     assert!(expected.contains(x));
1146     ///     i += 1;
1147     /// }
1148     /// assert_eq!(i, expected.len());
1149     /// ```
1150     fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1151         self.symmetric_difference(rhs).cloned().collect()
1152     }
1153 }
1154
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1157 where
1158     T: Eq + Hash + Clone,
1159     S: BuildHasher + Default,
1160 {
1161     type Output = HashSet<T, S>;
1162
1163     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1164     ///
1165     /// # Examples
1166     ///
1167     /// ```
1168     /// use std::collections::HashSet;
1169     ///
1170     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1171     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1172     ///
1173     /// let set = &a - &b;
1174     ///
1175     /// let mut i = 0;
1176     /// let expected = [1, 2];
1177     /// for x in &set {
1178     ///     assert!(expected.contains(x));
1179     ///     i += 1;
1180     /// }
1181     /// assert_eq!(i, expected.len());
1182     /// ```
1183     fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1184         self.difference(rhs).cloned().collect()
1185     }
1186 }
1187
1188 /// An iterator over the items of a `HashSet`.
1189 ///
1190 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1191 /// See its documentation for more.
1192 ///
1193 /// [`iter`]: HashSet::iter
1194 ///
1195 /// # Examples
1196 ///
1197 /// ```
1198 /// use std::collections::HashSet;
1199 ///
1200 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1201 ///
1202 /// let mut iter = a.iter();
1203 /// ```
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub struct Iter<'a, K: 'a> {
1206     base: base::Iter<'a, K>,
1207 }
1208
1209 /// An owning iterator over the items of a `HashSet`.
1210 ///
1211 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1212 /// (provided by the `IntoIterator` trait). See its documentation for more.
1213 ///
1214 /// [`into_iter`]: IntoIterator::into_iter
1215 ///
1216 /// # Examples
1217 ///
1218 /// ```
1219 /// use std::collections::HashSet;
1220 ///
1221 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1222 ///
1223 /// let mut iter = a.into_iter();
1224 /// ```
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub struct IntoIter<K> {
1227     base: base::IntoIter<K>,
1228 }
1229
1230 /// A draining iterator over the items of a `HashSet`.
1231 ///
1232 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1233 /// See its documentation for more.
1234 ///
1235 /// [`drain`]: HashSet::drain
1236 ///
1237 /// # Examples
1238 ///
1239 /// ```
1240 /// use std::collections::HashSet;
1241 ///
1242 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1243 ///
1244 /// let mut drain = a.drain();
1245 /// ```
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 pub struct Drain<'a, K: 'a> {
1248     base: base::Drain<'a, K>,
1249 }
1250
1251 /// A draining, filtering iterator over the items of a `HashSet`.
1252 ///
1253 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1254 ///
1255 /// [`drain_filter`]: HashSet::drain_filter
1256 ///
1257 /// # Examples
1258 ///
1259 /// ```
1260 /// #![feature(hash_drain_filter)]
1261 ///
1262 /// use std::collections::HashSet;
1263 ///
1264 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1265 ///
1266 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1267 /// ```
1268 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1269 pub struct DrainFilter<'a, K, F>
1270 where
1271     F: FnMut(&K) -> bool,
1272 {
1273     base: base::DrainFilter<'a, K, F>,
1274 }
1275
1276 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1277 ///
1278 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1279 /// See its documentation for more.
1280 ///
1281 /// [`intersection`]: HashSet::intersection
1282 ///
1283 /// # Examples
1284 ///
1285 /// ```
1286 /// use std::collections::HashSet;
1287 ///
1288 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1289 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1290 ///
1291 /// let mut intersection = a.intersection(&b);
1292 /// ```
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 pub struct Intersection<'a, T: 'a, S: 'a> {
1295     // iterator of the first set
1296     iter: Iter<'a, T>,
1297     // the second set
1298     other: &'a HashSet<T, S>,
1299 }
1300
1301 /// A lazy iterator producing elements in the difference of `HashSet`s.
1302 ///
1303 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1304 /// See its documentation for more.
1305 ///
1306 /// [`difference`]: HashSet::difference
1307 ///
1308 /// # Examples
1309 ///
1310 /// ```
1311 /// use std::collections::HashSet;
1312 ///
1313 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1314 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1315 ///
1316 /// let mut difference = a.difference(&b);
1317 /// ```
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub struct Difference<'a, T: 'a, S: 'a> {
1320     // iterator of the first set
1321     iter: Iter<'a, T>,
1322     // the second set
1323     other: &'a HashSet<T, S>,
1324 }
1325
1326 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1327 ///
1328 /// This `struct` is created by the [`symmetric_difference`] method on
1329 /// [`HashSet`]. See its documentation for more.
1330 ///
1331 /// [`symmetric_difference`]: HashSet::symmetric_difference
1332 ///
1333 /// # Examples
1334 ///
1335 /// ```
1336 /// use std::collections::HashSet;
1337 ///
1338 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1339 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1340 ///
1341 /// let mut intersection = a.symmetric_difference(&b);
1342 /// ```
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1345     iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1346 }
1347
1348 /// A lazy iterator producing elements in the union of `HashSet`s.
1349 ///
1350 /// This `struct` is created by the [`union`] method on [`HashSet`].
1351 /// See its documentation for more.
1352 ///
1353 /// [`union`]: HashSet::union
1354 ///
1355 /// # Examples
1356 ///
1357 /// ```
1358 /// use std::collections::HashSet;
1359 ///
1360 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1361 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1362 ///
1363 /// let mut union_iter = a.union(&b);
1364 /// ```
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub struct Union<'a, T: 'a, S: 'a> {
1367     iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1368 }
1369
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1372     type Item = &'a T;
1373     type IntoIter = Iter<'a, T>;
1374
1375     #[inline]
1376     fn into_iter(self) -> Iter<'a, T> {
1377         self.iter()
1378     }
1379 }
1380
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<T, S> IntoIterator for HashSet<T, S> {
1383     type Item = T;
1384     type IntoIter = IntoIter<T>;
1385
1386     /// Creates a consuming iterator, that is, one that moves each value out
1387     /// of the set in arbitrary order. The set cannot be used after calling
1388     /// this.
1389     ///
1390     /// # Examples
1391     ///
1392     /// ```
1393     /// use std::collections::HashSet;
1394     /// let mut set = HashSet::new();
1395     /// set.insert("a".to_string());
1396     /// set.insert("b".to_string());
1397     ///
1398     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1399     /// let v: Vec<String> = set.into_iter().collect();
1400     ///
1401     /// // Will print in an arbitrary order.
1402     /// for x in &v {
1403     ///     println!("{}", x);
1404     /// }
1405     /// ```
1406     #[inline]
1407     fn into_iter(self) -> IntoIter<T> {
1408         IntoIter { base: self.base.into_iter() }
1409     }
1410 }
1411
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 impl<K> Clone for Iter<'_, K> {
1414     #[inline]
1415     fn clone(&self) -> Self {
1416         Iter { base: self.base.clone() }
1417     }
1418 }
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<'a, K> Iterator for Iter<'a, K> {
1421     type Item = &'a K;
1422
1423     #[inline]
1424     fn next(&mut self) -> Option<&'a K> {
1425         self.base.next()
1426     }
1427     #[inline]
1428     fn size_hint(&self) -> (usize, Option<usize>) {
1429         self.base.size_hint()
1430     }
1431 }
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<K> ExactSizeIterator for Iter<'_, K> {
1434     #[inline]
1435     fn len(&self) -> usize {
1436         self.base.len()
1437     }
1438 }
1439 #[stable(feature = "fused", since = "1.26.0")]
1440 impl<K> FusedIterator for Iter<'_, K> {}
1441
1442 #[stable(feature = "std_debug", since = "1.16.0")]
1443 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1444     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1445         f.debug_list().entries(self.clone()).finish()
1446     }
1447 }
1448
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 impl<K> Iterator for IntoIter<K> {
1451     type Item = K;
1452
1453     #[inline]
1454     fn next(&mut self) -> Option<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 IntoIter<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 IntoIter<K> {}
1471
1472 #[stable(feature = "std_debug", since = "1.16.0")]
1473 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1474     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475         fmt::Debug::fmt(&self.base, f)
1476     }
1477 }
1478
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<'a, K> Iterator for Drain<'a, 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 Drain<'_, 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 Drain<'_, K> {}
1501
1502 #[stable(feature = "std_debug", since = "1.16.0")]
1503 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1504     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1505         fmt::Debug::fmt(&self.base, f)
1506     }
1507 }
1508
1509 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1510 impl<K, F> Iterator for DrainFilter<'_, K, F>
1511 where
1512     F: FnMut(&K) -> bool,
1513 {
1514     type Item = K;
1515
1516     #[inline]
1517     fn next(&mut self) -> Option<K> {
1518         self.base.next()
1519     }
1520     #[inline]
1521     fn size_hint(&self) -> (usize, Option<usize>) {
1522         self.base.size_hint()
1523     }
1524 }
1525
1526 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1527 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1528
1529 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1530 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1531 where
1532     F: FnMut(&K) -> bool,
1533 {
1534     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535         f.pad("DrainFilter { .. }")
1536     }
1537 }
1538
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<T, S> Clone for Intersection<'_, T, S> {
1541     #[inline]
1542     fn clone(&self) -> Self {
1543         Intersection { iter: self.iter.clone(), ..*self }
1544     }
1545 }
1546
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1549 where
1550     T: Eq + Hash,
1551     S: BuildHasher,
1552 {
1553     type Item = &'a T;
1554
1555     #[inline]
1556     fn next(&mut self) -> Option<&'a T> {
1557         loop {
1558             let elt = self.iter.next()?;
1559             if self.other.contains(elt) {
1560                 return Some(elt);
1561             }
1562         }
1563     }
1564
1565     #[inline]
1566     fn size_hint(&self) -> (usize, Option<usize>) {
1567         let (_, upper) = self.iter.size_hint();
1568         (0, upper)
1569     }
1570 }
1571
1572 #[stable(feature = "std_debug", since = "1.16.0")]
1573 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1574 where
1575     T: fmt::Debug + Eq + Hash,
1576     S: BuildHasher,
1577 {
1578     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1579         f.debug_list().entries(self.clone()).finish()
1580     }
1581 }
1582
1583 #[stable(feature = "fused", since = "1.26.0")]
1584 impl<T, S> FusedIterator for Intersection<'_, T, S>
1585 where
1586     T: Eq + Hash,
1587     S: BuildHasher,
1588 {
1589 }
1590
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<T, S> Clone for Difference<'_, T, S> {
1593     #[inline]
1594     fn clone(&self) -> Self {
1595         Difference { iter: self.iter.clone(), ..*self }
1596     }
1597 }
1598
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<'a, T, S> Iterator for Difference<'a, T, S>
1601 where
1602     T: Eq + Hash,
1603     S: BuildHasher,
1604 {
1605     type Item = &'a T;
1606
1607     #[inline]
1608     fn next(&mut self) -> Option<&'a T> {
1609         loop {
1610             let elt = self.iter.next()?;
1611             if !self.other.contains(elt) {
1612                 return Some(elt);
1613             }
1614         }
1615     }
1616
1617     #[inline]
1618     fn size_hint(&self) -> (usize, Option<usize>) {
1619         let (_, upper) = self.iter.size_hint();
1620         (0, upper)
1621     }
1622 }
1623
1624 #[stable(feature = "fused", since = "1.26.0")]
1625 impl<T, S> FusedIterator for Difference<'_, T, S>
1626 where
1627     T: Eq + Hash,
1628     S: BuildHasher,
1629 {
1630 }
1631
1632 #[stable(feature = "std_debug", since = "1.16.0")]
1633 impl<T, S> fmt::Debug for Difference<'_, T, S>
1634 where
1635     T: fmt::Debug + Eq + Hash,
1636     S: BuildHasher,
1637 {
1638     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1639         f.debug_list().entries(self.clone()).finish()
1640     }
1641 }
1642
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1645     #[inline]
1646     fn clone(&self) -> Self {
1647         SymmetricDifference { iter: self.iter.clone() }
1648     }
1649 }
1650
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1653 where
1654     T: Eq + Hash,
1655     S: BuildHasher,
1656 {
1657     type Item = &'a T;
1658
1659     #[inline]
1660     fn next(&mut self) -> Option<&'a T> {
1661         self.iter.next()
1662     }
1663     #[inline]
1664     fn size_hint(&self) -> (usize, Option<usize>) {
1665         self.iter.size_hint()
1666     }
1667 }
1668
1669 #[stable(feature = "fused", since = "1.26.0")]
1670 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1671 where
1672     T: Eq + Hash,
1673     S: BuildHasher,
1674 {
1675 }
1676
1677 #[stable(feature = "std_debug", since = "1.16.0")]
1678 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1679 where
1680     T: fmt::Debug + Eq + Hash,
1681     S: BuildHasher,
1682 {
1683     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1684         f.debug_list().entries(self.clone()).finish()
1685     }
1686 }
1687
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<T, S> Clone for Union<'_, T, S> {
1690     #[inline]
1691     fn clone(&self) -> Self {
1692         Union { iter: self.iter.clone() }
1693     }
1694 }
1695
1696 #[stable(feature = "fused", since = "1.26.0")]
1697 impl<T, S> FusedIterator for Union<'_, T, S>
1698 where
1699     T: Eq + Hash,
1700     S: BuildHasher,
1701 {
1702 }
1703
1704 #[stable(feature = "std_debug", since = "1.16.0")]
1705 impl<T, S> fmt::Debug for Union<'_, T, S>
1706 where
1707     T: fmt::Debug + Eq + Hash,
1708     S: BuildHasher,
1709 {
1710     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1711         f.debug_list().entries(self.clone()).finish()
1712     }
1713 }
1714
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<'a, T, S> Iterator for Union<'a, T, S>
1717 where
1718     T: Eq + Hash,
1719     S: BuildHasher,
1720 {
1721     type Item = &'a T;
1722
1723     #[inline]
1724     fn next(&mut self) -> Option<&'a T> {
1725         self.iter.next()
1726     }
1727     #[inline]
1728     fn size_hint(&self) -> (usize, Option<usize>) {
1729         self.iter.size_hint()
1730     }
1731 }
1732
1733 #[allow(dead_code)]
1734 fn assert_covariance() {
1735     fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1736         v
1737     }
1738     fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1739         v
1740     }
1741     fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1742         v
1743     }
1744     fn difference<'a, 'new>(
1745         v: Difference<'a, &'static str, RandomState>,
1746     ) -> Difference<'a, &'new str, RandomState> {
1747         v
1748     }
1749     fn symmetric_difference<'a, 'new>(
1750         v: SymmetricDifference<'a, &'static str, RandomState>,
1751     ) -> SymmetricDifference<'a, &'new str, RandomState> {
1752         v
1753     }
1754     fn intersection<'a, 'new>(
1755         v: Intersection<'a, &'static str, RandomState>,
1756     ) -> Intersection<'a, &'new str, RandomState> {
1757         v
1758     }
1759     fn union<'a, 'new>(
1760         v: Union<'a, &'static str, RandomState>,
1761     ) -> Union<'a, &'new str, RandomState> {
1762         v
1763     }
1764     fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1765         d
1766     }
1767 }