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};
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> {
153 /// Returns the number of elements the set can hold without reallocating.
158 /// use std::collections::HashSet;
159 /// let set: HashSet<i32> = HashSet::with_capacity(100);
160 /// assert!(set.capacity() >= 100);
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub fn capacity(&self) -> usize {
168 /// An iterator visiting all elements in arbitrary order.
169 /// The iterator element type is `&'a T`.
174 /// use std::collections::HashSet;
175 /// let mut set = HashSet::new();
179 /// // Will print in an arbitrary order.
180 /// for x in set.iter() {
181 /// println!("{}", x);
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub fn iter(&self) -> Iter<T> {
186 Iter { iter: self.map.keys() }
189 /// Returns the number of elements in the set.
194 /// use std::collections::HashSet;
196 /// let mut v = HashSet::new();
197 /// assert_eq!(v.len(), 0);
199 /// assert_eq!(v.len(), 1);
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub fn len(&self) -> usize {
206 /// Returns `true` if the set contains no elements.
211 /// use std::collections::HashSet;
213 /// let mut v = HashSet::new();
214 /// assert!(v.is_empty());
216 /// assert!(!v.is_empty());
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn is_empty(&self) -> bool {
223 /// Clears the set, returning all elements in an iterator.
228 /// use std::collections::HashSet;
230 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
231 /// assert!(!set.is_empty());
233 /// // print 1, 2, 3 in an arbitrary order
234 /// for i in set.drain() {
235 /// println!("{}", i);
238 /// assert!(set.is_empty());
241 #[stable(feature = "drain", since = "1.6.0")]
242 pub fn drain(&mut self) -> Drain<T> {
243 Drain { iter: self.map.drain() }
246 /// Clears the set, removing all values.
251 /// use std::collections::HashSet;
253 /// let mut v = HashSet::new();
256 /// assert!(v.is_empty());
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn clear(&mut self) {
264 impl<T, S> HashSet<T, S>
268 /// Creates a new empty hash set which will use the given hasher to hash
271 /// The hash set is also created with the default initial capacity.
273 /// Warning: `hasher` is normally randomly generated, and
274 /// is designed to allow `HashSet`s to be resistant to attacks that
275 /// cause many collisions and very poor performance. Setting it
276 /// manually using this function can expose a DoS attack vector.
281 /// use std::collections::HashSet;
282 /// use std::collections::hash_map::RandomState;
284 /// let s = RandomState::new();
285 /// let mut set = HashSet::with_hasher(s);
289 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
290 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
291 HashSet { map: HashMap::with_hasher(hasher) }
294 /// Creates an empty `HashSet` with the specified capacity, using
295 /// `hasher` to hash the keys.
297 /// The hash set will be able to hold at least `capacity` elements without
298 /// reallocating. If `capacity` is 0, the hash set will not allocate.
300 /// Warning: `hasher` is normally randomly generated, and
301 /// is designed to allow `HashSet`s to be resistant to attacks that
302 /// cause many collisions and very poor performance. Setting it
303 /// manually using this function can expose a DoS attack vector.
308 /// use std::collections::HashSet;
309 /// use std::collections::hash_map::RandomState;
311 /// let s = RandomState::new();
312 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
316 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
317 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
318 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
321 /// Returns a reference to the set's [`BuildHasher`].
323 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
328 /// use std::collections::HashSet;
329 /// use std::collections::hash_map::RandomState;
331 /// let hasher = RandomState::new();
332 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
333 /// let hasher: &RandomState = set.hasher();
335 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
336 pub fn hasher(&self) -> &S {
340 /// Reserves capacity for at least `additional` more elements to be inserted
341 /// in the `HashSet`. The collection may reserve more space to avoid
342 /// frequent reallocations.
346 /// Panics if the new allocation size overflows `usize`.
351 /// use std::collections::HashSet;
352 /// let mut set: HashSet<i32> = HashSet::new();
354 /// assert!(set.capacity() >= 10);
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn reserve(&mut self, additional: usize) {
358 self.map.reserve(additional)
361 /// Shrinks the capacity of the set as much as possible. It will drop
362 /// down as much as possible while maintaining the internal rules
363 /// and possibly leaving some space in accordance with the resize policy.
368 /// use std::collections::HashSet;
370 /// let mut set = HashSet::with_capacity(100);
373 /// assert!(set.capacity() >= 100);
374 /// set.shrink_to_fit();
375 /// assert!(set.capacity() >= 2);
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn shrink_to_fit(&mut self) {
379 self.map.shrink_to_fit()
382 /// Shrinks the capacity of the set with a lower limit. It will drop
383 /// down no lower than the supplied limit while maintaining the internal rules
384 /// and possibly leaving some space in accordance with the resize policy.
386 /// Panics if the current capacity is smaller than the supplied
387 /// minimum capacity.
392 /// #![feature(shrink_to)]
393 /// use std::collections::HashSet;
395 /// let mut set = HashSet::with_capacity(100);
398 /// assert!(set.capacity() >= 100);
399 /// set.shrink_to(10);
400 /// assert!(set.capacity() >= 10);
401 /// set.shrink_to(0);
402 /// assert!(set.capacity() >= 2);
405 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
406 pub fn shrink_to(&mut self, min_capacity: usize) {
407 self.map.shrink_to(min_capacity)
410 /// Visits the values representing the difference,
411 /// i.e., the values that are in `self` but not in `other`.
416 /// use std::collections::HashSet;
417 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
418 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
420 /// // Can be seen as `a - b`.
421 /// for x in a.difference(&b) {
422 /// println!("{}", x); // Print 1
425 /// let diff: HashSet<_> = a.difference(&b).collect();
426 /// assert_eq!(diff, [1].iter().collect());
428 /// // Note that difference is not symmetric,
429 /// // and `b - a` means something else:
430 /// let diff: HashSet<_> = b.difference(&a).collect();
431 /// assert_eq!(diff, [4].iter().collect());
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
441 /// Visits the values representing the symmetric difference,
442 /// i.e., the values that are in `self` or in `other` but not in both.
447 /// use std::collections::HashSet;
448 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
449 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
451 /// // Print 1, 4 in arbitrary order.
452 /// for x in a.symmetric_difference(&b) {
453 /// println!("{}", x);
456 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
457 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
459 /// assert_eq!(diff1, diff2);
460 /// assert_eq!(diff1, [1, 4].iter().collect());
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn symmetric_difference<'a>(&'a self,
464 other: &'a HashSet<T, S>)
465 -> SymmetricDifference<'a, T, S> {
466 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
469 /// Visits the values representing the intersection,
470 /// i.e., the values that are both in `self` and `other`.
475 /// use std::collections::HashSet;
476 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
477 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
479 /// // Print 2, 3 in arbitrary order.
480 /// for x in a.intersection(&b) {
481 /// println!("{}", x);
484 /// let intersection: HashSet<_> = a.intersection(&b).collect();
485 /// assert_eq!(intersection, [2, 3].iter().collect());
487 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
489 if self.len() <= other.len() {
502 /// Visits the values representing the union,
503 /// i.e., all the values in `self` or `other`, without duplicates.
508 /// use std::collections::HashSet;
509 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
510 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
512 /// // Print 1, 2, 3, 4 in arbitrary order.
513 /// for x in a.union(&b) {
514 /// println!("{}", x);
517 /// let union: HashSet<_> = a.union(&b).collect();
518 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
522 if self.len() <= other.len() {
524 iter: self.iter().chain(other.difference(self)),
528 iter: other.iter().chain(self.difference(other)),
533 /// Returns `true` if the set contains a value.
535 /// The value may be any borrowed form of the set's value type, but
536 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
542 /// use std::collections::HashSet;
544 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
545 /// assert_eq!(set.contains(&1), true);
546 /// assert_eq!(set.contains(&4), false);
549 /// [`Eq`]: ../../std/cmp/trait.Eq.html
550 /// [`Hash`]: ../../std/hash/trait.Hash.html
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
556 self.map.contains_key(value)
559 /// Returns a reference to the value in the set, if any, that is equal to the given value.
561 /// The value may be any borrowed form of the set's value type, but
562 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
568 /// use std::collections::HashSet;
570 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
571 /// assert_eq!(set.get(&2), Some(&2));
572 /// assert_eq!(set.get(&4), None);
575 /// [`Eq`]: ../../std/cmp/trait.Eq.html
576 /// [`Hash`]: ../../std/hash/trait.Hash.html
577 #[stable(feature = "set_recovery", since = "1.9.0")]
578 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
582 Recover::get(&self.map, value)
585 /// Returns `true` if `self` has no elements in common with `other`.
586 /// This is equivalent to checking for an empty intersection.
591 /// use std::collections::HashSet;
593 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
594 /// let mut b = HashSet::new();
596 /// assert_eq!(a.is_disjoint(&b), true);
598 /// assert_eq!(a.is_disjoint(&b), true);
600 /// assert_eq!(a.is_disjoint(&b), false);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
604 if self.len() <= other.len() {
605 self.iter().all(|v| !other.contains(v))
607 other.iter().all(|v| !self.contains(v))
611 /// Returns `true` if the set is a subset of another,
612 /// i.e., `other` contains at least all the values in `self`.
617 /// use std::collections::HashSet;
619 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
620 /// let mut set = HashSet::new();
622 /// assert_eq!(set.is_subset(&sup), true);
624 /// assert_eq!(set.is_subset(&sup), true);
626 /// assert_eq!(set.is_subset(&sup), false);
628 #[stable(feature = "rust1", since = "1.0.0")]
629 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
630 self.iter().all(|v| other.contains(v))
633 /// Returns `true` if the set is a superset of another,
634 /// i.e., `self` contains at least all the values in `other`.
639 /// use std::collections::HashSet;
641 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
642 /// let mut set = HashSet::new();
644 /// assert_eq!(set.is_superset(&sub), false);
648 /// assert_eq!(set.is_superset(&sub), false);
651 /// assert_eq!(set.is_superset(&sub), true);
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
656 other.is_subset(self)
659 /// Adds a value to the set.
661 /// If the set did not have this value present, `true` is returned.
663 /// If the set did have this value present, `false` is returned.
668 /// use std::collections::HashSet;
670 /// let mut set = HashSet::new();
672 /// assert_eq!(set.insert(2), true);
673 /// assert_eq!(set.insert(2), false);
674 /// assert_eq!(set.len(), 1);
676 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn insert(&mut self, value: T) -> bool {
678 self.map.insert(value, ()).is_none()
681 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
682 /// one. Returns the replaced value.
687 /// use std::collections::HashSet;
689 /// let mut set = HashSet::new();
690 /// set.insert(Vec::<i32>::new());
692 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
693 /// set.replace(Vec::with_capacity(10));
694 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
696 #[stable(feature = "set_recovery", since = "1.9.0")]
697 pub fn replace(&mut self, value: T) -> Option<T> {
698 Recover::replace(&mut self.map, value)
701 /// Removes a value from the set. Returns whether the value was
702 /// present in the set.
704 /// The value may be any borrowed form of the set's value type, but
705 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
711 /// use std::collections::HashSet;
713 /// let mut set = HashSet::new();
716 /// assert_eq!(set.remove(&2), true);
717 /// assert_eq!(set.remove(&2), false);
720 /// [`Eq`]: ../../std/cmp/trait.Eq.html
721 /// [`Hash`]: ../../std/hash/trait.Hash.html
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
727 self.map.remove(value).is_some()
730 /// Removes and returns the value in the set, if any, that is equal to the given one.
732 /// The value may be any borrowed form of the set's value type, but
733 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
739 /// use std::collections::HashSet;
741 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
742 /// assert_eq!(set.take(&2), Some(2));
743 /// assert_eq!(set.take(&2), None);
746 /// [`Eq`]: ../../std/cmp/trait.Eq.html
747 /// [`Hash`]: ../../std/hash/trait.Hash.html
748 #[stable(feature = "set_recovery", since = "1.9.0")]
749 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
753 Recover::take(&mut self.map, value)
756 /// Retains only the elements specified by the predicate.
758 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
763 /// use std::collections::HashSet;
765 /// let xs = [1,2,3,4,5,6];
766 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
767 /// set.retain(|&k| k % 2 == 0);
768 /// assert_eq!(set.len(), 3);
770 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
771 pub fn retain<F>(&mut self, mut f: F)
772 where F: FnMut(&T) -> bool
774 self.map.retain(|k, _| f(k));
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl<T, S> PartialEq for HashSet<T, S>
783 fn eq(&self, other: &HashSet<T, S>) -> bool {
784 if self.len() != other.len() {
788 self.iter().all(|key| other.contains(key))
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<T, S> Eq for HashSet<T, S>
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl<T, S> fmt::Debug for HashSet<T, S>
801 where T: Eq + Hash + fmt::Debug,
804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
805 f.debug_set().entries(self.iter()).finish()
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<T, S> FromIterator<T> for HashSet<T, S>
812 S: BuildHasher + Default
814 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
815 let mut set = HashSet::with_hasher(Default::default());
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl<T, S> Extend<T> for HashSet<T, S>
826 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
827 self.map.extend(iter.into_iter().map(|k| (k, ())));
831 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
832 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
833 where T: 'a + Eq + Hash + Copy,
836 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
837 self.extend(iter.into_iter().cloned());
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<T, S> Default for HashSet<T, S>
844 S: BuildHasher + Default
846 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
847 fn default() -> HashSet<T, S> {
848 HashSet { map: HashMap::default() }
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
854 where T: Eq + Hash + Clone,
855 S: BuildHasher + Default
857 type Output = HashSet<T, S>;
859 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
864 /// use std::collections::HashSet;
866 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
867 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
869 /// let set = &a | &b;
872 /// let expected = [1, 2, 3, 4, 5];
874 /// assert!(expected.contains(x));
877 /// assert_eq!(i, expected.len());
879 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
880 self.union(rhs).cloned().collect()
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
886 where T: Eq + Hash + Clone,
887 S: BuildHasher + Default
889 type Output = HashSet<T, S>;
891 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
896 /// use std::collections::HashSet;
898 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
899 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
901 /// let set = &a & &b;
904 /// let expected = [2, 3];
906 /// assert!(expected.contains(x));
909 /// assert_eq!(i, expected.len());
911 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
912 self.intersection(rhs).cloned().collect()
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
918 where T: Eq + Hash + Clone,
919 S: BuildHasher + Default
921 type Output = HashSet<T, S>;
923 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
928 /// use std::collections::HashSet;
930 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
931 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
933 /// let set = &a ^ &b;
936 /// let expected = [1, 2, 4, 5];
938 /// assert!(expected.contains(x));
941 /// assert_eq!(i, expected.len());
943 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
944 self.symmetric_difference(rhs).cloned().collect()
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
950 where T: Eq + Hash + Clone,
951 S: BuildHasher + Default
953 type Output = HashSet<T, S>;
955 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
960 /// use std::collections::HashSet;
962 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
963 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
965 /// let set = &a - &b;
968 /// let expected = [1, 2];
970 /// assert!(expected.contains(x));
973 /// assert_eq!(i, expected.len());
975 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
976 self.difference(rhs).cloned().collect()
980 /// An iterator over the items of a `HashSet`.
982 /// This `struct` is created by the [`iter`] method on [`HashSet`].
983 /// See its documentation for more.
985 /// [`HashSet`]: struct.HashSet.html
986 /// [`iter`]: struct.HashSet.html#method.iter
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub struct Iter<'a, K: 'a> {
989 iter: Keys<'a, K, ()>,
992 /// An owning iterator over the items of a `HashSet`.
994 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
995 /// (provided by the `IntoIterator` trait). See its documentation for more.
997 /// [`HashSet`]: struct.HashSet.html
998 /// [`into_iter`]: struct.HashSet.html#method.into_iter
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 pub struct IntoIter<K> {
1001 iter: map::IntoIter<K, ()>,
1004 /// A draining iterator over the items of a `HashSet`.
1006 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1007 /// See its documentation for more.
1009 /// [`HashSet`]: struct.HashSet.html
1010 /// [`drain`]: struct.HashSet.html#method.drain
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 pub struct Drain<'a, K: 'a> {
1013 iter: map::Drain<'a, K, ()>,
1016 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1018 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1019 /// See its documentation for more.
1021 /// [`HashSet`]: struct.HashSet.html
1022 /// [`intersection`]: struct.HashSet.html#method.intersection
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 pub struct Intersection<'a, T: 'a, S: 'a> {
1025 // iterator of the first set
1028 other: &'a HashSet<T, S>,
1031 /// A lazy iterator producing elements in the difference of `HashSet`s.
1033 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1034 /// See its documentation for more.
1036 /// [`HashSet`]: struct.HashSet.html
1037 /// [`difference`]: struct.HashSet.html#method.difference
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 pub struct Difference<'a, T: 'a, S: 'a> {
1040 // iterator of the first set
1043 other: &'a HashSet<T, S>,
1046 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1048 /// This `struct` is created by the [`symmetric_difference`] method on
1049 /// [`HashSet`]. See its documentation for more.
1051 /// [`HashSet`]: struct.HashSet.html
1052 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1055 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1058 /// A lazy iterator producing elements in the union of `HashSet`s.
1060 /// This `struct` is created by the [`union`] method on [`HashSet`].
1061 /// See its documentation for more.
1063 /// [`HashSet`]: struct.HashSet.html
1064 /// [`union`]: struct.HashSet.html#method.union
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 pub struct Union<'a, T: 'a, S: 'a> {
1067 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1073 type IntoIter = Iter<'a, T>;
1075 fn into_iter(self) -> Iter<'a, T> {
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T, S> IntoIterator for HashSet<T, S> {
1083 type IntoIter = IntoIter<T>;
1085 /// Creates a consuming iterator, that is, one that moves each value out
1086 /// of the set in arbitrary order. The set cannot be used after calling
1092 /// use std::collections::HashSet;
1093 /// let mut set = HashSet::new();
1094 /// set.insert("a".to_string());
1095 /// set.insert("b".to_string());
1097 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1098 /// let v: Vec<String> = set.into_iter().collect();
1100 /// // Will print in an arbitrary order.
1102 /// println!("{}", x);
1105 fn into_iter(self) -> IntoIter<T> {
1106 IntoIter { iter: self.map.into_iter() }
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<K> Clone for Iter<'_, K> {
1112 fn clone(&self) -> Self {
1113 Iter { iter: self.iter.clone() }
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<'a, K> Iterator for Iter<'a, K> {
1120 fn next(&mut self) -> Option<&'a K> {
1123 fn size_hint(&self) -> (usize, Option<usize>) {
1124 self.iter.size_hint()
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl<K> ExactSizeIterator for Iter<'_, K> {
1129 fn len(&self) -> usize {
1133 #[stable(feature = "fused", since = "1.26.0")]
1134 impl<K> FusedIterator for Iter<'_, K> {}
1136 #[stable(feature = "std_debug", since = "1.16.0")]
1137 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1139 f.debug_list().entries(self.clone()).finish()
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<K> Iterator for IntoIter<K> {
1147 fn next(&mut self) -> Option<K> {
1148 self.iter.next().map(|(k, _)| k)
1150 fn size_hint(&self) -> (usize, Option<usize>) {
1151 self.iter.size_hint()
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<K> ExactSizeIterator for IntoIter<K> {
1156 fn len(&self) -> usize {
1160 #[stable(feature = "fused", since = "1.26.0")]
1161 impl<K> FusedIterator for IntoIter<K> {}
1163 #[stable(feature = "std_debug", since = "1.16.0")]
1164 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1166 let entries_iter = self.iter
1170 f.debug_list().entries(entries_iter).finish()
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<'a, K> Iterator for Drain<'a, K> {
1178 fn next(&mut self) -> Option<K> {
1179 self.iter.next().map(|(k, _)| k)
1181 fn size_hint(&self) -> (usize, Option<usize>) {
1182 self.iter.size_hint()
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<K> ExactSizeIterator for Drain<'_, K> {
1187 fn len(&self) -> usize {
1191 #[stable(feature = "fused", since = "1.26.0")]
1192 impl<K> FusedIterator for Drain<'_, K> {}
1194 #[stable(feature = "std_debug", since = "1.16.0")]
1195 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1197 let entries_iter = self.iter
1201 f.debug_list().entries(entries_iter).finish()
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<T, S> Clone for Intersection<'_, T, S> {
1207 fn clone(&self) -> Self {
1208 Intersection { iter: self.iter.clone(), ..*self }
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1219 fn next(&mut self) -> Option<&'a T> {
1221 let elt = self.iter.next()?;
1222 if self.other.contains(elt) {
1228 fn size_hint(&self) -> (usize, Option<usize>) {
1229 let (_, upper) = self.iter.size_hint();
1234 #[stable(feature = "std_debug", since = "1.16.0")]
1235 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1236 where T: fmt::Debug + Eq + Hash,
1239 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1240 f.debug_list().entries(self.clone()).finish()
1244 #[stable(feature = "fused", since = "1.26.0")]
1245 impl<T, S> FusedIterator for Intersection<'_, T, S>
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<T, S> Clone for Difference<'_, T, S> {
1253 fn clone(&self) -> Self {
1254 Difference { iter: self.iter.clone(), ..*self }
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<'a, T, S> Iterator for Difference<'a, T, S>
1265 fn next(&mut self) -> Option<&'a T> {
1267 let elt = self.iter.next()?;
1268 if !self.other.contains(elt) {
1274 fn size_hint(&self) -> (usize, Option<usize>) {
1275 let (_, upper) = self.iter.size_hint();
1280 #[stable(feature = "fused", since = "1.26.0")]
1281 impl<T, S> FusedIterator for Difference<'_, T, S>
1287 #[stable(feature = "std_debug", since = "1.16.0")]
1288 impl<T, S> fmt::Debug for Difference<'_, T, S>
1289 where T: fmt::Debug + Eq + Hash,
1292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1293 f.debug_list().entries(self.clone()).finish()
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1299 fn clone(&self) -> Self {
1300 SymmetricDifference { iter: self.iter.clone() }
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1311 fn next(&mut self) -> Option<&'a T> {
1314 fn size_hint(&self) -> (usize, Option<usize>) {
1315 self.iter.size_hint()
1319 #[stable(feature = "fused", since = "1.26.0")]
1320 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1326 #[stable(feature = "std_debug", since = "1.16.0")]
1327 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1328 where T: fmt::Debug + Eq + Hash,
1331 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1332 f.debug_list().entries(self.clone()).finish()
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<T, S> Clone for Union<'_, T, S> {
1338 fn clone(&self) -> Self {
1339 Union { iter: self.iter.clone() }
1343 #[stable(feature = "fused", since = "1.26.0")]
1344 impl<T, S> FusedIterator for Union<'_, T, S>
1350 #[stable(feature = "std_debug", since = "1.16.0")]
1351 impl<T, S> fmt::Debug for Union<'_, T, S>
1352 where T: fmt::Debug + Eq + Hash,
1355 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1356 f.debug_list().entries(self.clone()).finish()
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 impl<'a, T, S> Iterator for Union<'a, T, S>
1367 fn next(&mut self) -> Option<&'a T> {
1370 fn size_hint(&self) -> (usize, Option<usize>) {
1371 self.iter.size_hint()
1376 fn assert_covariance() {
1377 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1380 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1383 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1386 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1387 -> Difference<'a, &'new str, RandomState> {
1390 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1391 -> SymmetricDifference<'a, &'new str, RandomState> {
1394 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1395 -> Intersection<'a, &'new str, RandomState> {
1398 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1399 -> Union<'a, &'new str, RandomState> {
1402 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1410 use super::super::map::RandomState;
1413 fn test_zero_capacities() {
1414 type HS = HashSet<i32>;
1417 assert_eq!(s.capacity(), 0);
1419 let s = HS::default();
1420 assert_eq!(s.capacity(), 0);
1422 let s = HS::with_hasher(RandomState::new());
1423 assert_eq!(s.capacity(), 0);
1425 let s = HS::with_capacity(0);
1426 assert_eq!(s.capacity(), 0);
1428 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1429 assert_eq!(s.capacity(), 0);
1431 let mut s = HS::new();
1437 assert_eq!(s.capacity(), 0);
1439 let mut s = HS::new();
1441 assert_eq!(s.capacity(), 0);
1445 fn test_disjoint() {
1446 let mut xs = HashSet::new();
1447 let mut ys = HashSet::new();
1448 assert!(xs.is_disjoint(&ys));
1449 assert!(ys.is_disjoint(&xs));
1450 assert!(xs.insert(5));
1451 assert!(ys.insert(11));
1452 assert!(xs.is_disjoint(&ys));
1453 assert!(ys.is_disjoint(&xs));
1454 assert!(xs.insert(7));
1455 assert!(xs.insert(19));
1456 assert!(xs.insert(4));
1457 assert!(ys.insert(2));
1458 assert!(ys.insert(-11));
1459 assert!(xs.is_disjoint(&ys));
1460 assert!(ys.is_disjoint(&xs));
1461 assert!(ys.insert(7));
1462 assert!(!xs.is_disjoint(&ys));
1463 assert!(!ys.is_disjoint(&xs));
1467 fn test_subset_and_superset() {
1468 let mut a = HashSet::new();
1469 assert!(a.insert(0));
1470 assert!(a.insert(5));
1471 assert!(a.insert(11));
1472 assert!(a.insert(7));
1474 let mut b = HashSet::new();
1475 assert!(b.insert(0));
1476 assert!(b.insert(7));
1477 assert!(b.insert(19));
1478 assert!(b.insert(250));
1479 assert!(b.insert(11));
1480 assert!(b.insert(200));
1482 assert!(!a.is_subset(&b));
1483 assert!(!a.is_superset(&b));
1484 assert!(!b.is_subset(&a));
1485 assert!(!b.is_superset(&a));
1487 assert!(b.insert(5));
1489 assert!(a.is_subset(&b));
1490 assert!(!a.is_superset(&b));
1491 assert!(!b.is_subset(&a));
1492 assert!(b.is_superset(&a));
1497 let mut a = HashSet::new();
1499 assert!(a.insert(i));
1501 let mut observed: u32 = 0;
1503 observed |= 1 << *k;
1505 assert_eq!(observed, 0xFFFF_FFFF);
1509 fn test_intersection() {
1510 let mut a = HashSet::new();
1511 let mut b = HashSet::new();
1512 assert!(a.intersection(&b).next().is_none());
1514 assert!(a.insert(11));
1515 assert!(a.insert(1));
1516 assert!(a.insert(3));
1517 assert!(a.insert(77));
1518 assert!(a.insert(103));
1519 assert!(a.insert(5));
1520 assert!(a.insert(-5));
1522 assert!(b.insert(2));
1523 assert!(b.insert(11));
1524 assert!(b.insert(77));
1525 assert!(b.insert(-9));
1526 assert!(b.insert(-42));
1527 assert!(b.insert(5));
1528 assert!(b.insert(3));
1531 let expected = [3, 5, 11, 77];
1532 for x in a.intersection(&b) {
1533 assert!(expected.contains(x));
1536 assert_eq!(i, expected.len());
1538 assert!(a.insert(9)); // make a bigger than b
1541 for x in a.intersection(&b) {
1542 assert!(expected.contains(x));
1545 assert_eq!(i, expected.len());
1548 for x in b.intersection(&a) {
1549 assert!(expected.contains(x));
1552 assert_eq!(i, expected.len());
1556 fn test_difference() {
1557 let mut a = HashSet::new();
1558 let mut b = HashSet::new();
1560 assert!(a.insert(1));
1561 assert!(a.insert(3));
1562 assert!(a.insert(5));
1563 assert!(a.insert(9));
1564 assert!(a.insert(11));
1566 assert!(b.insert(3));
1567 assert!(b.insert(9));
1570 let expected = [1, 5, 11];
1571 for x in a.difference(&b) {
1572 assert!(expected.contains(x));
1575 assert_eq!(i, expected.len());
1579 fn test_symmetric_difference() {
1580 let mut a = HashSet::new();
1581 let mut b = HashSet::new();
1583 assert!(a.insert(1));
1584 assert!(a.insert(3));
1585 assert!(a.insert(5));
1586 assert!(a.insert(9));
1587 assert!(a.insert(11));
1589 assert!(b.insert(-2));
1590 assert!(b.insert(3));
1591 assert!(b.insert(9));
1592 assert!(b.insert(14));
1593 assert!(b.insert(22));
1596 let expected = [-2, 1, 5, 11, 14, 22];
1597 for x in a.symmetric_difference(&b) {
1598 assert!(expected.contains(x));
1601 assert_eq!(i, expected.len());
1606 let mut a = HashSet::new();
1607 let mut b = HashSet::new();
1608 assert!(a.union(&b).next().is_none());
1609 assert!(b.union(&a).next().is_none());
1611 assert!(a.insert(1));
1612 assert!(a.insert(3));
1613 assert!(a.insert(11));
1614 assert!(a.insert(16));
1615 assert!(a.insert(19));
1616 assert!(a.insert(24));
1618 assert!(b.insert(-2));
1619 assert!(b.insert(1));
1620 assert!(b.insert(5));
1621 assert!(b.insert(9));
1622 assert!(b.insert(13));
1623 assert!(b.insert(19));
1626 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1627 for x in a.union(&b) {
1628 assert!(expected.contains(x));
1631 assert_eq!(i, expected.len());
1633 assert!(a.insert(9)); // make a bigger than b
1634 assert!(a.insert(5));
1637 for x in a.union(&b) {
1638 assert!(expected.contains(x));
1641 assert_eq!(i, expected.len());
1644 for x in b.union(&a) {
1645 assert!(expected.contains(x));
1648 assert_eq!(i, expected.len());
1652 fn test_from_iter() {
1653 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1655 let set: HashSet<_> = xs.iter().cloned().collect();
1658 assert!(set.contains(x));
1663 fn test_move_iter() {
1665 let mut hs = HashSet::new();
1673 let v = hs.into_iter().collect::<Vec<char>>();
1674 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1679 // These constants once happened to expose a bug in insert().
1680 // I'm keeping them around to prevent a regression.
1681 let mut s1 = HashSet::new();
1687 let mut s2 = HashSet::new();
1701 let mut set = HashSet::new();
1702 let empty = HashSet::<i32>::new();
1707 let set_str = format!("{:?}", set);
1709 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1710 assert_eq!(format!("{:?}", empty), "{}");
1714 fn test_trivial_drain() {
1715 let mut s = HashSet::<i32>::new();
1716 for _ in s.drain() {}
1717 assert!(s.is_empty());
1720 let mut s = HashSet::<i32>::new();
1722 assert!(s.is_empty());
1727 let mut s: HashSet<_> = (1..100).collect();
1729 // try this a bunch of times to make sure we don't screw up internal state.
1731 assert_eq!(s.len(), 99);
1735 let mut d = s.drain();
1736 for (i, x) in d.by_ref().take(50).enumerate() {
1740 assert_eq!(last_i, 49);
1744 panic!("s should be empty!");
1747 // reset to try again.
1757 struct Foo(&'static str, i32);
1759 impl PartialEq for Foo {
1760 fn eq(&self, other: &Self) -> bool {
1767 impl hash::Hash for Foo {
1768 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1773 let mut s = HashSet::new();
1774 assert_eq!(s.replace(Foo("a", 1)), None);
1775 assert_eq!(s.len(), 1);
1776 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1777 assert_eq!(s.len(), 1);
1779 let mut it = s.iter();
1780 assert_eq!(it.next(), Some(&Foo("a", 2)));
1781 assert_eq!(it.next(), None);
1785 fn test_extend_ref() {
1786 let mut a = HashSet::new();
1789 a.extend(&[2, 3, 4]);
1791 assert_eq!(a.len(), 4);
1792 assert!(a.contains(&1));
1793 assert!(a.contains(&2));
1794 assert!(a.contains(&3));
1795 assert!(a.contains(&4));
1797 let mut b = HashSet::new();
1803 assert_eq!(a.len(), 6);
1804 assert!(a.contains(&1));
1805 assert!(a.contains(&2));
1806 assert!(a.contains(&3));
1807 assert!(a.contains(&4));
1808 assert!(a.contains(&5));
1809 assert!(a.contains(&6));
1814 let xs = [1, 2, 3, 4, 5, 6];
1815 let mut set: HashSet<i32> = xs.iter().cloned().collect();
1816 set.retain(|&k| k % 2 == 0);
1817 assert_eq!(set.len(), 3);
1818 assert!(set.contains(&2));
1819 assert!(set.contains(&4));
1820 assert!(set.contains(&6));