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