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