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