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