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
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct HashSet<T, S = RandomState> {
122 map: HashMap<T, (), S>,
125 impl<T: Hash + Eq> HashSet<T, RandomState> {
126 /// Creates an empty `HashSet`.
131 /// use std::collections::HashSet;
132 /// let set: HashSet<i32> = HashSet::new();
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub fn new() -> HashSet<T, RandomState> {
137 HashSet { map: HashMap::new() }
140 /// Creates an empty `HashSet` with the specified capacity.
142 /// The hash set will be able to hold at least `capacity` elements without
143 /// reallocating. If `capacity` is 0, the hash set will not allocate.
148 /// use std::collections::HashSet;
149 /// let set: HashSet<i32> = HashSet::with_capacity(10);
150 /// assert!(set.capacity() >= 10);
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
155 HashSet { map: HashMap::with_capacity(capacity) }
159 impl<T, S> HashSet<T, S>
163 /// Creates a new empty hash set which will use the given hasher to hash
166 /// The hash set is also created with the default initial capacity.
168 /// Warning: `hasher` is normally randomly generated, and
169 /// is designed to allow `HashSet`s to be resistant to attacks that
170 /// cause many collisions and very poor performance. Setting it
171 /// manually using this function can expose a DoS attack vector.
176 /// use std::collections::HashSet;
177 /// use std::collections::hash_map::RandomState;
179 /// let s = RandomState::new();
180 /// let mut set = HashSet::with_hasher(s);
184 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
185 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
186 HashSet { map: HashMap::with_hasher(hasher) }
189 /// Creates an empty `HashSet` with with the specified capacity, using
190 /// `hasher` to hash the keys.
192 /// The hash set will be able to hold at least `capacity` elements without
193 /// reallocating. If `capacity` is 0, the hash set will not allocate.
195 /// Warning: `hasher` is normally randomly generated, and
196 /// is designed to allow `HashSet`s to be resistant to attacks that
197 /// cause many collisions and very poor performance. Setting it
198 /// manually using this function can expose a DoS attack vector.
203 /// use std::collections::HashSet;
204 /// use std::collections::hash_map::RandomState;
206 /// let s = RandomState::new();
207 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
211 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
212 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
213 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
216 /// Returns a reference to the set's [`BuildHasher`].
218 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
223 /// use std::collections::HashSet;
224 /// use std::collections::hash_map::RandomState;
226 /// let hasher = RandomState::new();
227 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
228 /// let hasher: &RandomState = set.hasher();
230 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
231 pub fn hasher(&self) -> &S {
235 /// Returns the number of elements the set can hold without reallocating.
240 /// use std::collections::HashSet;
241 /// let set: HashSet<i32> = HashSet::with_capacity(100);
242 /// assert!(set.capacity() >= 100);
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn capacity(&self) -> usize {
250 /// Reserves capacity for at least `additional` more elements to be inserted
251 /// in the `HashSet`. The collection may reserve more space to avoid
252 /// frequent reallocations.
256 /// Panics if the new allocation size overflows `usize`.
261 /// use std::collections::HashSet;
262 /// let mut set: HashSet<i32> = HashSet::new();
264 /// assert!(set.capacity() >= 10);
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn reserve(&mut self, additional: usize) {
268 self.map.reserve(additional)
271 /// Shrinks the capacity of the set as much as possible. It will drop
272 /// down as much as possible while maintaining the internal rules
273 /// and possibly leaving some space in accordance with the resize policy.
278 /// use std::collections::HashSet;
280 /// let mut set = HashSet::with_capacity(100);
283 /// assert!(set.capacity() >= 100);
284 /// set.shrink_to_fit();
285 /// assert!(set.capacity() >= 2);
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn shrink_to_fit(&mut self) {
289 self.map.shrink_to_fit()
292 /// An iterator visiting all elements in arbitrary order.
293 /// The iterator element type is `&'a T`.
298 /// use std::collections::HashSet;
299 /// let mut set = HashSet::new();
303 /// // Will print in an arbitrary order.
304 /// for x in set.iter() {
305 /// println!("{}", x);
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn iter(&self) -> Iter<T> {
310 Iter { iter: self.map.keys() }
313 /// Visits the values representing the difference,
314 /// i.e. the values that are in `self` but not in `other`.
319 /// use std::collections::HashSet;
320 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
321 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
323 /// // Can be seen as `a - b`.
324 /// for x in a.difference(&b) {
325 /// println!("{}", x); // Print 1
328 /// let diff: HashSet<_> = a.difference(&b).collect();
329 /// assert_eq!(diff, [1].iter().collect());
331 /// // Note that difference is not symmetric,
332 /// // and `b - a` means something else:
333 /// let diff: HashSet<_> = b.difference(&a).collect();
334 /// assert_eq!(diff, [4].iter().collect());
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
344 /// Visits the values representing the symmetric difference,
345 /// i.e. the values that are in `self` or in `other` but not in both.
350 /// use std::collections::HashSet;
351 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
352 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
354 /// // Print 1, 4 in arbitrary order.
355 /// for x in a.symmetric_difference(&b) {
356 /// println!("{}", x);
359 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
360 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
362 /// assert_eq!(diff1, diff2);
363 /// assert_eq!(diff1, [1, 4].iter().collect());
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn symmetric_difference<'a>(&'a self,
367 other: &'a HashSet<T, S>)
368 -> SymmetricDifference<'a, T, S> {
369 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
372 /// Visits the values representing the intersection,
373 /// i.e. the values that are both in `self` and `other`.
378 /// use std::collections::HashSet;
379 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
380 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
382 /// // Print 2, 3 in arbitrary order.
383 /// for x in a.intersection(&b) {
384 /// println!("{}", x);
387 /// let intersection: HashSet<_> = a.intersection(&b).collect();
388 /// assert_eq!(intersection, [2, 3].iter().collect());
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
398 /// Visits the values representing the union,
399 /// i.e. all the values in `self` or `other`, without duplicates.
404 /// use std::collections::HashSet;
405 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
406 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
408 /// // Print 1, 2, 3, 4 in arbitrary order.
409 /// for x in a.union(&b) {
410 /// println!("{}", x);
413 /// let union: HashSet<_> = a.union(&b).collect();
414 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
418 Union { iter: self.iter().chain(other.difference(self)) }
421 /// Returns the number of elements in the set.
426 /// use std::collections::HashSet;
428 /// let mut v = HashSet::new();
429 /// assert_eq!(v.len(), 0);
431 /// assert_eq!(v.len(), 1);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn len(&self) -> usize {
438 /// Returns true if the set contains no elements.
443 /// use std::collections::HashSet;
445 /// let mut v = HashSet::new();
446 /// assert!(v.is_empty());
448 /// assert!(!v.is_empty());
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn is_empty(&self) -> bool {
455 /// Clears the set, returning all elements in an iterator.
460 /// use std::collections::HashSet;
462 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
463 /// assert!(!set.is_empty());
465 /// // print 1, 2, 3 in an arbitrary order
466 /// for i in set.drain() {
467 /// println!("{}", i);
470 /// assert!(set.is_empty());
473 #[stable(feature = "drain", since = "1.6.0")]
474 pub fn drain(&mut self) -> Drain<T> {
475 Drain { iter: self.map.drain() }
478 /// Clears the set, removing all values.
483 /// use std::collections::HashSet;
485 /// let mut v = HashSet::new();
488 /// assert!(v.is_empty());
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn clear(&mut self) {
495 /// Returns `true` if the set contains a value.
497 /// The value may be any borrowed form of the set's value type, but
498 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
504 /// use std::collections::HashSet;
506 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
507 /// assert_eq!(set.contains(&1), true);
508 /// assert_eq!(set.contains(&4), false);
511 /// [`Eq`]: ../../std/cmp/trait.Eq.html
512 /// [`Hash`]: ../../std/hash/trait.Hash.html
513 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
518 self.map.contains_key(value)
521 /// Returns a reference to the value in the set, if any, that is equal to the given value.
523 /// The value may be any borrowed form of the set's value type, but
524 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
527 /// [`Eq`]: ../../std/cmp/trait.Eq.html
528 /// [`Hash`]: ../../std/hash/trait.Hash.html
529 #[stable(feature = "set_recovery", since = "1.9.0")]
530 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
534 Recover::get(&self.map, value)
537 /// Returns `true` if `self` has no elements in common with `other`.
538 /// This is equivalent to checking for an empty intersection.
543 /// use std::collections::HashSet;
545 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
546 /// let mut b = HashSet::new();
548 /// assert_eq!(a.is_disjoint(&b), true);
550 /// assert_eq!(a.is_disjoint(&b), true);
552 /// assert_eq!(a.is_disjoint(&b), false);
554 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
556 self.iter().all(|v| !other.contains(v))
559 /// Returns `true` if the set is a subset of another,
560 /// i.e. `other` contains at least all the values in `self`.
565 /// use std::collections::HashSet;
567 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
568 /// let mut set = HashSet::new();
570 /// assert_eq!(set.is_subset(&sup), true);
572 /// assert_eq!(set.is_subset(&sup), true);
574 /// assert_eq!(set.is_subset(&sup), false);
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
578 self.iter().all(|v| other.contains(v))
581 /// Returns `true` if the set is a superset of another,
582 /// i.e. `self` contains at least all the values in `other`.
587 /// use std::collections::HashSet;
589 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
590 /// let mut set = HashSet::new();
592 /// assert_eq!(set.is_superset(&sub), false);
596 /// assert_eq!(set.is_superset(&sub), false);
599 /// assert_eq!(set.is_superset(&sub), true);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
604 other.is_subset(self)
607 /// Adds a value to the set.
609 /// If the set did not have this value present, `true` is returned.
611 /// If the set did have this value present, `false` is returned.
616 /// use std::collections::HashSet;
618 /// let mut set = HashSet::new();
620 /// assert_eq!(set.insert(2), true);
621 /// assert_eq!(set.insert(2), false);
622 /// assert_eq!(set.len(), 1);
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn insert(&mut self, value: T) -> bool {
626 self.map.insert(value, ()).is_none()
629 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
630 /// one. Returns the replaced value.
631 #[stable(feature = "set_recovery", since = "1.9.0")]
632 pub fn replace(&mut self, value: T) -> Option<T> {
633 Recover::replace(&mut self.map, value)
636 /// Removes a value from the set. Returns `true` if the value was
637 /// present in the set.
639 /// The value may be any borrowed form of the set's value type, but
640 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
646 /// use std::collections::HashSet;
648 /// let mut set = HashSet::new();
651 /// assert_eq!(set.remove(&2), true);
652 /// assert_eq!(set.remove(&2), false);
655 /// [`Eq`]: ../../std/cmp/trait.Eq.html
656 /// [`Hash`]: ../../std/hash/trait.Hash.html
657 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
662 self.map.remove(value).is_some()
665 /// Removes and returns the value in the set, if any, that is equal to the given one.
667 /// The value may be any borrowed form of the set's value type, but
668 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
671 /// [`Eq`]: ../../std/cmp/trait.Eq.html
672 /// [`Hash`]: ../../std/hash/trait.Hash.html
673 #[stable(feature = "set_recovery", since = "1.9.0")]
674 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
678 Recover::take(&mut self.map, value)
681 /// Retains only the elements specified by the predicate.
683 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
688 /// use std::collections::HashSet;
690 /// let xs = [1,2,3,4,5,6];
691 /// let mut set: HashSet<isize> = xs.iter().cloned().collect();
692 /// set.retain(|&k| k % 2 == 0);
693 /// assert_eq!(set.len(), 3);
695 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
696 pub fn retain<F>(&mut self, mut f: F)
697 where F: FnMut(&T) -> bool
699 self.map.retain(|k, _| f(k));
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T, S> PartialEq for HashSet<T, S>
708 fn eq(&self, other: &HashSet<T, S>) -> bool {
709 if self.len() != other.len() {
713 self.iter().all(|key| other.contains(key))
717 #[stable(feature = "rust1", since = "1.0.0")]
718 impl<T, S> Eq for HashSet<T, S>
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl<T, S> fmt::Debug for HashSet<T, S>
726 where T: Eq + Hash + fmt::Debug,
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730 f.debug_set().entries(self.iter()).finish()
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T, S> FromIterator<T> for HashSet<T, S>
737 S: BuildHasher + Default
739 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
740 let mut set = HashSet::with_hasher(Default::default());
746 #[stable(feature = "rust1", since = "1.0.0")]
747 impl<T, S> Extend<T> for HashSet<T, S>
751 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
752 self.map.extend(iter.into_iter().map(|k| (k, ())));
756 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
757 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
758 where T: 'a + Eq + Hash + Copy,
761 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
762 self.extend(iter.into_iter().cloned());
766 #[stable(feature = "rust1", since = "1.0.0")]
767 impl<T, S> Default for HashSet<T, S>
769 S: BuildHasher + Default
771 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
772 fn default() -> HashSet<T, S> {
773 HashSet { map: HashMap::default() }
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
779 where T: Eq + Hash + Clone,
780 S: BuildHasher + Default
782 type Output = HashSet<T, S>;
784 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
789 /// use std::collections::HashSet;
791 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
792 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
794 /// let set = &a | &b;
797 /// let expected = [1, 2, 3, 4, 5];
799 /// assert!(expected.contains(x));
802 /// assert_eq!(i, expected.len());
804 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
805 self.union(rhs).cloned().collect()
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
811 where T: Eq + Hash + Clone,
812 S: BuildHasher + Default
814 type Output = HashSet<T, S>;
816 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
821 /// use std::collections::HashSet;
823 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
824 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
826 /// let set = &a & &b;
829 /// let expected = [2, 3];
831 /// assert!(expected.contains(x));
834 /// assert_eq!(i, expected.len());
836 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
837 self.intersection(rhs).cloned().collect()
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
843 where T: Eq + Hash + Clone,
844 S: BuildHasher + Default
846 type Output = HashSet<T, S>;
848 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
853 /// use std::collections::HashSet;
855 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
856 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
858 /// let set = &a ^ &b;
861 /// let expected = [1, 2, 4, 5];
863 /// assert!(expected.contains(x));
866 /// assert_eq!(i, expected.len());
868 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
869 self.symmetric_difference(rhs).cloned().collect()
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
875 where T: Eq + Hash + Clone,
876 S: BuildHasher + Default
878 type Output = HashSet<T, S>;
880 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
885 /// use std::collections::HashSet;
887 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
888 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
890 /// let set = &a - &b;
893 /// let expected = [1, 2];
895 /// assert!(expected.contains(x));
898 /// assert_eq!(i, expected.len());
900 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
901 self.difference(rhs).cloned().collect()
905 /// An iterator over the items of a `HashSet`.
907 /// This `struct` is created by the [`iter`] method on [`HashSet`].
908 /// See its documentation for more.
910 /// [`HashSet`]: struct.HashSet.html
911 /// [`iter`]: struct.HashSet.html#method.iter
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub struct Iter<'a, K: 'a> {
914 iter: Keys<'a, K, ()>,
917 /// An owning iterator over the items of a `HashSet`.
919 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
920 /// (provided by the `IntoIterator` trait). See its documentation for more.
922 /// [`HashSet`]: struct.HashSet.html
923 /// [`into_iter`]: struct.HashSet.html#method.into_iter
924 #[stable(feature = "rust1", since = "1.0.0")]
925 pub struct IntoIter<K> {
926 iter: map::IntoIter<K, ()>,
929 /// A draining iterator over the items of a `HashSet`.
931 /// This `struct` is created by the [`drain`] method on [`HashSet`].
932 /// See its documentation for more.
934 /// [`HashSet`]: struct.HashSet.html
935 /// [`drain`]: struct.HashSet.html#method.drain
936 #[stable(feature = "rust1", since = "1.0.0")]
937 pub struct Drain<'a, K: 'a> {
938 iter: map::Drain<'a, K, ()>,
941 /// A lazy iterator producing elements in the intersection of `HashSet`s.
943 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
944 /// See its documentation for more.
946 /// [`HashSet`]: struct.HashSet.html
947 /// [`intersection`]: struct.HashSet.html#method.intersection
948 #[stable(feature = "rust1", since = "1.0.0")]
949 pub struct Intersection<'a, T: 'a, S: 'a> {
950 // iterator of the first set
953 other: &'a HashSet<T, S>,
956 /// A lazy iterator producing elements in the difference of `HashSet`s.
958 /// This `struct` is created by the [`difference`] method on [`HashSet`].
959 /// See its documentation for more.
961 /// [`HashSet`]: struct.HashSet.html
962 /// [`difference`]: struct.HashSet.html#method.difference
963 #[stable(feature = "rust1", since = "1.0.0")]
964 pub struct Difference<'a, T: 'a, S: 'a> {
965 // iterator of the first set
968 other: &'a HashSet<T, S>,
971 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
973 /// This `struct` is created by the [`symmetric_difference`] method on
974 /// [`HashSet`]. See its documentation for more.
976 /// [`HashSet`]: struct.HashSet.html
977 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
980 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
983 /// A lazy iterator producing elements in the union of `HashSet`s.
985 /// This `struct` is created by the [`union`] method on [`HashSet`].
986 /// See its documentation for more.
988 /// [`HashSet`]: struct.HashSet.html
989 /// [`union`]: struct.HashSet.html#method.union
990 #[stable(feature = "rust1", since = "1.0.0")]
991 pub struct Union<'a, T: 'a, S: 'a> {
992 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
995 #[stable(feature = "rust1", since = "1.0.0")]
996 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
1001 type IntoIter = Iter<'a, T>;
1003 fn into_iter(self) -> Iter<'a, T> {
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T, S> IntoIterator for HashSet<T, S>
1014 type IntoIter = IntoIter<T>;
1016 /// Creates a consuming iterator, that is, one that moves each value out
1017 /// of the set in arbitrary order. The set cannot be used after calling
1023 /// use std::collections::HashSet;
1024 /// let mut set = HashSet::new();
1025 /// set.insert("a".to_string());
1026 /// set.insert("b".to_string());
1028 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1029 /// let v: Vec<String> = set.into_iter().collect();
1031 /// // Will print in an arbitrary order.
1033 /// println!("{}", x);
1036 fn into_iter(self) -> IntoIter<T> {
1037 IntoIter { iter: self.map.into_iter() }
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<'a, K> Clone for Iter<'a, K> {
1043 fn clone(&self) -> Iter<'a, K> {
1044 Iter { iter: self.iter.clone() }
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 impl<'a, K> Iterator for Iter<'a, K> {
1051 fn next(&mut self) -> Option<&'a K> {
1054 fn size_hint(&self) -> (usize, Option<usize>) {
1055 self.iter.size_hint()
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
1060 fn len(&self) -> usize {
1064 #[unstable(feature = "fused", issue = "35602")]
1065 impl<'a, K> FusedIterator for Iter<'a, K> {}
1067 #[stable(feature = "std_debug", since = "1.16.0")]
1068 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
1069 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1070 f.debug_list().entries(self.clone()).finish()
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 impl<K> Iterator for IntoIter<K> {
1078 fn next(&mut self) -> Option<K> {
1079 self.iter.next().map(|(k, _)| k)
1081 fn size_hint(&self) -> (usize, Option<usize>) {
1082 self.iter.size_hint()
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<K> ExactSizeIterator for IntoIter<K> {
1087 fn len(&self) -> usize {
1091 #[unstable(feature = "fused", issue = "35602")]
1092 impl<K> FusedIterator for IntoIter<K> {}
1094 #[stable(feature = "std_debug", since = "1.16.0")]
1095 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1097 let entries_iter = self.iter
1101 f.debug_list().entries(entries_iter).finish()
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a, K> Iterator for Drain<'a, K> {
1109 fn next(&mut self) -> Option<K> {
1110 self.iter.next().map(|(k, _)| k)
1112 fn size_hint(&self) -> (usize, Option<usize>) {
1113 self.iter.size_hint()
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1118 fn len(&self) -> usize {
1122 #[unstable(feature = "fused", issue = "35602")]
1123 impl<'a, K> FusedIterator for Drain<'a, K> {}
1125 #[stable(feature = "std_debug", since = "1.16.0")]
1126 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128 let entries_iter = self.iter
1132 f.debug_list().entries(entries_iter).finish()
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1138 fn clone(&self) -> Intersection<'a, T, S> {
1139 Intersection { iter: self.iter.clone(), ..*self }
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1150 fn next(&mut self) -> Option<&'a T> {
1152 match self.iter.next() {
1153 None => return None,
1155 if self.other.contains(elt) {
1163 fn size_hint(&self) -> (usize, Option<usize>) {
1164 let (_, upper) = self.iter.size_hint();
1169 #[stable(feature = "std_debug", since = "1.16.0")]
1170 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1171 where T: fmt::Debug + Eq + Hash,
1174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1175 f.debug_list().entries(self.clone()).finish()
1179 #[unstable(feature = "fused", issue = "35602")]
1180 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 impl<'a, T, S> Clone for Difference<'a, T, S> {
1188 fn clone(&self) -> Difference<'a, T, S> {
1189 Difference { iter: self.iter.clone(), ..*self }
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<'a, T, S> Iterator for Difference<'a, T, S>
1200 fn next(&mut self) -> Option<&'a T> {
1202 match self.iter.next() {
1203 None => return None,
1205 if !self.other.contains(elt) {
1213 fn size_hint(&self) -> (usize, Option<usize>) {
1214 let (_, upper) = self.iter.size_hint();
1219 #[unstable(feature = "fused", issue = "35602")]
1220 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1226 #[stable(feature = "std_debug", since = "1.16.0")]
1227 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1228 where T: fmt::Debug + Eq + Hash,
1231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232 f.debug_list().entries(self.clone()).finish()
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1238 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1239 SymmetricDifference { iter: self.iter.clone() }
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1250 fn next(&mut self) -> Option<&'a T> {
1253 fn size_hint(&self) -> (usize, Option<usize>) {
1254 self.iter.size_hint()
1258 #[unstable(feature = "fused", issue = "35602")]
1259 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1265 #[stable(feature = "std_debug", since = "1.16.0")]
1266 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1267 where T: fmt::Debug + Eq + Hash,
1270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1271 f.debug_list().entries(self.clone()).finish()
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<'a, T, S> Clone for Union<'a, T, S> {
1277 fn clone(&self) -> Union<'a, T, S> {
1278 Union { iter: self.iter.clone() }
1282 #[unstable(feature = "fused", issue = "35602")]
1283 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1289 #[stable(feature = "std_debug", since = "1.16.0")]
1290 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1291 where T: fmt::Debug + Eq + Hash,
1294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1295 f.debug_list().entries(self.clone()).finish()
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl<'a, T, S> Iterator for Union<'a, T, S>
1306 fn next(&mut self) -> Option<&'a T> {
1309 fn size_hint(&self) -> (usize, Option<usize>) {
1310 self.iter.size_hint()
1315 fn assert_covariance() {
1316 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1319 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1322 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1325 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1326 -> Difference<'a, &'new str, RandomState> {
1329 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1330 -> SymmetricDifference<'a, &'new str, RandomState> {
1333 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1334 -> Intersection<'a, &'new str, RandomState> {
1337 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1338 -> Union<'a, &'new str, RandomState> {
1341 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1349 use super::super::map::RandomState;
1352 fn test_zero_capacities() {
1353 type HS = HashSet<i32>;
1356 assert_eq!(s.capacity(), 0);
1358 let s = HS::default();
1359 assert_eq!(s.capacity(), 0);
1361 let s = HS::with_hasher(RandomState::new());
1362 assert_eq!(s.capacity(), 0);
1364 let s = HS::with_capacity(0);
1365 assert_eq!(s.capacity(), 0);
1367 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1368 assert_eq!(s.capacity(), 0);
1370 let mut s = HS::new();
1376 assert_eq!(s.capacity(), 0);
1378 let mut s = HS::new();
1380 assert_eq!(s.capacity(), 0);
1384 fn test_disjoint() {
1385 let mut xs = HashSet::new();
1386 let mut ys = HashSet::new();
1387 assert!(xs.is_disjoint(&ys));
1388 assert!(ys.is_disjoint(&xs));
1389 assert!(xs.insert(5));
1390 assert!(ys.insert(11));
1391 assert!(xs.is_disjoint(&ys));
1392 assert!(ys.is_disjoint(&xs));
1393 assert!(xs.insert(7));
1394 assert!(xs.insert(19));
1395 assert!(xs.insert(4));
1396 assert!(ys.insert(2));
1397 assert!(ys.insert(-11));
1398 assert!(xs.is_disjoint(&ys));
1399 assert!(ys.is_disjoint(&xs));
1400 assert!(ys.insert(7));
1401 assert!(!xs.is_disjoint(&ys));
1402 assert!(!ys.is_disjoint(&xs));
1406 fn test_subset_and_superset() {
1407 let mut a = HashSet::new();
1408 assert!(a.insert(0));
1409 assert!(a.insert(5));
1410 assert!(a.insert(11));
1411 assert!(a.insert(7));
1413 let mut b = HashSet::new();
1414 assert!(b.insert(0));
1415 assert!(b.insert(7));
1416 assert!(b.insert(19));
1417 assert!(b.insert(250));
1418 assert!(b.insert(11));
1419 assert!(b.insert(200));
1421 assert!(!a.is_subset(&b));
1422 assert!(!a.is_superset(&b));
1423 assert!(!b.is_subset(&a));
1424 assert!(!b.is_superset(&a));
1426 assert!(b.insert(5));
1428 assert!(a.is_subset(&b));
1429 assert!(!a.is_superset(&b));
1430 assert!(!b.is_subset(&a));
1431 assert!(b.is_superset(&a));
1436 let mut a = HashSet::new();
1438 assert!(a.insert(i));
1440 let mut observed: u32 = 0;
1442 observed |= 1 << *k;
1444 assert_eq!(observed, 0xFFFF_FFFF);
1448 fn test_intersection() {
1449 let mut a = HashSet::new();
1450 let mut b = HashSet::new();
1452 assert!(a.insert(11));
1453 assert!(a.insert(1));
1454 assert!(a.insert(3));
1455 assert!(a.insert(77));
1456 assert!(a.insert(103));
1457 assert!(a.insert(5));
1458 assert!(a.insert(-5));
1460 assert!(b.insert(2));
1461 assert!(b.insert(11));
1462 assert!(b.insert(77));
1463 assert!(b.insert(-9));
1464 assert!(b.insert(-42));
1465 assert!(b.insert(5));
1466 assert!(b.insert(3));
1469 let expected = [3, 5, 11, 77];
1470 for x in a.intersection(&b) {
1471 assert!(expected.contains(x));
1474 assert_eq!(i, expected.len());
1478 fn test_difference() {
1479 let mut a = HashSet::new();
1480 let mut b = HashSet::new();
1482 assert!(a.insert(1));
1483 assert!(a.insert(3));
1484 assert!(a.insert(5));
1485 assert!(a.insert(9));
1486 assert!(a.insert(11));
1488 assert!(b.insert(3));
1489 assert!(b.insert(9));
1492 let expected = [1, 5, 11];
1493 for x in a.difference(&b) {
1494 assert!(expected.contains(x));
1497 assert_eq!(i, expected.len());
1501 fn test_symmetric_difference() {
1502 let mut a = HashSet::new();
1503 let mut b = HashSet::new();
1505 assert!(a.insert(1));
1506 assert!(a.insert(3));
1507 assert!(a.insert(5));
1508 assert!(a.insert(9));
1509 assert!(a.insert(11));
1511 assert!(b.insert(-2));
1512 assert!(b.insert(3));
1513 assert!(b.insert(9));
1514 assert!(b.insert(14));
1515 assert!(b.insert(22));
1518 let expected = [-2, 1, 5, 11, 14, 22];
1519 for x in a.symmetric_difference(&b) {
1520 assert!(expected.contains(x));
1523 assert_eq!(i, expected.len());
1528 let mut a = HashSet::new();
1529 let mut b = HashSet::new();
1531 assert!(a.insert(1));
1532 assert!(a.insert(3));
1533 assert!(a.insert(5));
1534 assert!(a.insert(9));
1535 assert!(a.insert(11));
1536 assert!(a.insert(16));
1537 assert!(a.insert(19));
1538 assert!(a.insert(24));
1540 assert!(b.insert(-2));
1541 assert!(b.insert(1));
1542 assert!(b.insert(5));
1543 assert!(b.insert(9));
1544 assert!(b.insert(13));
1545 assert!(b.insert(19));
1548 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1549 for x in a.union(&b) {
1550 assert!(expected.contains(x));
1553 assert_eq!(i, expected.len());
1557 fn test_from_iter() {
1558 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1560 let set: HashSet<_> = xs.iter().cloned().collect();
1563 assert!(set.contains(x));
1568 fn test_move_iter() {
1570 let mut hs = HashSet::new();
1578 let v = hs.into_iter().collect::<Vec<char>>();
1579 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1584 // These constants once happened to expose a bug in insert().
1585 // I'm keeping them around to prevent a regression.
1586 let mut s1 = HashSet::new();
1592 let mut s2 = HashSet::new();
1606 let mut set = HashSet::new();
1607 let empty = HashSet::<i32>::new();
1612 let set_str = format!("{:?}", set);
1614 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1615 assert_eq!(format!("{:?}", empty), "{}");
1619 fn test_trivial_drain() {
1620 let mut s = HashSet::<i32>::new();
1621 for _ in s.drain() {}
1622 assert!(s.is_empty());
1625 let mut s = HashSet::<i32>::new();
1627 assert!(s.is_empty());
1632 let mut s: HashSet<_> = (1..100).collect();
1634 // try this a bunch of times to make sure we don't screw up internal state.
1636 assert_eq!(s.len(), 99);
1640 let mut d = s.drain();
1641 for (i, x) in d.by_ref().take(50).enumerate() {
1645 assert_eq!(last_i, 49);
1649 panic!("s should be empty!");
1652 // reset to try again.
1662 struct Foo(&'static str, i32);
1664 impl PartialEq for Foo {
1665 fn eq(&self, other: &Self) -> bool {
1672 impl hash::Hash for Foo {
1673 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1678 let mut s = HashSet::new();
1679 assert_eq!(s.replace(Foo("a", 1)), None);
1680 assert_eq!(s.len(), 1);
1681 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1682 assert_eq!(s.len(), 1);
1684 let mut it = s.iter();
1685 assert_eq!(it.next(), Some(&Foo("a", 2)));
1686 assert_eq!(it.next(), None);
1690 fn test_extend_ref() {
1691 let mut a = HashSet::new();
1694 a.extend(&[2, 3, 4]);
1696 assert_eq!(a.len(), 4);
1697 assert!(a.contains(&1));
1698 assert!(a.contains(&2));
1699 assert!(a.contains(&3));
1700 assert!(a.contains(&4));
1702 let mut b = HashSet::new();
1708 assert_eq!(a.len(), 6);
1709 assert!(a.contains(&1));
1710 assert!(a.contains(&2));
1711 assert!(a.contains(&3));
1712 assert!(a.contains(&4));
1713 assert!(a.contains(&5));
1714 assert!(a.contains(&6));
1719 let xs = [1, 2, 3, 4, 5, 6];
1720 let mut set: HashSet<isize> = xs.iter().cloned().collect();
1721 set.retain(|&k| k % 2 == 0);
1722 assert_eq!(set.len(), 3);
1723 assert!(set.contains(&2));
1724 assert!(set.contains(&4));
1725 assert!(set.contains(&6));