1 use crate::borrow::Borrow;
3 use crate::hash::{Hash, BuildHasher};
4 use crate::iter::{Chain, FromIterator, FusedIterator};
5 use crate::ops::{BitOr, BitAnd, BitXor, Sub};
7 use super::map::{self, HashMap, Keys, RandomState};
9 // Future Optimization (FIXME!)
10 // ============================
12 // Iteration over zero sized values is a noop. There is no need
13 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
14 // to get rid of it properly.
16 /// A hash set implemented as a `HashMap` where the value is `()`.
18 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
19 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
20 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
21 /// it is important that the following property holds:
24 /// k1 == k2 -> hash(k1) == hash(k2)
27 /// In other words, if two keys are equal, their hashes must be equal.
30 /// It is a logic error for an item to be modified in such a way that the
31 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
32 /// determined by the [`Eq`] trait, changes while it is in the set. This is
33 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
39 /// use std::collections::HashSet;
40 /// // Type inference lets us omit an explicit type signature (which
41 /// // would be `HashSet<String>` in this example).
42 /// let mut books = HashSet::new();
44 /// // Add some books.
45 /// books.insert("A Dance With Dragons".to_string());
46 /// books.insert("To Kill a Mockingbird".to_string());
47 /// books.insert("The Odyssey".to_string());
48 /// books.insert("The Great Gatsby".to_string());
50 /// // Check for a specific one.
51 /// if !books.contains("The Winds of Winter") {
52 /// println!("We have {} books, but The Winds of Winter ain't one.",
57 /// books.remove("The Odyssey");
59 /// // Iterate over everything.
60 /// for book in &books {
61 /// println!("{}", book);
65 /// The easiest way to use `HashSet` with a custom type is to derive
66 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
67 /// future be implied by [`Eq`].
70 /// use std::collections::HashSet;
71 /// #[derive(Hash, Eq, PartialEq, Debug)]
77 /// let mut vikings = HashSet::new();
79 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
80 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
81 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
82 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
84 /// // Use derived implementation to print the vikings.
85 /// for x in &vikings {
86 /// println!("{:?}", x);
90 /// A `HashSet` with fixed list of elements can be initialized from an array:
93 /// use std::collections::HashSet;
96 /// let viking_names: HashSet<&'static str> =
97 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
98 /// // use the values stored in the set
102 /// [`Cell`]: ../../std/cell/struct.Cell.html
103 /// [`Eq`]: ../../std/cmp/trait.Eq.html
104 /// [`Hash`]: ../../std/hash/trait.Hash.html
105 /// [`HashMap`]: struct.HashMap.html
106 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
107 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
109 #[stable(feature = "rust1", since = "1.0.0")]
110 pub struct HashSet<T, S = RandomState> {
111 map: HashMap<T, (), S>,
114 impl<T: Hash + Eq> HashSet<T, RandomState> {
115 /// Creates an empty `HashSet`.
117 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
118 /// is first inserted into.
123 /// use std::collections::HashSet;
124 /// let set: HashSet<i32> = HashSet::new();
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub fn new() -> HashSet<T, RandomState> {
129 HashSet { map: HashMap::new() }
132 /// Creates an empty `HashSet` with the specified capacity.
134 /// The hash set will be able to hold at least `capacity` elements without
135 /// reallocating. If `capacity` is 0, the hash set will not allocate.
140 /// use std::collections::HashSet;
141 /// let set: HashSet<i32> = HashSet::with_capacity(10);
142 /// assert!(set.capacity() >= 10);
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
147 HashSet { map: HashMap::with_capacity(capacity) }
151 impl<T, S> HashSet<T, S> {
152 /// Returns the number of elements the set can hold without reallocating.
157 /// use std::collections::HashSet;
158 /// let set: HashSet<i32> = HashSet::with_capacity(100);
159 /// assert!(set.capacity() >= 100);
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn capacity(&self) -> usize {
167 /// An iterator visiting all elements in arbitrary order.
168 /// The iterator element type is `&'a T`.
173 /// use std::collections::HashSet;
174 /// let mut set = HashSet::new();
178 /// // Will print in an arbitrary order.
179 /// for x in set.iter() {
180 /// println!("{}", x);
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn iter(&self) -> Iter<'_, T> {
185 Iter { iter: self.map.keys() }
188 /// Returns the number of elements in the set.
193 /// use std::collections::HashSet;
195 /// let mut v = HashSet::new();
196 /// assert_eq!(v.len(), 0);
198 /// assert_eq!(v.len(), 1);
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub fn len(&self) -> usize {
205 /// Returns `true` if the set contains no elements.
210 /// use std::collections::HashSet;
212 /// let mut v = HashSet::new();
213 /// assert!(v.is_empty());
215 /// assert!(!v.is_empty());
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn is_empty(&self) -> bool {
222 /// Clears the set, returning all elements in an iterator.
227 /// use std::collections::HashSet;
229 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
230 /// assert!(!set.is_empty());
232 /// // print 1, 2, 3 in an arbitrary order
233 /// for i in set.drain() {
234 /// println!("{}", i);
237 /// assert!(set.is_empty());
240 #[stable(feature = "drain", since = "1.6.0")]
241 pub fn drain(&mut self) -> Drain<'_, T> {
242 Drain { iter: self.map.drain() }
245 /// Clears the set, removing all values.
250 /// use std::collections::HashSet;
252 /// let mut v = HashSet::new();
255 /// assert!(v.is_empty());
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn clear(&mut self) {
263 impl<T, S> HashSet<T, S>
267 /// Creates a new empty hash set which will use the given hasher to hash
270 /// The hash set is also created with the default initial capacity.
272 /// Warning: `hasher` is normally randomly generated, and
273 /// is designed to allow `HashSet`s to be resistant to attacks that
274 /// cause many collisions and very poor performance. Setting it
275 /// manually using this function can expose a DoS attack vector.
280 /// use std::collections::HashSet;
281 /// use std::collections::hash_map::RandomState;
283 /// let s = RandomState::new();
284 /// let mut set = HashSet::with_hasher(s);
288 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
289 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
290 HashSet { map: HashMap::with_hasher(hasher) }
293 /// Creates an empty `HashSet` with the specified capacity, using
294 /// `hasher` to hash the keys.
296 /// The hash set will be able to hold at least `capacity` elements without
297 /// reallocating. If `capacity` is 0, the hash set will not allocate.
299 /// Warning: `hasher` is normally randomly generated, and
300 /// is designed to allow `HashSet`s to be resistant to attacks that
301 /// cause many collisions and very poor performance. Setting it
302 /// manually using this function can expose a DoS attack vector.
307 /// use std::collections::HashSet;
308 /// use std::collections::hash_map::RandomState;
310 /// let s = RandomState::new();
311 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
315 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
316 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
317 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
320 /// Returns a reference to the set's [`BuildHasher`].
322 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
327 /// use std::collections::HashSet;
328 /// use std::collections::hash_map::RandomState;
330 /// let hasher = RandomState::new();
331 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
332 /// let hasher: &RandomState = set.hasher();
334 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
335 pub fn hasher(&self) -> &S {
339 /// Reserves capacity for at least `additional` more elements to be inserted
340 /// in the `HashSet`. The collection may reserve more space to avoid
341 /// frequent reallocations.
345 /// Panics if the new allocation size overflows `usize`.
350 /// use std::collections::HashSet;
351 /// let mut set: HashSet<i32> = HashSet::new();
353 /// assert!(set.capacity() >= 10);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn reserve(&mut self, additional: usize) {
357 self.map.reserve(additional)
360 /// Shrinks the capacity of the set as much as possible. It will drop
361 /// down as much as possible while maintaining the internal rules
362 /// and possibly leaving some space in accordance with the resize policy.
367 /// use std::collections::HashSet;
369 /// let mut set = HashSet::with_capacity(100);
372 /// assert!(set.capacity() >= 100);
373 /// set.shrink_to_fit();
374 /// assert!(set.capacity() >= 2);
376 #[stable(feature = "rust1", since = "1.0.0")]
377 pub fn shrink_to_fit(&mut self) {
378 self.map.shrink_to_fit()
381 /// Shrinks the capacity of the set with a lower limit. It will drop
382 /// down no lower than the supplied limit while maintaining the internal rules
383 /// and possibly leaving some space in accordance with the resize policy.
385 /// Panics if the current capacity is smaller than the supplied
386 /// minimum capacity.
391 /// #![feature(shrink_to)]
392 /// use std::collections::HashSet;
394 /// let mut set = HashSet::with_capacity(100);
397 /// assert!(set.capacity() >= 100);
398 /// set.shrink_to(10);
399 /// assert!(set.capacity() >= 10);
400 /// set.shrink_to(0);
401 /// assert!(set.capacity() >= 2);
404 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
405 pub fn shrink_to(&mut self, min_capacity: usize) {
406 self.map.shrink_to(min_capacity)
409 /// Visits the values representing the difference,
410 /// i.e., the values that are in `self` but not in `other`.
415 /// use std::collections::HashSet;
416 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
417 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
419 /// // Can be seen as `a - b`.
420 /// for x in a.difference(&b) {
421 /// println!("{}", x); // Print 1
424 /// let diff: HashSet<_> = a.difference(&b).collect();
425 /// assert_eq!(diff, [1].iter().collect());
427 /// // Note that difference is not symmetric,
428 /// // and `b - a` means something else:
429 /// let diff: HashSet<_> = b.difference(&a).collect();
430 /// assert_eq!(diff, [4].iter().collect());
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
440 /// Visits the values representing the symmetric difference,
441 /// i.e., the values that are in `self` or in `other` but not in both.
446 /// use std::collections::HashSet;
447 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
448 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
450 /// // Print 1, 4 in arbitrary order.
451 /// for x in a.symmetric_difference(&b) {
452 /// println!("{}", x);
455 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
456 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
458 /// assert_eq!(diff1, diff2);
459 /// assert_eq!(diff1, [1, 4].iter().collect());
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn symmetric_difference<'a>(&'a self,
463 other: &'a HashSet<T, S>)
464 -> SymmetricDifference<'a, T, S> {
465 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
468 /// Visits the values representing the intersection,
469 /// i.e., the values that are both in `self` and `other`.
474 /// use std::collections::HashSet;
475 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
476 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
478 /// // Print 2, 3 in arbitrary order.
479 /// for x in a.intersection(&b) {
480 /// println!("{}", x);
483 /// let intersection: HashSet<_> = a.intersection(&b).collect();
484 /// assert_eq!(intersection, [2, 3].iter().collect());
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
488 if self.len() <= other.len() {
501 /// Visits the values representing the union,
502 /// i.e., all the values in `self` or `other`, without duplicates.
507 /// use std::collections::HashSet;
508 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
509 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
511 /// // Print 1, 2, 3, 4 in arbitrary order.
512 /// for x in a.union(&b) {
513 /// println!("{}", x);
516 /// let union: HashSet<_> = a.union(&b).collect();
517 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
521 if self.len() <= other.len() {
523 iter: self.iter().chain(other.difference(self)),
527 iter: other.iter().chain(self.difference(other)),
532 /// Returns `true` if the set contains a value.
534 /// The value may be any borrowed form of the set's value type, but
535 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
541 /// use std::collections::HashSet;
543 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
544 /// assert_eq!(set.contains(&1), true);
545 /// assert_eq!(set.contains(&4), false);
548 /// [`Eq`]: ../../std/cmp/trait.Eq.html
549 /// [`Hash`]: ../../std/hash/trait.Hash.html
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
555 self.map.contains_key(value)
558 /// Returns a reference to the value in the set, if any, that is equal to the given value.
560 /// The value may be any borrowed form of the set's value type, but
561 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
567 /// use std::collections::HashSet;
569 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
570 /// assert_eq!(set.get(&2), Some(&2));
571 /// assert_eq!(set.get(&4), None);
574 /// [`Eq`]: ../../std/cmp/trait.Eq.html
575 /// [`Hash`]: ../../std/hash/trait.Hash.html
576 #[stable(feature = "set_recovery", since = "1.9.0")]
577 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
581 self.map.get_key_value(value).map(|(k, _)| k)
584 /// Returns `true` if `self` has no elements in common with `other`.
585 /// This is equivalent to checking for an empty intersection.
590 /// use std::collections::HashSet;
592 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
593 /// let mut b = HashSet::new();
595 /// assert_eq!(a.is_disjoint(&b), true);
597 /// assert_eq!(a.is_disjoint(&b), true);
599 /// assert_eq!(a.is_disjoint(&b), false);
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
603 if self.len() <= other.len() {
604 self.iter().all(|v| !other.contains(v))
606 other.iter().all(|v| !self.contains(v))
610 /// Returns `true` if the set is a subset of another,
611 /// i.e., `other` contains at least all the values in `self`.
616 /// use std::collections::HashSet;
618 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
619 /// let mut set = HashSet::new();
621 /// assert_eq!(set.is_subset(&sup), true);
623 /// assert_eq!(set.is_subset(&sup), true);
625 /// assert_eq!(set.is_subset(&sup), false);
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
629 if self.len() <= other.len() {
630 self.iter().all(|v| other.contains(v))
636 /// Returns `true` if the set is a superset of another,
637 /// i.e., `self` contains at least all the values in `other`.
642 /// use std::collections::HashSet;
644 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
645 /// let mut set = HashSet::new();
647 /// assert_eq!(set.is_superset(&sub), false);
651 /// assert_eq!(set.is_superset(&sub), false);
654 /// assert_eq!(set.is_superset(&sub), true);
657 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
659 other.is_subset(self)
662 /// Adds a value to the set.
664 /// If the set did not have this value present, `true` is returned.
666 /// If the set did have this value present, `false` is returned.
671 /// use std::collections::HashSet;
673 /// let mut set = HashSet::new();
675 /// assert_eq!(set.insert(2), true);
676 /// assert_eq!(set.insert(2), false);
677 /// assert_eq!(set.len(), 1);
679 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn insert(&mut self, value: T) -> bool {
681 self.map.insert(value, ()).is_none()
684 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
685 /// one. Returns the replaced value.
690 /// use std::collections::HashSet;
692 /// let mut set = HashSet::new();
693 /// set.insert(Vec::<i32>::new());
695 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
696 /// set.replace(Vec::with_capacity(10));
697 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
699 #[stable(feature = "set_recovery", since = "1.9.0")]
700 pub fn replace(&mut self, value: T) -> Option<T> {
701 match self.map.entry(value) {
702 map::Entry::Occupied(occupied) => Some(occupied.replace_key()),
703 map::Entry::Vacant(vacant) => {
710 /// Removes a value from the set. Returns whether the value was
711 /// present in the set.
713 /// The value may be any borrowed form of the set's value type, but
714 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
720 /// use std::collections::HashSet;
722 /// let mut set = HashSet::new();
725 /// assert_eq!(set.remove(&2), true);
726 /// assert_eq!(set.remove(&2), false);
729 /// [`Eq`]: ../../std/cmp/trait.Eq.html
730 /// [`Hash`]: ../../std/hash/trait.Hash.html
731 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
736 self.map.remove(value).is_some()
739 /// Removes and returns the value in the set, if any, that is equal to the given one.
741 /// The value may be any borrowed form of the set's value type, but
742 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
748 /// use std::collections::HashSet;
750 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
751 /// assert_eq!(set.take(&2), Some(2));
752 /// assert_eq!(set.take(&2), None);
755 /// [`Eq`]: ../../std/cmp/trait.Eq.html
756 /// [`Hash`]: ../../std/hash/trait.Hash.html
757 #[stable(feature = "set_recovery", since = "1.9.0")]
758 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
762 self.map.remove_entry(value).map(|(k, _)| k)
765 /// Retains only the elements specified by the predicate.
767 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
772 /// use std::collections::HashSet;
774 /// let xs = [1,2,3,4,5,6];
775 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
776 /// set.retain(|&k| k % 2 == 0);
777 /// assert_eq!(set.len(), 3);
779 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
780 pub fn retain<F>(&mut self, mut f: F)
781 where F: FnMut(&T) -> bool
783 self.map.retain(|k, _| f(k));
787 #[stable(feature = "rust1", since = "1.0.0")]
788 impl<T, S> PartialEq for HashSet<T, S>
792 fn eq(&self, other: &HashSet<T, S>) -> bool {
793 if self.len() != other.len() {
797 self.iter().all(|key| other.contains(key))
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<T, S> Eq for HashSet<T, S>
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl<T, S> fmt::Debug for HashSet<T, S>
810 where T: Eq + Hash + fmt::Debug,
813 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
814 f.debug_set().entries(self.iter()).finish()
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl<T, S> FromIterator<T> for HashSet<T, S>
821 S: BuildHasher + Default
823 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
824 let mut set = HashSet::with_hasher(Default::default());
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<T, S> Extend<T> for HashSet<T, S>
835 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
836 self.map.extend(iter.into_iter().map(|k| (k, ())));
840 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
841 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
842 where T: 'a + Eq + Hash + Copy,
845 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
846 self.extend(iter.into_iter().cloned());
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<T, S> Default for HashSet<T, S>
853 S: BuildHasher + Default
855 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
856 fn default() -> HashSet<T, S> {
857 HashSet { map: HashMap::default() }
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
863 where T: Eq + Hash + Clone,
864 S: BuildHasher + Default
866 type Output = HashSet<T, S>;
868 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
873 /// use std::collections::HashSet;
875 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
876 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
878 /// let set = &a | &b;
881 /// let expected = [1, 2, 3, 4, 5];
883 /// assert!(expected.contains(x));
886 /// assert_eq!(i, expected.len());
888 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
889 self.union(rhs).cloned().collect()
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
895 where T: Eq + Hash + Clone,
896 S: BuildHasher + Default
898 type Output = HashSet<T, S>;
900 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
905 /// use std::collections::HashSet;
907 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
908 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
910 /// let set = &a & &b;
913 /// let expected = [2, 3];
915 /// assert!(expected.contains(x));
918 /// assert_eq!(i, expected.len());
920 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
921 self.intersection(rhs).cloned().collect()
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
927 where T: Eq + Hash + Clone,
928 S: BuildHasher + Default
930 type Output = HashSet<T, S>;
932 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
937 /// use std::collections::HashSet;
939 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
940 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
942 /// let set = &a ^ &b;
945 /// let expected = [1, 2, 4, 5];
947 /// assert!(expected.contains(x));
950 /// assert_eq!(i, expected.len());
952 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
953 self.symmetric_difference(rhs).cloned().collect()
957 #[stable(feature = "rust1", since = "1.0.0")]
958 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
959 where T: Eq + Hash + Clone,
960 S: BuildHasher + Default
962 type Output = HashSet<T, S>;
964 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
969 /// use std::collections::HashSet;
971 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
972 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
974 /// let set = &a - &b;
977 /// let expected = [1, 2];
979 /// assert!(expected.contains(x));
982 /// assert_eq!(i, expected.len());
984 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
985 self.difference(rhs).cloned().collect()
989 /// An iterator over the items of a `HashSet`.
991 /// This `struct` is created by the [`iter`] method on [`HashSet`].
992 /// See its documentation for more.
994 /// [`HashSet`]: struct.HashSet.html
995 /// [`iter`]: struct.HashSet.html#method.iter
996 #[stable(feature = "rust1", since = "1.0.0")]
997 pub struct Iter<'a, K: 'a> {
998 iter: Keys<'a, K, ()>,
1001 /// An owning iterator over the items of a `HashSet`.
1003 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
1004 /// (provided by the `IntoIterator` trait). See its documentation for more.
1006 /// [`HashSet`]: struct.HashSet.html
1007 /// [`into_iter`]: struct.HashSet.html#method.into_iter
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 pub struct IntoIter<K> {
1010 iter: map::IntoIter<K, ()>,
1013 /// A draining iterator over the items of a `HashSet`.
1015 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1016 /// See its documentation for more.
1018 /// [`HashSet`]: struct.HashSet.html
1019 /// [`drain`]: struct.HashSet.html#method.drain
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub struct Drain<'a, K: 'a> {
1022 iter: map::Drain<'a, K, ()>,
1025 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1027 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1028 /// See its documentation for more.
1030 /// [`HashSet`]: struct.HashSet.html
1031 /// [`intersection`]: struct.HashSet.html#method.intersection
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub struct Intersection<'a, T: 'a, S: 'a> {
1034 // iterator of the first set
1037 other: &'a HashSet<T, S>,
1040 /// A lazy iterator producing elements in the difference of `HashSet`s.
1042 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1043 /// See its documentation for more.
1045 /// [`HashSet`]: struct.HashSet.html
1046 /// [`difference`]: struct.HashSet.html#method.difference
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub struct Difference<'a, T: 'a, S: 'a> {
1049 // iterator of the first set
1052 other: &'a HashSet<T, S>,
1055 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1057 /// This `struct` is created by the [`symmetric_difference`] method on
1058 /// [`HashSet`]. See its documentation for more.
1060 /// [`HashSet`]: struct.HashSet.html
1061 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1064 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1067 /// A lazy iterator producing elements in the union of `HashSet`s.
1069 /// This `struct` is created by the [`union`] method on [`HashSet`].
1070 /// See its documentation for more.
1072 /// [`HashSet`]: struct.HashSet.html
1073 /// [`union`]: struct.HashSet.html#method.union
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub struct Union<'a, T: 'a, S: 'a> {
1076 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1082 type IntoIter = Iter<'a, T>;
1084 fn into_iter(self) -> Iter<'a, T> {
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T, S> IntoIterator for HashSet<T, S> {
1092 type IntoIter = IntoIter<T>;
1094 /// Creates a consuming iterator, that is, one that moves each value out
1095 /// of the set in arbitrary order. The set cannot be used after calling
1101 /// use std::collections::HashSet;
1102 /// let mut set = HashSet::new();
1103 /// set.insert("a".to_string());
1104 /// set.insert("b".to_string());
1106 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1107 /// let v: Vec<String> = set.into_iter().collect();
1109 /// // Will print in an arbitrary order.
1111 /// println!("{}", x);
1114 fn into_iter(self) -> IntoIter<T> {
1115 IntoIter { iter: self.map.into_iter() }
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<K> Clone for Iter<'_, K> {
1121 fn clone(&self) -> Self {
1122 Iter { iter: self.iter.clone() }
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 impl<'a, K> Iterator for Iter<'a, K> {
1129 fn next(&mut self) -> Option<&'a K> {
1132 fn size_hint(&self) -> (usize, Option<usize>) {
1133 self.iter.size_hint()
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<K> ExactSizeIterator for Iter<'_, K> {
1138 fn len(&self) -> usize {
1142 #[stable(feature = "fused", since = "1.26.0")]
1143 impl<K> FusedIterator for Iter<'_, K> {}
1145 #[stable(feature = "std_debug", since = "1.16.0")]
1146 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1148 f.debug_list().entries(self.clone()).finish()
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<K> Iterator for IntoIter<K> {
1156 fn next(&mut self) -> Option<K> {
1157 self.iter.next().map(|(k, _)| k)
1159 fn size_hint(&self) -> (usize, Option<usize>) {
1160 self.iter.size_hint()
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 impl<K> ExactSizeIterator for IntoIter<K> {
1165 fn len(&self) -> usize {
1169 #[stable(feature = "fused", since = "1.26.0")]
1170 impl<K> FusedIterator for IntoIter<K> {}
1172 #[stable(feature = "std_debug", since = "1.16.0")]
1173 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1175 let entries_iter = self.iter
1179 f.debug_list().entries(entries_iter).finish()
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<'a, K> Iterator for Drain<'a, K> {
1187 fn next(&mut self) -> Option<K> {
1188 self.iter.next().map(|(k, _)| k)
1190 fn size_hint(&self) -> (usize, Option<usize>) {
1191 self.iter.size_hint()
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 impl<K> ExactSizeIterator for Drain<'_, K> {
1196 fn len(&self) -> usize {
1200 #[stable(feature = "fused", since = "1.26.0")]
1201 impl<K> FusedIterator for Drain<'_, K> {}
1203 #[stable(feature = "std_debug", since = "1.16.0")]
1204 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1206 let entries_iter = self.iter
1210 f.debug_list().entries(entries_iter).finish()
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<T, S> Clone for Intersection<'_, T, S> {
1216 fn clone(&self) -> Self {
1217 Intersection { iter: self.iter.clone(), ..*self }
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1228 fn next(&mut self) -> Option<&'a T> {
1230 let elt = self.iter.next()?;
1231 if self.other.contains(elt) {
1237 fn size_hint(&self) -> (usize, Option<usize>) {
1238 let (_, upper) = self.iter.size_hint();
1243 #[stable(feature = "std_debug", since = "1.16.0")]
1244 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1245 where T: fmt::Debug + Eq + Hash,
1248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1249 f.debug_list().entries(self.clone()).finish()
1253 #[stable(feature = "fused", since = "1.26.0")]
1254 impl<T, S> FusedIterator for Intersection<'_, T, S>
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl<T, S> Clone for Difference<'_, T, S> {
1262 fn clone(&self) -> Self {
1263 Difference { iter: self.iter.clone(), ..*self }
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 impl<'a, T, S> Iterator for Difference<'a, T, S>
1274 fn next(&mut self) -> Option<&'a T> {
1276 let elt = self.iter.next()?;
1277 if !self.other.contains(elt) {
1283 fn size_hint(&self) -> (usize, Option<usize>) {
1284 let (_, upper) = self.iter.size_hint();
1289 #[stable(feature = "fused", since = "1.26.0")]
1290 impl<T, S> FusedIterator for Difference<'_, T, S>
1296 #[stable(feature = "std_debug", since = "1.16.0")]
1297 impl<T, S> fmt::Debug for Difference<'_, T, S>
1298 where T: fmt::Debug + Eq + Hash,
1301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1302 f.debug_list().entries(self.clone()).finish()
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1308 fn clone(&self) -> Self {
1309 SymmetricDifference { iter: self.iter.clone() }
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1320 fn next(&mut self) -> Option<&'a T> {
1323 fn size_hint(&self) -> (usize, Option<usize>) {
1324 self.iter.size_hint()
1328 #[stable(feature = "fused", since = "1.26.0")]
1329 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1335 #[stable(feature = "std_debug", since = "1.16.0")]
1336 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1337 where T: fmt::Debug + Eq + Hash,
1340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1341 f.debug_list().entries(self.clone()).finish()
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 impl<T, S> Clone for Union<'_, T, S> {
1347 fn clone(&self) -> Self {
1348 Union { iter: self.iter.clone() }
1352 #[stable(feature = "fused", since = "1.26.0")]
1353 impl<T, S> FusedIterator for Union<'_, T, S>
1359 #[stable(feature = "std_debug", since = "1.16.0")]
1360 impl<T, S> fmt::Debug for Union<'_, T, S>
1361 where T: fmt::Debug + Eq + Hash,
1364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1365 f.debug_list().entries(self.clone()).finish()
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<'a, T, S> Iterator for Union<'a, T, S>
1376 fn next(&mut self) -> Option<&'a T> {
1379 fn size_hint(&self) -> (usize, Option<usize>) {
1380 self.iter.size_hint()
1385 fn assert_covariance() {
1386 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1389 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1392 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1395 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1396 -> Difference<'a, &'new str, RandomState> {
1399 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1400 -> SymmetricDifference<'a, &'new str, RandomState> {
1403 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1404 -> Intersection<'a, &'new str, RandomState> {
1407 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1408 -> Union<'a, &'new str, RandomState> {
1411 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1419 use super::super::map::RandomState;
1422 fn test_zero_capacities() {
1423 type HS = HashSet<i32>;
1426 assert_eq!(s.capacity(), 0);
1428 let s = HS::default();
1429 assert_eq!(s.capacity(), 0);
1431 let s = HS::with_hasher(RandomState::new());
1432 assert_eq!(s.capacity(), 0);
1434 let s = HS::with_capacity(0);
1435 assert_eq!(s.capacity(), 0);
1437 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1438 assert_eq!(s.capacity(), 0);
1440 let mut s = HS::new();
1446 assert_eq!(s.capacity(), 0);
1448 let mut s = HS::new();
1450 assert_eq!(s.capacity(), 0);
1454 fn test_disjoint() {
1455 let mut xs = HashSet::new();
1456 let mut ys = HashSet::new();
1457 assert!(xs.is_disjoint(&ys));
1458 assert!(ys.is_disjoint(&xs));
1459 assert!(xs.insert(5));
1460 assert!(ys.insert(11));
1461 assert!(xs.is_disjoint(&ys));
1462 assert!(ys.is_disjoint(&xs));
1463 assert!(xs.insert(7));
1464 assert!(xs.insert(19));
1465 assert!(xs.insert(4));
1466 assert!(ys.insert(2));
1467 assert!(ys.insert(-11));
1468 assert!(xs.is_disjoint(&ys));
1469 assert!(ys.is_disjoint(&xs));
1470 assert!(ys.insert(7));
1471 assert!(!xs.is_disjoint(&ys));
1472 assert!(!ys.is_disjoint(&xs));
1476 fn test_subset_and_superset() {
1477 let mut a = HashSet::new();
1478 assert!(a.insert(0));
1479 assert!(a.insert(5));
1480 assert!(a.insert(11));
1481 assert!(a.insert(7));
1483 let mut b = HashSet::new();
1484 assert!(b.insert(0));
1485 assert!(b.insert(7));
1486 assert!(b.insert(19));
1487 assert!(b.insert(250));
1488 assert!(b.insert(11));
1489 assert!(b.insert(200));
1491 assert!(!a.is_subset(&b));
1492 assert!(!a.is_superset(&b));
1493 assert!(!b.is_subset(&a));
1494 assert!(!b.is_superset(&a));
1496 assert!(b.insert(5));
1498 assert!(a.is_subset(&b));
1499 assert!(!a.is_superset(&b));
1500 assert!(!b.is_subset(&a));
1501 assert!(b.is_superset(&a));
1506 let mut a = HashSet::new();
1508 assert!(a.insert(i));
1510 let mut observed: u32 = 0;
1512 observed |= 1 << *k;
1514 assert_eq!(observed, 0xFFFF_FFFF);
1518 fn test_intersection() {
1519 let mut a = HashSet::new();
1520 let mut b = HashSet::new();
1521 assert!(a.intersection(&b).next().is_none());
1523 assert!(a.insert(11));
1524 assert!(a.insert(1));
1525 assert!(a.insert(3));
1526 assert!(a.insert(77));
1527 assert!(a.insert(103));
1528 assert!(a.insert(5));
1529 assert!(a.insert(-5));
1531 assert!(b.insert(2));
1532 assert!(b.insert(11));
1533 assert!(b.insert(77));
1534 assert!(b.insert(-9));
1535 assert!(b.insert(-42));
1536 assert!(b.insert(5));
1537 assert!(b.insert(3));
1540 let expected = [3, 5, 11, 77];
1541 for x in a.intersection(&b) {
1542 assert!(expected.contains(x));
1545 assert_eq!(i, expected.len());
1547 assert!(a.insert(9)); // make a bigger than b
1550 for x in a.intersection(&b) {
1551 assert!(expected.contains(x));
1554 assert_eq!(i, expected.len());
1557 for x in b.intersection(&a) {
1558 assert!(expected.contains(x));
1561 assert_eq!(i, expected.len());
1565 fn test_difference() {
1566 let mut a = HashSet::new();
1567 let mut b = HashSet::new();
1569 assert!(a.insert(1));
1570 assert!(a.insert(3));
1571 assert!(a.insert(5));
1572 assert!(a.insert(9));
1573 assert!(a.insert(11));
1575 assert!(b.insert(3));
1576 assert!(b.insert(9));
1579 let expected = [1, 5, 11];
1580 for x in a.difference(&b) {
1581 assert!(expected.contains(x));
1584 assert_eq!(i, expected.len());
1588 fn test_symmetric_difference() {
1589 let mut a = HashSet::new();
1590 let mut b = HashSet::new();
1592 assert!(a.insert(1));
1593 assert!(a.insert(3));
1594 assert!(a.insert(5));
1595 assert!(a.insert(9));
1596 assert!(a.insert(11));
1598 assert!(b.insert(-2));
1599 assert!(b.insert(3));
1600 assert!(b.insert(9));
1601 assert!(b.insert(14));
1602 assert!(b.insert(22));
1605 let expected = [-2, 1, 5, 11, 14, 22];
1606 for x in a.symmetric_difference(&b) {
1607 assert!(expected.contains(x));
1610 assert_eq!(i, expected.len());
1615 let mut a = HashSet::new();
1616 let mut b = HashSet::new();
1617 assert!(a.union(&b).next().is_none());
1618 assert!(b.union(&a).next().is_none());
1620 assert!(a.insert(1));
1621 assert!(a.insert(3));
1622 assert!(a.insert(11));
1623 assert!(a.insert(16));
1624 assert!(a.insert(19));
1625 assert!(a.insert(24));
1627 assert!(b.insert(-2));
1628 assert!(b.insert(1));
1629 assert!(b.insert(5));
1630 assert!(b.insert(9));
1631 assert!(b.insert(13));
1632 assert!(b.insert(19));
1635 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1636 for x in a.union(&b) {
1637 assert!(expected.contains(x));
1640 assert_eq!(i, expected.len());
1642 assert!(a.insert(9)); // make a bigger than b
1643 assert!(a.insert(5));
1646 for x in a.union(&b) {
1647 assert!(expected.contains(x));
1650 assert_eq!(i, expected.len());
1653 for x in b.union(&a) {
1654 assert!(expected.contains(x));
1657 assert_eq!(i, expected.len());
1661 fn test_from_iter() {
1662 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1664 let set: HashSet<_> = xs.iter().cloned().collect();
1667 assert!(set.contains(x));
1672 fn test_move_iter() {
1674 let mut hs = HashSet::new();
1682 let v = hs.into_iter().collect::<Vec<char>>();
1683 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1688 // These constants once happened to expose a bug in insert().
1689 // I'm keeping them around to prevent a regression.
1690 let mut s1 = HashSet::new();
1696 let mut s2 = HashSet::new();
1710 let mut set = HashSet::new();
1711 let empty = HashSet::<i32>::new();
1716 let set_str = format!("{:?}", set);
1718 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1719 assert_eq!(format!("{:?}", empty), "{}");
1723 fn test_trivial_drain() {
1724 let mut s = HashSet::<i32>::new();
1725 for _ in s.drain() {}
1726 assert!(s.is_empty());
1729 let mut s = HashSet::<i32>::new();
1731 assert!(s.is_empty());
1736 let mut s: HashSet<_> = (1..100).collect();
1738 // try this a bunch of times to make sure we don't screw up internal state.
1740 assert_eq!(s.len(), 99);
1744 let mut d = s.drain();
1745 for (i, x) in d.by_ref().take(50).enumerate() {
1749 assert_eq!(last_i, 49);
1753 panic!("s should be empty!");
1756 // reset to try again.
1766 struct Foo(&'static str, i32);
1768 impl PartialEq for Foo {
1769 fn eq(&self, other: &Self) -> bool {
1776 impl hash::Hash for Foo {
1777 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1782 let mut s = HashSet::new();
1783 assert_eq!(s.replace(Foo("a", 1)), None);
1784 assert_eq!(s.len(), 1);
1785 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1786 assert_eq!(s.len(), 1);
1788 let mut it = s.iter();
1789 assert_eq!(it.next(), Some(&Foo("a", 2)));
1790 assert_eq!(it.next(), None);
1794 fn test_extend_ref() {
1795 let mut a = HashSet::new();
1798 a.extend(&[2, 3, 4]);
1800 assert_eq!(a.len(), 4);
1801 assert!(a.contains(&1));
1802 assert!(a.contains(&2));
1803 assert!(a.contains(&3));
1804 assert!(a.contains(&4));
1806 let mut b = HashSet::new();
1812 assert_eq!(a.len(), 6);
1813 assert!(a.contains(&1));
1814 assert!(a.contains(&2));
1815 assert!(a.contains(&3));
1816 assert!(a.contains(&4));
1817 assert!(a.contains(&5));
1818 assert!(a.contains(&6));
1823 let xs = [1, 2, 3, 4, 5, 6];
1824 let mut set: HashSet<i32> = xs.iter().cloned().collect();
1825 set.retain(|&k| k % 2 == 0);
1826 assert_eq!(set.len(), 3);
1827 assert!(set.contains(&2));
1828 assert!(set.contains(&4));
1829 assert!(set.contains(&6));