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, PartialEq};
16 use core::marker::Sized;
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};
25 use super::map::{self, HashMap, Keys, INITIAL_CAPACITY, RandomState, Hasher};
26 use super::state::HashState;
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 /// #[derive(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);
94 pub struct HashSet<T, S = RandomState> {
95 map: HashMap<T, (), S>
98 impl<T: Hash<Hasher> + Eq> HashSet<T, RandomState> {
99 /// Create an empty HashSet.
104 /// use std::collections::HashSet;
105 /// let mut set: HashSet<int> = HashSet::new();
109 pub fn new() -> HashSet<T, RandomState> {
110 HashSet::with_capacity(INITIAL_CAPACITY)
113 /// Create an empty HashSet with space for at least `n` elements in
119 /// use std::collections::HashSet;
120 /// let mut set: HashSet<int> = HashSet::with_capacity(10);
124 pub fn with_capacity(capacity: uint) -> HashSet<T, RandomState> {
125 HashSet { map: HashMap::with_capacity(capacity) }
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>
134 /// Creates a new empty hash set which will use the given hasher to hash
137 /// The hash set is also created with the default initial capacity.
142 /// use std::collections::HashSet;
143 /// use std::collections::hash_map::RandomState;
145 /// let s = RandomState::new();
146 /// let mut set = HashSet::with_hash_state(s);
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)
155 /// Create an empty HashSet with space for at least `capacity`
156 /// elements in the hash table, using `hasher` to hash the keys.
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.
166 /// use std::collections::HashSet;
167 /// use std::collections::hash_map::RandomState;
169 /// let s = RandomState::new();
170 /// let mut set = HashSet::with_capacity_and_hash_state(10u, s);
174 #[unstable = "hasher stuff is unclear"]
175 pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S)
178 map: HashMap::with_capacity_and_hash_state(capacity, hash_state),
182 /// Returns the number of elements the set can hold without reallocating.
187 /// use std::collections::HashSet;
188 /// let set: HashSet<int> = HashSet::with_capacity(100);
189 /// assert!(set.capacity() >= 100);
193 pub fn capacity(&self) -> uint {
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.
203 /// Panics if the new allocation size overflows `uint`.
208 /// use std::collections::HashSet;
209 /// let mut set: HashSet<int> = HashSet::new();
213 pub fn reserve(&mut self, additional: uint) {
214 self.map.reserve(additional)
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.
224 /// use std::collections::HashSet;
226 /// let mut set: HashSet<int> = HashSet::with_capacity(100);
229 /// assert!(set.capacity() >= 100);
230 /// set.shrink_to_fit();
231 /// assert!(set.capacity() >= 2);
234 pub fn shrink_to_fit(&mut self) {
235 self.map.shrink_to_fit()
238 /// An iterator visiting all elements in arbitrary order.
239 /// Iterator element type is &'a T.
244 /// use std::collections::HashSet;
245 /// let mut set = HashSet::new();
249 /// // Will print in an arbitrary order.
250 /// for x in set.iter() {
251 /// println!("{}", x);
255 pub fn iter(&self) -> Iter<T> {
256 Iter { iter: self.map.keys() }
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
266 /// use std::collections::HashSet;
267 /// let mut set = HashSet::new();
268 /// set.insert("a".to_string());
269 /// set.insert("b".to_string());
271 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
272 /// let v: Vec<String> = set.into_iter().collect();
274 /// // Will print in an arbitrary order.
275 /// for x in v.iter() {
276 /// println!("{}", x);
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;
284 IntoIter { iter: self.map.into_iter().map(first) }
287 /// Visit the values representing the difference.
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();
296 /// // Can be seen as `a - b`.
297 /// for x in a.difference(&b) {
298 /// println!("{}", x); // Print 1
301 /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
302 /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
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());
310 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
317 /// Visit the values representing the symmetric difference.
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();
326 /// // Print 1, 4 in arbitrary order.
327 /// for x in a.symmetric_difference(&b) {
328 /// println!("{}", x);
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();
334 /// assert_eq!(diff1, diff2);
335 /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
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)) }
343 /// Visit the values representing the intersection.
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();
352 /// // Print 2, 3 in arbitrary order.
353 /// for x in a.intersection(&b) {
354 /// println!("{}", x);
357 /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
358 /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
361 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
368 /// Visit the values representing the union.
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();
377 /// // Print 1, 2, 3, 4 in arbitrary order.
378 /// for x in a.union(&b) {
379 /// println!("{}", x);
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());
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)) }
390 /// Return the number of elements in the set
395 /// use std::collections::HashSet;
397 /// let mut v = HashSet::new();
398 /// assert_eq!(v.len(), 0);
400 /// assert_eq!(v.len(), 1);
403 pub fn len(&self) -> uint { self.map.len() }
405 /// Returns true if the set contains no elements
410 /// use std::collections::HashSet;
412 /// let mut v = HashSet::new();
413 /// assert!(v.is_empty());
415 /// assert!(!v.is_empty());
418 pub fn is_empty(&self) -> bool { self.map.len() == 0 }
420 /// Clears the set, returning all elements in an iterator.
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
427 Drain { iter: self.map.drain().map(first) }
430 /// Clears the set, removing all values.
435 /// use std::collections::HashSet;
437 /// let mut v = HashSet::new();
440 /// assert!(v.is_empty());
443 pub fn clear(&mut self) { self.map.clear() }
445 /// Returns `true` if the set contains a value.
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
454 /// use std::collections::HashSet;
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);
461 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
462 where Q: BorrowFrom<T> + Hash<H> + Eq
464 self.map.contains_key(value)
467 /// Returns `true` if the set has no elements in common with `other`.
468 /// This is equivalent to checking for an empty intersection.
473 /// use std::collections::HashSet;
475 /// let a: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
476 /// let mut b: HashSet<uint> = HashSet::new();
478 /// assert_eq!(a.is_disjoint(&b), true);
480 /// assert_eq!(a.is_disjoint(&b), true);
482 /// assert_eq!(a.is_disjoint(&b), false);
485 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
486 self.iter().all(|v| !other.contains(v))
489 /// Returns `true` if the set is a subset of another.
494 /// use std::collections::HashSet;
496 /// let sup: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
497 /// let mut set: HashSet<uint> = HashSet::new();
499 /// assert_eq!(set.is_subset(&sup), true);
501 /// assert_eq!(set.is_subset(&sup), true);
503 /// assert_eq!(set.is_subset(&sup), false);
506 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
507 self.iter().all(|v| other.contains(v))
510 /// Returns `true` if the set is a superset of another.
515 /// use std::collections::HashSet;
517 /// let sub: HashSet<uint> = [1, 2].iter().map(|&x| x).collect();
518 /// let mut set: HashSet<uint> = HashSet::new();
520 /// assert_eq!(set.is_superset(&sub), false);
524 /// assert_eq!(set.is_superset(&sub), false);
527 /// assert_eq!(set.is_superset(&sub), true);
531 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
532 other.is_subset(self)
535 /// Adds a value to the set. Returns `true` if the value was not already
536 /// present in the set.
541 /// use std::collections::HashSet;
543 /// let mut set = HashSet::new();
545 /// assert_eq!(set.insert(2u), true);
546 /// assert_eq!(set.insert(2), false);
547 /// assert_eq!(set.len(), 1);
550 pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
552 /// Removes a value from the set. Returns `true` if the value was
553 /// present in the set.
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
562 /// use std::collections::HashSet;
564 /// let mut set = HashSet::new();
567 /// assert_eq!(set.remove(&2), true);
568 /// assert_eq!(set.remove(&2), false);
571 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
572 where Q: BorrowFrom<T> + Hash<H> + Eq
574 self.map.remove(value).is_some()
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>
584 fn eq(&self, other: &HashSet<T, S>) -> bool {
585 if self.len() != other.len() { return false; }
587 self.iter().all(|key| other.contains(key))
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>
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>
604 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
605 try!(write!(f, "HashSet {{"));
607 for (i, x) in self.iter().enumerate() {
608 if i != 0 { try!(write!(f, ", ")); }
609 try!(write!(f, "{:?}", *x));
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>
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());
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>
636 fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) {
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>
650 fn default() -> HashSet<T, S> {
651 HashSet::with_hash_state(Default::default())
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>
661 type Output = HashSet<T, S>;
663 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
668 /// use std::collections::HashSet;
670 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
671 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
673 /// let set: HashSet<int> = &a | &b;
676 /// let expected = [1, 2, 3, 4, 5];
677 /// for x in set.iter() {
678 /// assert!(expected.contains(x));
681 /// assert_eq!(i, expected.len());
683 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
684 self.union(rhs).cloned().collect()
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>
694 type Output = HashSet<T, S>;
696 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
701 /// use std::collections::HashSet;
703 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
704 /// let b: HashSet<int> = vec![2, 3, 4].into_iter().collect();
706 /// let set: HashSet<int> = &a & &b;
709 /// let expected = [2, 3];
710 /// for x in set.iter() {
711 /// assert!(expected.contains(x));
714 /// assert_eq!(i, expected.len());
716 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
717 self.intersection(rhs).cloned().collect()
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>
727 type Output = HashSet<T, S>;
729 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
734 /// use std::collections::HashSet;
736 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
737 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
739 /// let set: HashSet<int> = &a ^ &b;
742 /// let expected = [1, 2, 4, 5];
743 /// for x in set.iter() {
744 /// assert!(expected.contains(x));
747 /// assert_eq!(i, expected.len());
749 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
750 self.symmetric_difference(rhs).cloned().collect()
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>
760 type Output = HashSet<T, S>;
762 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
767 /// use std::collections::HashSet;
769 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
770 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
772 /// let set: HashSet<int> = &a - &b;
775 /// let expected = [1, 2];
776 /// for x in set.iter() {
777 /// assert!(expected.contains(x));
780 /// assert_eq!(i, expected.len());
782 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
783 self.difference(rhs).cloned().collect()
789 pub struct Iter<'a, K: 'a> {
790 iter: Keys<'a, K, ()>
793 /// HashSet move iterator
795 pub struct IntoIter<K> {
796 iter: Map<(K, ()), K, map::IntoIter<K, ()>, fn((K, ())) -> K>
799 /// HashSet drain iterator
801 pub struct Drain<'a, K: 'a> {
802 iter: Map<(K, ()), K, map::Drain<'a, K, ()>, fn((K, ())) -> K>,
805 /// Intersection iterator
807 pub struct Intersection<'a, T: 'a, S: 'a> {
808 // iterator of the first set
811 other: &'a HashSet<T, S>,
814 /// Difference iterator
816 pub struct Difference<'a, T: 'a, S: 'a> {
817 // iterator of the first set
820 other: &'a HashSet<T, S>,
823 /// Symmetric difference iterator.
825 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
826 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>
829 /// Set union iterator.
831 pub struct Union<'a, T: 'a, S: 'a> {
832 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>
836 impl<'a, K> Iterator for Iter<'a, K> {
839 fn next(&mut self) -> Option<&'a K> { self.iter.next() }
840 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
843 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
844 fn len(&self) -> usize { self.iter.len() }
848 impl<K> Iterator for IntoIter<K> {
851 fn next(&mut self) -> Option<K> { self.iter.next() }
852 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
855 impl<K> ExactSizeIterator for IntoIter<K> {
856 fn len(&self) -> usize { self.iter.len() }
860 impl<'a, K> Iterator for Drain<'a, K> {
863 fn next(&mut self) -> Option<K> { self.iter.next() }
864 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
867 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
868 fn len(&self) -> usize { self.iter.len() }
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>
879 fn next(&mut self) -> Option<&'a T> {
881 match self.iter.next() {
883 Some(elt) => if self.other.contains(elt) {
890 fn size_hint(&self) -> (usize, Option<usize>) {
891 let (_, upper) = self.iter.size_hint();
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>
904 fn next(&mut self) -> Option<&'a T> {
906 match self.iter.next() {
908 Some(elt) => if !self.other.contains(elt) {
915 fn size_hint(&self) -> (usize, Option<usize>) {
916 let (_, upper) = self.iter.size_hint();
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>
929 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
930 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
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>
941 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
942 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
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));
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));
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));
989 assert!(!a.is_subset(&b));
990 assert!(!a.is_superset(&b));
991 assert!(!b.is_subset(&a));
992 assert!(!b.is_superset(&a));
994 assert!(b.insert(5));
996 assert!(a.is_subset(&b));
997 assert!(!a.is_superset(&b));
998 assert!(!b.is_subset(&a));
999 assert!(b.is_superset(&a));
1004 let mut a = HashSet::new();
1005 for i in range(0u, 32) {
1006 assert!(a.insert(i));
1008 let mut observed: u32 = 0;
1010 observed |= 1 << *k;
1012 assert_eq!(observed, 0xFFFF_FFFF);
1016 fn test_intersection() {
1017 let mut a = HashSet::new();
1018 let mut b = HashSet::new();
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));
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));
1037 let expected = [3, 5, 11, 77];
1038 for x in a.intersection(&b) {
1039 assert!(expected.contains(x));
1042 assert_eq!(i, expected.len());
1046 fn test_difference() {
1047 let mut a = HashSet::new();
1048 let mut b = HashSet::new();
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));
1056 assert!(b.insert(3i));
1057 assert!(b.insert(9));
1060 let expected = [1, 5, 11];
1061 for x in a.difference(&b) {
1062 assert!(expected.contains(x));
1065 assert_eq!(i, expected.len());
1069 fn test_symmetric_difference() {
1070 let mut a = HashSet::new();
1071 let mut b = HashSet::new();
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));
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));
1086 let expected = [-2, 1, 5, 11, 14, 22];
1087 for x in a.symmetric_difference(&b) {
1088 assert!(expected.contains(x));
1091 assert_eq!(i, expected.len());
1096 let mut a = HashSet::new();
1097 let mut b = HashSet::new();
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));
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));
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));
1121 assert_eq!(i, expected.len());
1125 fn test_from_iter() {
1126 let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
1128 let set: HashSet<int> = xs.iter().map(|&x| x).collect();
1130 for x in xs.iter() {
1131 assert!(set.contains(x));
1136 fn test_move_iter() {
1138 let mut hs = HashSet::new();
1146 let v = hs.into_iter().collect::<Vec<char>>();
1147 assert!(['a', 'b'] == v || ['b', 'a'] == v);
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();
1160 let mut s2 = HashSet::new();
1174 let mut set: HashSet<int> = HashSet::new();
1175 let empty: HashSet<int> = HashSet::new();
1180 let set_str = format!("{:?}", set);
1182 assert!(set_str == "HashSet {1i, 2i}" || set_str == "HashSet {2i, 1i}");
1183 assert_eq!(format!("{:?}", empty), "HashSet {}");
1187 fn test_trivial_drain() {
1188 let mut s = HashSet::<int>::new();
1189 for _ in s.drain() {}
1190 assert!(s.is_empty());
1193 let mut s = HashSet::<int>::new();
1195 assert!(s.is_empty());
1200 let mut s: HashSet<int> = range(1, 100).collect();
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);
1208 let mut d = s.drain();
1209 for (i, x) in d.by_ref().take(50).enumerate() {
1213 assert_eq!(last_i, 49);
1216 for _ in s.iter() { panic!("s should be empty!"); }
1218 // reset to try again.
1219 s.extend(range(1, 100));