]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/set.rs
6132d288da2799ca4698acf467c3ab6db7cb935e
[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, Equiv, 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, mod};
24 use result::Result::{Ok, Err};
25
26 use super::map::{mod, 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 /// #[deriving(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 #[deriving(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     /// Deprecated: use `contains` and `BorrowFrom`.
232     #[deprecated = "use contains and BorrowFrom"]
233     #[allow(deprecated)]
234     pub fn contains_equiv<Sized? Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
235       self.map.contains_key_equiv(value)
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, H>) -> Difference<'a, T, H> {
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, H>)
339         -> SymmetricDifference<'a, T, H> {
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, H>) -> Intersection<'a, T, H> {
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, H>) -> Union<'a, T, H> {
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<Sized? Q>(&self, value: &Q) -> bool
462         where Q: BorrowFrom<T> + Hash<S> + 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, H>) -> 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, H>) -> 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, H>) -> 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<Sized? Q>(&mut self, value: &Q) -> bool
572         where Q: BorrowFrom<T> + Hash<S> + Eq
573     {
574         self.map.remove(value).is_some()
575     }
576 }
577
578 #[stable]
579 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
580     fn eq(&self, other: &HashSet<T, H>) -> bool {
581         if self.len() != other.len() { return false; }
582
583         self.iter().all(|key| other.contains(key))
584     }
585 }
586
587 #[stable]
588 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
589
590 #[stable]
591 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
592     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
593         try!(write!(f, "{{"));
594
595         for (i, x) in self.iter().enumerate() {
596             if i != 0 { try!(write!(f, ", ")); }
597             try!(write!(f, "{}", *x));
598         }
599
600         write!(f, "}}")
601     }
602 }
603
604 #[stable]
605 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
606     fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
607         let lower = iter.size_hint().0;
608         let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
609         set.extend(iter);
610         set
611     }
612 }
613
614 #[stable]
615 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extend<T> for HashSet<T, H> {
616     fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
617         for k in iter {
618             self.insert(k);
619         }
620     }
621 }
622
623 #[stable]
624 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
625     #[stable]
626     fn default() -> HashSet<T, H> {
627         HashSet::with_hasher(Default::default())
628     }
629 }
630
631 #[stable]
632 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
633 BitOr<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
634     /// Returns the union of `self` and `rhs` as a new `HashSet<T, H>`.
635     ///
636     /// # Examples
637     ///
638     /// ```
639     /// use std::collections::HashSet;
640     ///
641     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
642     /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
643     ///
644     /// let set: HashSet<int> = &a | &b;
645     ///
646     /// let mut i = 0;
647     /// let expected = [1, 2, 3, 4, 5];
648     /// for x in set.iter() {
649     ///     assert!(expected.contains(x));
650     ///     i += 1;
651     /// }
652     /// assert_eq!(i, expected.len());
653     /// ```
654     fn bitor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
655         self.union(rhs).cloned().collect()
656     }
657 }
658
659 #[stable]
660 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
661 BitAnd<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
662     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, H>`.
663     ///
664     /// # Examples
665     ///
666     /// ```
667     /// use std::collections::HashSet;
668     ///
669     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
670     /// let b: HashSet<int> = vec![2, 3, 4].into_iter().collect();
671     ///
672     /// let set: HashSet<int> = &a & &b;
673     ///
674     /// let mut i = 0;
675     /// let expected = [2, 3];
676     /// for x in set.iter() {
677     ///     assert!(expected.contains(x));
678     ///     i += 1;
679     /// }
680     /// assert_eq!(i, expected.len());
681     /// ```
682     fn bitand(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
683         self.intersection(rhs).cloned().collect()
684     }
685 }
686
687 #[stable]
688 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
689 BitXor<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
690     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, H>`.
691     ///
692     /// # Examples
693     ///
694     /// ```
695     /// use std::collections::HashSet;
696     ///
697     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
698     /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
699     ///
700     /// let set: HashSet<int> = &a ^ &b;
701     ///
702     /// let mut i = 0;
703     /// let expected = [1, 2, 4, 5];
704     /// for x in set.iter() {
705     ///     assert!(expected.contains(x));
706     ///     i += 1;
707     /// }
708     /// assert_eq!(i, expected.len());
709     /// ```
710     fn bitxor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
711         self.symmetric_difference(rhs).cloned().collect()
712     }
713 }
714
715 #[stable]
716 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
717 Sub<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
718     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, H>`.
719     ///
720     /// # Examples
721     ///
722     /// ```
723     /// use std::collections::HashSet;
724     ///
725     /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
726     /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
727     ///
728     /// let set: HashSet<int> = &a - &b;
729     ///
730     /// let mut i = 0;
731     /// let expected = [1, 2];
732     /// for x in set.iter() {
733     ///     assert!(expected.contains(x));
734     ///     i += 1;
735     /// }
736     /// assert_eq!(i, expected.len());
737     /// ```
738     fn sub(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
739         self.difference(rhs).cloned().collect()
740     }
741 }
742
743 /// HashSet iterator
744 #[stable]
745 pub struct Iter<'a, K: 'a> {
746     iter: Keys<'a, K, ()>
747 }
748
749 /// HashSet move iterator
750 #[stable]
751 pub struct IntoIter<K> {
752     iter: Map<(K, ()), K, map::IntoIter<K, ()>, fn((K, ())) -> K>
753 }
754
755 /// HashSet drain iterator
756 #[stable]
757 pub struct Drain<'a, K: 'a> {
758     iter: Map<(K, ()), K, map::Drain<'a, K, ()>, fn((K, ())) -> K>,
759 }
760
761 /// Intersection iterator
762 #[stable]
763 pub struct Intersection<'a, T: 'a, H: 'a> {
764     // iterator of the first set
765     iter: Iter<'a, T>,
766     // the second set
767     other: &'a HashSet<T, H>,
768 }
769
770 /// Difference iterator
771 #[stable]
772 pub struct Difference<'a, T: 'a, H: 'a> {
773     // iterator of the first set
774     iter: Iter<'a, T>,
775     // the second set
776     other: &'a HashSet<T, H>,
777 }
778
779 /// Symmetric difference iterator.
780 #[stable]
781 pub struct SymmetricDifference<'a, T: 'a, H: 'a> {
782     iter: Chain<Difference<'a, T, H>, Difference<'a, T, H>>
783 }
784
785 /// Set union iterator.
786 #[stable]
787 pub struct Union<'a, T: 'a, H: 'a> {
788     iter: Chain<Iter<'a, T>, Difference<'a, T, H>>
789 }
790
791 #[stable]
792 impl<'a, K> Iterator<&'a K> for Iter<'a, K> {
793     fn next(&mut self) -> Option<&'a K> { self.iter.next() }
794     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
795 }
796
797 #[stable]
798 impl<K> Iterator<K> for IntoIter<K> {
799     fn next(&mut self) -> Option<K> { self.iter.next() }
800     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
801 }
802
803 #[stable]
804 impl<'a, K: 'a> Iterator<K> for Drain<'a, K> {
805     fn next(&mut self) -> Option<K> { self.iter.next() }
806     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
807 }
808
809 #[stable]
810 impl<'a, T, S, H> Iterator<&'a T> for Intersection<'a, T, H>
811     where T: Eq + Hash<S>, H: Hasher<S>
812 {
813     fn next(&mut self) -> Option<&'a T> {
814         loop {
815             match self.iter.next() {
816                 None => return None,
817                 Some(elt) => if self.other.contains(elt) {
818                     return Some(elt)
819                 },
820             }
821         }
822     }
823
824     fn size_hint(&self) -> (uint, Option<uint>) {
825         let (_, upper) = self.iter.size_hint();
826         (0, upper)
827     }
828 }
829
830 #[stable]
831 impl<'a, T, S, H> Iterator<&'a T> for Difference<'a, T, H>
832     where T: Eq + Hash<S>, H: Hasher<S>
833 {
834     fn next(&mut self) -> Option<&'a T> {
835         loop {
836             match self.iter.next() {
837                 None => return None,
838                 Some(elt) => if !self.other.contains(elt) {
839                     return Some(elt)
840                 },
841             }
842         }
843     }
844
845     fn size_hint(&self) -> (uint, Option<uint>) {
846         let (_, upper) = self.iter.size_hint();
847         (0, upper)
848     }
849 }
850
851 #[stable]
852 impl<'a, T, S, H> Iterator<&'a T> for SymmetricDifference<'a, T, H>
853     where T: Eq + Hash<S>, H: Hasher<S>
854 {
855     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
856     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
857 }
858
859 #[stable]
860 impl<'a, T, S, H> Iterator<&'a T> for Union<'a, T, H>
861     where T: Eq + Hash<S>, H: Hasher<S>
862 {
863     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
864     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
865 }
866
867 #[cfg(test)]
868 mod test_set {
869     use prelude::v1::*;
870
871     use super::HashSet;
872
873     #[test]
874     fn test_disjoint() {
875         let mut xs = HashSet::new();
876         let mut ys = HashSet::new();
877         assert!(xs.is_disjoint(&ys));
878         assert!(ys.is_disjoint(&xs));
879         assert!(xs.insert(5i));
880         assert!(ys.insert(11i));
881         assert!(xs.is_disjoint(&ys));
882         assert!(ys.is_disjoint(&xs));
883         assert!(xs.insert(7));
884         assert!(xs.insert(19));
885         assert!(xs.insert(4));
886         assert!(ys.insert(2));
887         assert!(ys.insert(-11));
888         assert!(xs.is_disjoint(&ys));
889         assert!(ys.is_disjoint(&xs));
890         assert!(ys.insert(7));
891         assert!(!xs.is_disjoint(&ys));
892         assert!(!ys.is_disjoint(&xs));
893     }
894
895     #[test]
896     fn test_subset_and_superset() {
897         let mut a = HashSet::new();
898         assert!(a.insert(0i));
899         assert!(a.insert(5));
900         assert!(a.insert(11));
901         assert!(a.insert(7));
902
903         let mut b = HashSet::new();
904         assert!(b.insert(0i));
905         assert!(b.insert(7));
906         assert!(b.insert(19));
907         assert!(b.insert(250));
908         assert!(b.insert(11));
909         assert!(b.insert(200));
910
911         assert!(!a.is_subset(&b));
912         assert!(!a.is_superset(&b));
913         assert!(!b.is_subset(&a));
914         assert!(!b.is_superset(&a));
915
916         assert!(b.insert(5));
917
918         assert!(a.is_subset(&b));
919         assert!(!a.is_superset(&b));
920         assert!(!b.is_subset(&a));
921         assert!(b.is_superset(&a));
922     }
923
924     #[test]
925     fn test_iterate() {
926         let mut a = HashSet::new();
927         for i in range(0u, 32) {
928             assert!(a.insert(i));
929         }
930         let mut observed: u32 = 0;
931         for k in a.iter() {
932             observed |= 1 << *k;
933         }
934         assert_eq!(observed, 0xFFFF_FFFF);
935     }
936
937     #[test]
938     fn test_intersection() {
939         let mut a = HashSet::new();
940         let mut b = HashSet::new();
941
942         assert!(a.insert(11i));
943         assert!(a.insert(1));
944         assert!(a.insert(3));
945         assert!(a.insert(77));
946         assert!(a.insert(103));
947         assert!(a.insert(5));
948         assert!(a.insert(-5));
949
950         assert!(b.insert(2i));
951         assert!(b.insert(11));
952         assert!(b.insert(77));
953         assert!(b.insert(-9));
954         assert!(b.insert(-42));
955         assert!(b.insert(5));
956         assert!(b.insert(3));
957
958         let mut i = 0;
959         let expected = [3, 5, 11, 77];
960         for x in a.intersection(&b) {
961             assert!(expected.contains(x));
962             i += 1
963         }
964         assert_eq!(i, expected.len());
965     }
966
967     #[test]
968     fn test_difference() {
969         let mut a = HashSet::new();
970         let mut b = HashSet::new();
971
972         assert!(a.insert(1i));
973         assert!(a.insert(3));
974         assert!(a.insert(5));
975         assert!(a.insert(9));
976         assert!(a.insert(11));
977
978         assert!(b.insert(3i));
979         assert!(b.insert(9));
980
981         let mut i = 0;
982         let expected = [1, 5, 11];
983         for x in a.difference(&b) {
984             assert!(expected.contains(x));
985             i += 1
986         }
987         assert_eq!(i, expected.len());
988     }
989
990     #[test]
991     fn test_symmetric_difference() {
992         let mut a = HashSet::new();
993         let mut b = HashSet::new();
994
995         assert!(a.insert(1i));
996         assert!(a.insert(3));
997         assert!(a.insert(5));
998         assert!(a.insert(9));
999         assert!(a.insert(11));
1000
1001         assert!(b.insert(-2i));
1002         assert!(b.insert(3));
1003         assert!(b.insert(9));
1004         assert!(b.insert(14));
1005         assert!(b.insert(22));
1006
1007         let mut i = 0;
1008         let expected = [-2, 1, 5, 11, 14, 22];
1009         for x in a.symmetric_difference(&b) {
1010             assert!(expected.contains(x));
1011             i += 1
1012         }
1013         assert_eq!(i, expected.len());
1014     }
1015
1016     #[test]
1017     fn test_union() {
1018         let mut a = HashSet::new();
1019         let mut b = HashSet::new();
1020
1021         assert!(a.insert(1i));
1022         assert!(a.insert(3));
1023         assert!(a.insert(5));
1024         assert!(a.insert(9));
1025         assert!(a.insert(11));
1026         assert!(a.insert(16));
1027         assert!(a.insert(19));
1028         assert!(a.insert(24));
1029
1030         assert!(b.insert(-2i));
1031         assert!(b.insert(1));
1032         assert!(b.insert(5));
1033         assert!(b.insert(9));
1034         assert!(b.insert(13));
1035         assert!(b.insert(19));
1036
1037         let mut i = 0;
1038         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1039         for x in a.union(&b) {
1040             assert!(expected.contains(x));
1041             i += 1
1042         }
1043         assert_eq!(i, expected.len());
1044     }
1045
1046     #[test]
1047     fn test_from_iter() {
1048         let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
1049
1050         let set: HashSet<int> = xs.iter().map(|&x| x).collect();
1051
1052         for x in xs.iter() {
1053             assert!(set.contains(x));
1054         }
1055     }
1056
1057     #[test]
1058     fn test_move_iter() {
1059         let hs = {
1060             let mut hs = HashSet::new();
1061
1062             hs.insert('a');
1063             hs.insert('b');
1064
1065             hs
1066         };
1067
1068         let v = hs.into_iter().collect::<Vec<char>>();
1069         assert!(['a', 'b'] == v || ['b', 'a'] == v);
1070     }
1071
1072     #[test]
1073     fn test_eq() {
1074         // These constants once happened to expose a bug in insert().
1075         // I'm keeping them around to prevent a regression.
1076         let mut s1 = HashSet::new();
1077
1078         s1.insert(1i);
1079         s1.insert(2);
1080         s1.insert(3);
1081
1082         let mut s2 = HashSet::new();
1083
1084         s2.insert(1i);
1085         s2.insert(2);
1086
1087         assert!(s1 != s2);
1088
1089         s2.insert(3);
1090
1091         assert_eq!(s1, s2);
1092     }
1093
1094     #[test]
1095     fn test_show() {
1096         let mut set: HashSet<int> = HashSet::new();
1097         let empty: HashSet<int> = HashSet::new();
1098
1099         set.insert(1i);
1100         set.insert(2);
1101
1102         let set_str = format!("{}", set);
1103
1104         assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1105         assert_eq!(format!("{}", empty), "{}");
1106     }
1107
1108     #[test]
1109     fn test_trivial_drain() {
1110         let mut s = HashSet::<int>::new();
1111         for _ in s.drain() {}
1112         assert!(s.is_empty());
1113         drop(s);
1114
1115         let mut s = HashSet::<int>::new();
1116         drop(s.drain());
1117         assert!(s.is_empty());
1118     }
1119
1120     #[test]
1121     fn test_drain() {
1122         let mut s: HashSet<int> = range(1, 100).collect();
1123
1124         // try this a bunch of times to make sure we don't screw up internal state.
1125         for _ in range(0i, 20) {
1126             assert_eq!(s.len(), 99);
1127
1128             {
1129                 let mut last_i = 0;
1130                 let mut d = s.drain();
1131                 for (i, x) in d.by_ref().take(50).enumerate() {
1132                     last_i = i;
1133                     assert!(x != 0);
1134                 }
1135                 assert_eq!(last_i, 49);
1136             }
1137
1138             for _ in s.iter() { panic!("s should be empty!"); }
1139
1140             // reset to try again.
1141             s.extend(range(1, 100));
1142         }
1143     }
1144 }