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.
13 use hash::{Hash, BuildHasher};
14 use iter::{Chain, FromIterator, FusedIterator};
15 use ops::{BitOr, BitAnd, BitXor, Sub};
18 use super::map::{self, HashMap, Keys, RandomState};
20 const INITIAL_CAPACITY: usize = 32;
22 // Future Optimization (FIXME!)
23 // =============================
25 // Iteration over zero sized values is a noop. There is no need
26 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
27 // to get rid of it properly.
29 /// An implementation of a hash set using the underlying representation of a
30 /// HashMap where the value is ().
32 /// As with the `HashMap` type, a `HashSet` requires that the elements
33 /// implement the `Eq` and `Hash` traits. This can frequently be achieved by
34 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
35 /// it is important that the following property holds:
38 /// k1 == k2 -> hash(k1) == hash(k2)
41 /// In other words, if two keys are equal, their hashes must be equal.
44 /// It is a logic error for an item to be modified in such a way that the
45 /// item's hash, as determined by the `Hash` trait, or its equality, as
46 /// determined by the `Eq` trait, changes while it is in the set. This is
47 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or
53 /// use std::collections::HashSet;
54 /// // Type inference lets us omit an explicit type signature (which
55 /// // would be `HashSet<&str>` in this example).
56 /// let mut books = HashSet::new();
58 /// // Add some books.
59 /// books.insert("A Dance With Dragons");
60 /// books.insert("To Kill a Mockingbird");
61 /// books.insert("The Odyssey");
62 /// books.insert("The Great Gatsby");
64 /// // Check for a specific one.
65 /// if !books.contains("The Winds of Winter") {
66 /// println!("We have {} books, but The Winds of Winter ain't one.",
71 /// books.remove("The Odyssey");
73 /// // Iterate over everything.
74 /// for book in &books {
75 /// println!("{}", book);
79 /// The easiest way to use `HashSet` with a custom type is to derive
80 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
81 /// future be implied by `Eq`.
84 /// use std::collections::HashSet;
85 /// #[derive(Hash, Eq, PartialEq, Debug)]
86 /// struct Viking<'a> {
91 /// let mut vikings = HashSet::new();
93 /// vikings.insert(Viking { name: "Einar", power: 9 });
94 /// vikings.insert(Viking { name: "Einar", power: 9 });
95 /// vikings.insert(Viking { name: "Olaf", power: 4 });
96 /// vikings.insert(Viking { name: "Harald", power: 8 });
98 /// // Use derived implementation to print the vikings.
99 /// for x in &vikings {
100 /// println!("{:?}", x);
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub struct HashSet<T, S = RandomState> {
106 map: HashMap<T, (), S>
109 impl<T: Hash + Eq> HashSet<T, RandomState> {
110 /// Creates an empty HashSet.
115 /// use std::collections::HashSet;
116 /// let mut set: HashSet<i32> = HashSet::new();
119 #[stable(feature = "rust1", since = "1.0.0")]
120 pub fn new() -> HashSet<T, RandomState> {
121 HashSet::with_capacity(INITIAL_CAPACITY)
124 /// Creates an empty HashSet with space for at least `n` elements in
130 /// use std::collections::HashSet;
131 /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
136 HashSet { map: HashMap::with_capacity(capacity) }
140 impl<T, S> HashSet<T, S>
141 where T: Eq + Hash, S: BuildHasher
143 /// Creates a new empty hash set which will use the given hasher to hash
146 /// The hash set is also created with the default initial capacity.
148 /// Warning: `hasher` is normally randomly generated, and
149 /// is designed to allow `HashSet`s to be resistant to attacks that
150 /// cause many collisions and very poor performance. Setting it
151 /// manually using this function can expose a DoS attack vector.
156 /// use std::collections::HashSet;
157 /// use std::collections::hash_map::RandomState;
159 /// let s = RandomState::new();
160 /// let mut set = HashSet::with_hasher(s);
164 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
165 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
166 HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
169 /// Creates an empty HashSet with space for at least `capacity`
170 /// elements in the hash table, using `hasher` to hash the keys.
172 /// Warning: `hasher` is normally randomly generated, and
173 /// is designed to allow `HashSet`s to be resistant to attacks that
174 /// cause many collisions and very poor performance. Setting it
175 /// manually using this function can expose a DoS attack vector.
180 /// use std::collections::HashSet;
181 /// use std::collections::hash_map::RandomState;
183 /// let s = RandomState::new();
184 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
188 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
189 pub fn with_capacity_and_hasher(capacity: usize, hasher: S)
192 map: HashMap::with_capacity_and_hasher(capacity, hasher),
196 /// Returns a reference to the set's hasher.
197 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
198 pub fn hasher(&self) -> &S {
202 /// Returns the number of elements the set can hold without reallocating.
207 /// use std::collections::HashSet;
208 /// let set: HashSet<i32> = HashSet::with_capacity(100);
209 /// assert!(set.capacity() >= 100);
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn capacity(&self) -> usize {
217 /// Reserves capacity for at least `additional` more elements to be inserted
218 /// in the `HashSet`. The collection may reserve more space to avoid
219 /// frequent reallocations.
223 /// Panics if the new allocation size overflows `usize`.
228 /// use std::collections::HashSet;
229 /// let mut set: HashSet<i32> = HashSet::new();
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn reserve(&mut self, additional: usize) {
234 self.map.reserve(additional)
237 /// Shrinks the capacity of the set as much as possible. It will drop
238 /// down as much as possible while maintaining the internal rules
239 /// and possibly leaving some space in accordance with the resize policy.
244 /// use std::collections::HashSet;
246 /// let mut set = HashSet::with_capacity(100);
249 /// assert!(set.capacity() >= 100);
250 /// set.shrink_to_fit();
251 /// assert!(set.capacity() >= 2);
253 #[stable(feature = "rust1", since = "1.0.0")]
254 pub fn shrink_to_fit(&mut self) {
255 self.map.shrink_to_fit()
258 /// An iterator visiting all elements in arbitrary order.
259 /// Iterator element type is &'a T.
264 /// use std::collections::HashSet;
265 /// let mut set = HashSet::new();
269 /// // Will print in an arbitrary order.
270 /// for x in set.iter() {
271 /// println!("{}", x);
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn iter(&self) -> Iter<T> {
276 Iter { iter: self.map.keys() }
279 /// Visit the values representing the difference.
284 /// use std::collections::HashSet;
285 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
286 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
288 /// // Can be seen as `a - b`.
289 /// for x in a.difference(&b) {
290 /// println!("{}", x); // Print 1
293 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
294 /// assert_eq!(diff, [1].iter().cloned().collect());
296 /// // Note that difference is not symmetric,
297 /// // and `b - a` means something else:
298 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
299 /// assert_eq!(diff, [4].iter().cloned().collect());
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
309 /// Visit the values representing the symmetric difference.
314 /// use std::collections::HashSet;
315 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
316 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
318 /// // Print 1, 4 in arbitrary order.
319 /// for x in a.symmetric_difference(&b) {
320 /// println!("{}", x);
323 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
324 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
326 /// assert_eq!(diff1, diff2);
327 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>)
331 -> SymmetricDifference<'a, T, S> {
332 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
335 /// Visit the values representing the intersection.
340 /// use std::collections::HashSet;
341 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
342 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
344 /// // Print 2, 3 in arbitrary order.
345 /// for x in a.intersection(&b) {
346 /// println!("{}", x);
349 /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
350 /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
360 /// Visit the values representing the union.
365 /// use std::collections::HashSet;
366 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
367 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
369 /// // Print 1, 2, 3, 4 in arbitrary order.
370 /// for x in a.union(&b) {
371 /// println!("{}", x);
374 /// let union: HashSet<_> = a.union(&b).cloned().collect();
375 /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
379 Union { iter: self.iter().chain(other.difference(self)) }
382 /// Returns the number of elements in the set.
387 /// use std::collections::HashSet;
389 /// let mut v = HashSet::new();
390 /// assert_eq!(v.len(), 0);
392 /// assert_eq!(v.len(), 1);
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn len(&self) -> usize { self.map.len() }
397 /// Returns true if the set contains no elements.
402 /// use std::collections::HashSet;
404 /// let mut v = HashSet::new();
405 /// assert!(v.is_empty());
407 /// assert!(!v.is_empty());
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn is_empty(&self) -> bool { self.map.is_empty() }
412 /// Clears the set, returning all elements in an iterator.
414 #[stable(feature = "drain", since = "1.6.0")]
415 pub fn drain(&mut self) -> Drain<T> {
416 Drain { iter: self.map.drain() }
419 /// Clears the set, removing all values.
424 /// use std::collections::HashSet;
426 /// let mut v = HashSet::new();
429 /// assert!(v.is_empty());
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn clear(&mut self) { self.map.clear() }
434 /// Returns `true` if the set contains a value.
436 /// The value may be any borrowed form of the set's value type, but
437 /// `Hash` and `Eq` on the borrowed form *must* match those for
443 /// use std::collections::HashSet;
445 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
446 /// assert_eq!(set.contains(&1), true);
447 /// assert_eq!(set.contains(&4), false);
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
451 where T: Borrow<Q>, Q: Hash + Eq
453 self.map.contains_key(value)
456 /// Returns a reference to the value in the set, if any, that is equal to the given value.
458 /// The value may be any borrowed form of the set's value type, but
459 /// `Hash` and `Eq` on the borrowed form *must* match those for
461 #[stable(feature = "set_recovery", since = "1.9.0")]
462 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
463 where T: Borrow<Q>, Q: Hash + Eq
465 Recover::get(&self.map, value)
468 /// Returns `true` if the set has no elements in common with `other`.
469 /// This is equivalent to checking for an empty intersection.
474 /// use std::collections::HashSet;
476 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
477 /// let mut b = HashSet::new();
479 /// assert_eq!(a.is_disjoint(&b), true);
481 /// assert_eq!(a.is_disjoint(&b), true);
483 /// assert_eq!(a.is_disjoint(&b), false);
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
487 self.iter().all(|v| !other.contains(v))
490 /// Returns `true` if the set is a subset of another.
495 /// use std::collections::HashSet;
497 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
498 /// let mut set = HashSet::new();
500 /// assert_eq!(set.is_subset(&sup), true);
502 /// assert_eq!(set.is_subset(&sup), true);
504 /// assert_eq!(set.is_subset(&sup), false);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
508 self.iter().all(|v| other.contains(v))
511 /// Returns `true` if the set is a superset of another.
516 /// use std::collections::HashSet;
518 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
519 /// let mut set = HashSet::new();
521 /// assert_eq!(set.is_superset(&sub), false);
525 /// assert_eq!(set.is_superset(&sub), false);
528 /// assert_eq!(set.is_superset(&sub), true);
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
533 other.is_subset(self)
536 /// Adds a value to the set.
538 /// If the set did not have this value present, `true` is returned.
540 /// If the set did have this value present, `false` is returned.
545 /// use std::collections::HashSet;
547 /// let mut set = HashSet::new();
549 /// assert_eq!(set.insert(2), true);
550 /// assert_eq!(set.insert(2), false);
551 /// assert_eq!(set.len(), 1);
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
556 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
557 /// one. Returns the replaced value.
558 #[stable(feature = "set_recovery", since = "1.9.0")]
559 pub fn replace(&mut self, value: T) -> Option<T> {
560 Recover::replace(&mut self.map, value)
563 /// Removes a value from the set. Returns `true` if the value was
564 /// present in the set.
566 /// The value may be any borrowed form of the set's value type, but
567 /// `Hash` and `Eq` on the borrowed form *must* match those for
573 /// use std::collections::HashSet;
575 /// let mut set = HashSet::new();
578 /// assert_eq!(set.remove(&2), true);
579 /// assert_eq!(set.remove(&2), false);
581 #[stable(feature = "rust1", since = "1.0.0")]
582 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
583 where T: Borrow<Q>, Q: Hash + Eq
585 self.map.remove(value).is_some()
588 /// Removes and returns the value in the set, if any, that is equal to the given one.
590 /// The value may be any borrowed form of the set's value type, but
591 /// `Hash` and `Eq` on the borrowed form *must* match those for
593 #[stable(feature = "set_recovery", since = "1.9.0")]
594 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
595 where T: Borrow<Q>, Q: Hash + Eq
597 Recover::take(&mut self.map, value)
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl<T, S> PartialEq for HashSet<T, S>
603 where T: Eq + Hash, S: BuildHasher
605 fn eq(&self, other: &HashSet<T, S>) -> bool {
606 if self.len() != other.len() { return false; }
608 self.iter().all(|key| other.contains(key))
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl<T, S> Eq for HashSet<T, S>
614 where T: Eq + Hash, S: BuildHasher
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<T, S> fmt::Debug for HashSet<T, S>
619 where T: Eq + Hash + fmt::Debug,
622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
623 f.debug_set().entries(self.iter()).finish()
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl<T, S> FromIterator<T> for HashSet<T, S>
630 S: BuildHasher + Default,
632 fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> HashSet<T, S> {
633 let iterator = iter.into_iter();
634 let lower = iterator.size_hint().0;
635 let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
636 set.extend(iterator);
641 #[stable(feature = "rust1", since = "1.0.0")]
642 impl<T, S> Extend<T> for HashSet<T, S>
646 fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
653 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
654 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
655 where T: 'a + Eq + Hash + Copy,
658 fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
659 self.extend(iter.into_iter().cloned());
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl<T, S> Default for HashSet<T, S>
666 S: BuildHasher + Default,
668 fn default() -> HashSet<T, S> {
669 HashSet::with_hasher(Default::default())
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
675 where T: Eq + Hash + Clone,
676 S: BuildHasher + Default,
678 type Output = HashSet<T, S>;
680 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
685 /// use std::collections::HashSet;
687 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
688 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
690 /// let set = &a | &b;
693 /// let expected = [1, 2, 3, 4, 5];
695 /// assert!(expected.contains(x));
698 /// assert_eq!(i, expected.len());
700 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
701 self.union(rhs).cloned().collect()
705 #[stable(feature = "rust1", since = "1.0.0")]
706 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
707 where T: Eq + Hash + Clone,
708 S: BuildHasher + Default,
710 type Output = HashSet<T, S>;
712 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
717 /// use std::collections::HashSet;
719 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
720 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
722 /// let set = &a & &b;
725 /// let expected = [2, 3];
727 /// assert!(expected.contains(x));
730 /// assert_eq!(i, expected.len());
732 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
733 self.intersection(rhs).cloned().collect()
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
739 where T: Eq + Hash + Clone,
740 S: BuildHasher + Default,
742 type Output = HashSet<T, S>;
744 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
749 /// use std::collections::HashSet;
751 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
752 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
754 /// let set = &a ^ &b;
757 /// let expected = [1, 2, 4, 5];
759 /// assert!(expected.contains(x));
762 /// assert_eq!(i, expected.len());
764 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
765 self.symmetric_difference(rhs).cloned().collect()
769 #[stable(feature = "rust1", since = "1.0.0")]
770 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
771 where T: Eq + Hash + Clone,
772 S: BuildHasher + Default,
774 type Output = HashSet<T, S>;
776 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
781 /// use std::collections::HashSet;
783 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
784 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
786 /// let set = &a - &b;
789 /// let expected = [1, 2];
791 /// assert!(expected.contains(x));
794 /// assert_eq!(i, expected.len());
796 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
797 self.difference(rhs).cloned().collect()
802 #[stable(feature = "rust1", since = "1.0.0")]
803 pub struct Iter<'a, K: 'a> {
804 iter: Keys<'a, K, ()>
807 /// HashSet move iterator
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub struct IntoIter<K> {
810 iter: map::IntoIter<K, ()>
813 /// HashSet drain iterator
814 #[stable(feature = "rust1", since = "1.0.0")]
815 pub struct Drain<'a, K: 'a> {
816 iter: map::Drain<'a, K, ()>,
819 /// Intersection iterator
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub struct Intersection<'a, T: 'a, S: 'a> {
822 // iterator of the first set
825 other: &'a HashSet<T, S>,
828 /// Difference iterator
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub struct Difference<'a, T: 'a, S: 'a> {
831 // iterator of the first set
834 other: &'a HashSet<T, S>,
837 /// Symmetric difference iterator.
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
840 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>
843 /// Set union iterator.
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub struct Union<'a, T: 'a, S: 'a> {
846 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
851 where T: Eq + Hash, S: BuildHasher
854 type IntoIter = Iter<'a, T>;
856 fn into_iter(self) -> Iter<'a, T> {
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<T, S> IntoIterator for HashSet<T, S>
867 type IntoIter = IntoIter<T>;
869 /// Creates a consuming iterator, that is, one that moves each value out
870 /// of the set in arbitrary order. The set cannot be used after calling
876 /// use std::collections::HashSet;
877 /// let mut set = HashSet::new();
878 /// set.insert("a".to_string());
879 /// set.insert("b".to_string());
881 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
882 /// let v: Vec<String> = set.into_iter().collect();
884 /// // Will print in an arbitrary order.
886 /// println!("{}", x);
889 fn into_iter(self) -> IntoIter<T> {
890 IntoIter { iter: self.map.into_iter() }
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<'a, K> Clone for Iter<'a, K> {
896 fn clone(&self) -> Iter<'a, K> { Iter { iter: self.iter.clone() } }
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a, K> Iterator for Iter<'a, K> {
902 fn next(&mut self) -> Option<&'a K> { self.iter.next() }
903 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
907 fn len(&self) -> usize { self.iter.len() }
909 #[unstable(feature = "fused", issue = "35602")]
910 impl<'a, K> FusedIterator for Iter<'a, K> {}
912 #[stable(feature = "rust1", since = "1.0.0")]
913 impl<K> Iterator for IntoIter<K> {
916 fn next(&mut self) -> Option<K> { self.iter.next().map(|(k, _)| k) }
917 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl<K> ExactSizeIterator for IntoIter<K> {
921 fn len(&self) -> usize { self.iter.len() }
923 #[unstable(feature = "fused", issue = "35602")]
924 impl<K> FusedIterator for IntoIter<K> {}
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl<'a, K> Iterator for Drain<'a, K> {
930 fn next(&mut self) -> Option<K> { self.iter.next().map(|(k, _)| k) }
931 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
935 fn len(&self) -> usize { self.iter.len() }
937 #[unstable(feature = "fused", issue = "35602")]
938 impl<'a, K> FusedIterator for Drain<'a, K> {}
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl<'a, T, S> Clone for Intersection<'a, T, S> {
942 fn clone(&self) -> Intersection<'a, T, S> {
943 Intersection { iter: self.iter.clone(), ..*self }
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a, T, S> Iterator for Intersection<'a, T, S>
949 where T: Eq + Hash, S: BuildHasher
953 fn next(&mut self) -> Option<&'a T> {
955 match self.iter.next() {
957 Some(elt) => if self.other.contains(elt) {
964 fn size_hint(&self) -> (usize, Option<usize>) {
965 let (_, upper) = self.iter.size_hint();
970 #[unstable(feature = "fused", issue = "35602")]
971 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
972 where T: Eq + Hash, S: BuildHasher
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<'a, T, S> Clone for Difference<'a, T, S> {
977 fn clone(&self) -> Difference<'a, T, S> {
978 Difference { iter: self.iter.clone(), ..*self }
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<'a, T, S> Iterator for Difference<'a, T, S>
984 where T: Eq + Hash, S: BuildHasher
988 fn next(&mut self) -> Option<&'a T> {
990 match self.iter.next() {
992 Some(elt) => if !self.other.contains(elt) {
999 fn size_hint(&self) -> (usize, Option<usize>) {
1000 let (_, upper) = self.iter.size_hint();
1005 #[unstable(feature = "fused", issue = "35602")]
1006 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1007 where T: Eq + Hash, S: BuildHasher
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1012 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1013 SymmetricDifference { iter: self.iter.clone() }
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1019 where T: Eq + Hash, S: BuildHasher
1023 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
1024 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1027 #[unstable(feature = "fused", issue = "35602")]
1028 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1029 where T: Eq + Hash, S: BuildHasher
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 impl<'a, T, S> Clone for Union<'a, T, S> {
1034 fn clone(&self) -> Union<'a, T, S> { Union { iter: self.iter.clone() } }
1037 #[unstable(feature = "fused", issue = "35602")]
1038 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1039 where T: Eq + Hash, S: BuildHasher
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<'a, T, S> Iterator for Union<'a, T, S>
1044 where T: Eq + Hash, S: BuildHasher
1048 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
1049 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1053 fn assert_covariance() {
1054 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> { v }
1055 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> { v }
1056 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> { v }
1057 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1058 -> Difference<'a, &'new str, RandomState> { v }
1059 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1060 -> SymmetricDifference<'a, &'new str, RandomState> { v }
1061 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1062 -> Intersection<'a, &'new str, RandomState> { v }
1063 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1064 -> Union<'a, &'new str, RandomState> { v }
1065 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> { d }
1073 fn test_disjoint() {
1074 let mut xs = HashSet::new();
1075 let mut ys = HashSet::new();
1076 assert!(xs.is_disjoint(&ys));
1077 assert!(ys.is_disjoint(&xs));
1078 assert!(xs.insert(5));
1079 assert!(ys.insert(11));
1080 assert!(xs.is_disjoint(&ys));
1081 assert!(ys.is_disjoint(&xs));
1082 assert!(xs.insert(7));
1083 assert!(xs.insert(19));
1084 assert!(xs.insert(4));
1085 assert!(ys.insert(2));
1086 assert!(ys.insert(-11));
1087 assert!(xs.is_disjoint(&ys));
1088 assert!(ys.is_disjoint(&xs));
1089 assert!(ys.insert(7));
1090 assert!(!xs.is_disjoint(&ys));
1091 assert!(!ys.is_disjoint(&xs));
1095 fn test_subset_and_superset() {
1096 let mut a = HashSet::new();
1097 assert!(a.insert(0));
1098 assert!(a.insert(5));
1099 assert!(a.insert(11));
1100 assert!(a.insert(7));
1102 let mut b = HashSet::new();
1103 assert!(b.insert(0));
1104 assert!(b.insert(7));
1105 assert!(b.insert(19));
1106 assert!(b.insert(250));
1107 assert!(b.insert(11));
1108 assert!(b.insert(200));
1110 assert!(!a.is_subset(&b));
1111 assert!(!a.is_superset(&b));
1112 assert!(!b.is_subset(&a));
1113 assert!(!b.is_superset(&a));
1115 assert!(b.insert(5));
1117 assert!(a.is_subset(&b));
1118 assert!(!a.is_superset(&b));
1119 assert!(!b.is_subset(&a));
1120 assert!(b.is_superset(&a));
1125 let mut a = HashSet::new();
1127 assert!(a.insert(i));
1129 let mut observed: u32 = 0;
1131 observed |= 1 << *k;
1133 assert_eq!(observed, 0xFFFF_FFFF);
1137 fn test_intersection() {
1138 let mut a = HashSet::new();
1139 let mut b = HashSet::new();
1141 assert!(a.insert(11));
1142 assert!(a.insert(1));
1143 assert!(a.insert(3));
1144 assert!(a.insert(77));
1145 assert!(a.insert(103));
1146 assert!(a.insert(5));
1147 assert!(a.insert(-5));
1149 assert!(b.insert(2));
1150 assert!(b.insert(11));
1151 assert!(b.insert(77));
1152 assert!(b.insert(-9));
1153 assert!(b.insert(-42));
1154 assert!(b.insert(5));
1155 assert!(b.insert(3));
1158 let expected = [3, 5, 11, 77];
1159 for x in a.intersection(&b) {
1160 assert!(expected.contains(x));
1163 assert_eq!(i, expected.len());
1167 fn test_difference() {
1168 let mut a = HashSet::new();
1169 let mut b = HashSet::new();
1171 assert!(a.insert(1));
1172 assert!(a.insert(3));
1173 assert!(a.insert(5));
1174 assert!(a.insert(9));
1175 assert!(a.insert(11));
1177 assert!(b.insert(3));
1178 assert!(b.insert(9));
1181 let expected = [1, 5, 11];
1182 for x in a.difference(&b) {
1183 assert!(expected.contains(x));
1186 assert_eq!(i, expected.len());
1190 fn test_symmetric_difference() {
1191 let mut a = HashSet::new();
1192 let mut b = HashSet::new();
1194 assert!(a.insert(1));
1195 assert!(a.insert(3));
1196 assert!(a.insert(5));
1197 assert!(a.insert(9));
1198 assert!(a.insert(11));
1200 assert!(b.insert(-2));
1201 assert!(b.insert(3));
1202 assert!(b.insert(9));
1203 assert!(b.insert(14));
1204 assert!(b.insert(22));
1207 let expected = [-2, 1, 5, 11, 14, 22];
1208 for x in a.symmetric_difference(&b) {
1209 assert!(expected.contains(x));
1212 assert_eq!(i, expected.len());
1217 let mut a = HashSet::new();
1218 let mut b = HashSet::new();
1220 assert!(a.insert(1));
1221 assert!(a.insert(3));
1222 assert!(a.insert(5));
1223 assert!(a.insert(9));
1224 assert!(a.insert(11));
1225 assert!(a.insert(16));
1226 assert!(a.insert(19));
1227 assert!(a.insert(24));
1229 assert!(b.insert(-2));
1230 assert!(b.insert(1));
1231 assert!(b.insert(5));
1232 assert!(b.insert(9));
1233 assert!(b.insert(13));
1234 assert!(b.insert(19));
1237 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1238 for x in a.union(&b) {
1239 assert!(expected.contains(x));
1242 assert_eq!(i, expected.len());
1246 fn test_from_iter() {
1247 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1249 let set: HashSet<_> = xs.iter().cloned().collect();
1252 assert!(set.contains(x));
1257 fn test_move_iter() {
1259 let mut hs = HashSet::new();
1267 let v = hs.into_iter().collect::<Vec<char>>();
1268 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1273 // These constants once happened to expose a bug in insert().
1274 // I'm keeping them around to prevent a regression.
1275 let mut s1 = HashSet::new();
1281 let mut s2 = HashSet::new();
1295 let mut set = HashSet::new();
1296 let empty = HashSet::<i32>::new();
1301 let set_str = format!("{:?}", set);
1303 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1304 assert_eq!(format!("{:?}", empty), "{}");
1308 fn test_trivial_drain() {
1309 let mut s = HashSet::<i32>::new();
1310 for _ in s.drain() {}
1311 assert!(s.is_empty());
1314 let mut s = HashSet::<i32>::new();
1316 assert!(s.is_empty());
1321 let mut s: HashSet<_> = (1..100).collect();
1323 // try this a bunch of times to make sure we don't screw up internal state.
1325 assert_eq!(s.len(), 99);
1329 let mut d = s.drain();
1330 for (i, x) in d.by_ref().take(50).enumerate() {
1334 assert_eq!(last_i, 49);
1337 for _ in &s { panic!("s should be empty!"); }
1339 // reset to try again.
1349 struct Foo(&'static str, i32);
1351 impl PartialEq for Foo {
1352 fn eq(&self, other: &Self) -> bool {
1359 impl hash::Hash for Foo {
1360 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1365 let mut s = HashSet::new();
1366 assert_eq!(s.replace(Foo("a", 1)), None);
1367 assert_eq!(s.len(), 1);
1368 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1369 assert_eq!(s.len(), 1);
1371 let mut it = s.iter();
1372 assert_eq!(it.next(), Some(&Foo("a", 2)));
1373 assert_eq!(it.next(), None);
1377 fn test_extend_ref() {
1378 let mut a = HashSet::new();
1381 a.extend(&[2, 3, 4]);
1383 assert_eq!(a.len(), 4);
1384 assert!(a.contains(&1));
1385 assert!(a.contains(&2));
1386 assert!(a.contains(&3));
1387 assert!(a.contains(&4));
1389 let mut b = HashSet::new();
1395 assert_eq!(a.len(), 6);
1396 assert!(a.contains(&1));
1397 assert!(a.contains(&2));
1398 assert!(a.contains(&3));
1399 assert!(a.contains(&4));
1400 assert!(a.contains(&5));
1401 assert!(a.contains(&6));