]> git.lizzy.rs Git - rust.git/blob - library/std/src/collections/hash/set.rs
Update std_collections_from_array stability version
[rust.git] / library / std / src / collections / hash / set.rs
1 #[cfg(test)]
2 mod tests;
3
4 use hashbrown::hash_set as base;
5
6 use crate::borrow::Borrow;
7 use crate::collections::TryReserveError;
8 use crate::fmt;
9 use crate::hash::{BuildHasher, Hash};
10 use crate::iter::{Chain, FromIterator, FusedIterator};
11 use crate::ops::{BitAnd, BitOr, BitXor, Sub};
12
13 use super::map::{map_try_reserve_error, RandomState};
14
15 // Future Optimization (FIXME!)
16 // ============================
17 //
18 // Iteration over zero sized values is a noop. There is no need
19 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
20 // to get rid of it properly.
21
22 /// A [hash set] implemented as a `HashMap` where the value is `()`.
23 ///
24 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
25 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
26 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
27 /// it is important that the following property holds:
28 ///
29 /// ```text
30 /// k1 == k2 -> hash(k1) == hash(k2)
31 /// ```
32 ///
33 /// In other words, if two keys are equal, their hashes must be equal.
34 ///
35 ///
36 /// It is a logic error for an item to be modified in such a way that the
37 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
38 /// determined by the [`Eq`] trait, changes while it is in the set. This is
39 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
40 /// unsafe code. The behavior resulting from such a logic error is not
41 /// specified, but will not result in undefined behavior. This could include
42 /// panics, incorrect results, aborts, memory leaks, and non-termination.
43 ///
44 /// # Examples
45 ///
46 /// ```
47 /// use std::collections::HashSet;
48 /// // Type inference lets us omit an explicit type signature (which
49 /// // would be `HashSet<String>` in this example).
50 /// let mut books = HashSet::new();
51 ///
52 /// // Add some books.
53 /// books.insert("A Dance With Dragons".to_string());
54 /// books.insert("To Kill a Mockingbird".to_string());
55 /// books.insert("The Odyssey".to_string());
56 /// books.insert("The Great Gatsby".to_string());
57 ///
58 /// // Check for a specific one.
59 /// if !books.contains("The Winds of Winter") {
60 ///     println!("We have {} books, but The Winds of Winter ain't one.",
61 ///              books.len());
62 /// }
63 ///
64 /// // Remove a book.
65 /// books.remove("The Odyssey");
66 ///
67 /// // Iterate over everything.
68 /// for book in &books {
69 ///     println!("{}", book);
70 /// }
71 /// ```
72 ///
73 /// The easiest way to use `HashSet` with a custom type is to derive
74 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
75 /// future be implied by [`Eq`].
76 ///
77 /// ```
78 /// use std::collections::HashSet;
79 /// #[derive(Hash, Eq, PartialEq, Debug)]
80 /// struct Viking {
81 ///     name: String,
82 ///     power: usize,
83 /// }
84 ///
85 /// let mut vikings = HashSet::new();
86 ///
87 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
88 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
89 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
90 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
91 ///
92 /// // Use derived implementation to print the vikings.
93 /// for x in &vikings {
94 ///     println!("{:?}", x);
95 /// }
96 /// ```
97 ///
98 /// A `HashSet` with a known list of items can be initialized from an array:
99 ///
100 /// ```
101 /// use std::collections::HashSet;
102 ///
103 /// let viking_names = HashSet::from(["Einar", "Olaf", "Harald"]);
104 /// ```
105 ///
106 /// [hash set]: crate::collections#use-the-set-variant-of-any-of-these-maps-when
107 /// [`HashMap`]: crate::collections::HashMap
108 /// [`RefCell`]: crate::cell::RefCell
109 /// [`Cell`]: crate::cell::Cell
110 #[cfg_attr(not(test), rustc_diagnostic_item = "hashset_type")]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct HashSet<T, S = RandomState> {
113     base: base::HashSet<T, S>,
114 }
115
116 impl<T> HashSet<T, RandomState> {
117     /// Creates an empty `HashSet`.
118     ///
119     /// The hash set is initially created with a capacity of 0, so it will not allocate until it
120     /// is first inserted into.
121     ///
122     /// # Examples
123     ///
124     /// ```
125     /// use std::collections::HashSet;
126     /// let set: HashSet<i32> = HashSet::new();
127     /// ```
128     #[inline]
129     #[stable(feature = "rust1", since = "1.0.0")]
130     pub fn new() -> HashSet<T, RandomState> {
131         Default::default()
132     }
133
134     /// Creates an empty `HashSet` with the specified capacity.
135     ///
136     /// The hash set will be able to hold at least `capacity` elements without
137     /// reallocating. If `capacity` is 0, the hash set will not allocate.
138     ///
139     /// # Examples
140     ///
141     /// ```
142     /// use std::collections::HashSet;
143     /// let set: HashSet<i32> = HashSet::with_capacity(10);
144     /// assert!(set.capacity() >= 10);
145     /// ```
146     #[inline]
147     #[stable(feature = "rust1", since = "1.0.0")]
148     pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
149         HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
150     }
151 }
152
153 impl<T, S> HashSet<T, S> {
154     /// Returns the number of elements the set can hold without reallocating.
155     ///
156     /// # Examples
157     ///
158     /// ```
159     /// use std::collections::HashSet;
160     /// let set: HashSet<i32> = HashSet::with_capacity(100);
161     /// assert!(set.capacity() >= 100);
162     /// ```
163     #[inline]
164     #[stable(feature = "rust1", since = "1.0.0")]
165     pub fn capacity(&self) -> usize {
166         self.base.capacity()
167     }
168
169     /// An iterator visiting all elements in arbitrary order.
170     /// The iterator element type is `&'a T`.
171     ///
172     /// # Examples
173     ///
174     /// ```
175     /// use std::collections::HashSet;
176     /// let mut set = HashSet::new();
177     /// set.insert("a");
178     /// set.insert("b");
179     ///
180     /// // Will print in an arbitrary order.
181     /// for x in set.iter() {
182     ///     println!("{}", x);
183     /// }
184     /// ```
185     #[inline]
186     #[stable(feature = "rust1", since = "1.0.0")]
187     pub fn iter(&self) -> Iter<'_, T> {
188         Iter { base: self.base.iter() }
189     }
190
191     /// Returns the number of elements in the set.
192     ///
193     /// # Examples
194     ///
195     /// ```
196     /// use std::collections::HashSet;
197     ///
198     /// let mut v = HashSet::new();
199     /// assert_eq!(v.len(), 0);
200     /// v.insert(1);
201     /// assert_eq!(v.len(), 1);
202     /// ```
203     #[doc(alias = "length")]
204     #[inline]
205     #[stable(feature = "rust1", since = "1.0.0")]
206     pub fn len(&self) -> usize {
207         self.base.len()
208     }
209
210     /// Returns `true` if the set contains no elements.
211     ///
212     /// # Examples
213     ///
214     /// ```
215     /// use std::collections::HashSet;
216     ///
217     /// let mut v = HashSet::new();
218     /// assert!(v.is_empty());
219     /// v.insert(1);
220     /// assert!(!v.is_empty());
221     /// ```
222     #[inline]
223     #[stable(feature = "rust1", since = "1.0.0")]
224     pub fn is_empty(&self) -> bool {
225         self.base.is_empty()
226     }
227
228     /// Clears the set, returning all elements in an iterator.
229     ///
230     /// # Examples
231     ///
232     /// ```
233     /// use std::collections::HashSet;
234     ///
235     /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
236     /// assert!(!set.is_empty());
237     ///
238     /// // print 1, 2, 3 in an arbitrary order
239     /// for i in set.drain() {
240     ///     println!("{}", i);
241     /// }
242     ///
243     /// assert!(set.is_empty());
244     /// ```
245     #[inline]
246     #[stable(feature = "drain", since = "1.6.0")]
247     pub fn drain(&mut self) -> Drain<'_, T> {
248         Drain { base: self.base.drain() }
249     }
250
251     /// Creates an iterator which uses a closure to determine if a value should be removed.
252     ///
253     /// If the closure returns true, then the value is removed and yielded.
254     /// If the closure returns false, the value will remain in the list and will not be yielded
255     /// by the iterator.
256     ///
257     /// If the iterator is only partially consumed or not consumed at all, each of the remaining
258     /// values will still be subjected to the closure and removed and dropped if it returns true.
259     ///
260     /// It is unspecified how many more values will be subjected to the closure
261     /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
262     /// `DrainFilter` itself is leaked.
263     ///
264     /// # Examples
265     ///
266     /// Splitting a set into even and odd values, reusing the original set:
267     ///
268     /// ```
269     /// #![feature(hash_drain_filter)]
270     /// use std::collections::HashSet;
271     ///
272     /// let mut set: HashSet<i32> = (0..8).collect();
273     /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
274     ///
275     /// let mut evens = drained.into_iter().collect::<Vec<_>>();
276     /// let mut odds = set.into_iter().collect::<Vec<_>>();
277     /// evens.sort();
278     /// odds.sort();
279     ///
280     /// assert_eq!(evens, vec![0, 2, 4, 6]);
281     /// assert_eq!(odds, vec![1, 3, 5, 7]);
282     /// ```
283     #[inline]
284     #[unstable(feature = "hash_drain_filter", issue = "59618")]
285     pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
286     where
287         F: FnMut(&T) -> bool,
288     {
289         DrainFilter { base: self.base.drain_filter(pred) }
290     }
291
292     /// Clears the set, removing all values.
293     ///
294     /// # Examples
295     ///
296     /// ```
297     /// use std::collections::HashSet;
298     ///
299     /// let mut v = HashSet::new();
300     /// v.insert(1);
301     /// v.clear();
302     /// assert!(v.is_empty());
303     /// ```
304     #[inline]
305     #[stable(feature = "rust1", since = "1.0.0")]
306     pub fn clear(&mut self) {
307         self.base.clear()
308     }
309
310     /// Creates a new empty hash set which will use the given hasher to hash
311     /// keys.
312     ///
313     /// The hash set is also created with the default initial capacity.
314     ///
315     /// Warning: `hasher` is normally randomly generated, and
316     /// is designed to allow `HashSet`s to be resistant to attacks that
317     /// cause many collisions and very poor performance. Setting it
318     /// manually using this function can expose a DoS attack vector.
319     ///
320     /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
321     /// the HashMap to be useful, see its documentation for details.
322     ///
323     /// # Examples
324     ///
325     /// ```
326     /// use std::collections::HashSet;
327     /// use std::collections::hash_map::RandomState;
328     ///
329     /// let s = RandomState::new();
330     /// let mut set = HashSet::with_hasher(s);
331     /// set.insert(2);
332     /// ```
333     #[inline]
334     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
335     pub fn with_hasher(hasher: S) -> HashSet<T, S> {
336         HashSet { base: base::HashSet::with_hasher(hasher) }
337     }
338
339     /// Creates an empty `HashSet` with the specified capacity, using
340     /// `hasher` to hash the keys.
341     ///
342     /// The hash set will be able to hold at least `capacity` elements without
343     /// reallocating. If `capacity` is 0, the hash set will not allocate.
344     ///
345     /// Warning: `hasher` is normally randomly generated, and
346     /// is designed to allow `HashSet`s to be resistant to attacks that
347     /// cause many collisions and very poor performance. Setting it
348     /// manually using this function can expose a DoS attack vector.
349     ///
350     /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
351     /// the HashMap to be useful, see its documentation for details.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// use std::collections::HashSet;
357     /// use std::collections::hash_map::RandomState;
358     ///
359     /// let s = RandomState::new();
360     /// let mut set = HashSet::with_capacity_and_hasher(10, s);
361     /// set.insert(1);
362     /// ```
363     #[inline]
364     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
365     pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
366         HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
367     }
368
369     /// Returns a reference to the set's [`BuildHasher`].
370     ///
371     /// # Examples
372     ///
373     /// ```
374     /// use std::collections::HashSet;
375     /// use std::collections::hash_map::RandomState;
376     ///
377     /// let hasher = RandomState::new();
378     /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
379     /// let hasher: &RandomState = set.hasher();
380     /// ```
381     #[inline]
382     #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
383     pub fn hasher(&self) -> &S {
384         self.base.hasher()
385     }
386 }
387
388 impl<T, S> HashSet<T, S>
389 where
390     T: Eq + Hash,
391     S: BuildHasher,
392 {
393     /// Reserves capacity for at least `additional` more elements to be inserted
394     /// in the `HashSet`. The collection may reserve more space to avoid
395     /// frequent reallocations.
396     ///
397     /// # Panics
398     ///
399     /// Panics if the new allocation size overflows `usize`.
400     ///
401     /// # Examples
402     ///
403     /// ```
404     /// use std::collections::HashSet;
405     /// let mut set: HashSet<i32> = HashSet::new();
406     /// set.reserve(10);
407     /// assert!(set.capacity() >= 10);
408     /// ```
409     #[inline]
410     #[stable(feature = "rust1", since = "1.0.0")]
411     pub fn reserve(&mut self, additional: usize) {
412         self.base.reserve(additional)
413     }
414
415     /// Tries to reserve capacity for at least `additional` more elements to be inserted
416     /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
417     /// frequent reallocations.
418     ///
419     /// # Errors
420     ///
421     /// If the capacity overflows, or the allocator reports a failure, then an error
422     /// is returned.
423     ///
424     /// # Examples
425     ///
426     /// ```
427     /// #![feature(try_reserve)]
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     #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
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     /// #![feature(shrink_to)]
469     /// use std::collections::HashSet;
470     ///
471     /// let mut set = HashSet::with_capacity(100);
472     /// set.insert(1);
473     /// set.insert(2);
474     /// assert!(set.capacity() >= 100);
475     /// set.shrink_to(10);
476     /// assert!(set.capacity() >= 10);
477     /// set.shrink_to(0);
478     /// assert!(set.capacity() >= 2);
479     /// ```
480     #[inline]
481     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
482     pub fn shrink_to(&mut self, min_capacity: usize) {
483         self.base.shrink_to(min_capacity)
484     }
485
486     /// Visits the values representing the difference,
487     /// i.e., the values that are in `self` but not in `other`.
488     ///
489     /// # Examples
490     ///
491     /// ```
492     /// use std::collections::HashSet;
493     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
494     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
495     ///
496     /// // Can be seen as `a - b`.
497     /// for x in a.difference(&b) {
498     ///     println!("{}", x); // Print 1
499     /// }
500     ///
501     /// let diff: HashSet<_> = a.difference(&b).collect();
502     /// assert_eq!(diff, [1].iter().collect());
503     ///
504     /// // Note that difference is not symmetric,
505     /// // and `b - a` means something else:
506     /// let diff: HashSet<_> = b.difference(&a).collect();
507     /// assert_eq!(diff, [4].iter().collect());
508     /// ```
509     #[inline]
510     #[stable(feature = "rust1", since = "1.0.0")]
511     pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
512         Difference { iter: self.iter(), other }
513     }
514
515     /// Visits the values representing the symmetric difference,
516     /// i.e., the values that are in `self` or in `other` but not in both.
517     ///
518     /// # Examples
519     ///
520     /// ```
521     /// use std::collections::HashSet;
522     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
523     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
524     ///
525     /// // Print 1, 4 in arbitrary order.
526     /// for x in a.symmetric_difference(&b) {
527     ///     println!("{}", x);
528     /// }
529     ///
530     /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
531     /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
532     ///
533     /// assert_eq!(diff1, diff2);
534     /// assert_eq!(diff1, [1, 4].iter().collect());
535     /// ```
536     #[inline]
537     #[stable(feature = "rust1", since = "1.0.0")]
538     pub fn symmetric_difference<'a>(
539         &'a self,
540         other: &'a HashSet<T, S>,
541     ) -> SymmetricDifference<'a, T, S> {
542         SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
543     }
544
545     /// Visits the values representing the intersection,
546     /// i.e., the values that are both in `self` and `other`.
547     ///
548     /// # Examples
549     ///
550     /// ```
551     /// use std::collections::HashSet;
552     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
553     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
554     ///
555     /// // Print 2, 3 in arbitrary order.
556     /// for x in a.intersection(&b) {
557     ///     println!("{}", x);
558     /// }
559     ///
560     /// let intersection: HashSet<_> = a.intersection(&b).collect();
561     /// assert_eq!(intersection, [2, 3].iter().collect());
562     /// ```
563     #[inline]
564     #[stable(feature = "rust1", since = "1.0.0")]
565     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
566         if self.len() <= other.len() {
567             Intersection { iter: self.iter(), other }
568         } else {
569             Intersection { iter: other.iter(), other: self }
570         }
571     }
572
573     /// Visits the values representing the union,
574     /// i.e., all the values in `self` or `other`, without duplicates.
575     ///
576     /// # Examples
577     ///
578     /// ```
579     /// use std::collections::HashSet;
580     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
581     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
582     ///
583     /// // Print 1, 2, 3, 4 in arbitrary order.
584     /// for x in a.union(&b) {
585     ///     println!("{}", x);
586     /// }
587     ///
588     /// let union: HashSet<_> = a.union(&b).collect();
589     /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
590     /// ```
591     #[inline]
592     #[stable(feature = "rust1", since = "1.0.0")]
593     pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
594         if self.len() >= other.len() {
595             Union { iter: self.iter().chain(other.difference(self)) }
596         } else {
597             Union { iter: other.iter().chain(self.difference(other)) }
598         }
599     }
600
601     /// Returns `true` if the set contains a value.
602     ///
603     /// The value may be any borrowed form of the set's value type, but
604     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
605     /// the value type.
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// use std::collections::HashSet;
611     ///
612     /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
613     /// assert_eq!(set.contains(&1), true);
614     /// assert_eq!(set.contains(&4), false);
615     /// ```
616     #[inline]
617     #[stable(feature = "rust1", since = "1.0.0")]
618     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
619     where
620         T: Borrow<Q>,
621         Q: Hash + Eq,
622     {
623         self.base.contains(value)
624     }
625
626     /// Returns a reference to the value in the set, if any, that is equal to the given value.
627     ///
628     /// The value may be any borrowed form of the set's value type, but
629     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
630     /// the value type.
631     ///
632     /// # Examples
633     ///
634     /// ```
635     /// use std::collections::HashSet;
636     ///
637     /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
638     /// assert_eq!(set.get(&2), Some(&2));
639     /// assert_eq!(set.get(&4), None);
640     /// ```
641     #[inline]
642     #[stable(feature = "set_recovery", since = "1.9.0")]
643     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
644     where
645         T: Borrow<Q>,
646         Q: Hash + Eq,
647     {
648         self.base.get(value)
649     }
650
651     /// Inserts the given `value` into the set if it is not present, then
652     /// returns a reference to the value in the set.
653     ///
654     /// # Examples
655     ///
656     /// ```
657     /// #![feature(hash_set_entry)]
658     ///
659     /// use std::collections::HashSet;
660     ///
661     /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
662     /// assert_eq!(set.len(), 3);
663     /// assert_eq!(set.get_or_insert(2), &2);
664     /// assert_eq!(set.get_or_insert(100), &100);
665     /// assert_eq!(set.len(), 4); // 100 was inserted
666     /// ```
667     #[inline]
668     #[unstable(feature = "hash_set_entry", issue = "60896")]
669     pub fn get_or_insert(&mut self, value: T) -> &T {
670         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
671         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
672         self.base.get_or_insert(value)
673     }
674
675     /// Inserts an owned copy of the given `value` into the set if it is not
676     /// present, then returns a reference to the value in the set.
677     ///
678     /// # Examples
679     ///
680     /// ```
681     /// #![feature(hash_set_entry)]
682     ///
683     /// use std::collections::HashSet;
684     ///
685     /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
686     ///     .iter().map(|&pet| pet.to_owned()).collect();
687     ///
688     /// assert_eq!(set.len(), 3);
689     /// for &pet in &["cat", "dog", "fish"] {
690     ///     let value = set.get_or_insert_owned(pet);
691     ///     assert_eq!(value, pet);
692     /// }
693     /// assert_eq!(set.len(), 4); // a new "fish" was inserted
694     /// ```
695     #[inline]
696     #[unstable(feature = "hash_set_entry", issue = "60896")]
697     pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
698     where
699         T: Borrow<Q>,
700         Q: Hash + Eq + ToOwned<Owned = T>,
701     {
702         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
703         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
704         self.base.get_or_insert_owned(value)
705     }
706
707     /// Inserts a value computed from `f` into the set if the given `value` is
708     /// not present, then returns a reference to the value in the set.
709     ///
710     /// # Examples
711     ///
712     /// ```
713     /// #![feature(hash_set_entry)]
714     ///
715     /// use std::collections::HashSet;
716     ///
717     /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
718     ///     .iter().map(|&pet| pet.to_owned()).collect();
719     ///
720     /// assert_eq!(set.len(), 3);
721     /// for &pet in &["cat", "dog", "fish"] {
722     ///     let value = set.get_or_insert_with(pet, str::to_owned);
723     ///     assert_eq!(value, pet);
724     /// }
725     /// assert_eq!(set.len(), 4); // a new "fish" was inserted
726     /// ```
727     #[inline]
728     #[unstable(feature = "hash_set_entry", issue = "60896")]
729     pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
730     where
731         T: Borrow<Q>,
732         Q: Hash + Eq,
733         F: FnOnce(&Q) -> T,
734     {
735         // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
736         // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
737         self.base.get_or_insert_with(value, f)
738     }
739
740     /// Returns `true` if `self` has no elements in common with `other`.
741     /// This is equivalent to checking for an empty intersection.
742     ///
743     /// # Examples
744     ///
745     /// ```
746     /// use std::collections::HashSet;
747     ///
748     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
749     /// let mut b = HashSet::new();
750     ///
751     /// assert_eq!(a.is_disjoint(&b), true);
752     /// b.insert(4);
753     /// assert_eq!(a.is_disjoint(&b), true);
754     /// b.insert(1);
755     /// assert_eq!(a.is_disjoint(&b), false);
756     /// ```
757     #[stable(feature = "rust1", since = "1.0.0")]
758     pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
759         if self.len() <= other.len() {
760             self.iter().all(|v| !other.contains(v))
761         } else {
762             other.iter().all(|v| !self.contains(v))
763         }
764     }
765
766     /// Returns `true` if the set is a subset of another,
767     /// i.e., `other` contains at least all the values in `self`.
768     ///
769     /// # Examples
770     ///
771     /// ```
772     /// use std::collections::HashSet;
773     ///
774     /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
775     /// let mut set = HashSet::new();
776     ///
777     /// assert_eq!(set.is_subset(&sup), true);
778     /// set.insert(2);
779     /// assert_eq!(set.is_subset(&sup), true);
780     /// set.insert(4);
781     /// assert_eq!(set.is_subset(&sup), false);
782     /// ```
783     #[stable(feature = "rust1", since = "1.0.0")]
784     pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
785         if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
786     }
787
788     /// Returns `true` if the set is a superset of another,
789     /// i.e., `self` contains at least all the values in `other`.
790     ///
791     /// # Examples
792     ///
793     /// ```
794     /// use std::collections::HashSet;
795     ///
796     /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
797     /// let mut set = HashSet::new();
798     ///
799     /// assert_eq!(set.is_superset(&sub), false);
800     ///
801     /// set.insert(0);
802     /// set.insert(1);
803     /// assert_eq!(set.is_superset(&sub), false);
804     ///
805     /// set.insert(2);
806     /// assert_eq!(set.is_superset(&sub), true);
807     /// ```
808     #[inline]
809     #[stable(feature = "rust1", since = "1.0.0")]
810     pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
811         other.is_subset(self)
812     }
813
814     /// Adds a value to the set.
815     ///
816     /// If the set did not have this value present, `true` is returned.
817     ///
818     /// If the set did have this value present, `false` is returned.
819     ///
820     /// # Examples
821     ///
822     /// ```
823     /// use std::collections::HashSet;
824     ///
825     /// let mut set = HashSet::new();
826     ///
827     /// assert_eq!(set.insert(2), true);
828     /// assert_eq!(set.insert(2), false);
829     /// assert_eq!(set.len(), 1);
830     /// ```
831     #[inline]
832     #[stable(feature = "rust1", since = "1.0.0")]
833     pub fn insert(&mut self, value: T) -> bool {
834         self.base.insert(value)
835     }
836
837     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
838     /// one. Returns the replaced value.
839     ///
840     /// # Examples
841     ///
842     /// ```
843     /// use std::collections::HashSet;
844     ///
845     /// let mut set = HashSet::new();
846     /// set.insert(Vec::<i32>::new());
847     ///
848     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
849     /// set.replace(Vec::with_capacity(10));
850     /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
851     /// ```
852     #[inline]
853     #[stable(feature = "set_recovery", since = "1.9.0")]
854     pub fn replace(&mut self, value: T) -> Option<T> {
855         self.base.replace(value)
856     }
857
858     /// Removes a value from the set. Returns whether the value was
859     /// present in the set.
860     ///
861     /// The value may be any borrowed form of the set's value type, but
862     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
863     /// the value type.
864     ///
865     /// # Examples
866     ///
867     /// ```
868     /// use std::collections::HashSet;
869     ///
870     /// let mut set = HashSet::new();
871     ///
872     /// set.insert(2);
873     /// assert_eq!(set.remove(&2), true);
874     /// assert_eq!(set.remove(&2), false);
875     /// ```
876     #[doc(alias = "delete")]
877     #[inline]
878     #[stable(feature = "rust1", since = "1.0.0")]
879     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
880     where
881         T: Borrow<Q>,
882         Q: Hash + Eq,
883     {
884         self.base.remove(value)
885     }
886
887     /// Removes and returns the value in the set, if any, that is equal to the given one.
888     ///
889     /// The value may be any borrowed form of the set's value type, but
890     /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
891     /// the value type.
892     ///
893     /// # Examples
894     ///
895     /// ```
896     /// use std::collections::HashSet;
897     ///
898     /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
899     /// assert_eq!(set.take(&2), Some(2));
900     /// assert_eq!(set.take(&2), None);
901     /// ```
902     #[inline]
903     #[stable(feature = "set_recovery", since = "1.9.0")]
904     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
905     where
906         T: Borrow<Q>,
907         Q: Hash + Eq,
908     {
909         self.base.take(value)
910     }
911
912     /// Retains only the elements specified by the predicate.
913     ///
914     /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
915     ///
916     /// # Examples
917     ///
918     /// ```
919     /// use std::collections::HashSet;
920     ///
921     /// let xs = [1, 2, 3, 4, 5, 6];
922     /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
923     /// set.retain(|&k| k % 2 == 0);
924     /// assert_eq!(set.len(), 3);
925     /// ```
926     #[stable(feature = "retain_hash_collection", since = "1.18.0")]
927     pub fn retain<F>(&mut self, f: F)
928     where
929         F: FnMut(&T) -> bool,
930     {
931         self.base.retain(f)
932     }
933 }
934
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<T, S> Clone for HashSet<T, S>
937 where
938     T: Clone,
939     S: Clone,
940 {
941     #[inline]
942     fn clone(&self) -> Self {
943         Self { base: self.base.clone() }
944     }
945
946     #[inline]
947     fn clone_from(&mut self, other: &Self) {
948         self.base.clone_from(&other.base);
949     }
950 }
951
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<T, S> PartialEq for HashSet<T, S>
954 where
955     T: Eq + Hash,
956     S: BuildHasher,
957 {
958     fn eq(&self, other: &HashSet<T, S>) -> bool {
959         if self.len() != other.len() {
960             return false;
961         }
962
963         self.iter().all(|key| other.contains(key))
964     }
965 }
966
967 #[stable(feature = "rust1", since = "1.0.0")]
968 impl<T, S> Eq for HashSet<T, S>
969 where
970     T: Eq + Hash,
971     S: BuildHasher,
972 {
973 }
974
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<T, S> fmt::Debug for HashSet<T, S>
977 where
978     T: fmt::Debug,
979 {
980     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981         f.debug_set().entries(self.iter()).finish()
982     }
983 }
984
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<T, S> FromIterator<T> for HashSet<T, S>
987 where
988     T: Eq + Hash,
989     S: BuildHasher + Default,
990 {
991     #[inline]
992     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
993         let mut set = HashSet::with_hasher(Default::default());
994         set.extend(iter);
995         set
996     }
997 }
998
999 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1000 // Note: as what is currently the most convenient built-in way to construct
1001 // a HashSet, a simple usage of this function must not *require* the user
1002 // to provide a type annotation in order to infer the third type parameter
1003 // (the hasher parameter, conventionally "S").
1004 // To that end, this impl is defined using RandomState as the concrete
1005 // type of S, rather than being generic over `S: BuildHasher + Default`.
1006 // It is expected that users who want to specify a hasher will manually use
1007 // `with_capacity_and_hasher`.
1008 // If type parameter defaults worked on impls, and if type parameter
1009 // defaults could be mixed with const generics, then perhaps
1010 // this could be generalized.
1011 // See also the equivalent impl on HashMap.
1012 impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
1013 where
1014     T: Eq + Hash,
1015 {
1016     /// # Examples
1017     ///
1018     /// ```
1019     /// use std::collections::HashSet;
1020     ///
1021     /// let set1 = HashSet::from([1, 2, 3, 4]);
1022     /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1023     /// assert_eq!(set1, set2);
1024     /// ```
1025     fn from(arr: [T; N]) -> Self {
1026         crate::array::IntoIter::new(arr).collect()
1027     }
1028 }
1029
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<T, S> Extend<T> for HashSet<T, S>
1032 where
1033     T: Eq + Hash,
1034     S: BuildHasher,
1035 {
1036     #[inline]
1037     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1038         self.base.extend(iter);
1039     }
1040
1041     #[inline]
1042     fn extend_one(&mut self, item: T) {
1043         self.base.insert(item);
1044     }
1045
1046     #[inline]
1047     fn extend_reserve(&mut self, additional: usize) {
1048         self.base.extend_reserve(additional);
1049     }
1050 }
1051
1052 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1053 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1054 where
1055     T: 'a + Eq + Hash + Copy,
1056     S: BuildHasher,
1057 {
1058     #[inline]
1059     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1060         self.extend(iter.into_iter().cloned());
1061     }
1062
1063     #[inline]
1064     fn extend_one(&mut self, &item: &'a T) {
1065         self.base.insert(item);
1066     }
1067
1068     #[inline]
1069     fn extend_reserve(&mut self, additional: usize) {
1070         Extend::<T>::extend_reserve(self, additional)
1071     }
1072 }
1073
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 impl<T, S> Default for HashSet<T, S>
1076 where
1077     S: Default,
1078 {
1079     /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1080     #[inline]
1081     fn default() -> HashSet<T, S> {
1082         HashSet { base: Default::default() }
1083     }
1084 }
1085
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1088 where
1089     T: Eq + Hash + Clone,
1090     S: BuildHasher + Default,
1091 {
1092     type Output = HashSet<T, S>;
1093
1094     /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1095     ///
1096     /// # Examples
1097     ///
1098     /// ```
1099     /// use std::collections::HashSet;
1100     ///
1101     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1102     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1103     ///
1104     /// let set = &a | &b;
1105     ///
1106     /// let mut i = 0;
1107     /// let expected = [1, 2, 3, 4, 5];
1108     /// for x in &set {
1109     ///     assert!(expected.contains(x));
1110     ///     i += 1;
1111     /// }
1112     /// assert_eq!(i, expected.len());
1113     /// ```
1114     fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1115         self.union(rhs).cloned().collect()
1116     }
1117 }
1118
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1121 where
1122     T: Eq + Hash + Clone,
1123     S: BuildHasher + Default,
1124 {
1125     type Output = HashSet<T, S>;
1126
1127     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1128     ///
1129     /// # Examples
1130     ///
1131     /// ```
1132     /// use std::collections::HashSet;
1133     ///
1134     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1135     /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1136     ///
1137     /// let set = &a & &b;
1138     ///
1139     /// let mut i = 0;
1140     /// let expected = [2, 3];
1141     /// for x in &set {
1142     ///     assert!(expected.contains(x));
1143     ///     i += 1;
1144     /// }
1145     /// assert_eq!(i, expected.len());
1146     /// ```
1147     fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1148         self.intersection(rhs).cloned().collect()
1149     }
1150 }
1151
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1154 where
1155     T: Eq + Hash + Clone,
1156     S: BuildHasher + Default,
1157 {
1158     type Output = HashSet<T, S>;
1159
1160     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1161     ///
1162     /// # Examples
1163     ///
1164     /// ```
1165     /// use std::collections::HashSet;
1166     ///
1167     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1168     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1169     ///
1170     /// let set = &a ^ &b;
1171     ///
1172     /// let mut i = 0;
1173     /// let expected = [1, 2, 4, 5];
1174     /// for x in &set {
1175     ///     assert!(expected.contains(x));
1176     ///     i += 1;
1177     /// }
1178     /// assert_eq!(i, expected.len());
1179     /// ```
1180     fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1181         self.symmetric_difference(rhs).cloned().collect()
1182     }
1183 }
1184
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1187 where
1188     T: Eq + Hash + Clone,
1189     S: BuildHasher + Default,
1190 {
1191     type Output = HashSet<T, S>;
1192
1193     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1194     ///
1195     /// # Examples
1196     ///
1197     /// ```
1198     /// use std::collections::HashSet;
1199     ///
1200     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1201     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1202     ///
1203     /// let set = &a - &b;
1204     ///
1205     /// let mut i = 0;
1206     /// let expected = [1, 2];
1207     /// for x in &set {
1208     ///     assert!(expected.contains(x));
1209     ///     i += 1;
1210     /// }
1211     /// assert_eq!(i, expected.len());
1212     /// ```
1213     fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1214         self.difference(rhs).cloned().collect()
1215     }
1216 }
1217
1218 /// An iterator over the items of a `HashSet`.
1219 ///
1220 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1221 /// See its documentation for more.
1222 ///
1223 /// [`iter`]: HashSet::iter
1224 ///
1225 /// # Examples
1226 ///
1227 /// ```
1228 /// use std::collections::HashSet;
1229 ///
1230 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1231 ///
1232 /// let mut iter = a.iter();
1233 /// ```
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 pub struct Iter<'a, K: 'a> {
1236     base: base::Iter<'a, K>,
1237 }
1238
1239 /// An owning iterator over the items of a `HashSet`.
1240 ///
1241 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1242 /// (provided by the `IntoIterator` trait). See its documentation for more.
1243 ///
1244 /// [`into_iter`]: IntoIterator::into_iter
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.pad("DrainFilter { .. }")
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 }