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 // Future Optimization (FIXME!)
21 // =============================
23 // Iteration over zero sized values is a noop. There is no need
24 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
25 // to get rid of it properly.
27 /// A hash set implemented as a `HashMap` where the value is `()`.
29 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
30 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
31 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
32 /// it is important that the following property holds:
35 /// k1 == k2 -> hash(k1) == hash(k2)
38 /// In other words, if two keys are equal, their hashes must be equal.
41 /// It is a logic error for an item to be modified in such a way that the
42 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
43 /// determined by the [`Eq`] trait, changes while it is in the set. This is
44 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
50 /// use std::collections::HashSet;
51 /// // Type inference lets us omit an explicit type signature (which
52 /// // would be `HashSet<&str>` in this example).
53 /// let mut books = HashSet::new();
55 /// // Add some books.
56 /// books.insert("A Dance With Dragons");
57 /// books.insert("To Kill a Mockingbird");
58 /// books.insert("The Odyssey");
59 /// books.insert("The Great Gatsby");
61 /// // Check for a specific one.
62 /// if !books.contains("The Winds of Winter") {
63 /// println!("We have {} books, but The Winds of Winter ain't one.",
68 /// books.remove("The Odyssey");
70 /// // Iterate over everything.
71 /// for book in &books {
72 /// println!("{}", book);
76 /// The easiest way to use `HashSet` with a custom type is to derive
77 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
78 /// future be implied by [`Eq`].
81 /// use std::collections::HashSet;
82 /// #[derive(Hash, Eq, PartialEq, Debug)]
83 /// struct Viking<'a> {
88 /// let mut vikings = HashSet::new();
90 /// vikings.insert(Viking { name: "Einar", power: 9 });
91 /// vikings.insert(Viking { name: "Einar", power: 9 });
92 /// vikings.insert(Viking { name: "Olaf", power: 4 });
93 /// vikings.insert(Viking { name: "Harald", power: 8 });
95 /// // Use derived implementation to print the vikings.
96 /// for x in &vikings {
97 /// println!("{:?}", x);
101 /// A `HashSet` with fixed list of elements can be initialized from an array:
104 /// use std::collections::HashSet;
107 /// let viking_names: HashSet<&str> =
108 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
109 /// // use the values stored in the set
113 /// [`Cell`]: ../../std/cell/struct.Cell.html
114 /// [`Eq`]: ../../std/cmp/trait.Eq.html
115 /// [`Hash`]: ../../std/hash/trait.Hash.html
116 /// [`HashMap`]: struct.HashMap.html
117 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
118 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub struct HashSet<T, S = RandomState> {
124 map: HashMap<T, (), S>,
127 impl<T: Hash + Eq> HashSet<T, RandomState> {
128 /// Creates an empty HashSet.
133 /// use std::collections::HashSet;
134 /// let mut set: HashSet<i32> = HashSet::new();
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub fn new() -> HashSet<T, RandomState> {
139 HashSet { map: HashMap::new() }
142 /// Creates an empty `HashSet` with the specified capacity.
144 /// The hash set will be able to hold at least `capacity` elements without
145 /// reallocating. If `capacity` is 0, the hash set will not allocate.
150 /// use std::collections::HashSet;
151 /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
156 HashSet { map: HashMap::with_capacity(capacity) }
160 impl<T, S> HashSet<T, S>
164 /// Creates a new empty hash set which will use the given hasher to hash
167 /// The hash set is also created with the default initial capacity.
169 /// Warning: `hasher` is normally randomly generated, and
170 /// is designed to allow `HashSet`s to be resistant to attacks that
171 /// cause many collisions and very poor performance. Setting it
172 /// manually using this function can expose a DoS attack vector.
177 /// use std::collections::HashSet;
178 /// use std::collections::hash_map::RandomState;
180 /// let s = RandomState::new();
181 /// let mut set = HashSet::with_hasher(s);
185 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
186 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
187 HashSet { map: HashMap::with_hasher(hasher) }
190 /// Creates an empty `HashSet` with with the specified capacity, using
191 /// `hasher` to hash the keys.
193 /// The hash set will be able to hold at least `capacity` elements without
194 /// reallocating. If `capacity` is 0, the hash set will not allocate.
196 /// Warning: `hasher` is normally randomly generated, and
197 /// is designed to allow `HashSet`s to be resistant to attacks that
198 /// cause many collisions and very poor performance. Setting it
199 /// manually using this function can expose a DoS attack vector.
204 /// use std::collections::HashSet;
205 /// use std::collections::hash_map::RandomState;
207 /// let s = RandomState::new();
208 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
212 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
213 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
214 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
217 /// Returns a reference to the set's [`BuildHasher`].
219 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
220 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
221 pub fn hasher(&self) -> &S {
225 /// Returns the number of elements the set can hold without reallocating.
230 /// use std::collections::HashSet;
231 /// let set: HashSet<i32> = HashSet::with_capacity(100);
232 /// assert!(set.capacity() >= 100);
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub fn capacity(&self) -> usize {
240 /// Reserves capacity for at least `additional` more elements to be inserted
241 /// in the `HashSet`. The collection may reserve more space to avoid
242 /// frequent reallocations.
246 /// Panics if the new allocation size overflows `usize`.
251 /// use std::collections::HashSet;
252 /// let mut set: HashSet<i32> = HashSet::new();
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn reserve(&mut self, additional: usize) {
257 self.map.reserve(additional)
260 /// Shrinks the capacity of the set as much as possible. It will drop
261 /// down as much as possible while maintaining the internal rules
262 /// and possibly leaving some space in accordance with the resize policy.
267 /// use std::collections::HashSet;
269 /// let mut set = HashSet::with_capacity(100);
272 /// assert!(set.capacity() >= 100);
273 /// set.shrink_to_fit();
274 /// assert!(set.capacity() >= 2);
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn shrink_to_fit(&mut self) {
278 self.map.shrink_to_fit()
281 /// An iterator visiting all elements in arbitrary order.
282 /// The iterator element type is `&'a T`.
287 /// use std::collections::HashSet;
288 /// let mut set = HashSet::new();
292 /// // Will print in an arbitrary order.
293 /// for x in set.iter() {
294 /// println!("{}", x);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn iter(&self) -> Iter<T> {
299 Iter { iter: self.map.keys() }
302 /// Visits the values representing the difference,
303 /// i.e. the values that are in `self` but not in `other`.
308 /// use std::collections::HashSet;
309 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
310 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
312 /// // Can be seen as `a - b`.
313 /// for x in a.difference(&b) {
314 /// println!("{}", x); // Print 1
317 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
318 /// assert_eq!(diff, [1].iter().cloned().collect());
320 /// // Note that difference is not symmetric,
321 /// // and `b - a` means something else:
322 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
323 /// assert_eq!(diff, [4].iter().cloned().collect());
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
333 /// Visits the values representing the symmetric difference,
334 /// i.e. the values that are in `self` or in `other` but not in both.
339 /// use std::collections::HashSet;
340 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
341 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
343 /// // Print 1, 4 in arbitrary order.
344 /// for x in a.symmetric_difference(&b) {
345 /// println!("{}", x);
348 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
349 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
351 /// assert_eq!(diff1, diff2);
352 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn symmetric_difference<'a>(&'a self,
356 other: &'a HashSet<T, S>)
357 -> SymmetricDifference<'a, T, S> {
358 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
361 /// Visits the values representing the intersection,
362 /// i.e. the values that are both in `self` and `other`.
367 /// use std::collections::HashSet;
368 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
369 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
371 /// // Print 2, 3 in arbitrary order.
372 /// for x in a.intersection(&b) {
373 /// println!("{}", x);
376 /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
377 /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
387 /// Visits the values representing the union,
388 /// i.e. all the values in `self` or `other`, without duplicates.
393 /// use std::collections::HashSet;
394 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
395 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
397 /// // Print 1, 2, 3, 4 in arbitrary order.
398 /// for x in a.union(&b) {
399 /// println!("{}", x);
402 /// let union: HashSet<_> = a.union(&b).cloned().collect();
403 /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
407 Union { iter: self.iter().chain(other.difference(self)) }
410 /// Returns the number of elements in the set.
415 /// use std::collections::HashSet;
417 /// let mut v = HashSet::new();
418 /// assert_eq!(v.len(), 0);
420 /// assert_eq!(v.len(), 1);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn len(&self) -> usize {
427 /// Returns true if the set contains no elements.
432 /// use std::collections::HashSet;
434 /// let mut v = HashSet::new();
435 /// assert!(v.is_empty());
437 /// assert!(!v.is_empty());
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn is_empty(&self) -> bool {
444 /// Clears the set, returning all elements in an iterator.
446 #[stable(feature = "drain", since = "1.6.0")]
447 pub fn drain(&mut self) -> Drain<T> {
448 Drain { iter: self.map.drain() }
451 /// Clears the set, removing all values.
456 /// use std::collections::HashSet;
458 /// let mut v = HashSet::new();
461 /// assert!(v.is_empty());
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn clear(&mut self) {
468 /// Returns `true` if the set contains a value.
470 /// The value may be any borrowed form of the set's value type, but
471 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
477 /// use std::collections::HashSet;
479 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
480 /// assert_eq!(set.contains(&1), true);
481 /// assert_eq!(set.contains(&4), false);
484 /// [`Eq`]: ../../std/cmp/trait.Eq.html
485 /// [`Hash`]: ../../std/hash/trait.Hash.html
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
491 self.map.contains_key(value)
494 /// Returns a reference to the value in the set, if any, that is equal to the given value.
496 /// The value may be any borrowed form of the set's value type, but
497 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
500 /// [`Eq`]: ../../std/cmp/trait.Eq.html
501 /// [`Hash`]: ../../std/hash/trait.Hash.html
502 #[stable(feature = "set_recovery", since = "1.9.0")]
503 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
507 Recover::get(&self.map, value)
510 /// Returns `true` if `self` has no elements in common with `other`.
511 /// This is equivalent to checking for an empty intersection.
516 /// use std::collections::HashSet;
518 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
519 /// let mut b = HashSet::new();
521 /// assert_eq!(a.is_disjoint(&b), true);
523 /// assert_eq!(a.is_disjoint(&b), true);
525 /// assert_eq!(a.is_disjoint(&b), false);
527 #[stable(feature = "rust1", since = "1.0.0")]
528 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
529 self.iter().all(|v| !other.contains(v))
532 /// Returns `true` if the set is a subset of another,
533 /// i.e. `other` contains at least all the values in `self`.
538 /// use std::collections::HashSet;
540 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
541 /// let mut set = HashSet::new();
543 /// assert_eq!(set.is_subset(&sup), true);
545 /// assert_eq!(set.is_subset(&sup), true);
547 /// assert_eq!(set.is_subset(&sup), false);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
551 self.iter().all(|v| other.contains(v))
554 /// Returns `true` if the set is a superset of another,
555 /// i.e. `self` contains at least all the values in `other`.
560 /// use std::collections::HashSet;
562 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
563 /// let mut set = HashSet::new();
565 /// assert_eq!(set.is_superset(&sub), false);
569 /// assert_eq!(set.is_superset(&sub), false);
572 /// assert_eq!(set.is_superset(&sub), true);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
577 other.is_subset(self)
580 /// Adds a value to the set.
582 /// If the set did not have this value present, `true` is returned.
584 /// If the set did have this value present, `false` is returned.
589 /// use std::collections::HashSet;
591 /// let mut set = HashSet::new();
593 /// assert_eq!(set.insert(2), true);
594 /// assert_eq!(set.insert(2), false);
595 /// assert_eq!(set.len(), 1);
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub fn insert(&mut self, value: T) -> bool {
599 self.map.insert(value, ()).is_none()
602 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
603 /// one. Returns the replaced value.
604 #[stable(feature = "set_recovery", since = "1.9.0")]
605 pub fn replace(&mut self, value: T) -> Option<T> {
606 Recover::replace(&mut self.map, value)
609 /// Removes a value from the set. Returns `true` if the value was
610 /// present in the set.
612 /// The value may be any borrowed form of the set's value type, but
613 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
619 /// use std::collections::HashSet;
621 /// let mut set = HashSet::new();
624 /// assert_eq!(set.remove(&2), true);
625 /// assert_eq!(set.remove(&2), false);
628 /// [`Eq`]: ../../std/cmp/trait.Eq.html
629 /// [`Hash`]: ../../std/hash/trait.Hash.html
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
635 self.map.remove(value).is_some()
638 /// Removes and returns the value in the set, if any, that is equal to the given one.
640 /// The value may be any borrowed form of the set's value type, but
641 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
644 /// [`Eq`]: ../../std/cmp/trait.Eq.html
645 /// [`Hash`]: ../../std/hash/trait.Hash.html
646 #[stable(feature = "set_recovery", since = "1.9.0")]
647 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
651 Recover::take(&mut self.map, value)
654 /// Retains only the elements specified by the predicate.
656 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
661 /// #![feature(retain_hash_collection)]
662 /// use std::collections::HashSet;
664 /// let xs = [1,2,3,4,5,6];
665 /// let mut set: HashSet<isize> = xs.iter().cloned().collect();
666 /// set.retain(|&k| k % 2 == 0);
667 /// assert_eq!(set.len(), 3);
669 #[unstable(feature = "retain_hash_collection", issue = "36648")]
670 pub fn retain<F>(&mut self, mut f: F)
671 where F: FnMut(&T) -> bool
673 self.map.retain(|k, _| f(k));
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<T, S> PartialEq for HashSet<T, S>
682 fn eq(&self, other: &HashSet<T, S>) -> bool {
683 if self.len() != other.len() {
687 self.iter().all(|key| other.contains(key))
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl<T, S> Eq for HashSet<T, S>
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T, S> fmt::Debug for HashSet<T, S>
700 where T: Eq + Hash + fmt::Debug,
703 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
704 f.debug_set().entries(self.iter()).finish()
708 #[stable(feature = "rust1", since = "1.0.0")]
709 impl<T, S> FromIterator<T> for HashSet<T, S>
711 S: BuildHasher + Default
713 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
714 let mut set = HashSet::with_hasher(Default::default());
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl<T, S> Extend<T> for HashSet<T, S>
725 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
726 self.map.extend(iter.into_iter().map(|k| (k, ())));
730 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
731 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
732 where T: 'a + Eq + Hash + Copy,
735 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
736 self.extend(iter.into_iter().cloned());
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T, S> Default for HashSet<T, S>
743 S: BuildHasher + Default
745 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
746 fn default() -> HashSet<T, S> {
747 HashSet { map: HashMap::default() }
751 #[stable(feature = "rust1", since = "1.0.0")]
752 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
753 where T: Eq + Hash + Clone,
754 S: BuildHasher + Default
756 type Output = HashSet<T, S>;
758 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
763 /// use std::collections::HashSet;
765 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
766 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
768 /// let set = &a | &b;
771 /// let expected = [1, 2, 3, 4, 5];
773 /// assert!(expected.contains(x));
776 /// assert_eq!(i, expected.len());
778 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
779 self.union(rhs).cloned().collect()
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
785 where T: Eq + Hash + Clone,
786 S: BuildHasher + Default
788 type Output = HashSet<T, S>;
790 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
795 /// use std::collections::HashSet;
797 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
798 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
800 /// let set = &a & &b;
803 /// let expected = [2, 3];
805 /// assert!(expected.contains(x));
808 /// assert_eq!(i, expected.len());
810 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
811 self.intersection(rhs).cloned().collect()
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
817 where T: Eq + Hash + Clone,
818 S: BuildHasher + Default
820 type Output = HashSet<T, S>;
822 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
827 /// use std::collections::HashSet;
829 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
830 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
832 /// let set = &a ^ &b;
835 /// let expected = [1, 2, 4, 5];
837 /// assert!(expected.contains(x));
840 /// assert_eq!(i, expected.len());
842 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
843 self.symmetric_difference(rhs).cloned().collect()
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
849 where T: Eq + Hash + Clone,
850 S: BuildHasher + Default
852 type Output = HashSet<T, S>;
854 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
859 /// use std::collections::HashSet;
861 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
862 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
864 /// let set = &a - &b;
867 /// let expected = [1, 2];
869 /// assert!(expected.contains(x));
872 /// assert_eq!(i, expected.len());
874 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
875 self.difference(rhs).cloned().collect()
879 /// An iterator over the items of a `HashSet`.
881 /// This `struct` is created by the [`iter`] method on [`HashSet`].
882 /// See its documentation for more.
884 /// [`HashSet`]: struct.HashSet.html
885 /// [`iter`]: struct.HashSet.html#method.iter
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub struct Iter<'a, K: 'a> {
888 iter: Keys<'a, K, ()>,
891 /// An owning iterator over the items of a `HashSet`.
893 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
894 /// (provided by the `IntoIterator` trait). See its documentation for more.
896 /// [`HashSet`]: struct.HashSet.html
897 /// [`into_iter`]: struct.HashSet.html#method.into_iter
898 #[stable(feature = "rust1", since = "1.0.0")]
899 pub struct IntoIter<K> {
900 iter: map::IntoIter<K, ()>,
903 /// A draining iterator over the items of a `HashSet`.
905 /// This `struct` is created by the [`drain`] method on [`HashSet`].
906 /// See its documentation for more.
908 /// [`HashSet`]: struct.HashSet.html
909 /// [`drain`]: struct.HashSet.html#method.drain
910 #[stable(feature = "rust1", since = "1.0.0")]
911 pub struct Drain<'a, K: 'a> {
912 iter: map::Drain<'a, K, ()>,
915 /// A lazy iterator producing elements in the intersection of `HashSet`s.
917 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
918 /// See its documentation for more.
920 /// [`HashSet`]: struct.HashSet.html
921 /// [`intersection`]: struct.HashSet.html#method.intersection
922 #[stable(feature = "rust1", since = "1.0.0")]
923 pub struct Intersection<'a, T: 'a, S: 'a> {
924 // iterator of the first set
927 other: &'a HashSet<T, S>,
930 /// A lazy iterator producing elements in the difference of `HashSet`s.
932 /// This `struct` is created by the [`difference`] method on [`HashSet`].
933 /// See its documentation for more.
935 /// [`HashSet`]: struct.HashSet.html
936 /// [`difference`]: struct.HashSet.html#method.difference
937 #[stable(feature = "rust1", since = "1.0.0")]
938 pub struct Difference<'a, T: 'a, S: 'a> {
939 // iterator of the first set
942 other: &'a HashSet<T, S>,
945 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
947 /// This `struct` is created by the [`symmetric_difference`] method on
948 /// [`HashSet`]. See its documentation for more.
950 /// [`HashSet`]: struct.HashSet.html
951 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
952 #[stable(feature = "rust1", since = "1.0.0")]
953 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
954 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
957 /// A lazy iterator producing elements in the union of `HashSet`s.
959 /// This `struct` is created by the [`union`] method on [`HashSet`].
960 /// See its documentation for more.
962 /// [`HashSet`]: struct.HashSet.html
963 /// [`union`]: struct.HashSet.html#method.union
964 #[stable(feature = "rust1", since = "1.0.0")]
965 pub struct Union<'a, T: 'a, S: 'a> {
966 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
969 #[stable(feature = "rust1", since = "1.0.0")]
970 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
975 type IntoIter = Iter<'a, T>;
977 fn into_iter(self) -> Iter<'a, T> {
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T, S> IntoIterator for HashSet<T, S>
988 type IntoIter = IntoIter<T>;
990 /// Creates a consuming iterator, that is, one that moves each value out
991 /// of the set in arbitrary order. The set cannot be used after calling
997 /// use std::collections::HashSet;
998 /// let mut set = HashSet::new();
999 /// set.insert("a".to_string());
1000 /// set.insert("b".to_string());
1002 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1003 /// let v: Vec<String> = set.into_iter().collect();
1005 /// // Will print in an arbitrary order.
1007 /// println!("{}", x);
1010 fn into_iter(self) -> IntoIter<T> {
1011 IntoIter { iter: self.map.into_iter() }
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<'a, K> Clone for Iter<'a, K> {
1017 fn clone(&self) -> Iter<'a, K> {
1018 Iter { iter: self.iter.clone() }
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 impl<'a, K> Iterator for Iter<'a, K> {
1025 fn next(&mut self) -> Option<&'a K> {
1028 fn size_hint(&self) -> (usize, Option<usize>) {
1029 self.iter.size_hint()
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
1034 fn len(&self) -> usize {
1038 #[unstable(feature = "fused", issue = "35602")]
1039 impl<'a, K> FusedIterator for Iter<'a, K> {}
1041 #[stable(feature = "std_debug", since = "1.16.0")]
1042 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
1043 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1045 .entries(self.clone())
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<K> Iterator for IntoIter<K> {
1054 fn next(&mut self) -> Option<K> {
1055 self.iter.next().map(|(k, _)| k)
1057 fn size_hint(&self) -> (usize, Option<usize>) {
1058 self.iter.size_hint()
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 impl<K> ExactSizeIterator for IntoIter<K> {
1063 fn len(&self) -> usize {
1067 #[unstable(feature = "fused", issue = "35602")]
1068 impl<K> FusedIterator for IntoIter<K> {}
1070 #[stable(feature = "std_debug", since = "1.16.0")]
1071 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1072 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1073 let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
1075 .entries(entries_iter)
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<'a, K> Iterator for Drain<'a, K> {
1084 fn next(&mut self) -> Option<K> {
1085 self.iter.next().map(|(k, _)| k)
1087 fn size_hint(&self) -> (usize, Option<usize>) {
1088 self.iter.size_hint()
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1093 fn len(&self) -> usize {
1097 #[unstable(feature = "fused", issue = "35602")]
1098 impl<'a, K> FusedIterator for Drain<'a, K> {}
1100 #[stable(feature = "std_debug", since = "1.16.0")]
1101 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1103 let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
1105 .entries(entries_iter)
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1112 fn clone(&self) -> Intersection<'a, T, S> {
1113 Intersection { iter: self.iter.clone(), ..*self }
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1124 fn next(&mut self) -> Option<&'a T> {
1126 match self.iter.next() {
1127 None => return None,
1129 if self.other.contains(elt) {
1137 fn size_hint(&self) -> (usize, Option<usize>) {
1138 let (_, upper) = self.iter.size_hint();
1143 #[stable(feature = "std_debug", since = "1.16.0")]
1144 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1145 where T: fmt::Debug + Eq + Hash,
1148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1150 .entries(self.clone())
1155 #[unstable(feature = "fused", issue = "35602")]
1156 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<'a, T, S> Clone for Difference<'a, T, S> {
1164 fn clone(&self) -> Difference<'a, T, S> {
1165 Difference { iter: self.iter.clone(), ..*self }
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl<'a, T, S> Iterator for Difference<'a, T, S>
1176 fn next(&mut self) -> Option<&'a T> {
1178 match self.iter.next() {
1179 None => return None,
1181 if !self.other.contains(elt) {
1189 fn size_hint(&self) -> (usize, Option<usize>) {
1190 let (_, upper) = self.iter.size_hint();
1195 #[unstable(feature = "fused", issue = "35602")]
1196 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1202 #[stable(feature = "std_debug", since = "1.16.0")]
1203 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1204 where T: fmt::Debug + Eq + Hash,
1207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1209 .entries(self.clone())
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1216 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1217 SymmetricDifference { iter: self.iter.clone() }
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1228 fn next(&mut self) -> Option<&'a T> {
1231 fn size_hint(&self) -> (usize, Option<usize>) {
1232 self.iter.size_hint()
1236 #[unstable(feature = "fused", issue = "35602")]
1237 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1243 #[stable(feature = "std_debug", since = "1.16.0")]
1244 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1245 where T: fmt::Debug + Eq + Hash,
1248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1250 .entries(self.clone())
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 impl<'a, T, S> Clone for Union<'a, T, S> {
1257 fn clone(&self) -> Union<'a, T, S> {
1258 Union { iter: self.iter.clone() }
1262 #[unstable(feature = "fused", issue = "35602")]
1263 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1269 #[stable(feature = "std_debug", since = "1.16.0")]
1270 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1271 where T: fmt::Debug + Eq + Hash,
1274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1276 .entries(self.clone())
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<'a, T, S> Iterator for Union<'a, T, S>
1288 fn next(&mut self) -> Option<&'a T> {
1291 fn size_hint(&self) -> (usize, Option<usize>) {
1292 self.iter.size_hint()
1297 fn assert_covariance() {
1298 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1301 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1304 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1307 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1308 -> Difference<'a, &'new str, RandomState> {
1311 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1312 -> SymmetricDifference<'a, &'new str, RandomState> {
1315 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1316 -> Intersection<'a, &'new str, RandomState> {
1319 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1320 -> Union<'a, &'new str, RandomState> {
1323 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1331 use super::super::map::RandomState;
1334 fn test_zero_capacities() {
1335 type HS = HashSet<i32>;
1338 assert_eq!(s.capacity(), 0);
1340 let s = HS::default();
1341 assert_eq!(s.capacity(), 0);
1343 let s = HS::with_hasher(RandomState::new());
1344 assert_eq!(s.capacity(), 0);
1346 let s = HS::with_capacity(0);
1347 assert_eq!(s.capacity(), 0);
1349 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1350 assert_eq!(s.capacity(), 0);
1352 let mut s = HS::new();
1358 assert_eq!(s.capacity(), 0);
1360 let mut s = HS::new();
1362 assert_eq!(s.capacity(), 0);
1366 fn test_disjoint() {
1367 let mut xs = HashSet::new();
1368 let mut ys = HashSet::new();
1369 assert!(xs.is_disjoint(&ys));
1370 assert!(ys.is_disjoint(&xs));
1371 assert!(xs.insert(5));
1372 assert!(ys.insert(11));
1373 assert!(xs.is_disjoint(&ys));
1374 assert!(ys.is_disjoint(&xs));
1375 assert!(xs.insert(7));
1376 assert!(xs.insert(19));
1377 assert!(xs.insert(4));
1378 assert!(ys.insert(2));
1379 assert!(ys.insert(-11));
1380 assert!(xs.is_disjoint(&ys));
1381 assert!(ys.is_disjoint(&xs));
1382 assert!(ys.insert(7));
1383 assert!(!xs.is_disjoint(&ys));
1384 assert!(!ys.is_disjoint(&xs));
1388 fn test_subset_and_superset() {
1389 let mut a = HashSet::new();
1390 assert!(a.insert(0));
1391 assert!(a.insert(5));
1392 assert!(a.insert(11));
1393 assert!(a.insert(7));
1395 let mut b = HashSet::new();
1396 assert!(b.insert(0));
1397 assert!(b.insert(7));
1398 assert!(b.insert(19));
1399 assert!(b.insert(250));
1400 assert!(b.insert(11));
1401 assert!(b.insert(200));
1403 assert!(!a.is_subset(&b));
1404 assert!(!a.is_superset(&b));
1405 assert!(!b.is_subset(&a));
1406 assert!(!b.is_superset(&a));
1408 assert!(b.insert(5));
1410 assert!(a.is_subset(&b));
1411 assert!(!a.is_superset(&b));
1412 assert!(!b.is_subset(&a));
1413 assert!(b.is_superset(&a));
1418 let mut a = HashSet::new();
1420 assert!(a.insert(i));
1422 let mut observed: u32 = 0;
1424 observed |= 1 << *k;
1426 assert_eq!(observed, 0xFFFF_FFFF);
1430 fn test_intersection() {
1431 let mut a = HashSet::new();
1432 let mut b = HashSet::new();
1434 assert!(a.insert(11));
1435 assert!(a.insert(1));
1436 assert!(a.insert(3));
1437 assert!(a.insert(77));
1438 assert!(a.insert(103));
1439 assert!(a.insert(5));
1440 assert!(a.insert(-5));
1442 assert!(b.insert(2));
1443 assert!(b.insert(11));
1444 assert!(b.insert(77));
1445 assert!(b.insert(-9));
1446 assert!(b.insert(-42));
1447 assert!(b.insert(5));
1448 assert!(b.insert(3));
1451 let expected = [3, 5, 11, 77];
1452 for x in a.intersection(&b) {
1453 assert!(expected.contains(x));
1456 assert_eq!(i, expected.len());
1460 fn test_difference() {
1461 let mut a = HashSet::new();
1462 let mut b = HashSet::new();
1464 assert!(a.insert(1));
1465 assert!(a.insert(3));
1466 assert!(a.insert(5));
1467 assert!(a.insert(9));
1468 assert!(a.insert(11));
1470 assert!(b.insert(3));
1471 assert!(b.insert(9));
1474 let expected = [1, 5, 11];
1475 for x in a.difference(&b) {
1476 assert!(expected.contains(x));
1479 assert_eq!(i, expected.len());
1483 fn test_symmetric_difference() {
1484 let mut a = HashSet::new();
1485 let mut b = HashSet::new();
1487 assert!(a.insert(1));
1488 assert!(a.insert(3));
1489 assert!(a.insert(5));
1490 assert!(a.insert(9));
1491 assert!(a.insert(11));
1493 assert!(b.insert(-2));
1494 assert!(b.insert(3));
1495 assert!(b.insert(9));
1496 assert!(b.insert(14));
1497 assert!(b.insert(22));
1500 let expected = [-2, 1, 5, 11, 14, 22];
1501 for x in a.symmetric_difference(&b) {
1502 assert!(expected.contains(x));
1505 assert_eq!(i, expected.len());
1510 let mut a = HashSet::new();
1511 let mut b = HashSet::new();
1513 assert!(a.insert(1));
1514 assert!(a.insert(3));
1515 assert!(a.insert(5));
1516 assert!(a.insert(9));
1517 assert!(a.insert(11));
1518 assert!(a.insert(16));
1519 assert!(a.insert(19));
1520 assert!(a.insert(24));
1522 assert!(b.insert(-2));
1523 assert!(b.insert(1));
1524 assert!(b.insert(5));
1525 assert!(b.insert(9));
1526 assert!(b.insert(13));
1527 assert!(b.insert(19));
1530 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1531 for x in a.union(&b) {
1532 assert!(expected.contains(x));
1535 assert_eq!(i, expected.len());
1539 fn test_from_iter() {
1540 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1542 let set: HashSet<_> = xs.iter().cloned().collect();
1545 assert!(set.contains(x));
1550 fn test_move_iter() {
1552 let mut hs = HashSet::new();
1560 let v = hs.into_iter().collect::<Vec<char>>();
1561 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1566 // These constants once happened to expose a bug in insert().
1567 // I'm keeping them around to prevent a regression.
1568 let mut s1 = HashSet::new();
1574 let mut s2 = HashSet::new();
1588 let mut set = HashSet::new();
1589 let empty = HashSet::<i32>::new();
1594 let set_str = format!("{:?}", set);
1596 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1597 assert_eq!(format!("{:?}", empty), "{}");
1601 fn test_trivial_drain() {
1602 let mut s = HashSet::<i32>::new();
1603 for _ in s.drain() {}
1604 assert!(s.is_empty());
1607 let mut s = HashSet::<i32>::new();
1609 assert!(s.is_empty());
1614 let mut s: HashSet<_> = (1..100).collect();
1616 // try this a bunch of times to make sure we don't screw up internal state.
1618 assert_eq!(s.len(), 99);
1622 let mut d = s.drain();
1623 for (i, x) in d.by_ref().take(50).enumerate() {
1627 assert_eq!(last_i, 49);
1631 panic!("s should be empty!");
1634 // reset to try again.
1644 struct Foo(&'static str, i32);
1646 impl PartialEq for Foo {
1647 fn eq(&self, other: &Self) -> bool {
1654 impl hash::Hash for Foo {
1655 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1660 let mut s = HashSet::new();
1661 assert_eq!(s.replace(Foo("a", 1)), None);
1662 assert_eq!(s.len(), 1);
1663 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1664 assert_eq!(s.len(), 1);
1666 let mut it = s.iter();
1667 assert_eq!(it.next(), Some(&Foo("a", 2)));
1668 assert_eq!(it.next(), None);
1672 fn test_extend_ref() {
1673 let mut a = HashSet::new();
1676 a.extend(&[2, 3, 4]);
1678 assert_eq!(a.len(), 4);
1679 assert!(a.contains(&1));
1680 assert!(a.contains(&2));
1681 assert!(a.contains(&3));
1682 assert!(a.contains(&4));
1684 let mut b = HashSet::new();
1690 assert_eq!(a.len(), 6);
1691 assert!(a.contains(&1));
1692 assert!(a.contains(&2));
1693 assert!(a.contains(&3));
1694 assert!(a.contains(&4));
1695 assert!(a.contains(&5));
1696 assert!(a.contains(&6));
1701 let xs = [1,2,3,4,5,6];
1702 let mut set: HashSet<isize> = xs.iter().cloned().collect();
1703 set.retain(|&k| k % 2 == 0);
1704 assert_eq!(set.len(), 3);
1705 assert!(set.contains(&2));
1706 assert!(set.contains(&4));
1707 assert!(set.contains(&6));