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.
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.
11 // ignore-lexer-test FIXME #15883
13 use borrow::BorrowFrom;
15 use cmp::{Eq, Equiv, PartialEq};
16 use core::kinds::Sized;
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};
26 use super::map::{mod, HashMap, Keys, INITIAL_CAPACITY};
28 // Future Optimization (FIXME!)
29 // =============================
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.
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.
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();
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");
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.",
60 /// books.remove(&"The Odyssey");
62 /// // Iterate over everything.
63 /// for book in books.iter() {
64 /// println!("{}", *book);
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`.
73 /// use std::collections::HashSet;
74 /// #[deriving(Hash, Eq, PartialEq, Show)]
75 /// struct Viking<'a> {
80 /// let mut vikings = HashSet::new();
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 });
87 /// // Use derived implementation to print the vikings.
88 /// for x in vikings.iter() {
89 /// println!("{}", x);
93 pub struct HashSet<T, H = RandomSipHasher> {
94 map: HashMap<T, (), H>
97 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
98 /// Create an empty HashSet.
103 /// use std::collections::HashSet;
104 /// let mut set: HashSet<int> = HashSet::new();
107 #[unstable = "matches collection reform specification, waiting for dust to settle"]
108 pub fn new() -> HashSet<T, RandomSipHasher> {
109 HashSet::with_capacity(INITIAL_CAPACITY)
112 /// Create an empty HashSet with space for at least `n` elements in
118 /// use std::collections::HashSet;
119 /// let mut set: HashSet<int> = HashSet::with_capacity(10);
122 #[unstable = "matches collection reform specification, waiting for dust to settle"]
123 pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
124 HashSet { map: HashMap::with_capacity(capacity) }
128 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
129 /// Creates a new empty hash set which will use the given hasher to hash
132 /// The hash set is also created with the default initial capacity.
137 /// use std::collections::HashSet;
138 /// use std::hash::sip::SipHasher;
140 /// let h = SipHasher::new();
141 /// let mut set = HashSet::with_hasher(h);
145 pub fn with_hasher(hasher: H) -> HashSet<T, H> {
146 HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
149 /// Create an empty HashSet with space for at least `capacity`
150 /// elements in the hash table, using `hasher` to hash the keys.
152 /// Warning: `hasher` is normally randomly generated, and
153 /// is designed to allow `HashSet`s to be resistant to attacks that
154 /// cause many collisions and very poor performance. Setting it
155 /// manually using this function can expose a DoS attack vector.
160 /// use std::collections::HashSet;
161 /// use std::hash::sip::SipHasher;
163 /// let h = SipHasher::new();
164 /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
168 pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
169 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
172 /// Returns the number of elements the set can hold without reallocating.
177 /// use std::collections::HashSet;
178 /// let set: HashSet<int> = HashSet::with_capacity(100);
179 /// assert!(set.capacity() >= 100);
182 #[unstable = "matches collection reform specification, waiting for dust to settle"]
183 pub fn capacity(&self) -> uint {
187 /// Reserves capacity for at least `additional` more elements to be inserted
188 /// in the `HashSet`. The collection may reserve more space to avoid
189 /// frequent reallocations.
193 /// Panics if the new allocation size overflows `uint`.
198 /// use std::collections::HashSet;
199 /// let mut set: HashSet<int> = HashSet::new();
202 #[unstable = "matches collection reform specification, waiting for dust to settle"]
203 pub fn reserve(&mut self, additional: uint) {
204 self.map.reserve(additional)
207 /// Shrinks the capacity of the set as much as possible. It will drop
208 /// down as much as possible while maintaining the internal rules
209 /// and possibly leaving some space in accordance with the resize policy.
214 /// use std::collections::HashSet;
216 /// let mut set: HashSet<int> = HashSet::with_capacity(100);
219 /// assert!(set.capacity() >= 100);
220 /// set.shrink_to_fit();
221 /// assert!(set.capacity() >= 2);
223 #[unstable = "matches collection reform specification, waiting for dust to settle"]
224 pub fn shrink_to_fit(&mut self) {
225 self.map.shrink_to_fit()
228 /// Deprecated: use `contains` and `BorrowFrom`.
229 #[deprecated = "use contains and BorrowFrom"]
231 pub fn contains_equiv<Sized? Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
232 self.map.contains_key_equiv(value)
235 /// An iterator visiting all elements in arbitrary order.
236 /// Iterator element type is &'a T.
241 /// use std::collections::HashSet;
242 /// let mut set = HashSet::new();
246 /// // Will print in an arbitrary order.
247 /// for x in set.iter() {
248 /// println!("{}", x);
251 #[unstable = "matches collection reform specification, waiting for dust to settle"]
252 pub fn iter<'a>(&'a self) -> Iter<'a, T> {
253 Iter { iter: self.map.keys() }
256 /// Creates a consuming iterator, that is, one that moves each value out
257 /// of the set in arbitrary order. The set cannot be used after calling
263 /// use std::collections::HashSet;
264 /// let mut set = HashSet::new();
265 /// set.insert("a".to_string());
266 /// set.insert("b".to_string());
268 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
269 /// let v: Vec<String> = set.into_iter().collect();
271 /// // Will print in an arbitrary order.
272 /// for x in v.iter() {
273 /// println!("{}", x);
276 #[unstable = "matches collection reform specification, waiting for dust to settle"]
277 pub fn into_iter(self) -> IntoIter<T> {
278 fn first<A, B>((a, _): (A, B)) -> A { a }
279 let first: fn((T, ())) -> T = first;
281 IntoIter { iter: self.map.into_iter().map(first) }
284 /// Visit the values representing the difference.
289 /// use std::collections::HashSet;
290 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
291 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
293 /// // Can be seen as `a - b`.
294 /// for x in a.difference(&b) {
295 /// println!("{}", x); // Print 1
298 /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
299 /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
301 /// // Note that difference is not symmetric,
302 /// // and `b - a` means something else:
303 /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
304 /// assert_eq!(diff, [4i].iter().map(|&x| x).collect());
306 #[unstable = "matches collection reform specification, waiting for dust to settle"]
307 pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> Difference<'a, T, H> {
314 /// Visit the values representing the symmetric difference.
319 /// use std::collections::HashSet;
320 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
321 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
323 /// // Print 1, 4 in arbitrary order.
324 /// for x in a.symmetric_difference(&b) {
325 /// println!("{}", x);
328 /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
329 /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
331 /// assert_eq!(diff1, diff2);
332 /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
334 #[unstable = "matches collection reform specification, waiting for dust to settle"]
335 pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
336 -> SymmetricDifference<'a, T, H> {
337 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
340 /// Visit the values representing the intersection.
345 /// use std::collections::HashSet;
346 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
347 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
349 /// // Print 2, 3 in arbitrary order.
350 /// for x in a.intersection(&b) {
351 /// println!("{}", x);
354 /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
355 /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
357 #[unstable = "matches collection reform specification, waiting for dust to settle"]
358 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>) -> Intersection<'a, T, H> {
365 /// Visit the values representing the union.
370 /// use std::collections::HashSet;
371 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
372 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
374 /// // Print 1, 2, 3, 4 in arbitrary order.
375 /// for x in a.union(&b) {
376 /// println!("{}", x);
379 /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
380 /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect());
382 #[unstable = "matches collection reform specification, waiting for dust to settle"]
383 pub fn union<'a>(&'a self, other: &'a HashSet<T, H>) -> Union<'a, T, H> {
384 Union { iter: self.iter().chain(other.difference(self)) }
387 /// Return the number of elements in the set
392 /// use std::collections::HashSet;
394 /// let mut v = HashSet::new();
395 /// assert_eq!(v.len(), 0);
397 /// assert_eq!(v.len(), 1);
399 #[unstable = "matches collection reform specification, waiting for dust to settle"]
400 pub fn len(&self) -> uint { self.map.len() }
402 /// Returns true if the set contains no elements
407 /// use std::collections::HashSet;
409 /// let mut v = HashSet::new();
410 /// assert!(v.is_empty());
412 /// assert!(!v.is_empty());
414 #[unstable = "matches collection reform specification, waiting for dust to settle"]
415 pub fn is_empty(&self) -> bool { self.map.len() == 0 }
417 /// Clears the set, returning all elements in an iterator.
419 #[unstable = "matches collection reform specification, waiting for dust to settle"]
420 pub fn drain(&mut self) -> Drain<T> {
421 fn first<A, B>((a, _): (A, B)) -> A { a }
422 let first: fn((T, ())) -> T = first; // coerce to fn pointer
424 Drain { iter: self.map.drain().map(first) }
427 /// Clears the set, removing all values.
432 /// use std::collections::HashSet;
434 /// let mut v = HashSet::new();
437 /// assert!(v.is_empty());
439 #[unstable = "matches collection reform specification, waiting for dust to settle"]
440 pub fn clear(&mut self) { self.map.clear() }
442 /// Returns `true` if the set contains a value.
444 /// The value may be any borrowed form of the set's value type, but
445 /// `Hash` and `Eq` on the borrowed form *must* match those for
451 /// use std::collections::HashSet;
453 /// let set: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
454 /// assert_eq!(set.contains(&1), true);
455 /// assert_eq!(set.contains(&4), false);
457 #[unstable = "matches collection reform specification, waiting for dust to settle"]
458 pub fn contains<Sized? Q>(&self, value: &Q) -> bool
459 where Q: BorrowFrom<T> + Hash<S> + Eq
461 self.map.contains_key(value)
464 /// Returns `true` if the set has no elements in common with `other`.
465 /// This is equivalent to checking for an empty intersection.
470 /// use std::collections::HashSet;
472 /// let a: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
473 /// let mut b: HashSet<uint> = HashSet::new();
475 /// assert_eq!(a.is_disjoint(&b), true);
477 /// assert_eq!(a.is_disjoint(&b), true);
479 /// assert_eq!(a.is_disjoint(&b), false);
481 #[unstable = "matches collection reform specification, waiting for dust to settle"]
482 pub fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
483 self.iter().all(|v| !other.contains(v))
486 /// Returns `true` if the set is a subset of another.
491 /// use std::collections::HashSet;
493 /// let sup: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
494 /// let mut set: HashSet<uint> = HashSet::new();
496 /// assert_eq!(set.is_subset(&sup), true);
498 /// assert_eq!(set.is_subset(&sup), true);
500 /// assert_eq!(set.is_subset(&sup), false);
502 #[unstable = "matches collection reform specification, waiting for dust to settle"]
503 pub fn is_subset(&self, other: &HashSet<T, H>) -> bool {
504 self.iter().all(|v| other.contains(v))
507 /// Returns `true` if the set is a superset of another.
512 /// use std::collections::HashSet;
514 /// let sub: HashSet<uint> = [1, 2].iter().map(|&x| x).collect();
515 /// let mut set: HashSet<uint> = HashSet::new();
517 /// assert_eq!(set.is_superset(&sub), false);
521 /// assert_eq!(set.is_superset(&sub), false);
524 /// assert_eq!(set.is_superset(&sub), true);
527 #[unstable = "matches collection reform specification, waiting for dust to settle"]
528 pub fn is_superset(&self, other: &HashSet<T, H>) -> bool {
529 other.is_subset(self)
532 /// Adds a value to the set. Returns `true` if the value was not already
533 /// present in the set.
538 /// use std::collections::HashSet;
540 /// let mut set = HashSet::new();
542 /// assert_eq!(set.insert(2u), true);
543 /// assert_eq!(set.insert(2), false);
544 /// assert_eq!(set.len(), 1);
546 #[unstable = "matches collection reform specification, waiting for dust to settle"]
547 pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
549 /// Removes a value from the set. Returns `true` if the value was
550 /// present in the set.
552 /// The value may be any borrowed form of the set's value type, but
553 /// `Hash` and `Eq` on the borrowed form *must* match those for
559 /// use std::collections::HashSet;
561 /// let mut set = HashSet::new();
564 /// assert_eq!(set.remove(&2), true);
565 /// assert_eq!(set.remove(&2), false);
567 #[unstable = "matches collection reform specification, waiting for dust to settle"]
568 pub fn remove<Sized? Q>(&mut self, value: &Q) -> bool
569 where Q: BorrowFrom<T> + Hash<S> + Eq
571 self.map.remove(value).is_some()
575 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
576 fn eq(&self, other: &HashSet<T, H>) -> bool {
577 if self.len() != other.len() { return false; }
579 self.iter().all(|key| other.contains(key))
583 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
585 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
586 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
587 try!(write!(f, "{{"));
589 for (i, x) in self.iter().enumerate() {
590 if i != 0 { try!(write!(f, ", ")); }
591 try!(write!(f, "{}", *x));
598 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
599 fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
600 let lower = iter.size_hint().0;
601 let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
607 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extend<T> for HashSet<T, H> {
608 fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
616 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
618 fn default() -> HashSet<T, H> {
619 HashSet::with_hasher(Default::default())
623 #[unstable = "matches collection reform specification, waiting for dust to settle"]
624 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
625 BitOr<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
626 /// Returns the union of `self` and `rhs` as a new `HashSet<T, H>`.
631 /// use std::collections::HashSet;
633 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
634 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
636 /// let set: HashSet<int> = &a | &b;
639 /// let expected = [1, 2, 3, 4, 5];
640 /// for x in set.iter() {
641 /// assert!(expected.contains(x));
644 /// assert_eq!(i, expected.len());
646 fn bitor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
647 self.union(rhs).cloned().collect()
651 #[unstable = "matches collection reform specification, waiting for dust to settle"]
652 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
653 BitAnd<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
654 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, H>`.
659 /// use std::collections::HashSet;
661 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
662 /// let b: HashSet<int> = vec![2, 3, 4].into_iter().collect();
664 /// let set: HashSet<int> = &a & &b;
667 /// let expected = [2, 3];
668 /// for x in set.iter() {
669 /// assert!(expected.contains(x));
672 /// assert_eq!(i, expected.len());
674 fn bitand(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
675 self.intersection(rhs).cloned().collect()
679 #[unstable = "matches collection reform specification, waiting for dust to settle"]
680 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
681 BitXor<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
682 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, H>`.
687 /// use std::collections::HashSet;
689 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
690 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
692 /// let set: HashSet<int> = &a ^ &b;
695 /// let expected = [1, 2, 4, 5];
696 /// for x in set.iter() {
697 /// assert!(expected.contains(x));
700 /// assert_eq!(i, expected.len());
702 fn bitxor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
703 self.symmetric_difference(rhs).cloned().collect()
707 #[unstable = "matches collection reform specification, waiting for dust to settle"]
708 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
709 Sub<&'b HashSet<T, H>, HashSet<T, H>> for &'a HashSet<T, H> {
710 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, H>`.
715 /// use std::collections::HashSet;
717 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
718 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
720 /// let set: HashSet<int> = &a - &b;
723 /// let expected = [1, 2];
724 /// for x in set.iter() {
725 /// assert!(expected.contains(x));
728 /// assert_eq!(i, expected.len());
730 fn sub(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
731 self.difference(rhs).cloned().collect()
736 pub struct Iter<'a, K: 'a> {
737 iter: Keys<'a, K, ()>
740 /// HashSet move iterator
741 pub struct IntoIter<K> {
742 iter: Map<(K, ()), K, map::IntoIter<K, ()>, fn((K, ())) -> K>
745 /// HashSet drain iterator
746 pub struct Drain<'a, K: 'a> {
747 iter: Map<(K, ()), K, map::Drain<'a, K, ()>, fn((K, ())) -> K>,
750 /// Intersection iterator
751 pub struct Intersection<'a, T: 'a, H: 'a> {
752 // iterator of the first set
755 other: &'a HashSet<T, H>,
758 /// Difference iterator
759 pub struct Difference<'a, T: 'a, H: 'a> {
760 // iterator of the first set
763 other: &'a HashSet<T, H>,
766 /// Symmetric difference iterator.
767 pub struct SymmetricDifference<'a, T: 'a, H: 'a> {
768 iter: Chain<Difference<'a, T, H>, Difference<'a, T, H>>
771 /// Set union iterator.
772 pub struct Union<'a, T: 'a, H: 'a> {
773 iter: Chain<Iter<'a, T>, Difference<'a, T, H>>
776 impl<'a, K> Iterator<&'a K> for Iter<'a, K> {
777 fn next(&mut self) -> Option<&'a K> { self.iter.next() }
778 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
781 impl<K> Iterator<K> for IntoIter<K> {
782 fn next(&mut self) -> Option<K> { self.iter.next() }
783 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
786 impl<'a, K: 'a> Iterator<K> for Drain<'a, K> {
787 fn next(&mut self) -> Option<K> { self.iter.next() }
788 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
791 impl<'a, T, S, H> Iterator<&'a T> for Intersection<'a, T, H>
792 where T: Eq + Hash<S>, H: Hasher<S>
794 fn next(&mut self) -> Option<&'a T> {
796 match self.iter.next() {
798 Some(elt) => if self.other.contains(elt) {
805 fn size_hint(&self) -> (uint, Option<uint>) {
806 let (_, upper) = self.iter.size_hint();
811 impl<'a, T, S, H> Iterator<&'a T> for Difference<'a, T, H>
812 where T: Eq + Hash<S>, H: Hasher<S>
814 fn next(&mut self) -> Option<&'a T> {
816 match self.iter.next() {
818 Some(elt) => if !self.other.contains(elt) {
825 fn size_hint(&self) -> (uint, Option<uint>) {
826 let (_, upper) = self.iter.size_hint();
831 impl<'a, T, S, H> Iterator<&'a T> for SymmetricDifference<'a, T, H>
832 where T: Eq + Hash<S>, H: Hasher<S>
834 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
835 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
838 impl<'a, T, S, H> Iterator<&'a T> for Union<'a, T, H>
839 where T: Eq + Hash<S>, H: Hasher<S>
841 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
842 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
853 let mut xs = HashSet::new();
854 let mut ys = HashSet::new();
855 assert!(xs.is_disjoint(&ys));
856 assert!(ys.is_disjoint(&xs));
857 assert!(xs.insert(5i));
858 assert!(ys.insert(11i));
859 assert!(xs.is_disjoint(&ys));
860 assert!(ys.is_disjoint(&xs));
861 assert!(xs.insert(7));
862 assert!(xs.insert(19));
863 assert!(xs.insert(4));
864 assert!(ys.insert(2));
865 assert!(ys.insert(-11));
866 assert!(xs.is_disjoint(&ys));
867 assert!(ys.is_disjoint(&xs));
868 assert!(ys.insert(7));
869 assert!(!xs.is_disjoint(&ys));
870 assert!(!ys.is_disjoint(&xs));
874 fn test_subset_and_superset() {
875 let mut a = HashSet::new();
876 assert!(a.insert(0i));
877 assert!(a.insert(5));
878 assert!(a.insert(11));
879 assert!(a.insert(7));
881 let mut b = HashSet::new();
882 assert!(b.insert(0i));
883 assert!(b.insert(7));
884 assert!(b.insert(19));
885 assert!(b.insert(250));
886 assert!(b.insert(11));
887 assert!(b.insert(200));
889 assert!(!a.is_subset(&b));
890 assert!(!a.is_superset(&b));
891 assert!(!b.is_subset(&a));
892 assert!(!b.is_superset(&a));
894 assert!(b.insert(5));
896 assert!(a.is_subset(&b));
897 assert!(!a.is_superset(&b));
898 assert!(!b.is_subset(&a));
899 assert!(b.is_superset(&a));
904 let mut a = HashSet::new();
905 for i in range(0u, 32) {
906 assert!(a.insert(i));
908 let mut observed: u32 = 0;
912 assert_eq!(observed, 0xFFFF_FFFF);
916 fn test_intersection() {
917 let mut a = HashSet::new();
918 let mut b = HashSet::new();
920 assert!(a.insert(11i));
921 assert!(a.insert(1));
922 assert!(a.insert(3));
923 assert!(a.insert(77));
924 assert!(a.insert(103));
925 assert!(a.insert(5));
926 assert!(a.insert(-5));
928 assert!(b.insert(2i));
929 assert!(b.insert(11));
930 assert!(b.insert(77));
931 assert!(b.insert(-9));
932 assert!(b.insert(-42));
933 assert!(b.insert(5));
934 assert!(b.insert(3));
937 let expected = [3, 5, 11, 77];
938 for x in a.intersection(&b) {
939 assert!(expected.contains(x));
942 assert_eq!(i, expected.len());
946 fn test_difference() {
947 let mut a = HashSet::new();
948 let mut b = HashSet::new();
950 assert!(a.insert(1i));
951 assert!(a.insert(3));
952 assert!(a.insert(5));
953 assert!(a.insert(9));
954 assert!(a.insert(11));
956 assert!(b.insert(3i));
957 assert!(b.insert(9));
960 let expected = [1, 5, 11];
961 for x in a.difference(&b) {
962 assert!(expected.contains(x));
965 assert_eq!(i, expected.len());
969 fn test_symmetric_difference() {
970 let mut a = HashSet::new();
971 let mut b = HashSet::new();
973 assert!(a.insert(1i));
974 assert!(a.insert(3));
975 assert!(a.insert(5));
976 assert!(a.insert(9));
977 assert!(a.insert(11));
979 assert!(b.insert(-2i));
980 assert!(b.insert(3));
981 assert!(b.insert(9));
982 assert!(b.insert(14));
983 assert!(b.insert(22));
986 let expected = [-2, 1, 5, 11, 14, 22];
987 for x in a.symmetric_difference(&b) {
988 assert!(expected.contains(x));
991 assert_eq!(i, expected.len());
996 let mut a = HashSet::new();
997 let mut b = HashSet::new();
999 assert!(a.insert(1i));
1000 assert!(a.insert(3));
1001 assert!(a.insert(5));
1002 assert!(a.insert(9));
1003 assert!(a.insert(11));
1004 assert!(a.insert(16));
1005 assert!(a.insert(19));
1006 assert!(a.insert(24));
1008 assert!(b.insert(-2i));
1009 assert!(b.insert(1));
1010 assert!(b.insert(5));
1011 assert!(b.insert(9));
1012 assert!(b.insert(13));
1013 assert!(b.insert(19));
1016 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1017 for x in a.union(&b) {
1018 assert!(expected.contains(x));
1021 assert_eq!(i, expected.len());
1025 fn test_from_iter() {
1026 let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
1028 let set: HashSet<int> = xs.iter().map(|&x| x).collect();
1030 for x in xs.iter() {
1031 assert!(set.contains(x));
1036 fn test_move_iter() {
1038 let mut hs = HashSet::new();
1046 let v = hs.into_iter().collect::<Vec<char>>();
1047 assert!(['a', 'b'] == v || ['b', 'a'] == v);
1052 // These constants once happened to expose a bug in insert().
1053 // I'm keeping them around to prevent a regression.
1054 let mut s1 = HashSet::new();
1060 let mut s2 = HashSet::new();
1074 let mut set: HashSet<int> = HashSet::new();
1075 let empty: HashSet<int> = HashSet::new();
1080 let set_str = format!("{}", set);
1082 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1083 assert_eq!(format!("{}", empty), "{}");
1087 fn test_trivial_drain() {
1088 let mut s = HashSet::<int>::new();
1089 for _ in s.drain() {}
1090 assert!(s.is_empty());
1093 let mut s = HashSet::<int>::new();
1095 assert!(s.is_empty());
1100 let mut s: HashSet<int> = range(1, 100).collect();
1102 // try this a bunch of times to make sure we don't screw up internal state.
1103 for _ in range(0i, 20) {
1104 assert_eq!(s.len(), 99);
1108 let mut d = s.drain();
1109 for (i, x) in d.by_ref().take(50).enumerate() {
1113 assert_eq!(last_i, 49);
1116 for _ in s.iter() { panic!("s should be empty!"); }
1118 // reset to try again.
1119 s.extend(range(1, 100));