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