3 use hash::{Hash, BuildHasher};
4 use iter::{Chain, FromIterator, FusedIterator};
5 use ops::{BitOr, BitAnd, BitXor, Sub};
8 use super::map::{self, HashMap, Keys, RandomState};
10 // Future Optimization (FIXME!)
11 // =============================
13 // Iteration over zero sized values is a noop. There is no need
14 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
15 // to get rid of it properly.
17 /// A hash set implemented as a `HashMap` where the value is `()`.
19 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
20 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
21 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
22 /// it is important that the following property holds:
25 /// k1 == k2 -> hash(k1) == hash(k2)
28 /// In other words, if two keys are equal, their hashes must be equal.
31 /// It is a logic error for an item to be modified in such a way that the
32 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
33 /// determined by the [`Eq`] trait, changes while it is in the set. This is
34 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
40 /// use std::collections::HashSet;
41 /// // Type inference lets us omit an explicit type signature (which
42 /// // would be `HashSet<String>` in this example).
43 /// let mut books = HashSet::new();
45 /// // Add some books.
46 /// books.insert("A Dance With Dragons".to_string());
47 /// books.insert("To Kill a Mockingbird".to_string());
48 /// books.insert("The Odyssey".to_string());
49 /// books.insert("The Great Gatsby".to_string());
51 /// // Check for a specific one.
52 /// if !books.contains("The Winds of Winter") {
53 /// println!("We have {} books, but The Winds of Winter ain't one.",
58 /// books.remove("The Odyssey");
60 /// // Iterate over everything.
61 /// for book in &books {
62 /// println!("{}", book);
66 /// The easiest way to use `HashSet` with a custom type is to derive
67 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
68 /// future be implied by [`Eq`].
71 /// use std::collections::HashSet;
72 /// #[derive(Hash, Eq, PartialEq, Debug)]
78 /// let mut vikings = HashSet::new();
80 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
81 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
82 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
83 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
85 /// // Use derived implementation to print the vikings.
86 /// for x in &vikings {
87 /// println!("{:?}", x);
91 /// A `HashSet` with fixed list of elements can be initialized from an array:
94 /// use std::collections::HashSet;
97 /// let viking_names: HashSet<&'static str> =
98 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
99 /// // use the values stored in the set
103 /// [`Cell`]: ../../std/cell/struct.Cell.html
104 /// [`Eq`]: ../../std/cmp/trait.Eq.html
105 /// [`Hash`]: ../../std/hash/trait.Hash.html
106 /// [`HashMap`]: struct.HashMap.html
107 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
108 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub struct HashSet<T, S = RandomState> {
112 map: HashMap<T, (), S>,
115 impl<T: Hash + Eq> HashSet<T, RandomState> {
116 /// Creates an empty `HashSet`.
118 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
119 /// is first inserted into.
124 /// use std::collections::HashSet;
125 /// let set: HashSet<i32> = HashSet::new();
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub fn new() -> HashSet<T, RandomState> {
130 HashSet { map: HashMap::new() }
133 /// Creates an empty `HashSet` with the specified capacity.
135 /// The hash set will be able to hold at least `capacity` elements without
136 /// reallocating. If `capacity` is 0, the hash set will not allocate.
141 /// use std::collections::HashSet;
142 /// let set: HashSet<i32> = HashSet::with_capacity(10);
143 /// assert!(set.capacity() >= 10);
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
148 HashSet { map: HashMap::with_capacity(capacity) }
152 impl<T, S> HashSet<T, S>
156 /// Creates a new empty hash set which will use the given hasher to hash
159 /// The hash set is also created with the default initial capacity.
161 /// Warning: `hasher` is normally randomly generated, and
162 /// is designed to allow `HashSet`s to be resistant to attacks that
163 /// cause many collisions and very poor performance. Setting it
164 /// manually using this function can expose a DoS attack vector.
169 /// use std::collections::HashSet;
170 /// use std::collections::hash_map::RandomState;
172 /// let s = RandomState::new();
173 /// let mut set = HashSet::with_hasher(s);
177 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
178 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
179 HashSet { map: HashMap::with_hasher(hasher) }
182 /// Creates an empty `HashSet` with the specified capacity, using
183 /// `hasher` to hash the keys.
185 /// The hash set will be able to hold at least `capacity` elements without
186 /// reallocating. If `capacity` is 0, the hash set will not allocate.
188 /// Warning: `hasher` is normally randomly generated, and
189 /// is designed to allow `HashSet`s to be resistant to attacks that
190 /// cause many collisions and very poor performance. Setting it
191 /// manually using this function can expose a DoS attack vector.
196 /// use std::collections::HashSet;
197 /// use std::collections::hash_map::RandomState;
199 /// let s = RandomState::new();
200 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
204 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
205 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
206 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
209 /// Returns a reference to the set's [`BuildHasher`].
211 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
216 /// use std::collections::HashSet;
217 /// use std::collections::hash_map::RandomState;
219 /// let hasher = RandomState::new();
220 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
221 /// let hasher: &RandomState = set.hasher();
223 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
224 pub fn hasher(&self) -> &S {
228 /// Returns the number of elements the set can hold without reallocating.
233 /// use std::collections::HashSet;
234 /// let set: HashSet<i32> = HashSet::with_capacity(100);
235 /// assert!(set.capacity() >= 100);
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn capacity(&self) -> usize {
243 /// Reserves capacity for at least `additional` more elements to be inserted
244 /// in the `HashSet`. The collection may reserve more space to avoid
245 /// frequent reallocations.
249 /// Panics if the new allocation size overflows `usize`.
254 /// use std::collections::HashSet;
255 /// let mut set: HashSet<i32> = HashSet::new();
257 /// assert!(set.capacity() >= 10);
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn reserve(&mut self, additional: usize) {
261 self.map.reserve(additional)
264 /// Shrinks the capacity of the set as much as possible. It will drop
265 /// down as much as possible while maintaining the internal rules
266 /// and possibly leaving some space in accordance with the resize policy.
271 /// use std::collections::HashSet;
273 /// let mut set = HashSet::with_capacity(100);
276 /// assert!(set.capacity() >= 100);
277 /// set.shrink_to_fit();
278 /// assert!(set.capacity() >= 2);
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn shrink_to_fit(&mut self) {
282 self.map.shrink_to_fit()
285 /// Shrinks the capacity of the set with a lower limit. It will drop
286 /// down no lower than the supplied limit while maintaining the internal rules
287 /// and possibly leaving some space in accordance with the resize policy.
289 /// Panics if the current capacity is smaller than the supplied
290 /// minimum capacity.
295 /// #![feature(shrink_to)]
296 /// use std::collections::HashSet;
298 /// let mut set = HashSet::with_capacity(100);
301 /// assert!(set.capacity() >= 100);
302 /// set.shrink_to(10);
303 /// assert!(set.capacity() >= 10);
304 /// set.shrink_to(0);
305 /// assert!(set.capacity() >= 2);
308 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
309 pub fn shrink_to(&mut self, min_capacity: usize) {
310 self.map.shrink_to(min_capacity)
313 /// An iterator visiting all elements in arbitrary order.
314 /// The iterator element type is `&'a T`.
319 /// use std::collections::HashSet;
320 /// let mut set = HashSet::new();
324 /// // Will print in an arbitrary order.
325 /// for x in set.iter() {
326 /// println!("{}", x);
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn iter(&self) -> Iter<T> {
331 Iter { iter: self.map.keys() }
334 /// Visits the values representing the difference,
335 /// i.e., the values that are in `self` but not in `other`.
340 /// use std::collections::HashSet;
341 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
342 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
344 /// // Can be seen as `a - b`.
345 /// for x in a.difference(&b) {
346 /// println!("{}", x); // Print 1
349 /// let diff: HashSet<_> = a.difference(&b).collect();
350 /// assert_eq!(diff, [1].iter().collect());
352 /// // Note that difference is not symmetric,
353 /// // and `b - a` means something else:
354 /// let diff: HashSet<_> = b.difference(&a).collect();
355 /// assert_eq!(diff, [4].iter().collect());
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
365 /// Visits the values representing the symmetric difference,
366 /// i.e., the values that are in `self` or in `other` but not in both.
371 /// use std::collections::HashSet;
372 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
373 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
375 /// // Print 1, 4 in arbitrary order.
376 /// for x in a.symmetric_difference(&b) {
377 /// println!("{}", x);
380 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
381 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
383 /// assert_eq!(diff1, diff2);
384 /// assert_eq!(diff1, [1, 4].iter().collect());
386 #[stable(feature = "rust1", since = "1.0.0")]
387 pub fn symmetric_difference<'a>(&'a self,
388 other: &'a HashSet<T, S>)
389 -> SymmetricDifference<'a, T, S> {
390 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
393 /// Visits the values representing the intersection,
394 /// i.e., the values that are both in `self` and `other`.
399 /// use std::collections::HashSet;
400 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
401 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
403 /// // Print 2, 3 in arbitrary order.
404 /// for x in a.intersection(&b) {
405 /// println!("{}", x);
408 /// let intersection: HashSet<_> = a.intersection(&b).collect();
409 /// assert_eq!(intersection, [2, 3].iter().collect());
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
413 if self.len() <= other.len() {
426 /// Visits the values representing the union,
427 /// i.e., all the values in `self` or `other`, without duplicates.
432 /// use std::collections::HashSet;
433 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
434 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
436 /// // Print 1, 2, 3, 4 in arbitrary order.
437 /// for x in a.union(&b) {
438 /// println!("{}", x);
441 /// let union: HashSet<_> = a.union(&b).collect();
442 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
446 if self.len() <= other.len() {
448 iter: self.iter().chain(other.difference(self)),
452 iter: other.iter().chain(self.difference(other)),
457 /// Returns the number of elements in the set.
462 /// use std::collections::HashSet;
464 /// let mut v = HashSet::new();
465 /// assert_eq!(v.len(), 0);
467 /// assert_eq!(v.len(), 1);
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn len(&self) -> usize {
474 /// Returns `true` if the set contains no elements.
479 /// use std::collections::HashSet;
481 /// let mut v = HashSet::new();
482 /// assert!(v.is_empty());
484 /// assert!(!v.is_empty());
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn is_empty(&self) -> bool {
491 /// Clears the set, returning all elements in an iterator.
496 /// use std::collections::HashSet;
498 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
499 /// assert!(!set.is_empty());
501 /// // print 1, 2, 3 in an arbitrary order
502 /// for i in set.drain() {
503 /// println!("{}", i);
506 /// assert!(set.is_empty());
509 #[stable(feature = "drain", since = "1.6.0")]
510 pub fn drain(&mut self) -> Drain<T> {
511 Drain { iter: self.map.drain() }
514 /// Clears the set, removing all values.
519 /// use std::collections::HashSet;
521 /// let mut v = HashSet::new();
524 /// assert!(v.is_empty());
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn clear(&mut self) {
531 /// Returns `true` if the set contains a value.
533 /// The value may be any borrowed form of the set's value type, but
534 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
540 /// use std::collections::HashSet;
542 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
543 /// assert_eq!(set.contains(&1), true);
544 /// assert_eq!(set.contains(&4), false);
547 /// [`Eq`]: ../../std/cmp/trait.Eq.html
548 /// [`Hash`]: ../../std/hash/trait.Hash.html
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
554 self.map.contains_key(value)
557 /// Returns a reference to the value in the set, if any, that is equal to the given value.
559 /// The value may be any borrowed form of the set's value type, but
560 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
566 /// use std::collections::HashSet;
568 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
569 /// assert_eq!(set.get(&2), Some(&2));
570 /// assert_eq!(set.get(&4), None);
573 /// [`Eq`]: ../../std/cmp/trait.Eq.html
574 /// [`Hash`]: ../../std/hash/trait.Hash.html
575 #[stable(feature = "set_recovery", since = "1.9.0")]
576 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
580 Recover::get(&self.map, value)
583 /// Returns `true` if `self` has no elements in common with `other`.
584 /// This is equivalent to checking for an empty intersection.
589 /// use std::collections::HashSet;
591 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
592 /// let mut b = HashSet::new();
594 /// assert_eq!(a.is_disjoint(&b), true);
596 /// assert_eq!(a.is_disjoint(&b), true);
598 /// assert_eq!(a.is_disjoint(&b), false);
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
602 if self.len() <= other.len() {
603 self.iter().all(|v| !other.contains(v))
605 other.iter().all(|v| !self.contains(v))
609 /// Returns `true` if the set is a subset of another,
610 /// i.e., `other` contains at least all the values in `self`.
615 /// use std::collections::HashSet;
617 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
618 /// let mut set = HashSet::new();
620 /// assert_eq!(set.is_subset(&sup), true);
622 /// assert_eq!(set.is_subset(&sup), true);
624 /// assert_eq!(set.is_subset(&sup), false);
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
628 self.iter().all(|v| other.contains(v))
631 /// Returns `true` if the set is a superset of another,
632 /// i.e., `self` contains at least all the values in `other`.
637 /// use std::collections::HashSet;
639 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
640 /// let mut set = HashSet::new();
642 /// assert_eq!(set.is_superset(&sub), false);
646 /// assert_eq!(set.is_superset(&sub), false);
649 /// assert_eq!(set.is_superset(&sub), true);
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
654 other.is_subset(self)
657 /// Adds a value to the set.
659 /// If the set did not have this value present, `true` is returned.
661 /// If the set did have this value present, `false` is returned.
666 /// use std::collections::HashSet;
668 /// let mut set = HashSet::new();
670 /// assert_eq!(set.insert(2), true);
671 /// assert_eq!(set.insert(2), false);
672 /// assert_eq!(set.len(), 1);
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn insert(&mut self, value: T) -> bool {
676 self.map.insert(value, ()).is_none()
679 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
680 /// one. Returns the replaced value.
685 /// use std::collections::HashSet;
687 /// let mut set = HashSet::new();
688 /// set.insert(Vec::<i32>::new());
690 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
691 /// set.replace(Vec::with_capacity(10));
692 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
694 #[stable(feature = "set_recovery", since = "1.9.0")]
695 pub fn replace(&mut self, value: T) -> Option<T> {
696 Recover::replace(&mut self.map, value)
699 /// Removes a value from the set. Returns whether the value was
700 /// present in the set.
702 /// The value may be any borrowed form of the set's value type, but
703 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
709 /// use std::collections::HashSet;
711 /// let mut set = HashSet::new();
714 /// assert_eq!(set.remove(&2), true);
715 /// assert_eq!(set.remove(&2), false);
718 /// [`Eq`]: ../../std/cmp/trait.Eq.html
719 /// [`Hash`]: ../../std/hash/trait.Hash.html
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
725 self.map.remove(value).is_some()
728 /// Removes and returns the value in the set, if any, that is equal to the given one.
730 /// The value may be any borrowed form of the set's value type, but
731 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
737 /// use std::collections::HashSet;
739 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
740 /// assert_eq!(set.take(&2), Some(2));
741 /// assert_eq!(set.take(&2), None);
744 /// [`Eq`]: ../../std/cmp/trait.Eq.html
745 /// [`Hash`]: ../../std/hash/trait.Hash.html
746 #[stable(feature = "set_recovery", since = "1.9.0")]
747 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
751 Recover::take(&mut self.map, value)
754 /// Retains only the elements specified by the predicate.
756 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
761 /// use std::collections::HashSet;
763 /// let xs = [1,2,3,4,5,6];
764 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
765 /// set.retain(|&k| k % 2 == 0);
766 /// assert_eq!(set.len(), 3);
768 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
769 pub fn retain<F>(&mut self, mut f: F)
770 where F: FnMut(&T) -> bool
772 self.map.retain(|k, _| f(k));
776 #[stable(feature = "rust1", since = "1.0.0")]
777 impl<T, S> PartialEq for HashSet<T, S>
781 fn eq(&self, other: &HashSet<T, S>) -> bool {
782 if self.len() != other.len() {
786 self.iter().all(|key| other.contains(key))
790 #[stable(feature = "rust1", since = "1.0.0")]
791 impl<T, S> Eq for HashSet<T, S>
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<T, S> fmt::Debug for HashSet<T, S>
799 where T: Eq + Hash + fmt::Debug,
802 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
803 f.debug_set().entries(self.iter()).finish()
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<T, S> FromIterator<T> for HashSet<T, S>
810 S: BuildHasher + Default
812 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
813 let mut set = HashSet::with_hasher(Default::default());
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl<T, S> Extend<T> for HashSet<T, S>
824 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
825 self.map.extend(iter.into_iter().map(|k| (k, ())));
829 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
830 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
831 where T: 'a + Eq + Hash + Copy,
834 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
835 self.extend(iter.into_iter().cloned());
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl<T, S> Default for HashSet<T, S>
842 S: BuildHasher + Default
844 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
845 fn default() -> HashSet<T, S> {
846 HashSet { map: HashMap::default() }
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
852 where T: Eq + Hash + Clone,
853 S: BuildHasher + Default
855 type Output = HashSet<T, S>;
857 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
862 /// use std::collections::HashSet;
864 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
865 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
867 /// let set = &a | &b;
870 /// let expected = [1, 2, 3, 4, 5];
872 /// assert!(expected.contains(x));
875 /// assert_eq!(i, expected.len());
877 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
878 self.union(rhs).cloned().collect()
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
884 where T: Eq + Hash + Clone,
885 S: BuildHasher + Default
887 type Output = HashSet<T, S>;
889 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
894 /// use std::collections::HashSet;
896 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
897 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
899 /// let set = &a & &b;
902 /// let expected = [2, 3];
904 /// assert!(expected.contains(x));
907 /// assert_eq!(i, expected.len());
909 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
910 self.intersection(rhs).cloned().collect()
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
916 where T: Eq + Hash + Clone,
917 S: BuildHasher + Default
919 type Output = HashSet<T, S>;
921 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
926 /// use std::collections::HashSet;
928 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
929 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
931 /// let set = &a ^ &b;
934 /// let expected = [1, 2, 4, 5];
936 /// assert!(expected.contains(x));
939 /// assert_eq!(i, expected.len());
941 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
942 self.symmetric_difference(rhs).cloned().collect()
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
948 where T: Eq + Hash + Clone,
949 S: BuildHasher + Default
951 type Output = HashSet<T, S>;
953 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
958 /// use std::collections::HashSet;
960 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
961 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
963 /// let set = &a - &b;
966 /// let expected = [1, 2];
968 /// assert!(expected.contains(x));
971 /// assert_eq!(i, expected.len());
973 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
974 self.difference(rhs).cloned().collect()
978 /// An iterator over the items of a `HashSet`.
980 /// This `struct` is created by the [`iter`] method on [`HashSet`].
981 /// See its documentation for more.
983 /// [`HashSet`]: struct.HashSet.html
984 /// [`iter`]: struct.HashSet.html#method.iter
985 #[stable(feature = "rust1", since = "1.0.0")]
986 pub struct Iter<'a, K: 'a> {
987 iter: Keys<'a, K, ()>,
990 /// An owning iterator over the items of a `HashSet`.
992 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
993 /// (provided by the `IntoIterator` trait). See its documentation for more.
995 /// [`HashSet`]: struct.HashSet.html
996 /// [`into_iter`]: struct.HashSet.html#method.into_iter
997 #[stable(feature = "rust1", since = "1.0.0")]
998 pub struct IntoIter<K> {
999 iter: map::IntoIter<K, ()>,
1002 /// A draining iterator over the items of a `HashSet`.
1004 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1005 /// See its documentation for more.
1007 /// [`HashSet`]: struct.HashSet.html
1008 /// [`drain`]: struct.HashSet.html#method.drain
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 pub struct Drain<'a, K: 'a> {
1011 iter: map::Drain<'a, K, ()>,
1014 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1016 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1017 /// See its documentation for more.
1019 /// [`HashSet`]: struct.HashSet.html
1020 /// [`intersection`]: struct.HashSet.html#method.intersection
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub struct Intersection<'a, T: 'a, S: 'a> {
1023 // iterator of the first set
1026 other: &'a HashSet<T, S>,
1029 /// A lazy iterator producing elements in the difference of `HashSet`s.
1031 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1032 /// See its documentation for more.
1034 /// [`HashSet`]: struct.HashSet.html
1035 /// [`difference`]: struct.HashSet.html#method.difference
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub struct Difference<'a, T: 'a, S: 'a> {
1038 // iterator of the first set
1041 other: &'a HashSet<T, S>,
1044 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1046 /// This `struct` is created by the [`symmetric_difference`] method on
1047 /// [`HashSet`]. See its documentation for more.
1049 /// [`HashSet`]: struct.HashSet.html
1050 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1053 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1056 /// A lazy iterator producing elements in the union of `HashSet`s.
1058 /// This `struct` is created by the [`union`] method on [`HashSet`].
1059 /// See its documentation for more.
1061 /// [`HashSet`]: struct.HashSet.html
1062 /// [`union`]: struct.HashSet.html#method.union
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 pub struct Union<'a, T: 'a, S: 'a> {
1065 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
1074 type IntoIter = Iter<'a, T>;
1076 fn into_iter(self) -> Iter<'a, T> {
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<T, S> IntoIterator for HashSet<T, S>
1087 type IntoIter = IntoIter<T>;
1089 /// Creates a consuming iterator, that is, one that moves each value out
1090 /// of the set in arbitrary order. The set cannot be used after calling
1096 /// use std::collections::HashSet;
1097 /// let mut set = HashSet::new();
1098 /// set.insert("a".to_string());
1099 /// set.insert("b".to_string());
1101 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1102 /// let v: Vec<String> = set.into_iter().collect();
1104 /// // Will print in an arbitrary order.
1106 /// println!("{}", x);
1109 fn into_iter(self) -> IntoIter<T> {
1110 IntoIter { iter: self.map.into_iter() }
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 impl<'a, K> Clone for Iter<'a, K> {
1116 fn clone(&self) -> Iter<'a, K> {
1117 Iter { iter: self.iter.clone() }
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 impl<'a, K> Iterator for Iter<'a, K> {
1124 fn next(&mut self) -> Option<&'a K> {
1127 fn size_hint(&self) -> (usize, Option<usize>) {
1128 self.iter.size_hint()
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
1133 fn len(&self) -> usize {
1137 #[stable(feature = "fused", since = "1.26.0")]
1138 impl<'a, K> FusedIterator for Iter<'a, K> {}
1140 #[stable(feature = "std_debug", since = "1.16.0")]
1141 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
1142 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1143 f.debug_list().entries(self.clone()).finish()
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<K> Iterator for IntoIter<K> {
1151 fn next(&mut self) -> Option<K> {
1152 self.iter.next().map(|(k, _)| k)
1154 fn size_hint(&self) -> (usize, Option<usize>) {
1155 self.iter.size_hint()
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<K> ExactSizeIterator for IntoIter<K> {
1160 fn len(&self) -> usize {
1164 #[stable(feature = "fused", since = "1.26.0")]
1165 impl<K> FusedIterator for IntoIter<K> {}
1167 #[stable(feature = "std_debug", since = "1.16.0")]
1168 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1169 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1170 let entries_iter = self.iter
1174 f.debug_list().entries(entries_iter).finish()
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<'a, K> Iterator for Drain<'a, K> {
1182 fn next(&mut self) -> Option<K> {
1183 self.iter.next().map(|(k, _)| k)
1185 fn size_hint(&self) -> (usize, Option<usize>) {
1186 self.iter.size_hint()
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1191 fn len(&self) -> usize {
1195 #[stable(feature = "fused", since = "1.26.0")]
1196 impl<'a, K> FusedIterator for Drain<'a, K> {}
1198 #[stable(feature = "std_debug", since = "1.16.0")]
1199 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1201 let entries_iter = self.iter
1205 f.debug_list().entries(entries_iter).finish()
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1211 fn clone(&self) -> Intersection<'a, T, S> {
1212 Intersection { iter: self.iter.clone(), ..*self }
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1223 fn next(&mut self) -> Option<&'a T> {
1225 let elt = self.iter.next()?;
1226 if self.other.contains(elt) {
1232 fn size_hint(&self) -> (usize, Option<usize>) {
1233 let (_, upper) = self.iter.size_hint();
1238 #[stable(feature = "std_debug", since = "1.16.0")]
1239 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1240 where T: fmt::Debug + Eq + Hash,
1243 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1244 f.debug_list().entries(self.clone()).finish()
1248 #[stable(feature = "fused", since = "1.26.0")]
1249 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 impl<'a, T, S> Clone for Difference<'a, T, S> {
1257 fn clone(&self) -> Difference<'a, T, S> {
1258 Difference { iter: self.iter.clone(), ..*self }
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<'a, T, S> Iterator for Difference<'a, T, S>
1269 fn next(&mut self) -> Option<&'a T> {
1271 let elt = self.iter.next()?;
1272 if !self.other.contains(elt) {
1278 fn size_hint(&self) -> (usize, Option<usize>) {
1279 let (_, upper) = self.iter.size_hint();
1284 #[stable(feature = "fused", since = "1.26.0")]
1285 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1291 #[stable(feature = "std_debug", since = "1.16.0")]
1292 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1293 where T: fmt::Debug + Eq + Hash,
1296 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1297 f.debug_list().entries(self.clone()).finish()
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1303 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1304 SymmetricDifference { iter: self.iter.clone() }
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1315 fn next(&mut self) -> Option<&'a T> {
1318 fn size_hint(&self) -> (usize, Option<usize>) {
1319 self.iter.size_hint()
1323 #[stable(feature = "fused", since = "1.26.0")]
1324 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1330 #[stable(feature = "std_debug", since = "1.16.0")]
1331 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1332 where T: fmt::Debug + Eq + Hash,
1335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1336 f.debug_list().entries(self.clone()).finish()
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<'a, T, S> Clone for Union<'a, T, S> {
1342 fn clone(&self) -> Union<'a, T, S> {
1343 Union { iter: self.iter.clone() }
1347 #[stable(feature = "fused", since = "1.26.0")]
1348 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1354 #[stable(feature = "std_debug", since = "1.16.0")]
1355 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1356 where T: fmt::Debug + Eq + Hash,
1359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1360 f.debug_list().entries(self.clone()).finish()
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl<'a, T, S> Iterator for Union<'a, T, S>
1371 fn next(&mut self) -> Option<&'a T> {
1374 fn size_hint(&self) -> (usize, Option<usize>) {
1375 self.iter.size_hint()
1380 fn assert_covariance() {
1381 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1384 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1387 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1390 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1391 -> Difference<'a, &'new str, RandomState> {
1394 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1395 -> SymmetricDifference<'a, &'new str, RandomState> {
1398 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1399 -> Intersection<'a, &'new str, RandomState> {
1402 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1403 -> Union<'a, &'new str, RandomState> {
1406 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1414 use super::super::map::RandomState;
1417 fn test_zero_capacities() {
1418 type HS = HashSet<i32>;
1421 assert_eq!(s.capacity(), 0);
1423 let s = HS::default();
1424 assert_eq!(s.capacity(), 0);
1426 let s = HS::with_hasher(RandomState::new());
1427 assert_eq!(s.capacity(), 0);
1429 let s = HS::with_capacity(0);
1430 assert_eq!(s.capacity(), 0);
1432 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1433 assert_eq!(s.capacity(), 0);
1435 let mut s = HS::new();
1441 assert_eq!(s.capacity(), 0);
1443 let mut s = HS::new();
1445 assert_eq!(s.capacity(), 0);
1449 fn test_disjoint() {
1450 let mut xs = HashSet::new();
1451 let mut ys = HashSet::new();
1452 assert!(xs.is_disjoint(&ys));
1453 assert!(ys.is_disjoint(&xs));
1454 assert!(xs.insert(5));
1455 assert!(ys.insert(11));
1456 assert!(xs.is_disjoint(&ys));
1457 assert!(ys.is_disjoint(&xs));
1458 assert!(xs.insert(7));
1459 assert!(xs.insert(19));
1460 assert!(xs.insert(4));
1461 assert!(ys.insert(2));
1462 assert!(ys.insert(-11));
1463 assert!(xs.is_disjoint(&ys));
1464 assert!(ys.is_disjoint(&xs));
1465 assert!(ys.insert(7));
1466 assert!(!xs.is_disjoint(&ys));
1467 assert!(!ys.is_disjoint(&xs));
1471 fn test_subset_and_superset() {
1472 let mut a = HashSet::new();
1473 assert!(a.insert(0));
1474 assert!(a.insert(5));
1475 assert!(a.insert(11));
1476 assert!(a.insert(7));
1478 let mut b = HashSet::new();
1479 assert!(b.insert(0));
1480 assert!(b.insert(7));
1481 assert!(b.insert(19));
1482 assert!(b.insert(250));
1483 assert!(b.insert(11));
1484 assert!(b.insert(200));
1486 assert!(!a.is_subset(&b));
1487 assert!(!a.is_superset(&b));
1488 assert!(!b.is_subset(&a));
1489 assert!(!b.is_superset(&a));
1491 assert!(b.insert(5));
1493 assert!(a.is_subset(&b));
1494 assert!(!a.is_superset(&b));
1495 assert!(!b.is_subset(&a));
1496 assert!(b.is_superset(&a));
1501 let mut a = HashSet::new();
1503 assert!(a.insert(i));
1505 let mut observed: u32 = 0;
1507 observed |= 1 << *k;
1509 assert_eq!(observed, 0xFFFF_FFFF);
1513 fn test_intersection() {
1514 let mut a = HashSet::new();
1515 let mut b = HashSet::new();
1516 assert!(a.intersection(&b).next().is_none());
1518 assert!(a.insert(11));
1519 assert!(a.insert(1));
1520 assert!(a.insert(3));
1521 assert!(a.insert(77));
1522 assert!(a.insert(103));
1523 assert!(a.insert(5));
1524 assert!(a.insert(-5));
1526 assert!(b.insert(2));
1527 assert!(b.insert(11));
1528 assert!(b.insert(77));
1529 assert!(b.insert(-9));
1530 assert!(b.insert(-42));
1531 assert!(b.insert(5));
1532 assert!(b.insert(3));
1535 let expected = [3, 5, 11, 77];
1536 for x in a.intersection(&b) {
1537 assert!(expected.contains(x));
1540 assert_eq!(i, expected.len());
1542 assert!(a.insert(9)); // make a bigger than b
1545 for x in a.intersection(&b) {
1546 assert!(expected.contains(x));
1549 assert_eq!(i, expected.len());
1552 for x in b.intersection(&a) {
1553 assert!(expected.contains(x));
1556 assert_eq!(i, expected.len());
1560 fn test_difference() {
1561 let mut a = HashSet::new();
1562 let mut b = HashSet::new();
1564 assert!(a.insert(1));
1565 assert!(a.insert(3));
1566 assert!(a.insert(5));
1567 assert!(a.insert(9));
1568 assert!(a.insert(11));
1570 assert!(b.insert(3));
1571 assert!(b.insert(9));
1574 let expected = [1, 5, 11];
1575 for x in a.difference(&b) {
1576 assert!(expected.contains(x));
1579 assert_eq!(i, expected.len());
1583 fn test_symmetric_difference() {
1584 let mut a = HashSet::new();
1585 let mut b = HashSet::new();
1587 assert!(a.insert(1));
1588 assert!(a.insert(3));
1589 assert!(a.insert(5));
1590 assert!(a.insert(9));
1591 assert!(a.insert(11));
1593 assert!(b.insert(-2));
1594 assert!(b.insert(3));
1595 assert!(b.insert(9));
1596 assert!(b.insert(14));
1597 assert!(b.insert(22));
1600 let expected = [-2, 1, 5, 11, 14, 22];
1601 for x in a.symmetric_difference(&b) {
1602 assert!(expected.contains(x));
1605 assert_eq!(i, expected.len());
1610 let mut a = HashSet::new();
1611 let mut b = HashSet::new();
1612 assert!(a.union(&b).next().is_none());
1613 assert!(b.union(&a).next().is_none());
1615 assert!(a.insert(1));
1616 assert!(a.insert(3));
1617 assert!(a.insert(11));
1618 assert!(a.insert(16));
1619 assert!(a.insert(19));
1620 assert!(a.insert(24));
1622 assert!(b.insert(-2));
1623 assert!(b.insert(1));
1624 assert!(b.insert(5));
1625 assert!(b.insert(9));
1626 assert!(b.insert(13));
1627 assert!(b.insert(19));
1630 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1631 for x in a.union(&b) {
1632 assert!(expected.contains(x));
1635 assert_eq!(i, expected.len());
1637 assert!(a.insert(9)); // make a bigger than b
1638 assert!(a.insert(5));
1641 for x in a.union(&b) {
1642 assert!(expected.contains(x));
1645 assert_eq!(i, expected.len());
1648 for x in b.union(&a) {
1649 assert!(expected.contains(x));
1652 assert_eq!(i, expected.len());
1656 fn test_from_iter() {
1657 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1659 let set: HashSet<_> = xs.iter().cloned().collect();
1662 assert!(set.contains(x));
1667 fn test_move_iter() {
1669 let mut hs = HashSet::new();
1677 let v = hs.into_iter().collect::<Vec<char>>();
1678 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1683 // These constants once happened to expose a bug in insert().
1684 // I'm keeping them around to prevent a regression.
1685 let mut s1 = HashSet::new();
1691 let mut s2 = HashSet::new();
1705 let mut set = HashSet::new();
1706 let empty = HashSet::<i32>::new();
1711 let set_str = format!("{:?}", set);
1713 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1714 assert_eq!(format!("{:?}", empty), "{}");
1718 fn test_trivial_drain() {
1719 let mut s = HashSet::<i32>::new();
1720 for _ in s.drain() {}
1721 assert!(s.is_empty());
1724 let mut s = HashSet::<i32>::new();
1726 assert!(s.is_empty());
1731 let mut s: HashSet<_> = (1..100).collect();
1733 // try this a bunch of times to make sure we don't screw up internal state.
1735 assert_eq!(s.len(), 99);
1739 let mut d = s.drain();
1740 for (i, x) in d.by_ref().take(50).enumerate() {
1744 assert_eq!(last_i, 49);
1748 panic!("s should be empty!");
1751 // reset to try again.
1761 struct Foo(&'static str, i32);
1763 impl PartialEq for Foo {
1764 fn eq(&self, other: &Self) -> bool {
1771 impl hash::Hash for Foo {
1772 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1777 let mut s = HashSet::new();
1778 assert_eq!(s.replace(Foo("a", 1)), None);
1779 assert_eq!(s.len(), 1);
1780 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1781 assert_eq!(s.len(), 1);
1783 let mut it = s.iter();
1784 assert_eq!(it.next(), Some(&Foo("a", 2)));
1785 assert_eq!(it.next(), None);
1789 fn test_extend_ref() {
1790 let mut a = HashSet::new();
1793 a.extend(&[2, 3, 4]);
1795 assert_eq!(a.len(), 4);
1796 assert!(a.contains(&1));
1797 assert!(a.contains(&2));
1798 assert!(a.contains(&3));
1799 assert!(a.contains(&4));
1801 let mut b = HashSet::new();
1807 assert_eq!(a.len(), 6);
1808 assert!(a.contains(&1));
1809 assert!(a.contains(&2));
1810 assert!(a.contains(&3));
1811 assert!(a.contains(&4));
1812 assert!(a.contains(&5));
1813 assert!(a.contains(&6));
1818 let xs = [1, 2, 3, 4, 5, 6];
1819 let mut set: HashSet<i32> = xs.iter().cloned().collect();
1820 set.retain(|&k| k % 2 == 0);
1821 assert_eq!(set.len(), 3);
1822 assert!(set.contains(&2));
1823 assert!(set.contains(&4));
1824 assert!(set.contains(&6));