4 use hashbrown::hash_set as base;
6 use crate::borrow::Borrow;
7 use crate::collections::TryReserveError;
9 use crate::hash::{BuildHasher, Hash};
10 use crate::iter::{Chain, FusedIterator};
11 use crate::ops::{BitAnd, BitOr, BitXor, Sub};
13 use super::map::{map_try_reserve_error, RandomState};
15 // Future Optimization (FIXME!)
16 // ============================
18 // Iteration over zero sized values is a noop. There is no need
19 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
20 // to get rid of it properly.
22 /// A [hash set] implemented as a `HashMap` where the value is `()`.
24 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
25 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
26 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
27 /// it is important that the following property holds:
30 /// k1 == k2 -> hash(k1) == hash(k2)
33 /// In other words, if two keys are equal, their hashes must be equal.
36 /// It is a logic error for a key to be modified in such a way that the key's
37 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
38 /// the [`Eq`] trait, changes while it is in the map. This is normally only
39 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
40 /// The behavior resulting from such a logic error is not specified, but will
41 /// be encapsulated to the `HashSet` that observed the logic error and not
42 /// result in undefined behavior. This could include panics, incorrect results,
43 /// aborts, memory leaks, and non-termination.
48 /// use std::collections::HashSet;
49 /// // Type inference lets us omit an explicit type signature (which
50 /// // would be `HashSet<String>` in this example).
51 /// let mut books = HashSet::new();
53 /// // Add some books.
54 /// books.insert("A Dance With Dragons".to_string());
55 /// books.insert("To Kill a Mockingbird".to_string());
56 /// books.insert("The Odyssey".to_string());
57 /// books.insert("The Great Gatsby".to_string());
59 /// // Check for a specific one.
60 /// if !books.contains("The Winds of Winter") {
61 /// println!("We have {} books, but The Winds of Winter ain't one.",
66 /// books.remove("The Odyssey");
68 /// // Iterate over everything.
69 /// for book in &books {
70 /// println!("{book}");
74 /// The easiest way to use `HashSet` with a custom type is to derive
75 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
76 /// future be implied by [`Eq`].
79 /// use std::collections::HashSet;
80 /// #[derive(Hash, Eq, PartialEq, Debug)]
86 /// let mut vikings = HashSet::new();
88 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
89 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
90 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
91 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
93 /// // Use derived implementation to print the vikings.
94 /// for x in &vikings {
95 /// println!("{x:?}");
99 /// A `HashSet` with a known list of items can be initialized from an array:
102 /// use std::collections::HashSet;
104 /// let viking_names = HashSet::from(["Einar", "Olaf", "Harald"]);
107 /// [hash set]: crate::collections#use-the-set-variant-of-any-of-these-maps-when
108 /// [`HashMap`]: crate::collections::HashMap
109 /// [`RefCell`]: crate::cell::RefCell
110 /// [`Cell`]: crate::cell::Cell
111 #[cfg_attr(not(test), rustc_diagnostic_item = "HashSet")]
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct HashSet<T, S = RandomState> {
114 base: base::HashSet<T, S>,
117 impl<T> HashSet<T, RandomState> {
118 /// Creates an empty `HashSet`.
120 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
121 /// is first inserted into.
126 /// use std::collections::HashSet;
127 /// let set: HashSet<i32> = HashSet::new();
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn new() -> HashSet<T, RandomState> {
136 /// Creates an empty `HashSet` with the specified capacity.
138 /// The hash set will be able to hold at least `capacity` elements without
139 /// reallocating. If `capacity` is 0, the hash set will not allocate.
144 /// use std::collections::HashSet;
145 /// let set: HashSet<i32> = HashSet::with_capacity(10);
146 /// assert!(set.capacity() >= 10);
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
152 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
156 impl<T, S> HashSet<T, S> {
157 /// Returns the number of elements the set can hold without reallocating.
162 /// use std::collections::HashSet;
163 /// let set: HashSet<i32> = HashSet::with_capacity(100);
164 /// assert!(set.capacity() >= 100);
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub fn capacity(&self) -> usize {
172 /// An iterator visiting all elements in arbitrary order.
173 /// The iterator element type is `&'a T`.
178 /// use std::collections::HashSet;
179 /// let mut set = HashSet::new();
183 /// // Will print in an arbitrary order.
184 /// for x in set.iter() {
191 /// In the current implementation, iterating over set takes O(capacity) time
192 /// instead of O(len) because it internally visits empty buckets too.
194 #[rustc_lint_query_instability]
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn iter(&self) -> Iter<'_, T> {
197 Iter { base: self.base.iter() }
200 /// Returns the number of elements in the set.
205 /// use std::collections::HashSet;
207 /// let mut v = HashSet::new();
208 /// assert_eq!(v.len(), 0);
210 /// assert_eq!(v.len(), 1);
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn len(&self) -> usize {
218 /// Returns `true` if the set contains no elements.
223 /// use std::collections::HashSet;
225 /// let mut v = HashSet::new();
226 /// assert!(v.is_empty());
228 /// assert!(!v.is_empty());
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn is_empty(&self) -> bool {
236 /// Clears the set, returning all elements as an iterator. Keeps the
237 /// allocated memory for reuse.
239 /// If the returned iterator is dropped before being fully consumed, it
240 /// drops the remaining elements. The returned iterator keeps a mutable
241 /// borrow on the vector to optimize its implementation.
246 /// use std::collections::HashSet;
248 /// let mut set = HashSet::from([1, 2, 3]);
249 /// assert!(!set.is_empty());
251 /// // print 1, 2, 3 in an arbitrary order
252 /// for i in set.drain() {
256 /// assert!(set.is_empty());
259 #[rustc_lint_query_instability]
260 #[stable(feature = "drain", since = "1.6.0")]
261 pub fn drain(&mut self) -> Drain<'_, T> {
262 Drain { base: self.base.drain() }
265 /// Creates an iterator which uses a closure to determine if a value should be removed.
267 /// If the closure returns true, then the value is removed and yielded.
268 /// If the closure returns false, the value will remain in the list and will not be yielded
271 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
272 /// values will still be subjected to the closure and removed and dropped if it returns true.
274 /// It is unspecified how many more values will be subjected to the closure
275 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
276 /// `DrainFilter` itself is leaked.
280 /// Splitting a set into even and odd values, reusing the original set:
283 /// #![feature(hash_drain_filter)]
284 /// use std::collections::HashSet;
286 /// let mut set: HashSet<i32> = (0..8).collect();
287 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
289 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
290 /// let mut odds = set.into_iter().collect::<Vec<_>>();
294 /// assert_eq!(evens, vec![0, 2, 4, 6]);
295 /// assert_eq!(odds, vec![1, 3, 5, 7]);
298 #[rustc_lint_query_instability]
299 #[unstable(feature = "hash_drain_filter", issue = "59618")]
300 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
302 F: FnMut(&T) -> bool,
304 DrainFilter { base: self.base.drain_filter(pred) }
307 /// Retains only the elements specified by the predicate.
309 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
310 /// The elements are visited in unsorted (and unspecified) order.
315 /// use std::collections::HashSet;
317 /// let mut set = HashSet::from([1, 2, 3, 4, 5, 6]);
318 /// set.retain(|&k| k % 2 == 0);
319 /// assert_eq!(set.len(), 3);
324 /// In the current implementation, this operation takes O(capacity) time
325 /// instead of O(len) because it internally visits empty buckets too.
326 #[rustc_lint_query_instability]
327 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
328 pub fn retain<F>(&mut self, f: F)
330 F: FnMut(&T) -> bool,
335 /// Clears the set, removing all values.
340 /// use std::collections::HashSet;
342 /// let mut v = HashSet::new();
345 /// assert!(v.is_empty());
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub fn clear(&mut self) {
353 /// Creates a new empty hash set which will use the given hasher to hash
356 /// The hash set is also created with the default initial capacity.
358 /// Warning: `hasher` is normally randomly generated, and
359 /// is designed to allow `HashSet`s to be resistant to attacks that
360 /// cause many collisions and very poor performance. Setting it
361 /// manually using this function can expose a DoS attack vector.
363 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
364 /// the HashMap to be useful, see its documentation for details.
369 /// use std::collections::HashSet;
370 /// use std::collections::hash_map::RandomState;
372 /// let s = RandomState::new();
373 /// let mut set = HashSet::with_hasher(s);
377 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
378 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
379 HashSet { base: base::HashSet::with_hasher(hasher) }
382 /// Creates an empty `HashSet` with the specified capacity, using
383 /// `hasher` to hash the keys.
385 /// The hash set will be able to hold at least `capacity` elements without
386 /// reallocating. If `capacity` is 0, the hash set will not allocate.
388 /// Warning: `hasher` is normally randomly generated, and
389 /// is designed to allow `HashSet`s to be resistant to attacks that
390 /// cause many collisions and very poor performance. Setting it
391 /// manually using this function can expose a DoS attack vector.
393 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
394 /// the HashMap to be useful, see its documentation for details.
399 /// use std::collections::HashSet;
400 /// use std::collections::hash_map::RandomState;
402 /// let s = RandomState::new();
403 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
407 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
408 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
409 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
412 /// Returns a reference to the set's [`BuildHasher`].
417 /// use std::collections::HashSet;
418 /// use std::collections::hash_map::RandomState;
420 /// let hasher = RandomState::new();
421 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
422 /// let hasher: &RandomState = set.hasher();
425 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
426 pub fn hasher(&self) -> &S {
431 impl<T, S> HashSet<T, S>
436 /// Reserves capacity for at least `additional` more elements to be inserted
437 /// in the `HashSet`. The collection may reserve more space to avoid
438 /// frequent reallocations.
442 /// Panics if the new allocation size overflows `usize`.
447 /// use std::collections::HashSet;
448 /// let mut set: HashSet<i32> = HashSet::new();
450 /// assert!(set.capacity() >= 10);
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn reserve(&mut self, additional: usize) {
455 self.base.reserve(additional)
458 /// Tries to reserve capacity for at least `additional` more elements to be inserted
459 /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
460 /// frequent reallocations.
464 /// If the capacity overflows, or the allocator reports a failure, then an error
470 /// use std::collections::HashSet;
471 /// let mut set: HashSet<i32> = HashSet::new();
472 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
475 #[stable(feature = "try_reserve", since = "1.57.0")]
476 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
477 self.base.try_reserve(additional).map_err(map_try_reserve_error)
480 /// Shrinks the capacity of the set as much as possible. It will drop
481 /// down as much as possible while maintaining the internal rules
482 /// and possibly leaving some space in accordance with the resize policy.
487 /// use std::collections::HashSet;
489 /// let mut set = HashSet::with_capacity(100);
492 /// assert!(set.capacity() >= 100);
493 /// set.shrink_to_fit();
494 /// assert!(set.capacity() >= 2);
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn shrink_to_fit(&mut self) {
499 self.base.shrink_to_fit()
502 /// Shrinks the capacity of the set with a lower limit. It will drop
503 /// down no lower than the supplied limit while maintaining the internal rules
504 /// and possibly leaving some space in accordance with the resize policy.
506 /// If the current capacity is less than the lower limit, this is a no-op.
510 /// use std::collections::HashSet;
512 /// let mut set = HashSet::with_capacity(100);
515 /// assert!(set.capacity() >= 100);
516 /// set.shrink_to(10);
517 /// assert!(set.capacity() >= 10);
518 /// set.shrink_to(0);
519 /// assert!(set.capacity() >= 2);
522 #[stable(feature = "shrink_to", since = "1.56.0")]
523 pub fn shrink_to(&mut self, min_capacity: usize) {
524 self.base.shrink_to(min_capacity)
527 /// Visits the values representing the difference,
528 /// i.e., the values that are in `self` but not in `other`.
533 /// use std::collections::HashSet;
534 /// let a = HashSet::from([1, 2, 3]);
535 /// let b = HashSet::from([4, 2, 3, 4]);
537 /// // Can be seen as `a - b`.
538 /// for x in a.difference(&b) {
539 /// println!("{x}"); // Print 1
542 /// let diff: HashSet<_> = a.difference(&b).collect();
543 /// assert_eq!(diff, [1].iter().collect());
545 /// // Note that difference is not symmetric,
546 /// // and `b - a` means something else:
547 /// let diff: HashSet<_> = b.difference(&a).collect();
548 /// assert_eq!(diff, [4].iter().collect());
551 #[rustc_lint_query_instability]
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
554 Difference { iter: self.iter(), other }
557 /// Visits the values representing the symmetric difference,
558 /// i.e., the values that are in `self` or in `other` but not in both.
563 /// use std::collections::HashSet;
564 /// let a = HashSet::from([1, 2, 3]);
565 /// let b = HashSet::from([4, 2, 3, 4]);
567 /// // Print 1, 4 in arbitrary order.
568 /// for x in a.symmetric_difference(&b) {
572 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
573 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
575 /// assert_eq!(diff1, diff2);
576 /// assert_eq!(diff1, [1, 4].iter().collect());
579 #[rustc_lint_query_instability]
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn symmetric_difference<'a>(
583 other: &'a HashSet<T, S>,
584 ) -> SymmetricDifference<'a, T, S> {
585 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
588 /// Visits the values representing the intersection,
589 /// i.e., the values that are both in `self` and `other`.
591 /// Note: this operation does not guarantee which collection
592 /// is visited from `self` or `other`. This has consequences
593 /// for values which may be defined as equal by the `Eq` trait
594 /// but which are not physically equivalent (eg. they may have
595 /// fields which differ or do not participate in the definition
601 /// use std::collections::HashSet;
602 /// let a = HashSet::from([1, 2, 3]);
603 /// let b = HashSet::from([4, 2, 3, 4]);
605 /// // Print 2, 3 in arbitrary order.
606 /// for x in a.intersection(&b) {
610 /// let intersection: HashSet<_> = a.intersection(&b).collect();
611 /// assert_eq!(intersection, [2, 3].iter().collect());
614 #[rustc_lint_query_instability]
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
617 if self.len() <= other.len() {
618 Intersection { iter: self.iter(), other }
620 Intersection { iter: other.iter(), other: self }
624 /// Visits the values representing the union,
625 /// i.e., all the values in `self` or `other`, without duplicates.
630 /// use std::collections::HashSet;
631 /// let a = HashSet::from([1, 2, 3]);
632 /// let b = HashSet::from([4, 2, 3, 4]);
634 /// // Print 1, 2, 3, 4 in arbitrary order.
635 /// for x in a.union(&b) {
639 /// let union: HashSet<_> = a.union(&b).collect();
640 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
643 #[rustc_lint_query_instability]
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
646 if self.len() >= other.len() {
647 Union { iter: self.iter().chain(other.difference(self)) }
649 Union { iter: other.iter().chain(self.difference(other)) }
653 /// Returns `true` if the set contains a value.
655 /// The value may be any borrowed form of the set's value type, but
656 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
662 /// use std::collections::HashSet;
664 /// let set = HashSet::from([1, 2, 3]);
665 /// assert_eq!(set.contains(&1), true);
666 /// assert_eq!(set.contains(&4), false);
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
675 self.base.contains(value)
678 /// Returns a reference to the value in the set, if any, that is equal to the given value.
680 /// The value may be any borrowed form of the set's value type, but
681 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
687 /// use std::collections::HashSet;
689 /// let set = HashSet::from([1, 2, 3]);
690 /// assert_eq!(set.get(&2), Some(&2));
691 /// assert_eq!(set.get(&4), None);
694 #[stable(feature = "set_recovery", since = "1.9.0")]
695 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
703 /// Inserts the given `value` into the set if it is not present, then
704 /// returns a reference to the value in the set.
709 /// #![feature(hash_set_entry)]
711 /// use std::collections::HashSet;
713 /// let mut set = HashSet::from([1, 2, 3]);
714 /// assert_eq!(set.len(), 3);
715 /// assert_eq!(set.get_or_insert(2), &2);
716 /// assert_eq!(set.get_or_insert(100), &100);
717 /// assert_eq!(set.len(), 4); // 100 was inserted
720 #[unstable(feature = "hash_set_entry", issue = "60896")]
721 pub fn get_or_insert(&mut self, value: T) -> &T {
722 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
723 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
724 self.base.get_or_insert(value)
727 /// Inserts an owned copy of the given `value` into the set if it is not
728 /// present, then returns a reference to the value in the set.
733 /// #![feature(hash_set_entry)]
735 /// use std::collections::HashSet;
737 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
738 /// .iter().map(|&pet| pet.to_owned()).collect();
740 /// assert_eq!(set.len(), 3);
741 /// for &pet in &["cat", "dog", "fish"] {
742 /// let value = set.get_or_insert_owned(pet);
743 /// assert_eq!(value, pet);
745 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
748 #[unstable(feature = "hash_set_entry", issue = "60896")]
749 pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
752 Q: Hash + Eq + ToOwned<Owned = T>,
754 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
755 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
756 self.base.get_or_insert_owned(value)
759 /// Inserts a value computed from `f` into the set if the given `value` is
760 /// not present, then returns a reference to the value in the set.
765 /// #![feature(hash_set_entry)]
767 /// use std::collections::HashSet;
769 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
770 /// .iter().map(|&pet| pet.to_owned()).collect();
772 /// assert_eq!(set.len(), 3);
773 /// for &pet in &["cat", "dog", "fish"] {
774 /// let value = set.get_or_insert_with(pet, str::to_owned);
775 /// assert_eq!(value, pet);
777 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
780 #[unstable(feature = "hash_set_entry", issue = "60896")]
781 pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
787 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
788 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
789 self.base.get_or_insert_with(value, f)
792 /// Returns `true` if `self` has no elements in common with `other`.
793 /// This is equivalent to checking for an empty intersection.
798 /// use std::collections::HashSet;
800 /// let a = HashSet::from([1, 2, 3]);
801 /// let mut b = HashSet::new();
803 /// assert_eq!(a.is_disjoint(&b), true);
805 /// assert_eq!(a.is_disjoint(&b), true);
807 /// assert_eq!(a.is_disjoint(&b), false);
809 #[stable(feature = "rust1", since = "1.0.0")]
810 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
811 if self.len() <= other.len() {
812 self.iter().all(|v| !other.contains(v))
814 other.iter().all(|v| !self.contains(v))
818 /// Returns `true` if the set is a subset of another,
819 /// i.e., `other` contains at least all the values in `self`.
824 /// use std::collections::HashSet;
826 /// let sup = HashSet::from([1, 2, 3]);
827 /// let mut set = HashSet::new();
829 /// assert_eq!(set.is_subset(&sup), true);
831 /// assert_eq!(set.is_subset(&sup), true);
833 /// assert_eq!(set.is_subset(&sup), false);
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
837 if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
840 /// Returns `true` if the set is a superset of another,
841 /// i.e., `self` contains at least all the values in `other`.
846 /// use std::collections::HashSet;
848 /// let sub = HashSet::from([1, 2]);
849 /// let mut set = HashSet::new();
851 /// assert_eq!(set.is_superset(&sub), false);
855 /// assert_eq!(set.is_superset(&sub), false);
858 /// assert_eq!(set.is_superset(&sub), true);
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
863 other.is_subset(self)
866 /// Adds a value to the set.
868 /// Returns whether the value was newly inserted. That is:
870 /// - If the set did not previously contain this value, `true` is returned.
871 /// - If the set already contained this value, `false` is returned.
876 /// use std::collections::HashSet;
878 /// let mut set = HashSet::new();
880 /// assert_eq!(set.insert(2), true);
881 /// assert_eq!(set.insert(2), false);
882 /// assert_eq!(set.len(), 1);
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn insert(&mut self, value: T) -> bool {
887 self.base.insert(value)
890 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
891 /// one. Returns the replaced value.
896 /// use std::collections::HashSet;
898 /// let mut set = HashSet::new();
899 /// set.insert(Vec::<i32>::new());
901 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
902 /// set.replace(Vec::with_capacity(10));
903 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
906 #[stable(feature = "set_recovery", since = "1.9.0")]
907 pub fn replace(&mut self, value: T) -> Option<T> {
908 self.base.replace(value)
911 /// Removes a value from the set. Returns whether the value was
912 /// present in the set.
914 /// The value may be any borrowed form of the set's value type, but
915 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
921 /// use std::collections::HashSet;
923 /// let mut set = HashSet::new();
926 /// assert_eq!(set.remove(&2), true);
927 /// assert_eq!(set.remove(&2), false);
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
936 self.base.remove(value)
939 /// Removes and returns the value in the set, if any, that is equal to the given one.
941 /// The value may be any borrowed form of the set's value type, but
942 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
948 /// use std::collections::HashSet;
950 /// let mut set = HashSet::from([1, 2, 3]);
951 /// assert_eq!(set.take(&2), Some(2));
952 /// assert_eq!(set.take(&2), None);
955 #[stable(feature = "set_recovery", since = "1.9.0")]
956 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
961 self.base.take(value)
965 #[stable(feature = "rust1", since = "1.0.0")]
966 impl<T, S> Clone for HashSet<T, S>
972 fn clone(&self) -> Self {
973 Self { base: self.base.clone() }
977 fn clone_from(&mut self, other: &Self) {
978 self.base.clone_from(&other.base);
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T, S> PartialEq for HashSet<T, S>
988 fn eq(&self, other: &HashSet<T, S>) -> bool {
989 if self.len() != other.len() {
993 self.iter().all(|key| other.contains(key))
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<T, S> Eq for HashSet<T, S>
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 impl<T, S> fmt::Debug for HashSet<T, S>
1010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011 f.debug_set().entries(self.iter()).finish()
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<T, S> FromIterator<T> for HashSet<T, S>
1019 S: BuildHasher + Default,
1022 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
1023 let mut set = HashSet::with_hasher(Default::default());
1029 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1030 // Note: as what is currently the most convenient built-in way to construct
1031 // a HashSet, a simple usage of this function must not *require* the user
1032 // to provide a type annotation in order to infer the third type parameter
1033 // (the hasher parameter, conventionally "S").
1034 // To that end, this impl is defined using RandomState as the concrete
1035 // type of S, rather than being generic over `S: BuildHasher + Default`.
1036 // It is expected that users who want to specify a hasher will manually use
1037 // `with_capacity_and_hasher`.
1038 // If type parameter defaults worked on impls, and if type parameter
1039 // defaults could be mixed with const generics, then perhaps
1040 // this could be generalized.
1041 // See also the equivalent impl on HashMap.
1042 impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
1049 /// use std::collections::HashSet;
1051 /// let set1 = HashSet::from([1, 2, 3, 4]);
1052 /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1053 /// assert_eq!(set1, set2);
1055 fn from(arr: [T; N]) -> Self {
1056 Self::from_iter(arr)
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<T, S> Extend<T> for HashSet<T, S>
1067 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1068 self.base.extend(iter);
1072 fn extend_one(&mut self, item: T) {
1073 self.base.insert(item);
1077 fn extend_reserve(&mut self, additional: usize) {
1078 self.base.extend_reserve(additional);
1082 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1083 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1085 T: 'a + Eq + Hash + Copy,
1089 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1090 self.extend(iter.into_iter().cloned());
1094 fn extend_one(&mut self, &item: &'a T) {
1095 self.base.insert(item);
1099 fn extend_reserve(&mut self, additional: usize) {
1100 Extend::<T>::extend_reserve(self, additional)
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<T, S> Default for HashSet<T, S>
1109 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1111 fn default() -> HashSet<T, S> {
1112 HashSet { base: Default::default() }
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1119 T: Eq + Hash + Clone,
1120 S: BuildHasher + Default,
1122 type Output = HashSet<T, S>;
1124 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1129 /// use std::collections::HashSet;
1131 /// let a = HashSet::from([1, 2, 3]);
1132 /// let b = HashSet::from([3, 4, 5]);
1134 /// let set = &a | &b;
1137 /// let expected = [1, 2, 3, 4, 5];
1139 /// assert!(expected.contains(x));
1142 /// assert_eq!(i, expected.len());
1144 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1145 self.union(rhs).cloned().collect()
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1152 T: Eq + Hash + Clone,
1153 S: BuildHasher + Default,
1155 type Output = HashSet<T, S>;
1157 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1162 /// use std::collections::HashSet;
1164 /// let a = HashSet::from([1, 2, 3]);
1165 /// let b = HashSet::from([2, 3, 4]);
1167 /// let set = &a & &b;
1170 /// let expected = [2, 3];
1172 /// assert!(expected.contains(x));
1175 /// assert_eq!(i, expected.len());
1177 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1178 self.intersection(rhs).cloned().collect()
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1185 T: Eq + Hash + Clone,
1186 S: BuildHasher + Default,
1188 type Output = HashSet<T, S>;
1190 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1195 /// use std::collections::HashSet;
1197 /// let a = HashSet::from([1, 2, 3]);
1198 /// let b = HashSet::from([3, 4, 5]);
1200 /// let set = &a ^ &b;
1203 /// let expected = [1, 2, 4, 5];
1205 /// assert!(expected.contains(x));
1208 /// assert_eq!(i, expected.len());
1210 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1211 self.symmetric_difference(rhs).cloned().collect()
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1218 T: Eq + Hash + Clone,
1219 S: BuildHasher + Default,
1221 type Output = HashSet<T, S>;
1223 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1228 /// use std::collections::HashSet;
1230 /// let a = HashSet::from([1, 2, 3]);
1231 /// let b = HashSet::from([3, 4, 5]);
1233 /// let set = &a - &b;
1236 /// let expected = [1, 2];
1238 /// assert!(expected.contains(x));
1241 /// assert_eq!(i, expected.len());
1243 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1244 self.difference(rhs).cloned().collect()
1248 /// An iterator over the items of a `HashSet`.
1250 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1251 /// See its documentation for more.
1253 /// [`iter`]: HashSet::iter
1258 /// use std::collections::HashSet;
1260 /// let a = HashSet::from([1, 2, 3]);
1262 /// let mut iter = a.iter();
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub struct Iter<'a, K: 'a> {
1266 base: base::Iter<'a, K>,
1269 /// An owning iterator over the items of a `HashSet`.
1271 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1272 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1274 /// [`into_iter`]: IntoIterator::into_iter
1275 /// [`IntoIterator`]: crate::iter::IntoIterator
1280 /// use std::collections::HashSet;
1282 /// let a = HashSet::from([1, 2, 3]);
1284 /// let mut iter = a.into_iter();
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 pub struct IntoIter<K> {
1288 base: base::IntoIter<K>,
1291 /// A draining iterator over the items of a `HashSet`.
1293 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1294 /// See its documentation for more.
1296 /// [`drain`]: HashSet::drain
1301 /// use std::collections::HashSet;
1303 /// let mut a = HashSet::from([1, 2, 3]);
1305 /// let mut drain = a.drain();
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 pub struct Drain<'a, K: 'a> {
1309 base: base::Drain<'a, K>,
1312 /// A draining, filtering iterator over the items of a `HashSet`.
1314 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1316 /// [`drain_filter`]: HashSet::drain_filter
1321 /// #![feature(hash_drain_filter)]
1323 /// use std::collections::HashSet;
1325 /// let mut a = HashSet::from([1, 2, 3]);
1327 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1329 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1330 pub struct DrainFilter<'a, K, F>
1332 F: FnMut(&K) -> bool,
1334 base: base::DrainFilter<'a, K, F>,
1337 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1339 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1340 /// See its documentation for more.
1342 /// [`intersection`]: HashSet::intersection
1347 /// use std::collections::HashSet;
1349 /// let a = HashSet::from([1, 2, 3]);
1350 /// let b = HashSet::from([4, 2, 3, 4]);
1352 /// let mut intersection = a.intersection(&b);
1354 #[must_use = "this returns the intersection as an iterator, \
1355 without modifying either input set"]
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 pub struct Intersection<'a, T: 'a, S: 'a> {
1358 // iterator of the first set
1361 other: &'a HashSet<T, S>,
1364 /// A lazy iterator producing elements in the difference of `HashSet`s.
1366 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1367 /// See its documentation for more.
1369 /// [`difference`]: HashSet::difference
1374 /// use std::collections::HashSet;
1376 /// let a = HashSet::from([1, 2, 3]);
1377 /// let b = HashSet::from([4, 2, 3, 4]);
1379 /// let mut difference = a.difference(&b);
1381 #[must_use = "this returns the difference as an iterator, \
1382 without modifying either input set"]
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 pub struct Difference<'a, T: 'a, S: 'a> {
1385 // iterator of the first set
1388 other: &'a HashSet<T, S>,
1391 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1393 /// This `struct` is created by the [`symmetric_difference`] method on
1394 /// [`HashSet`]. See its documentation for more.
1396 /// [`symmetric_difference`]: HashSet::symmetric_difference
1401 /// use std::collections::HashSet;
1403 /// let a = HashSet::from([1, 2, 3]);
1404 /// let b = HashSet::from([4, 2, 3, 4]);
1406 /// let mut intersection = a.symmetric_difference(&b);
1408 #[must_use = "this returns the difference as an iterator, \
1409 without modifying either input set"]
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1412 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1415 /// A lazy iterator producing elements in the union of `HashSet`s.
1417 /// This `struct` is created by the [`union`] method on [`HashSet`].
1418 /// See its documentation for more.
1420 /// [`union`]: HashSet::union
1425 /// use std::collections::HashSet;
1427 /// let a = HashSet::from([1, 2, 3]);
1428 /// let b = HashSet::from([4, 2, 3, 4]);
1430 /// let mut union_iter = a.union(&b);
1432 #[must_use = "this returns the union as an iterator, \
1433 without modifying either input set"]
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 pub struct Union<'a, T: 'a, S: 'a> {
1436 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1442 type IntoIter = Iter<'a, T>;
1445 #[rustc_lint_query_instability]
1446 fn into_iter(self) -> Iter<'a, T> {
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<T, S> IntoIterator for HashSet<T, S> {
1454 type IntoIter = IntoIter<T>;
1456 /// Creates a consuming iterator, that is, one that moves each value out
1457 /// of the set in arbitrary order. The set cannot be used after calling
1463 /// use std::collections::HashSet;
1464 /// let mut set = HashSet::new();
1465 /// set.insert("a".to_string());
1466 /// set.insert("b".to_string());
1468 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1469 /// let v: Vec<String> = set.into_iter().collect();
1471 /// // Will print in an arbitrary order.
1473 /// println!("{x}");
1477 #[rustc_lint_query_instability]
1478 fn into_iter(self) -> IntoIter<T> {
1479 IntoIter { base: self.base.into_iter() }
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<K> Clone for Iter<'_, K> {
1486 fn clone(&self) -> Self {
1487 Iter { base: self.base.clone() }
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<'a, K> Iterator for Iter<'a, K> {
1495 fn next(&mut self) -> Option<&'a K> {
1499 fn size_hint(&self) -> (usize, Option<usize>) {
1500 self.base.size_hint()
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<K> ExactSizeIterator for Iter<'_, K> {
1506 fn len(&self) -> usize {
1510 #[stable(feature = "fused", since = "1.26.0")]
1511 impl<K> FusedIterator for Iter<'_, K> {}
1513 #[stable(feature = "std_debug", since = "1.16.0")]
1514 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1516 f.debug_list().entries(self.clone()).finish()
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<K> Iterator for IntoIter<K> {
1525 fn next(&mut self) -> Option<K> {
1529 fn size_hint(&self) -> (usize, Option<usize>) {
1530 self.base.size_hint()
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<K> ExactSizeIterator for IntoIter<K> {
1536 fn len(&self) -> usize {
1540 #[stable(feature = "fused", since = "1.26.0")]
1541 impl<K> FusedIterator for IntoIter<K> {}
1543 #[stable(feature = "std_debug", since = "1.16.0")]
1544 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1546 fmt::Debug::fmt(&self.base, f)
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl<'a, K> Iterator for Drain<'a, K> {
1555 fn next(&mut self) -> Option<K> {
1559 fn size_hint(&self) -> (usize, Option<usize>) {
1560 self.base.size_hint()
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl<K> ExactSizeIterator for Drain<'_, K> {
1566 fn len(&self) -> usize {
1570 #[stable(feature = "fused", since = "1.26.0")]
1571 impl<K> FusedIterator for Drain<'_, K> {}
1573 #[stable(feature = "std_debug", since = "1.16.0")]
1574 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1575 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1576 fmt::Debug::fmt(&self.base, f)
1580 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1581 impl<K, F> Iterator for DrainFilter<'_, K, F>
1583 F: FnMut(&K) -> bool,
1588 fn next(&mut self) -> Option<K> {
1592 fn size_hint(&self) -> (usize, Option<usize>) {
1593 self.base.size_hint()
1597 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1598 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1600 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1601 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1603 F: FnMut(&K) -> bool,
1605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606 f.debug_struct("DrainFilter").finish_non_exhaustive()
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 impl<T, S> Clone for Intersection<'_, T, S> {
1613 fn clone(&self) -> Self {
1614 Intersection { iter: self.iter.clone(), ..*self }
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1627 fn next(&mut self) -> Option<&'a T> {
1629 let elt = self.iter.next()?;
1630 if self.other.contains(elt) {
1637 fn size_hint(&self) -> (usize, Option<usize>) {
1638 let (_, upper) = self.iter.size_hint();
1643 #[stable(feature = "std_debug", since = "1.16.0")]
1644 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1646 T: fmt::Debug + Eq + Hash,
1649 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1650 f.debug_list().entries(self.clone()).finish()
1654 #[stable(feature = "fused", since = "1.26.0")]
1655 impl<T, S> FusedIterator for Intersection<'_, T, S>
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl<T, S> Clone for Difference<'_, T, S> {
1665 fn clone(&self) -> Self {
1666 Difference { iter: self.iter.clone(), ..*self }
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<'a, T, S> Iterator for Difference<'a, T, S>
1679 fn next(&mut self) -> Option<&'a T> {
1681 let elt = self.iter.next()?;
1682 if !self.other.contains(elt) {
1689 fn size_hint(&self) -> (usize, Option<usize>) {
1690 let (_, upper) = self.iter.size_hint();
1695 #[stable(feature = "fused", since = "1.26.0")]
1696 impl<T, S> FusedIterator for Difference<'_, T, S>
1703 #[stable(feature = "std_debug", since = "1.16.0")]
1704 impl<T, S> fmt::Debug for Difference<'_, T, S>
1706 T: fmt::Debug + Eq + Hash,
1709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1710 f.debug_list().entries(self.clone()).finish()
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1717 fn clone(&self) -> Self {
1718 SymmetricDifference { iter: self.iter.clone() }
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1731 fn next(&mut self) -> Option<&'a T> {
1735 fn size_hint(&self) -> (usize, Option<usize>) {
1736 self.iter.size_hint()
1740 #[stable(feature = "fused", since = "1.26.0")]
1741 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1748 #[stable(feature = "std_debug", since = "1.16.0")]
1749 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1751 T: fmt::Debug + Eq + Hash,
1754 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1755 f.debug_list().entries(self.clone()).finish()
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<T, S> Clone for Union<'_, T, S> {
1762 fn clone(&self) -> Self {
1763 Union { iter: self.iter.clone() }
1767 #[stable(feature = "fused", since = "1.26.0")]
1768 impl<T, S> FusedIterator for Union<'_, T, S>
1775 #[stable(feature = "std_debug", since = "1.16.0")]
1776 impl<T, S> fmt::Debug for Union<'_, T, S>
1778 T: fmt::Debug + Eq + Hash,
1781 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1782 f.debug_list().entries(self.clone()).finish()
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 impl<'a, T, S> Iterator for Union<'a, T, S>
1795 fn next(&mut self) -> Option<&'a T> {
1799 fn size_hint(&self) -> (usize, Option<usize>) {
1800 self.iter.size_hint()
1805 fn assert_covariance() {
1806 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1809 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1812 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1815 fn difference<'a, 'new>(
1816 v: Difference<'a, &'static str, RandomState>,
1817 ) -> Difference<'a, &'new str, RandomState> {
1820 fn symmetric_difference<'a, 'new>(
1821 v: SymmetricDifference<'a, &'static str, RandomState>,
1822 ) -> SymmetricDifference<'a, &'new str, RandomState> {
1825 fn intersection<'a, 'new>(
1826 v: Intersection<'a, &'static str, RandomState>,
1827 ) -> Intersection<'a, &'new str, RandomState> {
1831 v: Union<'a, &'static str, RandomState>,
1832 ) -> Union<'a, &'new str, RandomState> {
1835 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {