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