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, but will not result in undefined behavior. This could include
42 /// panics, incorrect results, aborts, memory leaks, and non-termination.
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();
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub fn new() -> HashSet<T, RandomState> {
134 /// Creates an empty `HashSet` with the specified capacity.
136 /// The hash set will be able to hold at least `capacity` elements without
137 /// reallocating. If `capacity` is 0, the hash set will not allocate.
142 /// use std::collections::HashSet;
143 /// let set: HashSet<i32> = HashSet::with_capacity(10);
144 /// assert!(set.capacity() >= 10);
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
149 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
153 impl<T, S> HashSet<T, S> {
154 /// Returns the number of elements the set can hold without reallocating.
159 /// use std::collections::HashSet;
160 /// let set: HashSet<i32> = HashSet::with_capacity(100);
161 /// assert!(set.capacity() >= 100);
164 #[stable(feature = "rust1", since = "1.0.0")]
165 pub fn capacity(&self) -> usize {
169 /// An iterator visiting all elements in arbitrary order.
170 /// The iterator element type is `&'a T`.
175 /// use std::collections::HashSet;
176 /// let mut set = HashSet::new();
180 /// // Will print in an arbitrary order.
181 /// for x in set.iter() {
182 /// println!("{}", x);
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn iter(&self) -> Iter<'_, T> {
188 Iter { base: self.base.iter() }
191 /// Returns the number of elements in the set.
196 /// use std::collections::HashSet;
198 /// let mut v = HashSet::new();
199 /// assert_eq!(v.len(), 0);
201 /// assert_eq!(v.len(), 1);
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn len(&self) -> usize {
209 /// Returns `true` if the set contains no elements.
214 /// use std::collections::HashSet;
216 /// let mut v = HashSet::new();
217 /// assert!(v.is_empty());
219 /// assert!(!v.is_empty());
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn is_empty(&self) -> bool {
227 /// Clears the set, returning all elements in an iterator.
232 /// use std::collections::HashSet;
234 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
235 /// assert!(!set.is_empty());
237 /// // print 1, 2, 3 in an arbitrary order
238 /// for i in set.drain() {
239 /// println!("{}", i);
242 /// assert!(set.is_empty());
245 #[stable(feature = "drain", since = "1.6.0")]
246 pub fn drain(&mut self) -> Drain<'_, T> {
247 Drain { base: self.base.drain() }
250 /// Creates an iterator which uses a closure to determine if a value should be removed.
252 /// If the closure returns true, then the value is removed and yielded.
253 /// If the closure returns false, the value will remain in the list and will not be yielded
256 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
257 /// values will still be subjected to the closure and removed and dropped if it returns true.
259 /// It is unspecified how many more values will be subjected to the closure
260 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
261 /// `DrainFilter` itself is leaked.
265 /// Splitting a set into even and odd values, reusing the original set:
268 /// #![feature(hash_drain_filter)]
269 /// use std::collections::HashSet;
271 /// let mut set: HashSet<i32> = (0..8).collect();
272 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
274 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
275 /// let mut odds = set.into_iter().collect::<Vec<_>>();
279 /// assert_eq!(evens, vec![0, 2, 4, 6]);
280 /// assert_eq!(odds, vec![1, 3, 5, 7]);
283 #[unstable(feature = "hash_drain_filter", issue = "59618")]
284 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
286 F: FnMut(&T) -> bool,
288 DrainFilter { base: self.base.drain_filter(pred) }
291 /// Clears the set, removing all values.
296 /// use std::collections::HashSet;
298 /// let mut v = HashSet::new();
301 /// assert!(v.is_empty());
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub fn clear(&mut self) {
309 /// Creates a new empty hash set which will use the given hasher to hash
312 /// The hash set is also created with the default initial capacity.
314 /// Warning: `hasher` is normally randomly generated, and
315 /// is designed to allow `HashSet`s to be resistant to attacks that
316 /// cause many collisions and very poor performance. Setting it
317 /// manually using this function can expose a DoS attack vector.
319 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
320 /// the HashMap to be useful, see its documentation for details.
325 /// use std::collections::HashSet;
326 /// use std::collections::hash_map::RandomState;
328 /// let s = RandomState::new();
329 /// let mut set = HashSet::with_hasher(s);
333 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
334 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
335 HashSet { base: base::HashSet::with_hasher(hasher) }
338 /// Creates an empty `HashSet` with the specified capacity, using
339 /// `hasher` to hash the keys.
341 /// The hash set will be able to hold at least `capacity` elements without
342 /// reallocating. If `capacity` is 0, the hash set will not allocate.
344 /// Warning: `hasher` is normally randomly generated, and
345 /// is designed to allow `HashSet`s to be resistant to attacks that
346 /// cause many collisions and very poor performance. Setting it
347 /// manually using this function can expose a DoS attack vector.
349 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
350 /// the HashMap to be useful, see its documentation for details.
355 /// use std::collections::HashSet;
356 /// use std::collections::hash_map::RandomState;
358 /// let s = RandomState::new();
359 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
363 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
364 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
365 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
368 /// Returns a reference to the set's [`BuildHasher`].
373 /// use std::collections::HashSet;
374 /// use std::collections::hash_map::RandomState;
376 /// let hasher = RandomState::new();
377 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
378 /// let hasher: &RandomState = set.hasher();
381 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
382 pub fn hasher(&self) -> &S {
387 impl<T, S> HashSet<T, S>
392 /// Reserves capacity for at least `additional` more elements to be inserted
393 /// in the `HashSet`. The collection may reserve more space to avoid
394 /// frequent reallocations.
398 /// Panics if the new allocation size overflows `usize`.
403 /// use std::collections::HashSet;
404 /// let mut set: HashSet<i32> = HashSet::new();
406 /// assert!(set.capacity() >= 10);
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn reserve(&mut self, additional: usize) {
411 self.base.reserve(additional)
414 /// Tries to reserve capacity for at least `additional` more elements to be inserted
415 /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
416 /// frequent reallocations.
420 /// If the capacity overflows, or the allocator reports a failure, then an error
426 /// use std::collections::HashSet;
427 /// let mut set: HashSet<i32> = HashSet::new();
428 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
431 #[stable(feature = "try_reserve", since = "1.57.0")]
432 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
433 self.base.try_reserve(additional).map_err(map_try_reserve_error)
436 /// Shrinks the capacity of the set as much as possible. It will drop
437 /// down as much as possible while maintaining the internal rules
438 /// and possibly leaving some space in accordance with the resize policy.
443 /// use std::collections::HashSet;
445 /// let mut set = HashSet::with_capacity(100);
448 /// assert!(set.capacity() >= 100);
449 /// set.shrink_to_fit();
450 /// assert!(set.capacity() >= 2);
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn shrink_to_fit(&mut self) {
455 self.base.shrink_to_fit()
458 /// Shrinks the capacity of the set with a lower limit. It will drop
459 /// down no lower than the supplied limit while maintaining the internal rules
460 /// and possibly leaving some space in accordance with the resize policy.
462 /// If the current capacity is less than the lower limit, this is a no-op.
466 /// use std::collections::HashSet;
468 /// let mut set = HashSet::with_capacity(100);
471 /// assert!(set.capacity() >= 100);
472 /// set.shrink_to(10);
473 /// assert!(set.capacity() >= 10);
474 /// set.shrink_to(0);
475 /// assert!(set.capacity() >= 2);
478 #[stable(feature = "shrink_to", since = "1.56.0")]
479 pub fn shrink_to(&mut self, min_capacity: usize) {
480 self.base.shrink_to(min_capacity)
483 /// Visits the values representing the difference,
484 /// i.e., the values that are in `self` but not in `other`.
489 /// use std::collections::HashSet;
490 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
491 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
493 /// // Can be seen as `a - b`.
494 /// for x in a.difference(&b) {
495 /// println!("{}", x); // Print 1
498 /// let diff: HashSet<_> = a.difference(&b).collect();
499 /// assert_eq!(diff, [1].iter().collect());
501 /// // Note that difference is not symmetric,
502 /// // and `b - a` means something else:
503 /// let diff: HashSet<_> = b.difference(&a).collect();
504 /// assert_eq!(diff, [4].iter().collect());
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
509 Difference { iter: self.iter(), other }
512 /// Visits the values representing the symmetric difference,
513 /// i.e., the values that are in `self` or in `other` but not in both.
518 /// use std::collections::HashSet;
519 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
520 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
522 /// // Print 1, 4 in arbitrary order.
523 /// for x in a.symmetric_difference(&b) {
524 /// println!("{}", x);
527 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
528 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
530 /// assert_eq!(diff1, diff2);
531 /// assert_eq!(diff1, [1, 4].iter().collect());
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn symmetric_difference<'a>(
537 other: &'a HashSet<T, S>,
538 ) -> SymmetricDifference<'a, T, S> {
539 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
542 /// Visits the values representing the intersection,
543 /// i.e., the values that are both in `self` and `other`.
548 /// use std::collections::HashSet;
549 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
550 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
552 /// // Print 2, 3 in arbitrary order.
553 /// for x in a.intersection(&b) {
554 /// println!("{}", x);
557 /// let intersection: HashSet<_> = a.intersection(&b).collect();
558 /// assert_eq!(intersection, [2, 3].iter().collect());
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
563 if self.len() <= other.len() {
564 Intersection { iter: self.iter(), other }
566 Intersection { iter: other.iter(), other: self }
570 /// Visits the values representing the union,
571 /// i.e., all the values in `self` or `other`, without duplicates.
576 /// use std::collections::HashSet;
577 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
578 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
580 /// // Print 1, 2, 3, 4 in arbitrary order.
581 /// for x in a.union(&b) {
582 /// println!("{}", x);
585 /// let union: HashSet<_> = a.union(&b).collect();
586 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
591 if self.len() >= other.len() {
592 Union { iter: self.iter().chain(other.difference(self)) }
594 Union { iter: other.iter().chain(self.difference(other)) }
598 /// Returns `true` if the set contains a value.
600 /// The value may be any borrowed form of the set's value type, but
601 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
607 /// use std::collections::HashSet;
609 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
610 /// assert_eq!(set.contains(&1), true);
611 /// assert_eq!(set.contains(&4), false);
614 #[stable(feature = "rust1", since = "1.0.0")]
615 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
620 self.base.contains(value)
623 /// Returns a reference to the value in the set, if any, that is equal to the given value.
625 /// The value may be any borrowed form of the set's value type, but
626 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
632 /// use std::collections::HashSet;
634 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
635 /// assert_eq!(set.get(&2), Some(&2));
636 /// assert_eq!(set.get(&4), None);
639 #[stable(feature = "set_recovery", since = "1.9.0")]
640 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
648 /// Inserts the given `value` into the set if it is not present, then
649 /// returns a reference to the value in the set.
654 /// #![feature(hash_set_entry)]
656 /// use std::collections::HashSet;
658 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
659 /// assert_eq!(set.len(), 3);
660 /// assert_eq!(set.get_or_insert(2), &2);
661 /// assert_eq!(set.get_or_insert(100), &100);
662 /// assert_eq!(set.len(), 4); // 100 was inserted
665 #[unstable(feature = "hash_set_entry", issue = "60896")]
666 pub fn get_or_insert(&mut self, value: T) -> &T {
667 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
668 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
669 self.base.get_or_insert(value)
672 /// Inserts an owned copy of the given `value` into the set if it is not
673 /// present, then returns a reference to the value in the set.
678 /// #![feature(hash_set_entry)]
680 /// use std::collections::HashSet;
682 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
683 /// .iter().map(|&pet| pet.to_owned()).collect();
685 /// assert_eq!(set.len(), 3);
686 /// for &pet in &["cat", "dog", "fish"] {
687 /// let value = set.get_or_insert_owned(pet);
688 /// assert_eq!(value, pet);
690 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
693 #[unstable(feature = "hash_set_entry", issue = "60896")]
694 pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
697 Q: Hash + Eq + ToOwned<Owned = T>,
699 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
700 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
701 self.base.get_or_insert_owned(value)
704 /// Inserts a value computed from `f` into the set if the given `value` is
705 /// not present, then returns a reference to the value in the set.
710 /// #![feature(hash_set_entry)]
712 /// use std::collections::HashSet;
714 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
715 /// .iter().map(|&pet| pet.to_owned()).collect();
717 /// assert_eq!(set.len(), 3);
718 /// for &pet in &["cat", "dog", "fish"] {
719 /// let value = set.get_or_insert_with(pet, str::to_owned);
720 /// assert_eq!(value, pet);
722 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
725 #[unstable(feature = "hash_set_entry", issue = "60896")]
726 pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
732 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
733 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
734 self.base.get_or_insert_with(value, f)
737 /// Returns `true` if `self` has no elements in common with `other`.
738 /// This is equivalent to checking for an empty intersection.
743 /// use std::collections::HashSet;
745 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
746 /// let mut b = HashSet::new();
748 /// assert_eq!(a.is_disjoint(&b), true);
750 /// assert_eq!(a.is_disjoint(&b), true);
752 /// assert_eq!(a.is_disjoint(&b), false);
754 #[stable(feature = "rust1", since = "1.0.0")]
755 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
756 if self.len() <= other.len() {
757 self.iter().all(|v| !other.contains(v))
759 other.iter().all(|v| !self.contains(v))
763 /// Returns `true` if the set is a subset of another,
764 /// i.e., `other` contains at least all the values in `self`.
769 /// use std::collections::HashSet;
771 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
772 /// let mut set = HashSet::new();
774 /// assert_eq!(set.is_subset(&sup), true);
776 /// assert_eq!(set.is_subset(&sup), true);
778 /// assert_eq!(set.is_subset(&sup), false);
780 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
782 if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
785 /// Returns `true` if the set is a superset of another,
786 /// i.e., `self` contains at least all the values in `other`.
791 /// use std::collections::HashSet;
793 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
794 /// let mut set = HashSet::new();
796 /// assert_eq!(set.is_superset(&sub), false);
800 /// assert_eq!(set.is_superset(&sub), false);
803 /// assert_eq!(set.is_superset(&sub), true);
806 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
808 other.is_subset(self)
811 /// Adds a value to the set.
813 /// If the set did not have this value present, `true` is returned.
815 /// If the set did have this value present, `false` is returned.
820 /// use std::collections::HashSet;
822 /// let mut set = HashSet::new();
824 /// assert_eq!(set.insert(2), true);
825 /// assert_eq!(set.insert(2), false);
826 /// assert_eq!(set.len(), 1);
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn insert(&mut self, value: T) -> bool {
831 self.base.insert(value)
834 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
835 /// one. Returns the replaced value.
840 /// use std::collections::HashSet;
842 /// let mut set = HashSet::new();
843 /// set.insert(Vec::<i32>::new());
845 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
846 /// set.replace(Vec::with_capacity(10));
847 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
850 #[stable(feature = "set_recovery", since = "1.9.0")]
851 pub fn replace(&mut self, value: T) -> Option<T> {
852 self.base.replace(value)
855 /// Removes a value from the set. Returns whether the value was
856 /// present in the set.
858 /// The value may be any borrowed form of the set's value type, but
859 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
865 /// use std::collections::HashSet;
867 /// let mut set = HashSet::new();
870 /// assert_eq!(set.remove(&2), true);
871 /// assert_eq!(set.remove(&2), false);
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
880 self.base.remove(value)
883 /// Removes and returns the value in the set, if any, that is equal to the given one.
885 /// The value may be any borrowed form of the set's value type, but
886 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
892 /// use std::collections::HashSet;
894 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
895 /// assert_eq!(set.take(&2), Some(2));
896 /// assert_eq!(set.take(&2), None);
899 #[stable(feature = "set_recovery", since = "1.9.0")]
900 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
905 self.base.take(value)
908 /// Retains only the elements specified by the predicate.
910 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
911 /// The elements are visited in unsorted (and unspecified) order.
916 /// use std::collections::HashSet;
918 /// let xs = [1, 2, 3, 4, 5, 6];
919 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
920 /// set.retain(|&k| k % 2 == 0);
921 /// assert_eq!(set.len(), 3);
923 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
924 pub fn retain<F>(&mut self, f: F)
926 F: FnMut(&T) -> bool,
932 #[stable(feature = "rust1", since = "1.0.0")]
933 impl<T, S> Clone for HashSet<T, S>
939 fn clone(&self) -> Self {
940 Self { base: self.base.clone() }
944 fn clone_from(&mut self, other: &Self) {
945 self.base.clone_from(&other.base);
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<T, S> PartialEq for HashSet<T, S>
955 fn eq(&self, other: &HashSet<T, S>) -> bool {
956 if self.len() != other.len() {
960 self.iter().all(|key| other.contains(key))
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl<T, S> Eq for HashSet<T, S>
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl<T, S> fmt::Debug for HashSet<T, S>
977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
978 f.debug_set().entries(self.iter()).finish()
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T, S> FromIterator<T> for HashSet<T, S>
986 S: BuildHasher + Default,
989 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
990 let mut set = HashSet::with_hasher(Default::default());
996 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
997 // Note: as what is currently the most convenient built-in way to construct
998 // a HashSet, a simple usage of this function must not *require* the user
999 // to provide a type annotation in order to infer the third type parameter
1000 // (the hasher parameter, conventionally "S").
1001 // To that end, this impl is defined using RandomState as the concrete
1002 // type of S, rather than being generic over `S: BuildHasher + Default`.
1003 // It is expected that users who want to specify a hasher will manually use
1004 // `with_capacity_and_hasher`.
1005 // If type parameter defaults worked on impls, and if type parameter
1006 // defaults could be mixed with const generics, then perhaps
1007 // this could be generalized.
1008 // See also the equivalent impl on HashMap.
1009 impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
1016 /// use std::collections::HashSet;
1018 /// let set1 = HashSet::from([1, 2, 3, 4]);
1019 /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1020 /// assert_eq!(set1, set2);
1022 fn from(arr: [T; N]) -> Self {
1023 crate::array::IntoIter::new(arr).collect()
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<T, S> Extend<T> for HashSet<T, S>
1034 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1035 self.base.extend(iter);
1039 fn extend_one(&mut self, item: T) {
1040 self.base.insert(item);
1044 fn extend_reserve(&mut self, additional: usize) {
1045 self.base.extend_reserve(additional);
1049 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1050 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1052 T: 'a + Eq + Hash + Copy,
1056 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1057 self.extend(iter.into_iter().cloned());
1061 fn extend_one(&mut self, &item: &'a T) {
1062 self.base.insert(item);
1066 fn extend_reserve(&mut self, additional: usize) {
1067 Extend::<T>::extend_reserve(self, additional)
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<T, S> Default for HashSet<T, S>
1076 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1078 fn default() -> HashSet<T, S> {
1079 HashSet { base: Default::default() }
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1086 T: Eq + Hash + Clone,
1087 S: BuildHasher + Default,
1089 type Output = HashSet<T, S>;
1091 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1096 /// use std::collections::HashSet;
1098 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1099 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1101 /// let set = &a | &b;
1104 /// let expected = [1, 2, 3, 4, 5];
1106 /// assert!(expected.contains(x));
1109 /// assert_eq!(i, expected.len());
1111 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1112 self.union(rhs).cloned().collect()
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<T, S> BitAnd<&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 intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1129 /// use std::collections::HashSet;
1131 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1132 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1134 /// let set = &a & &b;
1137 /// let expected = [2, 3];
1139 /// assert!(expected.contains(x));
1142 /// assert_eq!(i, expected.len());
1144 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1145 self.intersection(rhs).cloned().collect()
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<T, S> BitXor<&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 symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1162 /// use std::collections::HashSet;
1164 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1165 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1167 /// let set = &a ^ &b;
1170 /// let expected = [1, 2, 4, 5];
1172 /// assert!(expected.contains(x));
1175 /// assert_eq!(i, expected.len());
1177 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1178 self.symmetric_difference(rhs).cloned().collect()
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl<T, S> Sub<&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 difference of `self` and `rhs` as a new `HashSet<T, S>`.
1195 /// use std::collections::HashSet;
1197 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1198 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1200 /// let set = &a - &b;
1203 /// let expected = [1, 2];
1205 /// assert!(expected.contains(x));
1208 /// assert_eq!(i, expected.len());
1210 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1211 self.difference(rhs).cloned().collect()
1215 /// An iterator over the items of a `HashSet`.
1217 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1218 /// See its documentation for more.
1220 /// [`iter`]: HashSet::iter
1225 /// use std::collections::HashSet;
1227 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1229 /// let mut iter = a.iter();
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub struct Iter<'a, K: 'a> {
1233 base: base::Iter<'a, K>,
1236 /// An owning iterator over the items of a `HashSet`.
1238 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1239 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1241 /// [`into_iter`]: IntoIterator::into_iter
1242 /// [`IntoIterator`]: crate::iter::IntoIterator
1247 /// use std::collections::HashSet;
1249 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1251 /// let mut iter = a.into_iter();
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 pub struct IntoIter<K> {
1255 base: base::IntoIter<K>,
1258 /// A draining iterator over the items of a `HashSet`.
1260 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1261 /// See its documentation for more.
1263 /// [`drain`]: HashSet::drain
1268 /// use std::collections::HashSet;
1270 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1272 /// let mut drain = a.drain();
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 pub struct Drain<'a, K: 'a> {
1276 base: base::Drain<'a, K>,
1279 /// A draining, filtering iterator over the items of a `HashSet`.
1281 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1283 /// [`drain_filter`]: HashSet::drain_filter
1288 /// #![feature(hash_drain_filter)]
1290 /// use std::collections::HashSet;
1292 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1294 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1296 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1297 pub struct DrainFilter<'a, K, F>
1299 F: FnMut(&K) -> bool,
1301 base: base::DrainFilter<'a, K, F>,
1304 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1306 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1307 /// See its documentation for more.
1309 /// [`intersection`]: HashSet::intersection
1314 /// use std::collections::HashSet;
1316 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1317 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1319 /// let mut intersection = a.intersection(&b);
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub struct Intersection<'a, T: 'a, S: 'a> {
1323 // iterator of the first set
1326 other: &'a HashSet<T, S>,
1329 /// A lazy iterator producing elements in the difference of `HashSet`s.
1331 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1332 /// See its documentation for more.
1334 /// [`difference`]: HashSet::difference
1339 /// use std::collections::HashSet;
1341 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1342 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1344 /// let mut difference = a.difference(&b);
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 pub struct Difference<'a, T: 'a, S: 'a> {
1348 // iterator of the first set
1351 other: &'a HashSet<T, S>,
1354 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1356 /// This `struct` is created by the [`symmetric_difference`] method on
1357 /// [`HashSet`]. See its documentation for more.
1359 /// [`symmetric_difference`]: HashSet::symmetric_difference
1364 /// use std::collections::HashSet;
1366 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1367 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1369 /// let mut intersection = a.symmetric_difference(&b);
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1373 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1376 /// A lazy iterator producing elements in the union of `HashSet`s.
1378 /// This `struct` is created by the [`union`] method on [`HashSet`].
1379 /// See its documentation for more.
1381 /// [`union`]: HashSet::union
1386 /// use std::collections::HashSet;
1388 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1389 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1391 /// let mut union_iter = a.union(&b);
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 pub struct Union<'a, T: 'a, S: 'a> {
1395 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1401 type IntoIter = Iter<'a, T>;
1404 fn into_iter(self) -> Iter<'a, T> {
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl<T, S> IntoIterator for HashSet<T, S> {
1412 type IntoIter = IntoIter<T>;
1414 /// Creates a consuming iterator, that is, one that moves each value out
1415 /// of the set in arbitrary order. The set cannot be used after calling
1421 /// use std::collections::HashSet;
1422 /// let mut set = HashSet::new();
1423 /// set.insert("a".to_string());
1424 /// set.insert("b".to_string());
1426 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1427 /// let v: Vec<String> = set.into_iter().collect();
1429 /// // Will print in an arbitrary order.
1431 /// println!("{}", x);
1435 fn into_iter(self) -> IntoIter<T> {
1436 IntoIter { base: self.base.into_iter() }
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<K> Clone for Iter<'_, K> {
1443 fn clone(&self) -> Self {
1444 Iter { base: self.base.clone() }
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<'a, K> Iterator for Iter<'a, K> {
1452 fn next(&mut self) -> Option<&'a K> {
1456 fn size_hint(&self) -> (usize, Option<usize>) {
1457 self.base.size_hint()
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl<K> ExactSizeIterator for Iter<'_, K> {
1463 fn len(&self) -> usize {
1467 #[stable(feature = "fused", since = "1.26.0")]
1468 impl<K> FusedIterator for Iter<'_, K> {}
1470 #[stable(feature = "std_debug", since = "1.16.0")]
1471 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1473 f.debug_list().entries(self.clone()).finish()
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 impl<K> Iterator for IntoIter<K> {
1482 fn next(&mut self) -> Option<K> {
1486 fn size_hint(&self) -> (usize, Option<usize>) {
1487 self.base.size_hint()
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<K> ExactSizeIterator for IntoIter<K> {
1493 fn len(&self) -> usize {
1497 #[stable(feature = "fused", since = "1.26.0")]
1498 impl<K> FusedIterator for IntoIter<K> {}
1500 #[stable(feature = "std_debug", since = "1.16.0")]
1501 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1503 fmt::Debug::fmt(&self.base, f)
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<'a, K> Iterator for Drain<'a, K> {
1512 fn next(&mut self) -> Option<K> {
1516 fn size_hint(&self) -> (usize, Option<usize>) {
1517 self.base.size_hint()
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<K> ExactSizeIterator for Drain<'_, K> {
1523 fn len(&self) -> usize {
1527 #[stable(feature = "fused", since = "1.26.0")]
1528 impl<K> FusedIterator for Drain<'_, K> {}
1530 #[stable(feature = "std_debug", since = "1.16.0")]
1531 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533 fmt::Debug::fmt(&self.base, f)
1537 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1538 impl<K, F> Iterator for DrainFilter<'_, K, F>
1540 F: FnMut(&K) -> bool,
1545 fn next(&mut self) -> Option<K> {
1549 fn size_hint(&self) -> (usize, Option<usize>) {
1550 self.base.size_hint()
1554 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1555 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1557 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1558 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1560 F: FnMut(&K) -> bool,
1562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1563 f.debug_struct("DrainFilter").finish_non_exhaustive()
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl<T, S> Clone for Intersection<'_, T, S> {
1570 fn clone(&self) -> Self {
1571 Intersection { iter: self.iter.clone(), ..*self }
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1584 fn next(&mut self) -> Option<&'a T> {
1586 let elt = self.iter.next()?;
1587 if self.other.contains(elt) {
1594 fn size_hint(&self) -> (usize, Option<usize>) {
1595 let (_, upper) = self.iter.size_hint();
1600 #[stable(feature = "std_debug", since = "1.16.0")]
1601 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1603 T: fmt::Debug + Eq + Hash,
1606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1607 f.debug_list().entries(self.clone()).finish()
1611 #[stable(feature = "fused", since = "1.26.0")]
1612 impl<T, S> FusedIterator for Intersection<'_, T, S>
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl<T, S> Clone for Difference<'_, T, S> {
1622 fn clone(&self) -> Self {
1623 Difference { iter: self.iter.clone(), ..*self }
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<'a, T, S> Iterator for Difference<'a, T, S>
1636 fn next(&mut self) -> Option<&'a T> {
1638 let elt = self.iter.next()?;
1639 if !self.other.contains(elt) {
1646 fn size_hint(&self) -> (usize, Option<usize>) {
1647 let (_, upper) = self.iter.size_hint();
1652 #[stable(feature = "fused", since = "1.26.0")]
1653 impl<T, S> FusedIterator for Difference<'_, T, S>
1660 #[stable(feature = "std_debug", since = "1.16.0")]
1661 impl<T, S> fmt::Debug for Difference<'_, T, S>
1663 T: fmt::Debug + Eq + Hash,
1666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1667 f.debug_list().entries(self.clone()).finish()
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1674 fn clone(&self) -> Self {
1675 SymmetricDifference { iter: self.iter.clone() }
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1688 fn next(&mut self) -> Option<&'a T> {
1692 fn size_hint(&self) -> (usize, Option<usize>) {
1693 self.iter.size_hint()
1697 #[stable(feature = "fused", since = "1.26.0")]
1698 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1705 #[stable(feature = "std_debug", since = "1.16.0")]
1706 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1708 T: fmt::Debug + Eq + Hash,
1711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1712 f.debug_list().entries(self.clone()).finish()
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl<T, S> Clone for Union<'_, T, S> {
1719 fn clone(&self) -> Self {
1720 Union { iter: self.iter.clone() }
1724 #[stable(feature = "fused", since = "1.26.0")]
1725 impl<T, S> FusedIterator for Union<'_, T, S>
1732 #[stable(feature = "std_debug", since = "1.16.0")]
1733 impl<T, S> fmt::Debug for Union<'_, T, S>
1735 T: fmt::Debug + Eq + Hash,
1738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1739 f.debug_list().entries(self.clone()).finish()
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl<'a, T, S> Iterator for Union<'a, T, S>
1752 fn next(&mut self) -> Option<&'a T> {
1756 fn size_hint(&self) -> (usize, Option<usize>) {
1757 self.iter.size_hint()
1762 fn assert_covariance() {
1763 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1766 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1769 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1772 fn difference<'a, 'new>(
1773 v: Difference<'a, &'static str, RandomState>,
1774 ) -> Difference<'a, &'new str, RandomState> {
1777 fn symmetric_difference<'a, 'new>(
1778 v: SymmetricDifference<'a, &'static str, RandomState>,
1779 ) -> SymmetricDifference<'a, &'new str, RandomState> {
1782 fn intersection<'a, 'new>(
1783 v: Intersection<'a, &'static str, RandomState>,
1784 ) -> Intersection<'a, &'new str, RandomState> {
1788 v: Union<'a, &'static str, RandomState>,
1789 ) -> Union<'a, &'new str, RandomState> {
1792 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {