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