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, FromIterator, 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 an item to be modified in such a way that the
37 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
38 /// determined by the [`Eq`] trait, changes while it is in the set. This is
39 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
40 /// unsafe code. The behavior resulting from such a logic error is not
41 /// specified (it could include panics, incorrect results, aborts, memory
42 /// leaks, or non-termination) but will not be undefined behavior.
47 /// use std::collections::HashSet;
48 /// // Type inference lets us omit an explicit type signature (which
49 /// // would be `HashSet<String>` in this example).
50 /// let mut books = HashSet::new();
52 /// // Add some books.
53 /// books.insert("A Dance With Dragons".to_string());
54 /// books.insert("To Kill a Mockingbird".to_string());
55 /// books.insert("The Odyssey".to_string());
56 /// books.insert("The Great Gatsby".to_string());
58 /// // Check for a specific one.
59 /// if !books.contains("The Winds of Winter") {
60 /// println!("We have {} books, but The Winds of Winter ain't one.",
65 /// books.remove("The Odyssey");
67 /// // Iterate over everything.
68 /// for book in &books {
69 /// println!("{}", book);
73 /// The easiest way to use `HashSet` with a custom type is to derive
74 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
75 /// future be implied by [`Eq`].
78 /// use std::collections::HashSet;
79 /// #[derive(Hash, Eq, PartialEq, Debug)]
85 /// let mut vikings = HashSet::new();
87 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
88 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
89 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
90 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
92 /// // Use derived implementation to print the vikings.
93 /// for x in &vikings {
94 /// println!("{:?}", x);
98 /// A `HashSet` with a known list of items can be initialized from an array:
101 /// use std::collections::HashSet;
103 /// let viking_names = HashSet::from(["Einar", "Olaf", "Harald"]);
106 /// [hash set]: crate::collections#use-the-set-variant-of-any-of-these-maps-when
107 /// [`HashMap`]: crate::collections::HashMap
108 /// [`RefCell`]: crate::cell::RefCell
109 /// [`Cell`]: crate::cell::Cell
110 #[cfg_attr(not(test), rustc_diagnostic_item = "HashSet")]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct HashSet<T, S = RandomState> {
113 base: base::HashSet<T, S>,
116 impl<T> HashSet<T, RandomState> {
117 /// Creates an empty `HashSet`.
119 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
120 /// is first inserted into.
125 /// use std::collections::HashSet;
126 /// let set: HashSet<i32> = HashSet::new();
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub fn new() -> HashSet<T, RandomState> {
135 /// Creates an empty `HashSet` with the specified capacity.
137 /// The hash set will be able to hold at least `capacity` elements without
138 /// reallocating. If `capacity` is 0, the hash set will not allocate.
143 /// use std::collections::HashSet;
144 /// let set: HashSet<i32> = HashSet::with_capacity(10);
145 /// assert!(set.capacity() >= 10);
149 #[stable(feature = "rust1", since = "1.0.0")]
150 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
151 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
155 impl<T, S> HashSet<T, S> {
156 /// Returns the number of elements the set can hold without reallocating.
161 /// use std::collections::HashSet;
162 /// let set: HashSet<i32> = HashSet::with_capacity(100);
163 /// assert!(set.capacity() >= 100);
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub fn capacity(&self) -> usize {
171 /// An iterator visiting all elements in arbitrary order.
172 /// The iterator element type is `&'a T`.
177 /// use std::collections::HashSet;
178 /// let mut set = HashSet::new();
182 /// // Will print in an arbitrary order.
183 /// for x in set.iter() {
184 /// println!("{}", x);
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub fn iter(&self) -> Iter<'_, T> {
190 Iter { base: self.base.iter() }
193 /// Returns the number of elements in the set.
198 /// use std::collections::HashSet;
200 /// let mut v = HashSet::new();
201 /// assert_eq!(v.len(), 0);
203 /// assert_eq!(v.len(), 1);
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn len(&self) -> usize {
211 /// Returns `true` if the set contains no elements.
216 /// use std::collections::HashSet;
218 /// let mut v = HashSet::new();
219 /// assert!(v.is_empty());
221 /// assert!(!v.is_empty());
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn is_empty(&self) -> bool {
229 /// Clears the set, returning all elements in an iterator.
234 /// use std::collections::HashSet;
236 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
237 /// assert!(!set.is_empty());
239 /// // print 1, 2, 3 in an arbitrary order
240 /// for i in set.drain() {
241 /// println!("{}", i);
244 /// assert!(set.is_empty());
247 #[stable(feature = "drain", since = "1.6.0")]
248 pub fn drain(&mut self) -> Drain<'_, T> {
249 Drain { base: self.base.drain() }
252 /// Creates an iterator which uses a closure to determine if a value should be removed.
254 /// If the closure returns true, then the value is removed and yielded.
255 /// If the closure returns false, the value will remain in the list and will not be yielded
258 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
259 /// values will still be subjected to the closure and removed and dropped if it returns true.
261 /// It is unspecified how many more values will be subjected to the closure
262 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
263 /// `DrainFilter` itself is leaked.
267 /// Splitting a set into even and odd values, reusing the original set:
270 /// #![feature(hash_drain_filter)]
271 /// use std::collections::HashSet;
273 /// let mut set: HashSet<i32> = (0..8).collect();
274 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
276 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
277 /// let mut odds = set.into_iter().collect::<Vec<_>>();
281 /// assert_eq!(evens, vec![0, 2, 4, 6]);
282 /// assert_eq!(odds, vec![1, 3, 5, 7]);
285 #[unstable(feature = "hash_drain_filter", issue = "59618")]
286 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
288 F: FnMut(&T) -> bool,
290 DrainFilter { base: self.base.drain_filter(pred) }
293 /// Clears the set, removing all values.
298 /// use std::collections::HashSet;
300 /// let mut v = HashSet::new();
303 /// assert!(v.is_empty());
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn clear(&mut self) {
311 /// Creates a new empty hash set which will use the given hasher to hash
314 /// The hash set is also created with the default initial capacity.
316 /// Warning: `hasher` is normally randomly generated, and
317 /// is designed to allow `HashSet`s to be resistant to attacks that
318 /// cause many collisions and very poor performance. Setting it
319 /// manually using this function can expose a DoS attack vector.
321 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
322 /// the HashMap to be useful, see its documentation for details.
327 /// use std::collections::HashSet;
328 /// use std::collections::hash_map::RandomState;
330 /// let s = RandomState::new();
331 /// let mut set = HashSet::with_hasher(s);
335 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
336 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
337 HashSet { base: base::HashSet::with_hasher(hasher) }
340 /// Creates an empty `HashSet` with the specified capacity, using
341 /// `hasher` to hash the keys.
343 /// The hash set will be able to hold at least `capacity` elements without
344 /// reallocating. If `capacity` is 0, the hash set will not allocate.
346 /// Warning: `hasher` is normally randomly generated, and
347 /// is designed to allow `HashSet`s to be resistant to attacks that
348 /// cause many collisions and very poor performance. Setting it
349 /// manually using this function can expose a DoS attack vector.
351 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
352 /// the HashMap to be useful, see its documentation for details.
357 /// use std::collections::HashSet;
358 /// use std::collections::hash_map::RandomState;
360 /// let s = RandomState::new();
361 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
365 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
366 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
367 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
370 /// Returns a reference to the set's [`BuildHasher`].
375 /// use std::collections::HashSet;
376 /// use std::collections::hash_map::RandomState;
378 /// let hasher = RandomState::new();
379 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
380 /// let hasher: &RandomState = set.hasher();
383 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
384 pub fn hasher(&self) -> &S {
389 impl<T, S> HashSet<T, S>
394 /// Reserves capacity for at least `additional` more elements to be inserted
395 /// in the `HashSet`. The collection may reserve more space to avoid
396 /// frequent reallocations.
400 /// Panics if the new allocation size overflows `usize`.
405 /// use std::collections::HashSet;
406 /// let mut set: HashSet<i32> = HashSet::new();
408 /// assert!(set.capacity() >= 10);
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn reserve(&mut self, additional: usize) {
413 self.base.reserve(additional)
416 /// Tries to reserve capacity for at least `additional` more elements to be inserted
417 /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
418 /// frequent reallocations.
422 /// If the capacity overflows, or the allocator reports a failure, then an error
428 /// use std::collections::HashSet;
429 /// let mut set: HashSet<i32> = HashSet::new();
430 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
433 #[stable(feature = "try_reserve", since = "1.57.0")]
434 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
435 self.base.try_reserve(additional).map_err(map_try_reserve_error)
438 /// Shrinks the capacity of the set as much as possible. It will drop
439 /// down as much as possible while maintaining the internal rules
440 /// and possibly leaving some space in accordance with the resize policy.
445 /// use std::collections::HashSet;
447 /// let mut set = HashSet::with_capacity(100);
450 /// assert!(set.capacity() >= 100);
451 /// set.shrink_to_fit();
452 /// assert!(set.capacity() >= 2);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn shrink_to_fit(&mut self) {
457 self.base.shrink_to_fit()
460 /// Shrinks the capacity of the set with a lower limit. It will drop
461 /// down no lower than the supplied limit while maintaining the internal rules
462 /// and possibly leaving some space in accordance with the resize policy.
464 /// If the current capacity is less than the lower limit, this is a no-op.
468 /// use std::collections::HashSet;
470 /// let mut set = HashSet::with_capacity(100);
473 /// assert!(set.capacity() >= 100);
474 /// set.shrink_to(10);
475 /// assert!(set.capacity() >= 10);
476 /// set.shrink_to(0);
477 /// assert!(set.capacity() >= 2);
480 #[stable(feature = "shrink_to", since = "1.56.0")]
481 pub fn shrink_to(&mut self, min_capacity: usize) {
482 self.base.shrink_to(min_capacity)
485 /// Visits the values representing the difference,
486 /// i.e., the values that are in `self` but not in `other`.
491 /// use std::collections::HashSet;
492 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
493 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
495 /// // Can be seen as `a - b`.
496 /// for x in a.difference(&b) {
497 /// println!("{}", x); // Print 1
500 /// let diff: HashSet<_> = a.difference(&b).collect();
501 /// assert_eq!(diff, [1].iter().collect());
503 /// // Note that difference is not symmetric,
504 /// // and `b - a` means something else:
505 /// let diff: HashSet<_> = b.difference(&a).collect();
506 /// assert_eq!(diff, [4].iter().collect());
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
511 Difference { iter: self.iter(), other }
514 /// Visits the values representing the symmetric difference,
515 /// i.e., the values that are in `self` or in `other` but not in both.
520 /// use std::collections::HashSet;
521 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
522 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
524 /// // Print 1, 4 in arbitrary order.
525 /// for x in a.symmetric_difference(&b) {
526 /// println!("{}", x);
529 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
530 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
532 /// assert_eq!(diff1, diff2);
533 /// assert_eq!(diff1, [1, 4].iter().collect());
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn symmetric_difference<'a>(
539 other: &'a HashSet<T, S>,
540 ) -> SymmetricDifference<'a, T, S> {
541 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
544 /// Visits the values representing the intersection,
545 /// i.e., the values that are both in `self` and `other`.
550 /// use std::collections::HashSet;
551 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
552 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
554 /// // Print 2, 3 in arbitrary order.
555 /// for x in a.intersection(&b) {
556 /// println!("{}", x);
559 /// let intersection: HashSet<_> = a.intersection(&b).collect();
560 /// assert_eq!(intersection, [2, 3].iter().collect());
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
565 if self.len() <= other.len() {
566 Intersection { iter: self.iter(), other }
568 Intersection { iter: other.iter(), other: self }
572 /// Visits the values representing the union,
573 /// i.e., all the values in `self` or `other`, without duplicates.
578 /// use std::collections::HashSet;
579 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
580 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
582 /// // Print 1, 2, 3, 4 in arbitrary order.
583 /// for x in a.union(&b) {
584 /// println!("{}", x);
587 /// let union: HashSet<_> = a.union(&b).collect();
588 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
591 #[stable(feature = "rust1", since = "1.0.0")]
592 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
593 if self.len() >= other.len() {
594 Union { iter: self.iter().chain(other.difference(self)) }
596 Union { iter: other.iter().chain(self.difference(other)) }
600 /// Returns `true` if the set contains a value.
602 /// The value may be any borrowed form of the set's value type, but
603 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
609 /// use std::collections::HashSet;
611 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
612 /// assert_eq!(set.contains(&1), true);
613 /// assert_eq!(set.contains(&4), false);
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
622 self.base.contains(value)
625 /// Returns a reference to the value in the set, if any, that is equal to the given value.
627 /// The value may be any borrowed form of the set's value type, but
628 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
634 /// use std::collections::HashSet;
636 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
637 /// assert_eq!(set.get(&2), Some(&2));
638 /// assert_eq!(set.get(&4), None);
641 #[stable(feature = "set_recovery", since = "1.9.0")]
642 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
650 /// Inserts the given `value` into the set if it is not present, then
651 /// returns a reference to the value in the set.
656 /// #![feature(hash_set_entry)]
658 /// use std::collections::HashSet;
660 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
661 /// assert_eq!(set.len(), 3);
662 /// assert_eq!(set.get_or_insert(2), &2);
663 /// assert_eq!(set.get_or_insert(100), &100);
664 /// assert_eq!(set.len(), 4); // 100 was inserted
667 #[unstable(feature = "hash_set_entry", issue = "60896")]
668 pub fn get_or_insert(&mut self, value: T) -> &T {
669 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
670 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
671 self.base.get_or_insert(value)
674 /// Inserts an owned copy of the given `value` into the set if it is not
675 /// present, then returns a reference to the value in the set.
680 /// #![feature(hash_set_entry)]
682 /// use std::collections::HashSet;
684 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
685 /// .iter().map(|&pet| pet.to_owned()).collect();
687 /// assert_eq!(set.len(), 3);
688 /// for &pet in &["cat", "dog", "fish"] {
689 /// let value = set.get_or_insert_owned(pet);
690 /// assert_eq!(value, pet);
692 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
695 #[unstable(feature = "hash_set_entry", issue = "60896")]
696 pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
699 Q: Hash + Eq + ToOwned<Owned = T>,
701 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
702 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
703 self.base.get_or_insert_owned(value)
706 /// Inserts a value computed from `f` into the set if the given `value` is
707 /// not present, then returns a reference to the value in the set.
712 /// #![feature(hash_set_entry)]
714 /// use std::collections::HashSet;
716 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
717 /// .iter().map(|&pet| pet.to_owned()).collect();
719 /// assert_eq!(set.len(), 3);
720 /// for &pet in &["cat", "dog", "fish"] {
721 /// let value = set.get_or_insert_with(pet, str::to_owned);
722 /// assert_eq!(value, pet);
724 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
727 #[unstable(feature = "hash_set_entry", issue = "60896")]
728 pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
734 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
735 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
736 self.base.get_or_insert_with(value, f)
739 /// Returns `true` if `self` has no elements in common with `other`.
740 /// This is equivalent to checking for an empty intersection.
745 /// use std::collections::HashSet;
747 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
748 /// let mut b = HashSet::new();
750 /// assert_eq!(a.is_disjoint(&b), true);
752 /// assert_eq!(a.is_disjoint(&b), true);
754 /// assert_eq!(a.is_disjoint(&b), false);
756 #[stable(feature = "rust1", since = "1.0.0")]
757 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
758 if self.len() <= other.len() {
759 self.iter().all(|v| !other.contains(v))
761 other.iter().all(|v| !self.contains(v))
765 /// Returns `true` if the set is a subset of another,
766 /// i.e., `other` contains at least all the values in `self`.
771 /// use std::collections::HashSet;
773 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
774 /// let mut set = HashSet::new();
776 /// assert_eq!(set.is_subset(&sup), true);
778 /// assert_eq!(set.is_subset(&sup), true);
780 /// assert_eq!(set.is_subset(&sup), false);
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
784 if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
787 /// Returns `true` if the set is a superset of another,
788 /// i.e., `self` contains at least all the values in `other`.
793 /// use std::collections::HashSet;
795 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
796 /// let mut set = HashSet::new();
798 /// assert_eq!(set.is_superset(&sub), false);
802 /// assert_eq!(set.is_superset(&sub), false);
805 /// assert_eq!(set.is_superset(&sub), true);
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
810 other.is_subset(self)
813 /// Adds a value to the set.
815 /// If the set did not have this value present, `true` is returned.
817 /// If the set did have this value present, `false` is returned.
822 /// use std::collections::HashSet;
824 /// let mut set = HashSet::new();
826 /// assert_eq!(set.insert(2), true);
827 /// assert_eq!(set.insert(2), false);
828 /// assert_eq!(set.len(), 1);
831 #[stable(feature = "rust1", since = "1.0.0")]
832 pub fn insert(&mut self, value: T) -> bool {
833 self.base.insert(value)
836 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
837 /// one. Returns the replaced value.
842 /// use std::collections::HashSet;
844 /// let mut set = HashSet::new();
845 /// set.insert(Vec::<i32>::new());
847 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
848 /// set.replace(Vec::with_capacity(10));
849 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
852 #[stable(feature = "set_recovery", since = "1.9.0")]
853 pub fn replace(&mut self, value: T) -> Option<T> {
854 self.base.replace(value)
857 /// Removes a value from the set. Returns whether the value was
858 /// present in the set.
860 /// The value may be any borrowed form of the set's value type, but
861 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
867 /// use std::collections::HashSet;
869 /// let mut set = HashSet::new();
872 /// assert_eq!(set.remove(&2), true);
873 /// assert_eq!(set.remove(&2), false);
876 #[stable(feature = "rust1", since = "1.0.0")]
877 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
882 self.base.remove(value)
885 /// Removes and returns the value in the set, if any, that is equal to the given one.
887 /// The value may be any borrowed form of the set's value type, but
888 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
894 /// use std::collections::HashSet;
896 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
897 /// assert_eq!(set.take(&2), Some(2));
898 /// assert_eq!(set.take(&2), None);
901 #[stable(feature = "set_recovery", since = "1.9.0")]
902 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
907 self.base.take(value)
910 /// Retains only the elements specified by the predicate.
912 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
913 /// The elements are visited in unsorted (and unspecified) order.
918 /// use std::collections::HashSet;
920 /// let xs = [1, 2, 3, 4, 5, 6];
921 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
922 /// set.retain(|&k| k % 2 == 0);
923 /// assert_eq!(set.len(), 3);
925 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
926 pub fn retain<F>(&mut self, f: F)
928 F: FnMut(&T) -> bool,
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<T, S> Clone for HashSet<T, S>
941 fn clone(&self) -> Self {
942 Self { base: self.base.clone() }
946 fn clone_from(&mut self, other: &Self) {
947 self.base.clone_from(&other.base);
951 #[stable(feature = "rust1", since = "1.0.0")]
952 impl<T, S> PartialEq for HashSet<T, S>
957 fn eq(&self, other: &HashSet<T, S>) -> bool {
958 if self.len() != other.len() {
962 self.iter().all(|key| other.contains(key))
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<T, S> Eq for HashSet<T, S>
974 #[stable(feature = "rust1", since = "1.0.0")]
975 impl<T, S> fmt::Debug for HashSet<T, S>
979 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
980 f.debug_set().entries(self.iter()).finish()
984 #[stable(feature = "rust1", since = "1.0.0")]
985 impl<T, S> FromIterator<T> for HashSet<T, S>
988 S: BuildHasher + Default,
991 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
992 let mut set = HashSet::with_hasher(Default::default());
998 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
999 // Note: as what is currently the most convenient built-in way to construct
1000 // a HashSet, a simple usage of this function must not *require* the user
1001 // to provide a type annotation in order to infer the third type parameter
1002 // (the hasher parameter, conventionally "S").
1003 // To that end, this impl is defined using RandomState as the concrete
1004 // type of S, rather than being generic over `S: BuildHasher + Default`.
1005 // It is expected that users who want to specify a hasher will manually use
1006 // `with_capacity_and_hasher`.
1007 // If type parameter defaults worked on impls, and if type parameter
1008 // defaults could be mixed with const generics, then perhaps
1009 // this could be generalized.
1010 // See also the equivalent impl on HashMap.
1011 impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
1018 /// use std::collections::HashSet;
1020 /// let set1 = HashSet::from([1, 2, 3, 4]);
1021 /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1022 /// assert_eq!(set1, set2);
1024 fn from(arr: [T; N]) -> Self {
1025 crate::array::IntoIter::new(arr).collect()
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 impl<T, S> Extend<T> for HashSet<T, S>
1036 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1037 self.base.extend(iter);
1041 fn extend_one(&mut self, item: T) {
1042 self.base.insert(item);
1046 fn extend_reserve(&mut self, additional: usize) {
1047 self.base.extend_reserve(additional);
1051 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1052 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1054 T: 'a + Eq + Hash + Copy,
1058 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1059 self.extend(iter.into_iter().cloned());
1063 fn extend_one(&mut self, &item: &'a T) {
1064 self.base.insert(item);
1068 fn extend_reserve(&mut self, additional: usize) {
1069 Extend::<T>::extend_reserve(self, additional)
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<T, S> Default for HashSet<T, S>
1078 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1080 fn default() -> HashSet<T, S> {
1081 HashSet { base: Default::default() }
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1088 T: Eq + Hash + Clone,
1089 S: BuildHasher + Default,
1091 type Output = HashSet<T, S>;
1093 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1098 /// use std::collections::HashSet;
1100 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1101 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1103 /// let set = &a | &b;
1106 /// let expected = [1, 2, 3, 4, 5];
1108 /// assert!(expected.contains(x));
1111 /// assert_eq!(i, expected.len());
1113 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1114 self.union(rhs).cloned().collect()
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1121 T: Eq + Hash + Clone,
1122 S: BuildHasher + Default,
1124 type Output = HashSet<T, S>;
1126 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1131 /// use std::collections::HashSet;
1133 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1134 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1136 /// let set = &a & &b;
1139 /// let expected = [2, 3];
1141 /// assert!(expected.contains(x));
1144 /// assert_eq!(i, expected.len());
1146 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1147 self.intersection(rhs).cloned().collect()
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1154 T: Eq + Hash + Clone,
1155 S: BuildHasher + Default,
1157 type Output = HashSet<T, S>;
1159 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1164 /// use std::collections::HashSet;
1166 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1167 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1169 /// let set = &a ^ &b;
1172 /// let expected = [1, 2, 4, 5];
1174 /// assert!(expected.contains(x));
1177 /// assert_eq!(i, expected.len());
1179 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1180 self.symmetric_difference(rhs).cloned().collect()
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1187 T: Eq + Hash + Clone,
1188 S: BuildHasher + Default,
1190 type Output = HashSet<T, S>;
1192 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1197 /// use std::collections::HashSet;
1199 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1200 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1202 /// let set = &a - &b;
1205 /// let expected = [1, 2];
1207 /// assert!(expected.contains(x));
1210 /// assert_eq!(i, expected.len());
1212 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1213 self.difference(rhs).cloned().collect()
1217 /// An iterator over the items of a `HashSet`.
1219 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1220 /// See its documentation for more.
1222 /// [`iter`]: HashSet::iter
1227 /// use std::collections::HashSet;
1229 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1231 /// let mut iter = a.iter();
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 pub struct Iter<'a, K: 'a> {
1235 base: base::Iter<'a, K>,
1238 /// An owning iterator over the items of a `HashSet`.
1240 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1241 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1243 /// [`into_iter`]: IntoIterator::into_iter
1244 /// [`IntoIterator`]: crate::iter::IntoIterator
1249 /// use std::collections::HashSet;
1251 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1253 /// let mut iter = a.into_iter();
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub struct IntoIter<K> {
1257 base: base::IntoIter<K>,
1260 /// A draining iterator over the items of a `HashSet`.
1262 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1263 /// See its documentation for more.
1265 /// [`drain`]: HashSet::drain
1270 /// use std::collections::HashSet;
1272 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1274 /// let mut drain = a.drain();
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 pub struct Drain<'a, K: 'a> {
1278 base: base::Drain<'a, K>,
1281 /// A draining, filtering iterator over the items of a `HashSet`.
1283 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1285 /// [`drain_filter`]: HashSet::drain_filter
1290 /// #![feature(hash_drain_filter)]
1292 /// use std::collections::HashSet;
1294 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1296 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1298 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1299 pub struct DrainFilter<'a, K, F>
1301 F: FnMut(&K) -> bool,
1303 base: base::DrainFilter<'a, K, F>,
1306 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1308 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1309 /// See its documentation for more.
1311 /// [`intersection`]: HashSet::intersection
1316 /// use std::collections::HashSet;
1318 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1319 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1321 /// let mut intersection = a.intersection(&b);
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 pub struct Intersection<'a, T: 'a, S: 'a> {
1325 // iterator of the first set
1328 other: &'a HashSet<T, S>,
1331 /// A lazy iterator producing elements in the difference of `HashSet`s.
1333 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1334 /// See its documentation for more.
1336 /// [`difference`]: HashSet::difference
1341 /// use std::collections::HashSet;
1343 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1344 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1346 /// let mut difference = a.difference(&b);
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 pub struct Difference<'a, T: 'a, S: 'a> {
1350 // iterator of the first set
1353 other: &'a HashSet<T, S>,
1356 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1358 /// This `struct` is created by the [`symmetric_difference`] method on
1359 /// [`HashSet`]. See its documentation for more.
1361 /// [`symmetric_difference`]: HashSet::symmetric_difference
1366 /// use std::collections::HashSet;
1368 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1369 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1371 /// let mut intersection = a.symmetric_difference(&b);
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1375 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1378 /// A lazy iterator producing elements in the union of `HashSet`s.
1380 /// This `struct` is created by the [`union`] method on [`HashSet`].
1381 /// See its documentation for more.
1383 /// [`union`]: HashSet::union
1388 /// use std::collections::HashSet;
1390 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1391 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1393 /// let mut union_iter = a.union(&b);
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 pub struct Union<'a, T: 'a, S: 'a> {
1397 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1403 type IntoIter = Iter<'a, T>;
1406 fn into_iter(self) -> Iter<'a, T> {
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<T, S> IntoIterator for HashSet<T, S> {
1414 type IntoIter = IntoIter<T>;
1416 /// Creates a consuming iterator, that is, one that moves each value out
1417 /// of the set in arbitrary order. The set cannot be used after calling
1423 /// use std::collections::HashSet;
1424 /// let mut set = HashSet::new();
1425 /// set.insert("a".to_string());
1426 /// set.insert("b".to_string());
1428 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1429 /// let v: Vec<String> = set.into_iter().collect();
1431 /// // Will print in an arbitrary order.
1433 /// println!("{}", x);
1437 fn into_iter(self) -> IntoIter<T> {
1438 IntoIter { base: self.base.into_iter() }
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<K> Clone for Iter<'_, K> {
1445 fn clone(&self) -> Self {
1446 Iter { base: self.base.clone() }
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 impl<'a, K> Iterator for Iter<'a, K> {
1454 fn next(&mut self) -> Option<&'a K> {
1458 fn size_hint(&self) -> (usize, Option<usize>) {
1459 self.base.size_hint()
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 impl<K> ExactSizeIterator for Iter<'_, K> {
1465 fn len(&self) -> usize {
1469 #[stable(feature = "fused", since = "1.26.0")]
1470 impl<K> FusedIterator for Iter<'_, K> {}
1472 #[stable(feature = "std_debug", since = "1.16.0")]
1473 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 f.debug_list().entries(self.clone()).finish()
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<K> Iterator for IntoIter<K> {
1484 fn next(&mut self) -> Option<K> {
1488 fn size_hint(&self) -> (usize, Option<usize>) {
1489 self.base.size_hint()
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<K> ExactSizeIterator for IntoIter<K> {
1495 fn len(&self) -> usize {
1499 #[stable(feature = "fused", since = "1.26.0")]
1500 impl<K> FusedIterator for IntoIter<K> {}
1502 #[stable(feature = "std_debug", since = "1.16.0")]
1503 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1505 fmt::Debug::fmt(&self.base, f)
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<'a, K> Iterator for Drain<'a, K> {
1514 fn next(&mut self) -> Option<K> {
1518 fn size_hint(&self) -> (usize, Option<usize>) {
1519 self.base.size_hint()
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<K> ExactSizeIterator for Drain<'_, K> {
1525 fn len(&self) -> usize {
1529 #[stable(feature = "fused", since = "1.26.0")]
1530 impl<K> FusedIterator for Drain<'_, K> {}
1532 #[stable(feature = "std_debug", since = "1.16.0")]
1533 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535 fmt::Debug::fmt(&self.base, f)
1539 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1540 impl<K, F> Iterator for DrainFilter<'_, K, F>
1542 F: FnMut(&K) -> bool,
1547 fn next(&mut self) -> Option<K> {
1551 fn size_hint(&self) -> (usize, Option<usize>) {
1552 self.base.size_hint()
1556 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1557 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1559 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1560 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1562 F: FnMut(&K) -> bool,
1564 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1565 f.debug_struct("DrainFilter").finish_non_exhaustive()
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<T, S> Clone for Intersection<'_, T, S> {
1572 fn clone(&self) -> Self {
1573 Intersection { iter: self.iter.clone(), ..*self }
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1586 fn next(&mut self) -> Option<&'a T> {
1588 let elt = self.iter.next()?;
1589 if self.other.contains(elt) {
1596 fn size_hint(&self) -> (usize, Option<usize>) {
1597 let (_, upper) = self.iter.size_hint();
1602 #[stable(feature = "std_debug", since = "1.16.0")]
1603 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1605 T: fmt::Debug + Eq + Hash,
1608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1609 f.debug_list().entries(self.clone()).finish()
1613 #[stable(feature = "fused", since = "1.26.0")]
1614 impl<T, S> FusedIterator for Intersection<'_, T, S>
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<T, S> Clone for Difference<'_, T, S> {
1624 fn clone(&self) -> Self {
1625 Difference { iter: self.iter.clone(), ..*self }
1629 #[stable(feature = "rust1", since = "1.0.0")]
1630 impl<'a, T, S> Iterator for Difference<'a, T, S>
1638 fn next(&mut self) -> Option<&'a T> {
1640 let elt = self.iter.next()?;
1641 if !self.other.contains(elt) {
1648 fn size_hint(&self) -> (usize, Option<usize>) {
1649 let (_, upper) = self.iter.size_hint();
1654 #[stable(feature = "fused", since = "1.26.0")]
1655 impl<T, S> FusedIterator for Difference<'_, T, S>
1662 #[stable(feature = "std_debug", since = "1.16.0")]
1663 impl<T, S> fmt::Debug for Difference<'_, T, S>
1665 T: fmt::Debug + Eq + Hash,
1668 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669 f.debug_list().entries(self.clone()).finish()
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1676 fn clone(&self) -> Self {
1677 SymmetricDifference { iter: self.iter.clone() }
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1690 fn next(&mut self) -> Option<&'a T> {
1694 fn size_hint(&self) -> (usize, Option<usize>) {
1695 self.iter.size_hint()
1699 #[stable(feature = "fused", since = "1.26.0")]
1700 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1707 #[stable(feature = "std_debug", since = "1.16.0")]
1708 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1710 T: fmt::Debug + Eq + Hash,
1713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1714 f.debug_list().entries(self.clone()).finish()
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<T, S> Clone for Union<'_, T, S> {
1721 fn clone(&self) -> Self {
1722 Union { iter: self.iter.clone() }
1726 #[stable(feature = "fused", since = "1.26.0")]
1727 impl<T, S> FusedIterator for Union<'_, T, S>
1734 #[stable(feature = "std_debug", since = "1.16.0")]
1735 impl<T, S> fmt::Debug for Union<'_, T, S>
1737 T: fmt::Debug + Eq + Hash,
1740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1741 f.debug_list().entries(self.clone()).finish()
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<'a, T, S> Iterator for Union<'a, T, S>
1754 fn next(&mut self) -> Option<&'a T> {
1758 fn size_hint(&self) -> (usize, Option<usize>) {
1759 self.iter.size_hint()
1764 fn assert_covariance() {
1765 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1768 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1771 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1774 fn difference<'a, 'new>(
1775 v: Difference<'a, &'static str, RandomState>,
1776 ) -> Difference<'a, &'new str, RandomState> {
1779 fn symmetric_difference<'a, 'new>(
1780 v: SymmetricDifference<'a, &'static str, RandomState>,
1781 ) -> SymmetricDifference<'a, &'new str, RandomState> {
1784 fn intersection<'a, 'new>(
1785 v: Intersection<'a, &'static str, RandomState>,
1786 ) -> Intersection<'a, &'new str, RandomState> {
1790 v: Union<'a, &'static str, RandomState>,
1791 ) -> Union<'a, &'new str, RandomState> {
1794 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {