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