]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/set.rs
Merge pull request #20510 from tshepang/patch-6
[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 // ignore-lexer-test FIXME #15883
12
13 use borrow::BorrowFrom;
14 use clone::Clone;
15 use cmp::{Eq, PartialEq};
16 use core::kinds::Sized;
17 use default::Default;
18 use fmt::Show;
19 use fmt;
20 use hash::{Hash, Hasher, RandomSipHasher};
21 use iter::{Iterator, IteratorExt, IteratorCloneExt, FromIterator, Map, Chain, Extend};
22 use ops::{BitOr, BitAnd, BitXor, Sub};
23 use option::Option::{Some, None, self};
24 use result::Result::{Ok, Err};
25
26 use super::map::{self, HashMap, Keys, INITIAL_CAPACITY};
27
28 // Future Optimization (FIXME!)
29 // =============================
30 //
31 // Iteration over zero sized values is a noop. There is no need
32 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
33 // to get rid of it properly.
34
35 /// An implementation of a hash set using the underlying representation of a
36 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
37 /// requires that the elements implement the `Eq` and `Hash` traits.
38 ///
39 /// # Example
40 ///
41 /// ```
42 /// use std::collections::HashSet;
43 /// // Type inference lets us omit an explicit type signature (which
44 /// // would be `HashSet<&str>` in this example).
45 /// let mut books = HashSet::new();
46 ///
47 /// // Add some books.
48 /// books.insert("A Dance With Dragons");
49 /// books.insert("To Kill a Mockingbird");
50 /// books.insert("The Odyssey");
51 /// books.insert("The Great Gatsby");
52 ///
53 /// // Check for a specific one.
54 /// if !books.contains(&("The Winds of Winter")) {
55 ///     println!("We have {} books, but The Winds of Winter ain't one.",
56 ///              books.len());
57 /// }
58 ///
59 /// // Remove a book.
60 /// books.remove(&"The Odyssey");
61 ///
62 /// // Iterate over everything.
63 /// for book in books.iter() {
64 ///     println!("{}", *book);
65 /// }
66 /// ```
67 ///
68 /// The easiest way to use `HashSet` with a custom type is to derive
69 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
70 /// future be implied by `Eq`.
71 ///
72 /// ```
73 /// use std::collections::HashSet;
74 /// #[derive(Hash, Eq, PartialEq, Show)]
75 /// struct Viking<'a> {
76 ///     name: &'a str,
77 ///     power: uint,
78 /// }
79 ///
80 /// let mut vikings = HashSet::new();
81 ///
82 /// vikings.insert(Viking { name: "Einar", power: 9u });
83 /// vikings.insert(Viking { name: "Einar", power: 9u });
84 /// vikings.insert(Viking { name: "Olaf", power: 4u });
85 /// vikings.insert(Viking { name: "Harald", power: 8u });
86 ///
87 /// // Use derived implementation to print the vikings.
88 /// for x in vikings.iter() {
89 ///     println!("{}", x);
90 /// }
91 /// ```
92 #[derive(Clone)]
93 #[stable]
94 pub struct HashSet<T, H = RandomSipHasher> {
95     map: HashMap<T, (), H>
96 }
97
98 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
99     /// Create an empty HashSet.
100     ///
101     /// # Example
102     ///
103     /// ```
104     /// use std::collections::HashSet;
105     /// let mut set: HashSet<int> = HashSet::new();
106     /// ```
107     #[inline]
108     #[stable]
109     pub fn new() -> HashSet<T, RandomSipHasher> {
110         HashSet::with_capacity(INITIAL_CAPACITY)
111     }
112
113     /// Create an empty HashSet with space for at least `n` elements in
114     /// the hash table.
115     ///
116     /// # Example
117     ///
118     /// ```
119     /// use std::collections::HashSet;
120     /// let mut set: HashSet<int> = HashSet::with_capacity(10);
121     /// ```
122     #[inline]
123     #[stable]
124     pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
125         HashSet { map: HashMap::with_capacity(capacity) }
126     }
127 }
128
129 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
130     /// Creates a new empty hash set which will use the given hasher to hash
131     /// keys.
132     ///
133     /// The hash set is also created with the default initial capacity.
134     ///
135     /// # Example
136     ///
137     /// ```
138     /// use std::collections::HashSet;
139     /// use std::hash::sip::SipHasher;
140     ///
141     /// let h = SipHasher::new();
142     /// let mut set = HashSet::with_hasher(h);
143     /// set.insert(2u);
144     /// ```
145     #[inline]
146     #[unstable = "hasher stuff is unclear"]
147     pub fn with_hasher(hasher: H) -> HashSet<T, H> {
148         HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
149     }
150
151     /// Create an empty HashSet with space for at least `capacity`
152     /// elements in the hash table, using `hasher` to hash the keys.
153     ///
154     /// Warning: `hasher` is normally randomly generated, and
155     /// is designed to allow `HashSet`s to be resistant to attacks that
156     /// cause many collisions and very poor performance. Setting it
157     /// manually using this function can expose a DoS attack vector.
158     ///
159     /// # Example
160     ///
161     /// ```
162     /// use std::collections::HashSet;
163     /// use std::hash::sip::SipHasher;
164     ///
165     /// let h = SipHasher::new();
166     /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
167     /// set.insert(1i);
168     /// ```
169     #[inline]
170     #[unstable = "hasher stuff is unclear"]
171     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
172         HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
173     }
174
175     /// Returns the number of elements the set can hold without reallocating.
176     ///
177     /// # Example
178     ///
179     /// ```
180     /// use std::collections::HashSet;
181     /// let set: HashSet<int> = HashSet::with_capacity(100);
182     /// assert!(set.capacity() >= 100);
183     /// ```
184     #[inline]
185     #[stable]
186     pub fn capacity(&self) -> uint {
187         self.map.capacity()
188     }
189
190     /// Reserves capacity for at least `additional` more elements to be inserted
191     /// in the `HashSet`. The collection may reserve more space to avoid
192     /// frequent reallocations.
193     ///
194     /// # Panics
195     ///
196     /// Panics if the new allocation size overflows `uint`.
197     ///
198     /// # Example
199     ///
200     /// ```
201     /// use std::collections::HashSet;
202     /// let mut set: HashSet<int> = HashSet::new();
203     /// set.reserve(10);
204     /// ```
205     #[stable]
206     pub fn reserve(&mut self, additional: uint) {
207         self.map.reserve(additional)
208     }
209
210     /// Shrinks the capacity of the set as much as possible. It will drop
211     /// down as much as possible while maintaining the internal rules
212     /// and possibly leaving some space in accordance with the resize policy.
213     ///
214     /// # Example
215     ///
216     /// ```
217     /// use std::collections::HashSet;
218     ///
219     /// let mut set: HashSet<int> = HashSet::with_capacity(100);
220     /// set.insert(1);
221     /// set.insert(2);
222     /// assert!(set.capacity() >= 100);
223     /// set.shrink_to_fit();
224     /// assert!(set.capacity() >= 2);
225     /// ```
226     #[stable]
227     pub fn shrink_to_fit(&mut self) {
228         self.map.shrink_to_fit()
229     }
230
231     /// An iterator visiting all elements in arbitrary order.
232     /// Iterator element type is &'a T.
233     ///
234     /// # Example
235     ///
236     /// ```
237     /// use std::collections::HashSet;
238     /// let mut set = HashSet::new();
239     /// set.insert("a");
240     /// set.insert("b");
241     ///
242     /// // Will print in an arbitrary order.
243     /// for x in set.iter() {
244     ///     println!("{}", x);
245     /// }
246     /// ```
247     #[stable]
248     pub fn iter(&self) -> Iter<T> {
249         Iter { iter: self.map.keys() }
250     }
251
252     /// Creates a consuming iterator, that is, one that moves each value out
253     /// of the set in arbitrary order. The set cannot be used after calling
254     /// this.
255     ///
256     /// # Example
257     ///
258     /// ```
259     /// use std::collections::HashSet;
260     /// let mut set = HashSet::new();
261     /// set.insert("a".to_string());
262     /// set.insert("b".to_string());
263     ///
264     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
265     /// let v: Vec<String> = set.into_iter().collect();
266     ///
267     /// // Will print in an arbitrary order.
268     /// for x in v.iter() {
269     ///     println!("{}", x);
270     /// }
271     /// ```
272     #[stable]
273     pub fn into_iter(self) -> IntoIter<T> {
274         fn first<A, B>((a, _): (A, B)) -> A { a }
275         let first: fn((T, ())) -> T = first;
276
277         IntoIter { iter: self.map.into_iter().map(first) }
278     }
279
280     /// Visit the values representing the difference.
281     ///
282     /// # Example
283     ///
284     /// ```
285     /// use std::collections::HashSet;
286     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
287     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
288     ///
289     /// // Can be seen as `a - b`.
290     /// for x in a.difference(&b) {
291     ///     println!("{}", x); // Print 1
292     /// }
293     ///
294     /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
295     /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
296     ///
297     /// // Note that difference is not symmetric,
298     /// // and `b - a` means something else:
299     /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
300     /// assert_eq!(diff, [4i].iter().map(|&x| x).collect());
301     /// ```
302     #[stable]
303     pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> Difference<'a, T, H> {
304         Difference {
305             iter: self.iter(),
306             other: other,
307         }
308     }
309
310     /// Visit the values representing the symmetric difference.
311     ///
312     /// # Example
313     ///
314     /// ```
315     /// use std::collections::HashSet;
316     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
317     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
318     ///
319     /// // Print 1, 4 in arbitrary order.
320     /// for x in a.symmetric_difference(&b) {
321     ///     println!("{}", x);
322     /// }
323     ///
324     /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
325     /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
326     ///
327     /// assert_eq!(diff1, diff2);
328     /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
329     /// ```
330     #[stable]
331     pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
332         -> SymmetricDifference<'a, T, H> {
333         SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
334     }
335
336     /// Visit the values representing the intersection.
337     ///
338     /// # Example
339     ///
340     /// ```
341     /// use std::collections::HashSet;
342     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
343     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
344     ///
345     /// // Print 2, 3 in arbitrary order.
346     /// for x in a.intersection(&b) {
347     ///     println!("{}", x);
348     /// }
349     ///
350     /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
351     /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
352     /// ```
353     #[stable]
354     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>) -> Intersection<'a, T, H> {
355         Intersection {
356             iter: self.iter(),
357             other: other,
358         }
359     }
360
361     /// Visit the values representing the union.
362     ///
363     /// # Example
364     ///
365     /// ```
366     /// use std::collections::HashSet;
367     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
368     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
369     ///
370     /// // Print 1, 2, 3, 4 in arbitrary order.
371     /// for x in a.union(&b) {
372     ///     println!("{}", x);
373     /// }
374     ///
375     /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
376     /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect());
377     /// ```
378     #[stable]
379     pub fn union<'a>(&'a self, other: &'a HashSet<T, H>) -> Union<'a, T, H> {
380         Union { iter: self.iter().chain(other.difference(self)) }
381     }
382
383     /// Return the number of elements in the set
384     ///
385     /// # Example
386     ///
387     /// ```
388     /// use std::collections::HashSet;
389     ///
390     /// let mut v = HashSet::new();
391     /// assert_eq!(v.len(), 0);
392     /// v.insert(1u);
393     /// assert_eq!(v.len(), 1);
394     /// ```
395     #[stable]
396     pub fn len(&self) -> uint { self.map.len() }
397
398     /// Returns true if the set contains no elements
399     ///
400     /// # Example
401     ///
402     /// ```
403     /// use std::collections::HashSet;
404     ///
405     /// let mut v = HashSet::new();
406     /// assert!(v.is_empty());
407     /// v.insert(1u);
408     /// assert!(!v.is_empty());
409     /// ```
410     #[stable]
411     pub fn is_empty(&self) -> bool { self.map.len() == 0 }
412
413     /// Clears the set, returning all elements in an iterator.
414     #[inline]
415     #[unstable = "matches collection reform specification, waiting for dust to settle"]
416     pub fn drain(&mut self) -> Drain<T> {
417         fn first<A, B>((a, _): (A, B)) -> A { a }
418         let first: fn((T, ())) -> T = first; // coerce to fn pointer
419
420         Drain { iter: self.map.drain().map(first) }
421     }
422
423     /// Clears the set, removing all values.
424     ///
425     /// # Example
426     ///
427     /// ```
428     /// use std::collections::HashSet;
429     ///
430     /// let mut v = HashSet::new();
431     /// v.insert(1u);
432     /// v.clear();
433     /// assert!(v.is_empty());
434     /// ```
435     #[stable]
436     pub fn clear(&mut self) { self.map.clear() }
437
438     /// Returns `true` if the set contains a value.
439     ///
440     /// The value may be any borrowed form of the set's value type, but
441     /// `Hash` and `Eq` on the borrowed form *must* match those for
442     /// the value type.
443     ///
444     /// # Example
445     ///
446     /// ```
447     /// use std::collections::HashSet;
448     ///
449     /// let set: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
450     /// assert_eq!(set.contains(&1), true);
451     /// assert_eq!(set.contains(&4), false);
452     /// ```
453     #[stable]
454     pub fn contains<Sized? Q>(&self, value: &Q) -> bool
455         where Q: BorrowFrom<T> + Hash<S> + Eq
456     {
457         self.map.contains_key(value)
458     }
459
460     /// Returns `true` if the set has no elements in common with `other`.
461     /// This is equivalent to checking for an empty intersection.
462     ///
463     /// # Example
464     ///
465     /// ```
466     /// use std::collections::HashSet;
467     ///
468     /// let a: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
469     /// let mut b: HashSet<uint> = HashSet::new();
470     ///
471     /// assert_eq!(a.is_disjoint(&b), true);
472     /// b.insert(4);
473     /// assert_eq!(a.is_disjoint(&b), true);
474     /// b.insert(1);
475     /// assert_eq!(a.is_disjoint(&b), false);
476     /// ```
477     #[stable]
478     pub fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
479         self.iter().all(|v| !other.contains(v))
480     }
481
482     /// Returns `true` if the set is a subset of another.
483     ///
484     /// # Example
485     ///
486     /// ```
487     /// use std::collections::HashSet;
488     ///
489     /// let sup: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
490     /// let mut set: HashSet<uint> = HashSet::new();
491     ///
492     /// assert_eq!(set.is_subset(&sup), true);
493     /// set.insert(2);
494     /// assert_eq!(set.is_subset(&sup), true);
495     /// set.insert(4);
496     /// assert_eq!(set.is_subset(&sup), false);
497     /// ```
498     #[stable]
499     pub fn is_subset(&self, other: &HashSet<T, H>) -> bool {
500         self.iter().all(|v| other.contains(v))
501     }
502
503     /// Returns `true` if the set is a superset of another.
504     ///
505     /// # Example
506     ///
507     /// ```
508     /// use std::collections::HashSet;
509     ///
510     /// let sub: HashSet<uint> = [1, 2].iter().map(|&x| x).collect();
511     /// let mut set: HashSet<uint> = HashSet::new();
512     ///
513     /// assert_eq!(set.is_superset(&sub), false);
514     ///
515     /// set.insert(0);
516     /// set.insert(1);
517     /// assert_eq!(set.is_superset(&sub), false);
518     ///
519     /// set.insert(2);
520     /// assert_eq!(set.is_superset(&sub), true);
521     /// ```
522     #[inline]
523     #[stable]
524     pub fn is_superset(&self, other: &HashSet<T, H>) -> bool {
525         other.is_subset(self)
526     }
527
528     /// Adds a value to the set. Returns `true` if the value was not already
529     /// present in the set.
530     ///
531     /// # Example
532     ///
533     /// ```
534     /// use std::collections::HashSet;
535     ///
536     /// let mut set = HashSet::new();
537     ///
538     /// assert_eq!(set.insert(2u), true);
539     /// assert_eq!(set.insert(2), false);
540     /// assert_eq!(set.len(), 1);
541     /// ```
542     #[stable]
543     pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
544
545     /// Removes a value from the set. Returns `true` if the value was
546     /// present in the set.
547     ///
548     /// The value may be any borrowed form of the set's value type, but
549     /// `Hash` and `Eq` on the borrowed form *must* match those for
550     /// the value type.
551     ///
552     /// # Example
553     ///
554     /// ```
555     /// use std::collections::HashSet;
556     ///
557     /// let mut set = HashSet::new();
558     ///
559     /// set.insert(2u);
560     /// assert_eq!(set.remove(&2), true);
561     /// assert_eq!(set.remove(&2), false);
562     /// ```
563     #[stable]
564     pub fn remove<Sized? Q>(&mut self, value: &Q) -> bool
565         where Q: BorrowFrom<T> + Hash<S> + Eq
566     {
567         self.map.remove(value).is_some()
568     }
569 }
570
571 #[stable]
572 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
573     fn eq(&self, other: &HashSet<T, H>) -> bool {
574         if self.len() != other.len() { return false; }
575
576         self.iter().all(|key| other.contains(key))
577     }
578 }
579
580 #[stable]
581 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
582
583 #[stable]
584 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
585     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
586         try!(write!(f, "{{"));
587
588         for (i, x) in self.iter().enumerate() {
589             if i != 0 { try!(write!(f, ", ")); }
590             try!(write!(f, "{}", *x));
591         }
592
593         write!(f, "}}")
594     }
595 }
596
597 #[stable]
598 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
599     fn from_iter<I: Iterator<Item=T>>(iter: I) -> HashSet<T, H> {
600         let lower = iter.size_hint().0;
601         let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
602         set.extend(iter);
603         set
604     }
605 }
606
607 #[stable]
608 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extend<T> for HashSet<T, H> {
609     fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) {
610         for k in iter {
611             self.insert(k);
612         }
613     }
614 }
615
616 #[stable]
617 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
618     #[stable]
619     fn default() -> HashSet<T, H> {
620         HashSet::with_hasher(Default::default())
621     }
622 }
623
624 #[stable]
625 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
626 BitOr<&'b HashSet<T, H>> for &'a HashSet<T, H> {
627     type Output = HashSet<T, H>;
628
629     /// Returns the union of `self` and `rhs` as a new `HashSet<T, H>`.
630     ///
631     /// # Examples
632     ///
633     /// ```
634     /// use std::collections::HashSet;
635     ///
636     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
637     /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
638     ///
639     /// let set: HashSet<int> = &a | &b;
640     ///
641     /// let mut i = 0;
642     /// let expected = [1, 2, 3, 4, 5];
643     /// for x in set.iter() {
644     ///     assert!(expected.contains(x));
645     ///     i += 1;
646     /// }
647     /// assert_eq!(i, expected.len());
648     /// ```
649     fn bitor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
650         self.union(rhs).cloned().collect()
651     }
652 }
653
654 #[stable]
655 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
656 BitAnd<&'b HashSet<T, H>> for &'a HashSet<T, H> {
657     type Output = HashSet<T, H>;
658
659     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, H>`.
660     ///
661     /// # Examples
662     ///
663     /// ```
664     /// use std::collections::HashSet;
665     ///
666     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
667     /// let b: HashSet<int> = vec![2, 3, 4].into_iter().collect();
668     ///
669     /// let set: HashSet<int> = &a & &b;
670     ///
671     /// let mut i = 0;
672     /// let expected = [2, 3];
673     /// for x in set.iter() {
674     ///     assert!(expected.contains(x));
675     ///     i += 1;
676     /// }
677     /// assert_eq!(i, expected.len());
678     /// ```
679     fn bitand(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
680         self.intersection(rhs).cloned().collect()
681     }
682 }
683
684 #[stable]
685 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
686 BitXor<&'b HashSet<T, H>> for &'a HashSet<T, H> {
687     type Output = HashSet<T, H>;
688
689     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, H>`.
690     ///
691     /// # Examples
692     ///
693     /// ```
694     /// use std::collections::HashSet;
695     ///
696     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
697     /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
698     ///
699     /// let set: HashSet<int> = &a ^ &b;
700     ///
701     /// let mut i = 0;
702     /// let expected = [1, 2, 4, 5];
703     /// for x in set.iter() {
704     ///     assert!(expected.contains(x));
705     ///     i += 1;
706     /// }
707     /// assert_eq!(i, expected.len());
708     /// ```
709     fn bitxor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
710         self.symmetric_difference(rhs).cloned().collect()
711     }
712 }
713
714 #[stable]
715 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
716 Sub<&'b HashSet<T, H>> for &'a HashSet<T, H> {
717     type Output = HashSet<T, H>;
718
719     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, H>`.
720     ///
721     /// # Examples
722     ///
723     /// ```
724     /// use std::collections::HashSet;
725     ///
726     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
727     /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
728     ///
729     /// let set: HashSet<int> = &a - &b;
730     ///
731     /// let mut i = 0;
732     /// let expected = [1, 2];
733     /// for x in set.iter() {
734     ///     assert!(expected.contains(x));
735     ///     i += 1;
736     /// }
737     /// assert_eq!(i, expected.len());
738     /// ```
739     fn sub(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
740         self.difference(rhs).cloned().collect()
741     }
742 }
743
744 /// HashSet iterator
745 #[stable]
746 pub struct Iter<'a, K: 'a> {
747     iter: Keys<'a, K, ()>
748 }
749
750 /// HashSet move iterator
751 #[stable]
752 pub struct IntoIter<K> {
753     iter: Map<(K, ()), K, map::IntoIter<K, ()>, fn((K, ())) -> K>
754 }
755
756 /// HashSet drain iterator
757 #[stable]
758 pub struct Drain<'a, K: 'a> {
759     iter: Map<(K, ()), K, map::Drain<'a, K, ()>, fn((K, ())) -> K>,
760 }
761
762 /// Intersection iterator
763 #[stable]
764 pub struct Intersection<'a, T: 'a, H: 'a> {
765     // iterator of the first set
766     iter: Iter<'a, T>,
767     // the second set
768     other: &'a HashSet<T, H>,
769 }
770
771 /// Difference iterator
772 #[stable]
773 pub struct Difference<'a, T: 'a, H: 'a> {
774     // iterator of the first set
775     iter: Iter<'a, T>,
776     // the second set
777     other: &'a HashSet<T, H>,
778 }
779
780 /// Symmetric difference iterator.
781 #[stable]
782 pub struct SymmetricDifference<'a, T: 'a, H: 'a> {
783     iter: Chain<Difference<'a, T, H>, Difference<'a, T, H>>
784 }
785
786 /// Set union iterator.
787 #[stable]
788 pub struct Union<'a, T: 'a, H: 'a> {
789     iter: Chain<Iter<'a, T>, Difference<'a, T, H>>
790 }
791
792 #[stable]
793 impl<'a, K> Iterator for Iter<'a, K> {
794     type Item = &'a K;
795
796     fn next(&mut self) -> Option<&'a K> { self.iter.next() }
797     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
798 }
799
800 #[stable]
801 impl<K> Iterator for IntoIter<K> {
802     type Item = K;
803
804     fn next(&mut self) -> Option<K> { self.iter.next() }
805     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
806 }
807
808 #[stable]
809 impl<'a, K: 'a> Iterator for Drain<'a, K> {
810     type Item = K;
811
812     fn next(&mut self) -> Option<K> { self.iter.next() }
813     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
814 }
815
816 #[stable]
817 impl<'a, T, S, H> Iterator for Intersection<'a, T, H>
818     where T: Eq + Hash<S>, H: Hasher<S>
819 {
820     type Item = &'a T;
821
822     fn next(&mut self) -> Option<&'a T> {
823         loop {
824             match self.iter.next() {
825                 None => return None,
826                 Some(elt) => if self.other.contains(elt) {
827                     return Some(elt)
828                 },
829             }
830         }
831     }
832
833     fn size_hint(&self) -> (uint, Option<uint>) {
834         let (_, upper) = self.iter.size_hint();
835         (0, upper)
836     }
837 }
838
839 #[stable]
840 impl<'a, T, S, H> Iterator for Difference<'a, T, H>
841     where T: Eq + Hash<S>, H: Hasher<S>
842 {
843     type Item = &'a T;
844
845     fn next(&mut self) -> Option<&'a T> {
846         loop {
847             match self.iter.next() {
848                 None => return None,
849                 Some(elt) => if !self.other.contains(elt) {
850                     return Some(elt)
851                 },
852             }
853         }
854     }
855
856     fn size_hint(&self) -> (uint, Option<uint>) {
857         let (_, upper) = self.iter.size_hint();
858         (0, upper)
859     }
860 }
861
862 #[stable]
863 impl<'a, T, S, H> Iterator for SymmetricDifference<'a, T, H>
864     where T: Eq + Hash<S>, H: Hasher<S>
865 {
866     type Item = &'a T;
867
868     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
869     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
870 }
871
872 #[stable]
873 impl<'a, T, S, H> Iterator for Union<'a, T, H>
874     where T: Eq + Hash<S>, H: Hasher<S>
875 {
876     type Item = &'a T;
877
878     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
879     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
880 }
881
882 #[cfg(test)]
883 mod test_set {
884     use prelude::v1::*;
885
886     use super::HashSet;
887
888     #[test]
889     fn test_disjoint() {
890         let mut xs = HashSet::new();
891         let mut ys = HashSet::new();
892         assert!(xs.is_disjoint(&ys));
893         assert!(ys.is_disjoint(&xs));
894         assert!(xs.insert(5i));
895         assert!(ys.insert(11i));
896         assert!(xs.is_disjoint(&ys));
897         assert!(ys.is_disjoint(&xs));
898         assert!(xs.insert(7));
899         assert!(xs.insert(19));
900         assert!(xs.insert(4));
901         assert!(ys.insert(2));
902         assert!(ys.insert(-11));
903         assert!(xs.is_disjoint(&ys));
904         assert!(ys.is_disjoint(&xs));
905         assert!(ys.insert(7));
906         assert!(!xs.is_disjoint(&ys));
907         assert!(!ys.is_disjoint(&xs));
908     }
909
910     #[test]
911     fn test_subset_and_superset() {
912         let mut a = HashSet::new();
913         assert!(a.insert(0i));
914         assert!(a.insert(5));
915         assert!(a.insert(11));
916         assert!(a.insert(7));
917
918         let mut b = HashSet::new();
919         assert!(b.insert(0i));
920         assert!(b.insert(7));
921         assert!(b.insert(19));
922         assert!(b.insert(250));
923         assert!(b.insert(11));
924         assert!(b.insert(200));
925
926         assert!(!a.is_subset(&b));
927         assert!(!a.is_superset(&b));
928         assert!(!b.is_subset(&a));
929         assert!(!b.is_superset(&a));
930
931         assert!(b.insert(5));
932
933         assert!(a.is_subset(&b));
934         assert!(!a.is_superset(&b));
935         assert!(!b.is_subset(&a));
936         assert!(b.is_superset(&a));
937     }
938
939     #[test]
940     fn test_iterate() {
941         let mut a = HashSet::new();
942         for i in range(0u, 32) {
943             assert!(a.insert(i));
944         }
945         let mut observed: u32 = 0;
946         for k in a.iter() {
947             observed |= 1 << *k;
948         }
949         assert_eq!(observed, 0xFFFF_FFFF);
950     }
951
952     #[test]
953     fn test_intersection() {
954         let mut a = HashSet::new();
955         let mut b = HashSet::new();
956
957         assert!(a.insert(11i));
958         assert!(a.insert(1));
959         assert!(a.insert(3));
960         assert!(a.insert(77));
961         assert!(a.insert(103));
962         assert!(a.insert(5));
963         assert!(a.insert(-5));
964
965         assert!(b.insert(2i));
966         assert!(b.insert(11));
967         assert!(b.insert(77));
968         assert!(b.insert(-9));
969         assert!(b.insert(-42));
970         assert!(b.insert(5));
971         assert!(b.insert(3));
972
973         let mut i = 0;
974         let expected = [3, 5, 11, 77];
975         for x in a.intersection(&b) {
976             assert!(expected.contains(x));
977             i += 1
978         }
979         assert_eq!(i, expected.len());
980     }
981
982     #[test]
983     fn test_difference() {
984         let mut a = HashSet::new();
985         let mut b = HashSet::new();
986
987         assert!(a.insert(1i));
988         assert!(a.insert(3));
989         assert!(a.insert(5));
990         assert!(a.insert(9));
991         assert!(a.insert(11));
992
993         assert!(b.insert(3i));
994         assert!(b.insert(9));
995
996         let mut i = 0;
997         let expected = [1, 5, 11];
998         for x in a.difference(&b) {
999             assert!(expected.contains(x));
1000             i += 1
1001         }
1002         assert_eq!(i, expected.len());
1003     }
1004
1005     #[test]
1006     fn test_symmetric_difference() {
1007         let mut a = HashSet::new();
1008         let mut b = HashSet::new();
1009
1010         assert!(a.insert(1i));
1011         assert!(a.insert(3));
1012         assert!(a.insert(5));
1013         assert!(a.insert(9));
1014         assert!(a.insert(11));
1015
1016         assert!(b.insert(-2i));
1017         assert!(b.insert(3));
1018         assert!(b.insert(9));
1019         assert!(b.insert(14));
1020         assert!(b.insert(22));
1021
1022         let mut i = 0;
1023         let expected = [-2, 1, 5, 11, 14, 22];
1024         for x in a.symmetric_difference(&b) {
1025             assert!(expected.contains(x));
1026             i += 1
1027         }
1028         assert_eq!(i, expected.len());
1029     }
1030
1031     #[test]
1032     fn test_union() {
1033         let mut a = HashSet::new();
1034         let mut b = HashSet::new();
1035
1036         assert!(a.insert(1i));
1037         assert!(a.insert(3));
1038         assert!(a.insert(5));
1039         assert!(a.insert(9));
1040         assert!(a.insert(11));
1041         assert!(a.insert(16));
1042         assert!(a.insert(19));
1043         assert!(a.insert(24));
1044
1045         assert!(b.insert(-2i));
1046         assert!(b.insert(1));
1047         assert!(b.insert(5));
1048         assert!(b.insert(9));
1049         assert!(b.insert(13));
1050         assert!(b.insert(19));
1051
1052         let mut i = 0;
1053         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1054         for x in a.union(&b) {
1055             assert!(expected.contains(x));
1056             i += 1
1057         }
1058         assert_eq!(i, expected.len());
1059     }
1060
1061     #[test]
1062     fn test_from_iter() {
1063         let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
1064
1065         let set: HashSet<int> = xs.iter().map(|&x| x).collect();
1066
1067         for x in xs.iter() {
1068             assert!(set.contains(x));
1069         }
1070     }
1071
1072     #[test]
1073     fn test_move_iter() {
1074         let hs = {
1075             let mut hs = HashSet::new();
1076
1077             hs.insert('a');
1078             hs.insert('b');
1079
1080             hs
1081         };
1082
1083         let v = hs.into_iter().collect::<Vec<char>>();
1084         assert!(['a', 'b'] == v || ['b', 'a'] == v);
1085     }
1086
1087     #[test]
1088     fn test_eq() {
1089         // These constants once happened to expose a bug in insert().
1090         // I'm keeping them around to prevent a regression.
1091         let mut s1 = HashSet::new();
1092
1093         s1.insert(1i);
1094         s1.insert(2);
1095         s1.insert(3);
1096
1097         let mut s2 = HashSet::new();
1098
1099         s2.insert(1i);
1100         s2.insert(2);
1101
1102         assert!(s1 != s2);
1103
1104         s2.insert(3);
1105
1106         assert_eq!(s1, s2);
1107     }
1108
1109     #[test]
1110     fn test_show() {
1111         let mut set: HashSet<int> = HashSet::new();
1112         let empty: HashSet<int> = HashSet::new();
1113
1114         set.insert(1i);
1115         set.insert(2);
1116
1117         let set_str = format!("{}", set);
1118
1119         assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1120         assert_eq!(format!("{}", empty), "{}");
1121     }
1122
1123     #[test]
1124     fn test_trivial_drain() {
1125         let mut s = HashSet::<int>::new();
1126         for _ in s.drain() {}
1127         assert!(s.is_empty());
1128         drop(s);
1129
1130         let mut s = HashSet::<int>::new();
1131         drop(s.drain());
1132         assert!(s.is_empty());
1133     }
1134
1135     #[test]
1136     fn test_drain() {
1137         let mut s: HashSet<int> = range(1, 100).collect();
1138
1139         // try this a bunch of times to make sure we don't screw up internal state.
1140         for _ in range(0i, 20) {
1141             assert_eq!(s.len(), 99);
1142
1143             {
1144                 let mut last_i = 0;
1145                 let mut d = s.drain();
1146                 for (i, x) in d.by_ref().take(50).enumerate() {
1147                     last_i = i;
1148                     assert!(x != 0);
1149                 }
1150                 assert_eq!(last_i, 49);
1151             }
1152
1153             for _ in s.iter() { panic!("s should be empty!"); }
1154
1155             // reset to try again.
1156             s.extend(range(1, 100));
1157         }
1158     }
1159 }