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::kinds::Sized;
20 use hash::{Hash, Hasher, RandomSipHasher};
21 use iter::{Iterator, IteratorExt, FromIterator, Map, Chain, Extend};
22 use ops::{BitOr, BitAnd, BitXor, Sub};
23 use option::Option::{Some, None, self};
25 // NOTE: for old macros; remove after the next snapshot
26 #[cfg(stage0)] use result::Result::{Ok, Err};
28 use super::map::{self, HashMap, Keys, INITIAL_CAPACITY};
30 // Future Optimization (FIXME!)
31 // =============================
33 // Iteration over zero sized values is a noop. There is no need
34 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
35 // to get rid of it properly.
37 /// An implementation of a hash set using the underlying representation of a
38 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
39 /// requires that the elements implement the `Eq` and `Hash` traits.
44 /// use std::collections::HashSet;
45 /// // Type inference lets us omit an explicit type signature (which
46 /// // would be `HashSet<&str>` in this example).
47 /// let mut books = HashSet::new();
49 /// // Add some books.
50 /// books.insert("A Dance With Dragons");
51 /// books.insert("To Kill a Mockingbird");
52 /// books.insert("The Odyssey");
53 /// books.insert("The Great Gatsby");
55 /// // Check for a specific one.
56 /// if !books.contains(&("The Winds of Winter")) {
57 /// println!("We have {} books, but The Winds of Winter ain't one.",
62 /// books.remove(&"The Odyssey");
64 /// // Iterate over everything.
65 /// for book in books.iter() {
66 /// println!("{}", *book);
70 /// The easiest way to use `HashSet` with a custom type is to derive
71 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
72 /// future be implied by `Eq`.
75 /// use std::collections::HashSet;
76 /// #[derive(Hash, Eq, PartialEq, Show)]
77 /// struct Viking<'a> {
82 /// let mut vikings = HashSet::new();
84 /// vikings.insert(Viking { name: "Einar", power: 9u });
85 /// vikings.insert(Viking { name: "Einar", power: 9u });
86 /// vikings.insert(Viking { name: "Olaf", power: 4u });
87 /// vikings.insert(Viking { name: "Harald", power: 8u });
89 /// // Use derived implementation to print the vikings.
90 /// for x in vikings.iter() {
91 /// println!("{}", x);
96 pub struct HashSet<T, H = RandomSipHasher> {
97 map: HashMap<T, (), H>
100 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
101 /// Create an empty HashSet.
106 /// use std::collections::HashSet;
107 /// let mut set: HashSet<int> = HashSet::new();
111 pub fn new() -> HashSet<T, RandomSipHasher> {
112 HashSet::with_capacity(INITIAL_CAPACITY)
115 /// Create an empty HashSet with space for at least `n` elements in
121 /// use std::collections::HashSet;
122 /// let mut set: HashSet<int> = HashSet::with_capacity(10);
126 pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
127 HashSet { map: HashMap::with_capacity(capacity) }
131 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
132 /// Creates a new empty hash set which will use the given hasher to hash
135 /// The hash set is also created with the default initial capacity.
140 /// use std::collections::HashSet;
141 /// use std::hash::sip::SipHasher;
143 /// let h = SipHasher::new();
144 /// let mut set = HashSet::with_hasher(h);
148 #[unstable = "hasher stuff is unclear"]
149 pub fn with_hasher(hasher: H) -> HashSet<T, H> {
150 HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
153 /// Create an empty HashSet with space for at least `capacity`
154 /// elements in the hash table, using `hasher` to hash the keys.
156 /// Warning: `hasher` is normally randomly generated, and
157 /// is designed to allow `HashSet`s to be resistant to attacks that
158 /// cause many collisions and very poor performance. Setting it
159 /// manually using this function can expose a DoS attack vector.
164 /// use std::collections::HashSet;
165 /// use std::hash::sip::SipHasher;
167 /// let h = SipHasher::new();
168 /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
172 #[unstable = "hasher stuff is unclear"]
173 pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
174 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
177 /// Returns the number of elements the set can hold without reallocating.
182 /// use std::collections::HashSet;
183 /// let set: HashSet<int> = HashSet::with_capacity(100);
184 /// assert!(set.capacity() >= 100);
188 pub fn capacity(&self) -> uint {
192 /// Reserves capacity for at least `additional` more elements to be inserted
193 /// in the `HashSet`. The collection may reserve more space to avoid
194 /// frequent reallocations.
198 /// Panics if the new allocation size overflows `uint`.
203 /// use std::collections::HashSet;
204 /// let mut set: HashSet<int> = HashSet::new();
208 pub fn reserve(&mut self, additional: uint) {
209 self.map.reserve(additional)
212 /// Shrinks the capacity of the set as much as possible. It will drop
213 /// down as much as possible while maintaining the internal rules
214 /// and possibly leaving some space in accordance with the resize policy.
219 /// use std::collections::HashSet;
221 /// let mut set: HashSet<int> = HashSet::with_capacity(100);
224 /// assert!(set.capacity() >= 100);
225 /// set.shrink_to_fit();
226 /// assert!(set.capacity() >= 2);
229 pub fn shrink_to_fit(&mut self) {
230 self.map.shrink_to_fit()
233 /// An iterator visiting all elements in arbitrary order.
234 /// Iterator element type is &'a T.
239 /// use std::collections::HashSet;
240 /// let mut set = HashSet::new();
244 /// // Will print in an arbitrary order.
245 /// for x in set.iter() {
246 /// println!("{}", x);
250 pub fn iter(&self) -> Iter<T> {
251 Iter { iter: self.map.keys() }
254 /// Creates a consuming iterator, that is, one that moves each value out
255 /// of the set in arbitrary order. The set cannot be used after calling
261 /// use std::collections::HashSet;
262 /// let mut set = HashSet::new();
263 /// set.insert("a".to_string());
264 /// set.insert("b".to_string());
266 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
267 /// let v: Vec<String> = set.into_iter().collect();
269 /// // Will print in an arbitrary order.
270 /// for x in v.iter() {
271 /// println!("{}", x);
275 pub fn into_iter(self) -> IntoIter<T> {
276 fn first<A, B>((a, _): (A, B)) -> A { a }
277 let first: fn((T, ())) -> T = first;
279 IntoIter { iter: self.map.into_iter().map(first) }
282 /// Visit the values representing the difference.
287 /// use std::collections::HashSet;
288 /// let a: HashSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
289 /// let b: HashSet<int> = [4, 2, 3, 4].iter().map(|&x| x).collect();
291 /// // Can be seen as `a - b`.
292 /// for x in a.difference(&b) {
293 /// println!("{}", x); // Print 1
296 /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
297 /// assert_eq!(diff, [1].iter().map(|&x| x).collect());
299 /// // Note that difference is not symmetric,
300 /// // and `b - a` means something else:
301 /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
302 /// assert_eq!(diff, [4].iter().map(|&x| x).collect());
305 pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> Difference<'a, T, H> {
312 /// Visit the values representing the symmetric difference.
317 /// use std::collections::HashSet;
318 /// let a: HashSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
319 /// let b: HashSet<int> = [4, 2, 3, 4].iter().map(|&x| x).collect();
321 /// // Print 1, 4 in arbitrary order.
322 /// for x in a.symmetric_difference(&b) {
323 /// println!("{}", x);
326 /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
327 /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
329 /// assert_eq!(diff1, diff2);
330 /// assert_eq!(diff1, [1, 4].iter().map(|&x| x).collect());
333 pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
334 -> SymmetricDifference<'a, T, H> {
335 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
338 /// Visit the values representing the intersection.
343 /// use std::collections::HashSet;
344 /// let a: HashSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
345 /// let b: HashSet<int> = [4, 2, 3, 4].iter().map(|&x| x).collect();
347 /// // Print 2, 3 in arbitrary order.
348 /// for x in a.intersection(&b) {
349 /// println!("{}", x);
352 /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
353 /// assert_eq!(diff, [2, 3].iter().map(|&x| x).collect());
356 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>) -> Intersection<'a, T, H> {
363 /// Visit the values representing the union.
368 /// use std::collections::HashSet;
369 /// let a: HashSet<int> = [1, 2, 3].iter().map(|&x| x).collect();
370 /// let b: HashSet<int> = [4, 2, 3, 4].iter().map(|&x| x).collect();
372 /// // Print 1, 2, 3, 4 in arbitrary order.
373 /// for x in a.union(&b) {
374 /// println!("{}", x);
377 /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
378 /// assert_eq!(diff, [1, 2, 3, 4].iter().map(|&x| x).collect());
381 pub fn union<'a>(&'a self, other: &'a HashSet<T, H>) -> Union<'a, T, H> {
382 Union { iter: self.iter().chain(other.difference(self)) }
385 /// Return the number of elements in the set
390 /// use std::collections::HashSet;
392 /// let mut v = HashSet::new();
393 /// assert_eq!(v.len(), 0);
395 /// assert_eq!(v.len(), 1);
398 pub fn len(&self) -> uint { self.map.len() }
400 /// Returns true if the set contains no elements
405 /// use std::collections::HashSet;
407 /// let mut v = HashSet::new();
408 /// assert!(v.is_empty());
410 /// assert!(!v.is_empty());
413 pub fn is_empty(&self) -> bool { self.map.len() == 0 }
415 /// Clears the set, returning all elements in an iterator.
417 #[unstable = "matches collection reform specification, waiting for dust to settle"]
418 pub fn drain(&mut self) -> Drain<T> {
419 fn first<A, B>((a, _): (A, B)) -> A { a }
420 let first: fn((T, ())) -> T = first; // coerce to fn pointer
422 Drain { iter: self.map.drain().map(first) }
425 /// Clears the set, removing all values.
430 /// use std::collections::HashSet;
432 /// let mut v = HashSet::new();
435 /// assert!(v.is_empty());
438 pub fn clear(&mut self) { self.map.clear() }
440 /// Returns `true` if the set contains a value.
442 /// The value may be any borrowed form of the set's value type, but
443 /// `Hash` and `Eq` on the borrowed form *must* match those for
449 /// use std::collections::HashSet;
451 /// let set: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
452 /// assert_eq!(set.contains(&1), true);
453 /// assert_eq!(set.contains(&4), false);
456 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
457 where Q: BorrowFrom<T> + Hash<S> + Eq
459 self.map.contains_key(value)
462 /// Returns `true` if the set has no elements in common with `other`.
463 /// This is equivalent to checking for an empty intersection.
468 /// use std::collections::HashSet;
470 /// let a: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
471 /// let mut b: HashSet<uint> = HashSet::new();
473 /// assert_eq!(a.is_disjoint(&b), true);
475 /// assert_eq!(a.is_disjoint(&b), true);
477 /// assert_eq!(a.is_disjoint(&b), false);
480 pub fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
481 self.iter().all(|v| !other.contains(v))
484 /// Returns `true` if the set is a subset of another.
489 /// use std::collections::HashSet;
491 /// let sup: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
492 /// let mut set: HashSet<uint> = HashSet::new();
494 /// assert_eq!(set.is_subset(&sup), true);
496 /// assert_eq!(set.is_subset(&sup), true);
498 /// assert_eq!(set.is_subset(&sup), false);
501 pub fn is_subset(&self, other: &HashSet<T, H>) -> bool {
502 self.iter().all(|v| other.contains(v))
505 /// Returns `true` if the set is a superset of another.
510 /// use std::collections::HashSet;
512 /// let sub: HashSet<uint> = [1, 2].iter().map(|&x| x).collect();
513 /// let mut set: HashSet<uint> = HashSet::new();
515 /// assert_eq!(set.is_superset(&sub), false);
519 /// assert_eq!(set.is_superset(&sub), false);
522 /// assert_eq!(set.is_superset(&sub), true);
526 pub fn is_superset(&self, other: &HashSet<T, H>) -> bool {
527 other.is_subset(self)
530 /// Adds a value to the set. Returns `true` if the value was not already
531 /// present in the set.
536 /// use std::collections::HashSet;
538 /// let mut set = HashSet::new();
540 /// assert_eq!(set.insert(2u), true);
541 /// assert_eq!(set.insert(2), false);
542 /// assert_eq!(set.len(), 1);
545 pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
547 /// Removes a value from the set. Returns `true` if the value was
548 /// present in the set.
550 /// The value may be any borrowed form of the set's value type, but
551 /// `Hash` and `Eq` on the borrowed form *must* match those for
557 /// use std::collections::HashSet;
559 /// let mut set = HashSet::new();
562 /// assert_eq!(set.remove(&2), true);
563 /// assert_eq!(set.remove(&2), false);
566 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
567 where Q: BorrowFrom<T> + Hash<S> + Eq
569 self.map.remove(value).is_some()
574 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
575 fn eq(&self, other: &HashSet<T, H>) -> bool {
576 if self.len() != other.len() { return false; }
578 self.iter().all(|key| other.contains(key))
583 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
586 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
587 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
588 try!(write!(f, "{{"));
590 for (i, x) in self.iter().enumerate() {
591 if i != 0 { try!(write!(f, ", ")); }
592 try!(write!(f, "{}", *x));
600 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
601 fn from_iter<I: Iterator<Item=T>>(iter: I) -> HashSet<T, H> {
602 let lower = iter.size_hint().0;
603 let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
610 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Extend<T> for HashSet<T, H> {
611 fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) {
619 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
621 fn default() -> HashSet<T, H> {
622 HashSet::with_hasher(Default::default())
627 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
628 BitOr<&'b HashSet<T, H>> for &'a HashSet<T, H> {
629 type Output = HashSet<T, H>;
631 /// Returns the union of `self` and `rhs` as a new `HashSet<T, H>`.
636 /// use std::collections::HashSet;
638 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
639 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
641 /// let set: HashSet<int> = &a | &b;
644 /// let expected = [1, 2, 3, 4, 5];
645 /// for x in set.iter() {
646 /// assert!(expected.contains(x));
649 /// assert_eq!(i, expected.len());
651 fn bitor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
652 self.union(rhs).cloned().collect()
657 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
658 BitAnd<&'b HashSet<T, H>> for &'a HashSet<T, H> {
659 type Output = HashSet<T, H>;
661 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, H>`.
666 /// use std::collections::HashSet;
668 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
669 /// let b: HashSet<int> = vec![2, 3, 4].into_iter().collect();
671 /// let set: HashSet<int> = &a & &b;
674 /// let expected = [2, 3];
675 /// for x in set.iter() {
676 /// assert!(expected.contains(x));
679 /// assert_eq!(i, expected.len());
681 fn bitand(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
682 self.intersection(rhs).cloned().collect()
687 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
688 BitXor<&'b HashSet<T, H>> for &'a HashSet<T, H> {
689 type Output = HashSet<T, H>;
691 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, H>`.
696 /// use std::collections::HashSet;
698 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
699 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
701 /// let set: HashSet<int> = &a ^ &b;
704 /// let expected = [1, 2, 4, 5];
705 /// for x in set.iter() {
706 /// assert!(expected.contains(x));
709 /// assert_eq!(i, expected.len());
711 fn bitxor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
712 self.symmetric_difference(rhs).cloned().collect()
717 impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default>
718 Sub<&'b HashSet<T, H>> for &'a HashSet<T, H> {
719 type Output = HashSet<T, H>;
721 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, H>`.
726 /// use std::collections::HashSet;
728 /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
729 /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
731 /// let set: HashSet<int> = &a - &b;
734 /// let expected = [1, 2];
735 /// for x in set.iter() {
736 /// assert!(expected.contains(x));
739 /// assert_eq!(i, expected.len());
741 fn sub(self, rhs: &HashSet<T, H>) -> HashSet<T, H> {
742 self.difference(rhs).cloned().collect()
748 pub struct Iter<'a, K: 'a> {
749 iter: Keys<'a, K, ()>
752 /// HashSet move iterator
754 pub struct IntoIter<K> {
755 iter: Map<(K, ()), K, map::IntoIter<K, ()>, fn((K, ())) -> K>
758 /// HashSet drain iterator
760 pub struct Drain<'a, K: 'a> {
761 iter: Map<(K, ()), K, map::Drain<'a, K, ()>, fn((K, ())) -> K>,
764 /// Intersection iterator
766 pub struct Intersection<'a, T: 'a, H: 'a> {
767 // iterator of the first set
770 other: &'a HashSet<T, H>,
773 /// Difference iterator
775 pub struct Difference<'a, T: 'a, H: 'a> {
776 // iterator of the first set
779 other: &'a HashSet<T, H>,
782 /// Symmetric difference iterator.
784 pub struct SymmetricDifference<'a, T: 'a, H: 'a> {
785 iter: Chain<Difference<'a, T, H>, Difference<'a, T, H>>
788 /// Set union iterator.
790 pub struct Union<'a, T: 'a, H: 'a> {
791 iter: Chain<Iter<'a, T>, Difference<'a, T, H>>
795 impl<'a, K> Iterator for Iter<'a, K> {
798 fn next(&mut self) -> Option<&'a K> { self.iter.next() }
799 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
803 impl<K> Iterator for IntoIter<K> {
806 fn next(&mut self) -> Option<K> { self.iter.next() }
807 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
811 impl<'a, K: 'a> Iterator for Drain<'a, K> {
814 fn next(&mut self) -> Option<K> { self.iter.next() }
815 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
819 impl<'a, T, S, H> Iterator for Intersection<'a, T, H>
820 where T: Eq + Hash<S>, H: Hasher<S>
824 fn next(&mut self) -> Option<&'a T> {
826 match self.iter.next() {
828 Some(elt) => if self.other.contains(elt) {
835 fn size_hint(&self) -> (uint, Option<uint>) {
836 let (_, upper) = self.iter.size_hint();
842 impl<'a, T, S, H> Iterator for Difference<'a, T, H>
843 where T: Eq + Hash<S>, H: Hasher<S>
847 fn next(&mut self) -> Option<&'a T> {
849 match self.iter.next() {
851 Some(elt) => if !self.other.contains(elt) {
858 fn size_hint(&self) -> (uint, Option<uint>) {
859 let (_, upper) = self.iter.size_hint();
865 impl<'a, T, S, H> Iterator for SymmetricDifference<'a, T, H>
866 where T: Eq + Hash<S>, H: Hasher<S>
870 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
871 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
875 impl<'a, T, S, H> Iterator for Union<'a, T, H>
876 where T: Eq + Hash<S>, H: Hasher<S>
880 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
881 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
892 let mut xs = HashSet::new();
893 let mut ys = HashSet::new();
894 assert!(xs.is_disjoint(&ys));
895 assert!(ys.is_disjoint(&xs));
896 assert!(xs.insert(5i));
897 assert!(ys.insert(11i));
898 assert!(xs.is_disjoint(&ys));
899 assert!(ys.is_disjoint(&xs));
900 assert!(xs.insert(7));
901 assert!(xs.insert(19));
902 assert!(xs.insert(4));
903 assert!(ys.insert(2));
904 assert!(ys.insert(-11));
905 assert!(xs.is_disjoint(&ys));
906 assert!(ys.is_disjoint(&xs));
907 assert!(ys.insert(7));
908 assert!(!xs.is_disjoint(&ys));
909 assert!(!ys.is_disjoint(&xs));
913 fn test_subset_and_superset() {
914 let mut a = HashSet::new();
915 assert!(a.insert(0i));
916 assert!(a.insert(5));
917 assert!(a.insert(11));
918 assert!(a.insert(7));
920 let mut b = HashSet::new();
921 assert!(b.insert(0i));
922 assert!(b.insert(7));
923 assert!(b.insert(19));
924 assert!(b.insert(250));
925 assert!(b.insert(11));
926 assert!(b.insert(200));
928 assert!(!a.is_subset(&b));
929 assert!(!a.is_superset(&b));
930 assert!(!b.is_subset(&a));
931 assert!(!b.is_superset(&a));
933 assert!(b.insert(5));
935 assert!(a.is_subset(&b));
936 assert!(!a.is_superset(&b));
937 assert!(!b.is_subset(&a));
938 assert!(b.is_superset(&a));
943 let mut a = HashSet::new();
944 for i in range(0u, 32) {
945 assert!(a.insert(i));
947 let mut observed: u32 = 0;
951 assert_eq!(observed, 0xFFFF_FFFF);
955 fn test_intersection() {
956 let mut a = HashSet::new();
957 let mut b = HashSet::new();
959 assert!(a.insert(11i));
960 assert!(a.insert(1));
961 assert!(a.insert(3));
962 assert!(a.insert(77));
963 assert!(a.insert(103));
964 assert!(a.insert(5));
965 assert!(a.insert(-5));
967 assert!(b.insert(2i));
968 assert!(b.insert(11));
969 assert!(b.insert(77));
970 assert!(b.insert(-9));
971 assert!(b.insert(-42));
972 assert!(b.insert(5));
973 assert!(b.insert(3));
976 let expected = [3, 5, 11, 77];
977 for x in a.intersection(&b) {
978 assert!(expected.contains(x));
981 assert_eq!(i, expected.len());
985 fn test_difference() {
986 let mut a = HashSet::new();
987 let mut b = HashSet::new();
989 assert!(a.insert(1i));
990 assert!(a.insert(3));
991 assert!(a.insert(5));
992 assert!(a.insert(9));
993 assert!(a.insert(11));
995 assert!(b.insert(3i));
996 assert!(b.insert(9));
999 let expected = [1, 5, 11];
1000 for x in a.difference(&b) {
1001 assert!(expected.contains(x));
1004 assert_eq!(i, expected.len());
1008 fn test_symmetric_difference() {
1009 let mut a = HashSet::new();
1010 let mut b = HashSet::new();
1012 assert!(a.insert(1i));
1013 assert!(a.insert(3));
1014 assert!(a.insert(5));
1015 assert!(a.insert(9));
1016 assert!(a.insert(11));
1018 assert!(b.insert(-2i));
1019 assert!(b.insert(3));
1020 assert!(b.insert(9));
1021 assert!(b.insert(14));
1022 assert!(b.insert(22));
1025 let expected = [-2, 1, 5, 11, 14, 22];
1026 for x in a.symmetric_difference(&b) {
1027 assert!(expected.contains(x));
1030 assert_eq!(i, expected.len());
1035 let mut a = HashSet::new();
1036 let mut b = HashSet::new();
1038 assert!(a.insert(1i));
1039 assert!(a.insert(3));
1040 assert!(a.insert(5));
1041 assert!(a.insert(9));
1042 assert!(a.insert(11));
1043 assert!(a.insert(16));
1044 assert!(a.insert(19));
1045 assert!(a.insert(24));
1047 assert!(b.insert(-2i));
1048 assert!(b.insert(1));
1049 assert!(b.insert(5));
1050 assert!(b.insert(9));
1051 assert!(b.insert(13));
1052 assert!(b.insert(19));
1055 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1056 for x in a.union(&b) {
1057 assert!(expected.contains(x));
1060 assert_eq!(i, expected.len());
1064 fn test_from_iter() {
1065 let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
1067 let set: HashSet<int> = xs.iter().map(|&x| x).collect();
1069 for x in xs.iter() {
1070 assert!(set.contains(x));
1075 fn test_move_iter() {
1077 let mut hs = HashSet::new();
1085 let v = hs.into_iter().collect::<Vec<char>>();
1086 assert!(['a', 'b'] == v || ['b', 'a'] == v);
1091 // These constants once happened to expose a bug in insert().
1092 // I'm keeping them around to prevent a regression.
1093 let mut s1 = HashSet::new();
1099 let mut s2 = HashSet::new();
1113 let mut set: HashSet<int> = HashSet::new();
1114 let empty: HashSet<int> = HashSet::new();
1119 let set_str = format!("{}", set);
1121 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1122 assert_eq!(format!("{}", empty), "{}");
1126 fn test_trivial_drain() {
1127 let mut s = HashSet::<int>::new();
1128 for _ in s.drain() {}
1129 assert!(s.is_empty());
1132 let mut s = HashSet::<int>::new();
1134 assert!(s.is_empty());
1139 let mut s: HashSet<int> = range(1, 100).collect();
1141 // try this a bunch of times to make sure we don't screw up internal state.
1142 for _ in range(0i, 20) {
1143 assert_eq!(s.len(), 99);
1147 let mut d = s.drain();
1148 for (i, x) in d.by_ref().take(50).enumerate() {
1152 assert_eq!(last_i, 49);
1155 for _ in s.iter() { panic!("s should be empty!"); }
1157 // reset to try again.
1158 s.extend(range(1, 100));