1 use crate::borrow::Borrow;
2 use crate::collections::CollectionAllocErr;
4 use crate::hash::{Hash, BuildHasher};
5 use crate::iter::{Chain, FromIterator, FusedIterator};
6 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 /// Tries to reserve capacity for at least `additional` more elements to be inserted
362 /// in the given `HashSet<K,V>`. The collection may reserve more space to avoid
363 /// frequent reallocations.
367 /// If the capacity overflows, or the allocator reports a failure, then an error
373 /// #![feature(try_reserve)]
374 /// use std::collections::HashSet;
375 /// let mut set: HashSet<i32> = HashSet::new();
376 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
379 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
380 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
381 self.map.try_reserve(additional)
384 /// Shrinks the capacity of the set as much as possible. It will drop
385 /// down as much as possible while maintaining the internal rules
386 /// and possibly leaving some space in accordance with the resize policy.
391 /// use std::collections::HashSet;
393 /// let mut set = HashSet::with_capacity(100);
396 /// assert!(set.capacity() >= 100);
397 /// set.shrink_to_fit();
398 /// assert!(set.capacity() >= 2);
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn shrink_to_fit(&mut self) {
402 self.map.shrink_to_fit()
405 /// Shrinks the capacity of the set with a lower limit. It will drop
406 /// down no lower than the supplied limit while maintaining the internal rules
407 /// and possibly leaving some space in accordance with the resize policy.
409 /// Panics if the current capacity is smaller than the supplied
410 /// minimum capacity.
415 /// #![feature(shrink_to)]
416 /// use std::collections::HashSet;
418 /// let mut set = HashSet::with_capacity(100);
421 /// assert!(set.capacity() >= 100);
422 /// set.shrink_to(10);
423 /// assert!(set.capacity() >= 10);
424 /// set.shrink_to(0);
425 /// assert!(set.capacity() >= 2);
428 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
429 pub fn shrink_to(&mut self, min_capacity: usize) {
430 self.map.shrink_to(min_capacity)
433 /// Visits the values representing the difference,
434 /// i.e., the values that are in `self` but not in `other`.
439 /// use std::collections::HashSet;
440 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
441 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
443 /// // Can be seen as `a - b`.
444 /// for x in a.difference(&b) {
445 /// println!("{}", x); // Print 1
448 /// let diff: HashSet<_> = a.difference(&b).collect();
449 /// assert_eq!(diff, [1].iter().collect());
451 /// // Note that difference is not symmetric,
452 /// // and `b - a` means something else:
453 /// let diff: HashSet<_> = b.difference(&a).collect();
454 /// assert_eq!(diff, [4].iter().collect());
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
464 /// Visits the values representing the symmetric difference,
465 /// i.e., the values that are in `self` or in `other` but not in both.
470 /// use std::collections::HashSet;
471 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
472 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
474 /// // Print 1, 4 in arbitrary order.
475 /// for x in a.symmetric_difference(&b) {
476 /// println!("{}", x);
479 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
480 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
482 /// assert_eq!(diff1, diff2);
483 /// assert_eq!(diff1, [1, 4].iter().collect());
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn symmetric_difference<'a>(&'a self,
487 other: &'a HashSet<T, S>)
488 -> SymmetricDifference<'a, T, S> {
489 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
492 /// Visits the values representing the intersection,
493 /// i.e., the values that are both in `self` and `other`.
498 /// use std::collections::HashSet;
499 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
500 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
502 /// // Print 2, 3 in arbitrary order.
503 /// for x in a.intersection(&b) {
504 /// println!("{}", x);
507 /// let intersection: HashSet<_> = a.intersection(&b).collect();
508 /// assert_eq!(intersection, [2, 3].iter().collect());
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
512 if self.len() <= other.len() {
525 /// Visits the values representing the union,
526 /// i.e., all the values in `self` or `other`, without duplicates.
531 /// use std::collections::HashSet;
532 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
533 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
535 /// // Print 1, 2, 3, 4 in arbitrary order.
536 /// for x in a.union(&b) {
537 /// println!("{}", x);
540 /// let union: HashSet<_> = a.union(&b).collect();
541 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
545 if self.len() <= other.len() {
547 iter: self.iter().chain(other.difference(self)),
551 iter: other.iter().chain(self.difference(other)),
556 /// Returns `true` if the set contains a value.
558 /// The value may be any borrowed form of the set's value type, but
559 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
565 /// use std::collections::HashSet;
567 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
568 /// assert_eq!(set.contains(&1), true);
569 /// assert_eq!(set.contains(&4), false);
572 /// [`Eq`]: ../../std/cmp/trait.Eq.html
573 /// [`Hash`]: ../../std/hash/trait.Hash.html
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
579 self.map.contains_key(value)
582 /// Returns a reference to the value in the set, if any, that is equal to the given value.
584 /// The value may be any borrowed form of the set's value type, but
585 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
591 /// use std::collections::HashSet;
593 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
594 /// assert_eq!(set.get(&2), Some(&2));
595 /// assert_eq!(set.get(&4), None);
598 /// [`Eq`]: ../../std/cmp/trait.Eq.html
599 /// [`Hash`]: ../../std/hash/trait.Hash.html
600 #[stable(feature = "set_recovery", since = "1.9.0")]
601 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
605 self.map.get_key_value(value).map(|(k, _)| k)
608 /// Returns `true` if `self` has no elements in common with `other`.
609 /// This is equivalent to checking for an empty intersection.
614 /// use std::collections::HashSet;
616 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
617 /// let mut b = HashSet::new();
619 /// assert_eq!(a.is_disjoint(&b), true);
621 /// assert_eq!(a.is_disjoint(&b), true);
623 /// assert_eq!(a.is_disjoint(&b), false);
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
627 if self.len() <= other.len() {
628 self.iter().all(|v| !other.contains(v))
630 other.iter().all(|v| !self.contains(v))
634 /// Returns `true` if the set is a subset of another,
635 /// i.e., `other` contains at least all the values in `self`.
640 /// use std::collections::HashSet;
642 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
643 /// let mut set = HashSet::new();
645 /// assert_eq!(set.is_subset(&sup), true);
647 /// assert_eq!(set.is_subset(&sup), true);
649 /// assert_eq!(set.is_subset(&sup), false);
651 #[stable(feature = "rust1", since = "1.0.0")]
652 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
653 if self.len() <= other.len() {
654 self.iter().all(|v| other.contains(v))
660 /// Returns `true` if the set is a superset of another,
661 /// i.e., `self` contains at least all the values in `other`.
666 /// use std::collections::HashSet;
668 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
669 /// let mut set = HashSet::new();
671 /// assert_eq!(set.is_superset(&sub), false);
675 /// assert_eq!(set.is_superset(&sub), false);
678 /// assert_eq!(set.is_superset(&sub), true);
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
683 other.is_subset(self)
686 /// Adds a value to the set.
688 /// If the set did not have this value present, `true` is returned.
690 /// If the set did have this value present, `false` is returned.
695 /// use std::collections::HashSet;
697 /// let mut set = HashSet::new();
699 /// assert_eq!(set.insert(2), true);
700 /// assert_eq!(set.insert(2), false);
701 /// assert_eq!(set.len(), 1);
703 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn insert(&mut self, value: T) -> bool {
705 self.map.insert(value, ()).is_none()
708 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
709 /// one. Returns the replaced value.
714 /// use std::collections::HashSet;
716 /// let mut set = HashSet::new();
717 /// set.insert(Vec::<i32>::new());
719 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
720 /// set.replace(Vec::with_capacity(10));
721 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
723 #[stable(feature = "set_recovery", since = "1.9.0")]
724 pub fn replace(&mut self, value: T) -> Option<T> {
725 match self.map.entry(value) {
726 map::Entry::Occupied(occupied) => Some(occupied.replace_key()),
727 map::Entry::Vacant(vacant) => {
734 /// Removes a value from the set. Returns whether the value was
735 /// present in the set.
737 /// The value may be any borrowed form of the set's value type, but
738 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
744 /// use std::collections::HashSet;
746 /// let mut set = HashSet::new();
749 /// assert_eq!(set.remove(&2), true);
750 /// assert_eq!(set.remove(&2), false);
753 /// [`Eq`]: ../../std/cmp/trait.Eq.html
754 /// [`Hash`]: ../../std/hash/trait.Hash.html
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
760 self.map.remove(value).is_some()
763 /// Removes and returns the value in the set, if any, that is equal to the given one.
765 /// The value may be any borrowed form of the set's value type, but
766 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
772 /// use std::collections::HashSet;
774 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
775 /// assert_eq!(set.take(&2), Some(2));
776 /// assert_eq!(set.take(&2), None);
779 /// [`Eq`]: ../../std/cmp/trait.Eq.html
780 /// [`Hash`]: ../../std/hash/trait.Hash.html
781 #[stable(feature = "set_recovery", since = "1.9.0")]
782 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
786 self.map.remove_entry(value).map(|(k, _)| k)
789 /// Retains only the elements specified by the predicate.
791 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
796 /// use std::collections::HashSet;
798 /// let xs = [1,2,3,4,5,6];
799 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
800 /// set.retain(|&k| k % 2 == 0);
801 /// assert_eq!(set.len(), 3);
803 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
804 pub fn retain<F>(&mut self, mut f: F)
805 where F: FnMut(&T) -> bool
807 self.map.retain(|k, _| f(k));
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl<T, S> PartialEq for HashSet<T, S>
816 fn eq(&self, other: &HashSet<T, S>) -> bool {
817 if self.len() != other.len() {
821 self.iter().all(|key| other.contains(key))
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<T, S> Eq for HashSet<T, S>
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<T, S> fmt::Debug for HashSet<T, S>
834 where T: Eq + Hash + fmt::Debug,
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 f.debug_set().entries(self.iter()).finish()
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<T, S> FromIterator<T> for HashSet<T, S>
845 S: BuildHasher + Default
847 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
848 let mut set = HashSet::with_hasher(Default::default());
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<T, S> Extend<T> for HashSet<T, S>
859 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
860 self.map.extend(iter.into_iter().map(|k| (k, ())));
864 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
865 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
866 where T: 'a + Eq + Hash + Copy,
869 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
870 self.extend(iter.into_iter().cloned());
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl<T, S> Default for HashSet<T, S>
877 S: BuildHasher + Default
879 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
880 fn default() -> HashSet<T, S> {
881 HashSet { map: HashMap::default() }
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
887 where T: Eq + Hash + Clone,
888 S: BuildHasher + Default
890 type Output = HashSet<T, S>;
892 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
897 /// use std::collections::HashSet;
899 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
900 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
902 /// let set = &a | &b;
905 /// let expected = [1, 2, 3, 4, 5];
907 /// assert!(expected.contains(x));
910 /// assert_eq!(i, expected.len());
912 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
913 self.union(rhs).cloned().collect()
917 #[stable(feature = "rust1", since = "1.0.0")]
918 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
919 where T: Eq + Hash + Clone,
920 S: BuildHasher + Default
922 type Output = HashSet<T, S>;
924 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
929 /// use std::collections::HashSet;
931 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
932 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
934 /// let set = &a & &b;
937 /// let expected = [2, 3];
939 /// assert!(expected.contains(x));
942 /// assert_eq!(i, expected.len());
944 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
945 self.intersection(rhs).cloned().collect()
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
951 where T: Eq + Hash + Clone,
952 S: BuildHasher + Default
954 type Output = HashSet<T, S>;
956 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
961 /// use std::collections::HashSet;
963 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
964 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
966 /// let set = &a ^ &b;
969 /// let expected = [1, 2, 4, 5];
971 /// assert!(expected.contains(x));
974 /// assert_eq!(i, expected.len());
976 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
977 self.symmetric_difference(rhs).cloned().collect()
981 #[stable(feature = "rust1", since = "1.0.0")]
982 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
983 where T: Eq + Hash + Clone,
984 S: BuildHasher + Default
986 type Output = HashSet<T, S>;
988 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
993 /// use std::collections::HashSet;
995 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
996 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
998 /// let set = &a - &b;
1001 /// let expected = [1, 2];
1003 /// assert!(expected.contains(x));
1006 /// assert_eq!(i, expected.len());
1008 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1009 self.difference(rhs).cloned().collect()
1013 /// An iterator over the items of a `HashSet`.
1015 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1016 /// See its documentation for more.
1018 /// [`HashSet`]: struct.HashSet.html
1019 /// [`iter`]: struct.HashSet.html#method.iter
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub struct Iter<'a, K: 'a> {
1022 iter: Keys<'a, K, ()>,
1025 /// An owning iterator over the items of a `HashSet`.
1027 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
1028 /// (provided by the `IntoIterator` trait). See its documentation for more.
1030 /// [`HashSet`]: struct.HashSet.html
1031 /// [`into_iter`]: struct.HashSet.html#method.into_iter
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub struct IntoIter<K> {
1034 iter: map::IntoIter<K, ()>,
1037 /// A draining iterator over the items of a `HashSet`.
1039 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1040 /// See its documentation for more.
1042 /// [`HashSet`]: struct.HashSet.html
1043 /// [`drain`]: struct.HashSet.html#method.drain
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub struct Drain<'a, K: 'a> {
1046 iter: map::Drain<'a, K, ()>,
1049 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1051 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1052 /// See its documentation for more.
1054 /// [`HashSet`]: struct.HashSet.html
1055 /// [`intersection`]: struct.HashSet.html#method.intersection
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 pub struct Intersection<'a, T: 'a, S: 'a> {
1058 // iterator of the first set
1061 other: &'a HashSet<T, S>,
1064 /// A lazy iterator producing elements in the difference of `HashSet`s.
1066 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1067 /// See its documentation for more.
1069 /// [`HashSet`]: struct.HashSet.html
1070 /// [`difference`]: struct.HashSet.html#method.difference
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 pub struct Difference<'a, T: 'a, S: 'a> {
1073 // iterator of the first set
1076 other: &'a HashSet<T, S>,
1079 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1081 /// This `struct` is created by the [`symmetric_difference`] method on
1082 /// [`HashSet`]. See its documentation for more.
1084 /// [`HashSet`]: struct.HashSet.html
1085 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1088 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1091 /// A lazy iterator producing elements in the union of `HashSet`s.
1093 /// This `struct` is created by the [`union`] method on [`HashSet`].
1094 /// See its documentation for more.
1096 /// [`HashSet`]: struct.HashSet.html
1097 /// [`union`]: struct.HashSet.html#method.union
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 pub struct Union<'a, T: 'a, S: 'a> {
1100 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1106 type IntoIter = Iter<'a, T>;
1108 fn into_iter(self) -> Iter<'a, T> {
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<T, S> IntoIterator for HashSet<T, S> {
1116 type IntoIter = IntoIter<T>;
1118 /// Creates a consuming iterator, that is, one that moves each value out
1119 /// of the set in arbitrary order. The set cannot be used after calling
1125 /// use std::collections::HashSet;
1126 /// let mut set = HashSet::new();
1127 /// set.insert("a".to_string());
1128 /// set.insert("b".to_string());
1130 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1131 /// let v: Vec<String> = set.into_iter().collect();
1133 /// // Will print in an arbitrary order.
1135 /// println!("{}", x);
1138 fn into_iter(self) -> IntoIter<T> {
1139 IntoIter { iter: self.map.into_iter() }
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<K> Clone for Iter<'_, K> {
1145 fn clone(&self) -> Self {
1146 Iter { iter: self.iter.clone() }
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<'a, K> Iterator for Iter<'a, K> {
1153 fn next(&mut self) -> Option<&'a K> {
1156 fn size_hint(&self) -> (usize, Option<usize>) {
1157 self.iter.size_hint()
1160 #[stable(feature = "rust1", since = "1.0.0")]
1161 impl<K> ExactSizeIterator for Iter<'_, K> {
1162 fn len(&self) -> usize {
1166 #[stable(feature = "fused", since = "1.26.0")]
1167 impl<K> FusedIterator for Iter<'_, K> {}
1169 #[stable(feature = "std_debug", since = "1.16.0")]
1170 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1172 f.debug_list().entries(self.clone()).finish()
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<K> Iterator for IntoIter<K> {
1180 fn next(&mut self) -> Option<K> {
1181 self.iter.next().map(|(k, _)| k)
1183 fn size_hint(&self) -> (usize, Option<usize>) {
1184 self.iter.size_hint()
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 impl<K> ExactSizeIterator for IntoIter<K> {
1189 fn len(&self) -> usize {
1193 #[stable(feature = "fused", since = "1.26.0")]
1194 impl<K> FusedIterator for IntoIter<K> {}
1196 #[stable(feature = "std_debug", since = "1.16.0")]
1197 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1199 let entries_iter = self.iter
1203 f.debug_list().entries(entries_iter).finish()
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<'a, K> Iterator for Drain<'a, K> {
1211 fn next(&mut self) -> Option<K> {
1212 self.iter.next().map(|(k, _)| k)
1214 fn size_hint(&self) -> (usize, Option<usize>) {
1215 self.iter.size_hint()
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<K> ExactSizeIterator for Drain<'_, K> {
1220 fn len(&self) -> usize {
1224 #[stable(feature = "fused", since = "1.26.0")]
1225 impl<K> FusedIterator for Drain<'_, K> {}
1227 #[stable(feature = "std_debug", since = "1.16.0")]
1228 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1229 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1230 let entries_iter = self.iter
1234 f.debug_list().entries(entries_iter).finish()
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<T, S> Clone for Intersection<'_, T, S> {
1240 fn clone(&self) -> Self {
1241 Intersection { iter: self.iter.clone(), ..*self }
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1252 fn next(&mut self) -> Option<&'a T> {
1254 let elt = self.iter.next()?;
1255 if self.other.contains(elt) {
1261 fn size_hint(&self) -> (usize, Option<usize>) {
1262 let (_, upper) = self.iter.size_hint();
1267 #[stable(feature = "std_debug", since = "1.16.0")]
1268 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1269 where T: fmt::Debug + Eq + Hash,
1272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273 f.debug_list().entries(self.clone()).finish()
1277 #[stable(feature = "fused", since = "1.26.0")]
1278 impl<T, S> FusedIterator for Intersection<'_, T, S>
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl<T, S> Clone for Difference<'_, T, S> {
1286 fn clone(&self) -> Self {
1287 Difference { iter: self.iter.clone(), ..*self }
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 impl<'a, T, S> Iterator for Difference<'a, T, S>
1298 fn next(&mut self) -> Option<&'a T> {
1300 let elt = self.iter.next()?;
1301 if !self.other.contains(elt) {
1307 fn size_hint(&self) -> (usize, Option<usize>) {
1308 let (_, upper) = self.iter.size_hint();
1313 #[stable(feature = "fused", since = "1.26.0")]
1314 impl<T, S> FusedIterator for Difference<'_, T, S>
1320 #[stable(feature = "std_debug", since = "1.16.0")]
1321 impl<T, S> fmt::Debug for Difference<'_, T, S>
1322 where T: fmt::Debug + Eq + Hash,
1325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1326 f.debug_list().entries(self.clone()).finish()
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1332 fn clone(&self) -> Self {
1333 SymmetricDifference { iter: self.iter.clone() }
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1344 fn next(&mut self) -> Option<&'a T> {
1347 fn size_hint(&self) -> (usize, Option<usize>) {
1348 self.iter.size_hint()
1352 #[stable(feature = "fused", since = "1.26.0")]
1353 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1359 #[stable(feature = "std_debug", since = "1.16.0")]
1360 impl<T, S> fmt::Debug for SymmetricDifference<'_, 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<T, S> Clone for Union<'_, T, S> {
1371 fn clone(&self) -> Self {
1372 Union { iter: self.iter.clone() }
1376 #[stable(feature = "fused", since = "1.26.0")]
1377 impl<T, S> FusedIterator for Union<'_, T, S>
1383 #[stable(feature = "std_debug", since = "1.16.0")]
1384 impl<T, S> fmt::Debug for Union<'_, T, S>
1385 where T: fmt::Debug + Eq + Hash,
1388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1389 f.debug_list().entries(self.clone()).finish()
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl<'a, T, S> Iterator for Union<'a, T, S>
1400 fn next(&mut self) -> Option<&'a T> {
1403 fn size_hint(&self) -> (usize, Option<usize>) {
1404 self.iter.size_hint()
1409 fn assert_covariance() {
1410 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1413 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1416 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1419 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1420 -> Difference<'a, &'new str, RandomState> {
1423 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1424 -> SymmetricDifference<'a, &'new str, RandomState> {
1427 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1428 -> Intersection<'a, &'new str, RandomState> {
1431 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1432 -> Union<'a, &'new str, RandomState> {
1435 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1443 use super::super::map::RandomState;
1446 fn test_zero_capacities() {
1447 type HS = HashSet<i32>;
1450 assert_eq!(s.capacity(), 0);
1452 let s = HS::default();
1453 assert_eq!(s.capacity(), 0);
1455 let s = HS::with_hasher(RandomState::new());
1456 assert_eq!(s.capacity(), 0);
1458 let s = HS::with_capacity(0);
1459 assert_eq!(s.capacity(), 0);
1461 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1462 assert_eq!(s.capacity(), 0);
1464 let mut s = HS::new();
1470 assert_eq!(s.capacity(), 0);
1472 let mut s = HS::new();
1474 assert_eq!(s.capacity(), 0);
1478 fn test_disjoint() {
1479 let mut xs = HashSet::new();
1480 let mut ys = HashSet::new();
1481 assert!(xs.is_disjoint(&ys));
1482 assert!(ys.is_disjoint(&xs));
1483 assert!(xs.insert(5));
1484 assert!(ys.insert(11));
1485 assert!(xs.is_disjoint(&ys));
1486 assert!(ys.is_disjoint(&xs));
1487 assert!(xs.insert(7));
1488 assert!(xs.insert(19));
1489 assert!(xs.insert(4));
1490 assert!(ys.insert(2));
1491 assert!(ys.insert(-11));
1492 assert!(xs.is_disjoint(&ys));
1493 assert!(ys.is_disjoint(&xs));
1494 assert!(ys.insert(7));
1495 assert!(!xs.is_disjoint(&ys));
1496 assert!(!ys.is_disjoint(&xs));
1500 fn test_subset_and_superset() {
1501 let mut a = HashSet::new();
1502 assert!(a.insert(0));
1503 assert!(a.insert(5));
1504 assert!(a.insert(11));
1505 assert!(a.insert(7));
1507 let mut b = HashSet::new();
1508 assert!(b.insert(0));
1509 assert!(b.insert(7));
1510 assert!(b.insert(19));
1511 assert!(b.insert(250));
1512 assert!(b.insert(11));
1513 assert!(b.insert(200));
1515 assert!(!a.is_subset(&b));
1516 assert!(!a.is_superset(&b));
1517 assert!(!b.is_subset(&a));
1518 assert!(!b.is_superset(&a));
1520 assert!(b.insert(5));
1522 assert!(a.is_subset(&b));
1523 assert!(!a.is_superset(&b));
1524 assert!(!b.is_subset(&a));
1525 assert!(b.is_superset(&a));
1530 let mut a = HashSet::new();
1532 assert!(a.insert(i));
1534 let mut observed: u32 = 0;
1536 observed |= 1 << *k;
1538 assert_eq!(observed, 0xFFFF_FFFF);
1542 fn test_intersection() {
1543 let mut a = HashSet::new();
1544 let mut b = HashSet::new();
1545 assert!(a.intersection(&b).next().is_none());
1547 assert!(a.insert(11));
1548 assert!(a.insert(1));
1549 assert!(a.insert(3));
1550 assert!(a.insert(77));
1551 assert!(a.insert(103));
1552 assert!(a.insert(5));
1553 assert!(a.insert(-5));
1555 assert!(b.insert(2));
1556 assert!(b.insert(11));
1557 assert!(b.insert(77));
1558 assert!(b.insert(-9));
1559 assert!(b.insert(-42));
1560 assert!(b.insert(5));
1561 assert!(b.insert(3));
1564 let expected = [3, 5, 11, 77];
1565 for x in a.intersection(&b) {
1566 assert!(expected.contains(x));
1569 assert_eq!(i, expected.len());
1571 assert!(a.insert(9)); // make a bigger than b
1574 for x in a.intersection(&b) {
1575 assert!(expected.contains(x));
1578 assert_eq!(i, expected.len());
1581 for x in b.intersection(&a) {
1582 assert!(expected.contains(x));
1585 assert_eq!(i, expected.len());
1589 fn test_difference() {
1590 let mut a = HashSet::new();
1591 let mut b = HashSet::new();
1593 assert!(a.insert(1));
1594 assert!(a.insert(3));
1595 assert!(a.insert(5));
1596 assert!(a.insert(9));
1597 assert!(a.insert(11));
1599 assert!(b.insert(3));
1600 assert!(b.insert(9));
1603 let expected = [1, 5, 11];
1604 for x in a.difference(&b) {
1605 assert!(expected.contains(x));
1608 assert_eq!(i, expected.len());
1612 fn test_symmetric_difference() {
1613 let mut a = HashSet::new();
1614 let mut b = HashSet::new();
1616 assert!(a.insert(1));
1617 assert!(a.insert(3));
1618 assert!(a.insert(5));
1619 assert!(a.insert(9));
1620 assert!(a.insert(11));
1622 assert!(b.insert(-2));
1623 assert!(b.insert(3));
1624 assert!(b.insert(9));
1625 assert!(b.insert(14));
1626 assert!(b.insert(22));
1629 let expected = [-2, 1, 5, 11, 14, 22];
1630 for x in a.symmetric_difference(&b) {
1631 assert!(expected.contains(x));
1634 assert_eq!(i, expected.len());
1639 let mut a = HashSet::new();
1640 let mut b = HashSet::new();
1641 assert!(a.union(&b).next().is_none());
1642 assert!(b.union(&a).next().is_none());
1644 assert!(a.insert(1));
1645 assert!(a.insert(3));
1646 assert!(a.insert(11));
1647 assert!(a.insert(16));
1648 assert!(a.insert(19));
1649 assert!(a.insert(24));
1651 assert!(b.insert(-2));
1652 assert!(b.insert(1));
1653 assert!(b.insert(5));
1654 assert!(b.insert(9));
1655 assert!(b.insert(13));
1656 assert!(b.insert(19));
1659 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1660 for x in a.union(&b) {
1661 assert!(expected.contains(x));
1664 assert_eq!(i, expected.len());
1666 assert!(a.insert(9)); // make a bigger than b
1667 assert!(a.insert(5));
1670 for x in a.union(&b) {
1671 assert!(expected.contains(x));
1674 assert_eq!(i, expected.len());
1677 for x in b.union(&a) {
1678 assert!(expected.contains(x));
1681 assert_eq!(i, expected.len());
1685 fn test_from_iter() {
1686 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1688 let set: HashSet<_> = xs.iter().cloned().collect();
1691 assert!(set.contains(x));
1696 fn test_move_iter() {
1698 let mut hs = HashSet::new();
1706 let v = hs.into_iter().collect::<Vec<char>>();
1707 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1712 // These constants once happened to expose a bug in insert().
1713 // I'm keeping them around to prevent a regression.
1714 let mut s1 = HashSet::new();
1720 let mut s2 = HashSet::new();
1734 let mut set = HashSet::new();
1735 let empty = HashSet::<i32>::new();
1740 let set_str = format!("{:?}", set);
1742 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1743 assert_eq!(format!("{:?}", empty), "{}");
1747 fn test_trivial_drain() {
1748 let mut s = HashSet::<i32>::new();
1749 for _ in s.drain() {}
1750 assert!(s.is_empty());
1753 let mut s = HashSet::<i32>::new();
1755 assert!(s.is_empty());
1760 let mut s: HashSet<_> = (1..100).collect();
1762 // try this a bunch of times to make sure we don't screw up internal state.
1764 assert_eq!(s.len(), 99);
1768 let mut d = s.drain();
1769 for (i, x) in d.by_ref().take(50).enumerate() {
1773 assert_eq!(last_i, 49);
1777 panic!("s should be empty!");
1780 // reset to try again.
1790 struct Foo(&'static str, i32);
1792 impl PartialEq for Foo {
1793 fn eq(&self, other: &Self) -> bool {
1800 impl hash::Hash for Foo {
1801 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1806 let mut s = HashSet::new();
1807 assert_eq!(s.replace(Foo("a", 1)), None);
1808 assert_eq!(s.len(), 1);
1809 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1810 assert_eq!(s.len(), 1);
1812 let mut it = s.iter();
1813 assert_eq!(it.next(), Some(&Foo("a", 2)));
1814 assert_eq!(it.next(), None);
1818 fn test_extend_ref() {
1819 let mut a = HashSet::new();
1822 a.extend(&[2, 3, 4]);
1824 assert_eq!(a.len(), 4);
1825 assert!(a.contains(&1));
1826 assert!(a.contains(&2));
1827 assert!(a.contains(&3));
1828 assert!(a.contains(&4));
1830 let mut b = HashSet::new();
1836 assert_eq!(a.len(), 6);
1837 assert!(a.contains(&1));
1838 assert!(a.contains(&2));
1839 assert!(a.contains(&3));
1840 assert!(a.contains(&4));
1841 assert!(a.contains(&5));
1842 assert!(a.contains(&6));
1847 let xs = [1, 2, 3, 4, 5, 6];
1848 let mut set: HashSet<i32> = xs.iter().cloned().collect();
1849 set.retain(|&k| k % 2 == 0);
1850 assert_eq!(set.len(), 3);
1851 assert!(set.contains(&2));
1852 assert!(set.contains(&4));
1853 assert!(set.contains(&6));