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_type")]
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);
203 #[doc(alias = "length")]
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn len(&self) -> usize {
210 /// Returns `true` if the set contains no elements.
215 /// use std::collections::HashSet;
217 /// let mut v = HashSet::new();
218 /// assert!(v.is_empty());
220 /// assert!(!v.is_empty());
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn is_empty(&self) -> bool {
228 /// Clears the set, returning all elements in an iterator.
233 /// use std::collections::HashSet;
235 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
236 /// assert!(!set.is_empty());
238 /// // print 1, 2, 3 in an arbitrary order
239 /// for i in set.drain() {
240 /// println!("{}", i);
243 /// assert!(set.is_empty());
246 #[stable(feature = "drain", since = "1.6.0")]
247 pub fn drain(&mut self) -> Drain<'_, T> {
248 Drain { base: self.base.drain() }
251 /// Creates an iterator which uses a closure to determine if a value should be removed.
253 /// If the closure returns true, then the value is removed and yielded.
254 /// If the closure returns false, the value will remain in the list and will not be yielded
257 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
258 /// values will still be subjected to the closure and removed and dropped if it returns true.
260 /// It is unspecified how many more values will be subjected to the closure
261 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
262 /// `DrainFilter` itself is leaked.
266 /// Splitting a set into even and odd values, reusing the original set:
269 /// #![feature(hash_drain_filter)]
270 /// use std::collections::HashSet;
272 /// let mut set: HashSet<i32> = (0..8).collect();
273 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
275 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
276 /// let mut odds = set.into_iter().collect::<Vec<_>>();
280 /// assert_eq!(evens, vec![0, 2, 4, 6]);
281 /// assert_eq!(odds, vec![1, 3, 5, 7]);
284 #[unstable(feature = "hash_drain_filter", issue = "59618")]
285 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
287 F: FnMut(&T) -> bool,
289 DrainFilter { base: self.base.drain_filter(pred) }
292 /// Clears the set, removing all values.
297 /// use std::collections::HashSet;
299 /// let mut v = HashSet::new();
302 /// assert!(v.is_empty());
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn clear(&mut self) {
310 /// Creates a new empty hash set which will use the given hasher to hash
313 /// The hash set is also created with the default initial capacity.
315 /// Warning: `hasher` is normally randomly generated, and
316 /// is designed to allow `HashSet`s to be resistant to attacks that
317 /// cause many collisions and very poor performance. Setting it
318 /// manually using this function can expose a DoS attack vector.
320 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
321 /// the HashMap to be useful, see its documentation for details.
326 /// use std::collections::HashSet;
327 /// use std::collections::hash_map::RandomState;
329 /// let s = RandomState::new();
330 /// let mut set = HashSet::with_hasher(s);
334 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
335 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
336 HashSet { base: base::HashSet::with_hasher(hasher) }
339 /// Creates an empty `HashSet` with the specified capacity, using
340 /// `hasher` to hash the keys.
342 /// The hash set will be able to hold at least `capacity` elements without
343 /// reallocating. If `capacity` is 0, the hash set will not allocate.
345 /// Warning: `hasher` is normally randomly generated, and
346 /// is designed to allow `HashSet`s to be resistant to attacks that
347 /// cause many collisions and very poor performance. Setting it
348 /// manually using this function can expose a DoS attack vector.
350 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
351 /// the HashMap to be useful, see its documentation for details.
356 /// use std::collections::HashSet;
357 /// use std::collections::hash_map::RandomState;
359 /// let s = RandomState::new();
360 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
364 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
365 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
366 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
369 /// Returns a reference to the set's [`BuildHasher`].
374 /// use std::collections::HashSet;
375 /// use std::collections::hash_map::RandomState;
377 /// let hasher = RandomState::new();
378 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
379 /// let hasher: &RandomState = set.hasher();
382 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
383 pub fn hasher(&self) -> &S {
388 impl<T, S> HashSet<T, S>
393 /// Reserves capacity for at least `additional` more elements to be inserted
394 /// in the `HashSet`. The collection may reserve more space to avoid
395 /// frequent reallocations.
399 /// Panics if the new allocation size overflows `usize`.
404 /// use std::collections::HashSet;
405 /// let mut set: HashSet<i32> = HashSet::new();
407 /// assert!(set.capacity() >= 10);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn reserve(&mut self, additional: usize) {
412 self.base.reserve(additional)
415 /// Tries to reserve capacity for at least `additional` more elements to be inserted
416 /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
417 /// frequent reallocations.
421 /// If the capacity overflows, or the allocator reports a failure, then an error
427 /// #![feature(try_reserve)]
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 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
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 /// #![feature(shrink_to)]
469 /// use std::collections::HashSet;
471 /// let mut set = HashSet::with_capacity(100);
474 /// assert!(set.capacity() >= 100);
475 /// set.shrink_to(10);
476 /// assert!(set.capacity() >= 10);
477 /// set.shrink_to(0);
478 /// assert!(set.capacity() >= 2);
481 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
482 pub fn shrink_to(&mut self, min_capacity: usize) {
483 self.base.shrink_to(min_capacity)
486 /// Visits the values representing the difference,
487 /// i.e., the values that are in `self` but not in `other`.
492 /// use std::collections::HashSet;
493 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
494 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
496 /// // Can be seen as `a - b`.
497 /// for x in a.difference(&b) {
498 /// println!("{}", x); // Print 1
501 /// let diff: HashSet<_> = a.difference(&b).collect();
502 /// assert_eq!(diff, [1].iter().collect());
504 /// // Note that difference is not symmetric,
505 /// // and `b - a` means something else:
506 /// let diff: HashSet<_> = b.difference(&a).collect();
507 /// assert_eq!(diff, [4].iter().collect());
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
512 Difference { iter: self.iter(), other }
515 /// Visits the values representing the symmetric difference,
516 /// i.e., the values that are in `self` or in `other` but not in both.
521 /// use std::collections::HashSet;
522 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
523 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
525 /// // Print 1, 4 in arbitrary order.
526 /// for x in a.symmetric_difference(&b) {
527 /// println!("{}", x);
530 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
531 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
533 /// assert_eq!(diff1, diff2);
534 /// assert_eq!(diff1, [1, 4].iter().collect());
537 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn symmetric_difference<'a>(
540 other: &'a HashSet<T, S>,
541 ) -> SymmetricDifference<'a, T, S> {
542 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
545 /// Visits the values representing the intersection,
546 /// i.e., the values that are both in `self` and `other`.
551 /// use std::collections::HashSet;
552 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
553 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
555 /// // Print 2, 3 in arbitrary order.
556 /// for x in a.intersection(&b) {
557 /// println!("{}", x);
560 /// let intersection: HashSet<_> = a.intersection(&b).collect();
561 /// assert_eq!(intersection, [2, 3].iter().collect());
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
566 if self.len() <= other.len() {
567 Intersection { iter: self.iter(), other }
569 Intersection { iter: other.iter(), other: self }
573 /// Visits the values representing the union,
574 /// i.e., all the values in `self` or `other`, without duplicates.
579 /// use std::collections::HashSet;
580 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
581 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
583 /// // Print 1, 2, 3, 4 in arbitrary order.
584 /// for x in a.union(&b) {
585 /// println!("{}", x);
588 /// let union: HashSet<_> = a.union(&b).collect();
589 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
592 #[stable(feature = "rust1", since = "1.0.0")]
593 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
594 if self.len() >= other.len() {
595 Union { iter: self.iter().chain(other.difference(self)) }
597 Union { iter: other.iter().chain(self.difference(other)) }
601 /// Returns `true` if the set contains a value.
603 /// The value may be any borrowed form of the set's value type, but
604 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
610 /// use std::collections::HashSet;
612 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
613 /// assert_eq!(set.contains(&1), true);
614 /// assert_eq!(set.contains(&4), false);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
623 self.base.contains(value)
626 /// Returns a reference to the value in the set, if any, that is equal to the given value.
628 /// The value may be any borrowed form of the set's value type, but
629 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
635 /// use std::collections::HashSet;
637 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
638 /// assert_eq!(set.get(&2), Some(&2));
639 /// assert_eq!(set.get(&4), None);
642 #[stable(feature = "set_recovery", since = "1.9.0")]
643 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
651 /// Inserts the given `value` into the set if it is not present, then
652 /// returns a reference to the value in the set.
657 /// #![feature(hash_set_entry)]
659 /// use std::collections::HashSet;
661 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
662 /// assert_eq!(set.len(), 3);
663 /// assert_eq!(set.get_or_insert(2), &2);
664 /// assert_eq!(set.get_or_insert(100), &100);
665 /// assert_eq!(set.len(), 4); // 100 was inserted
668 #[unstable(feature = "hash_set_entry", issue = "60896")]
669 pub fn get_or_insert(&mut self, value: T) -> &T {
670 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
671 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
672 self.base.get_or_insert(value)
675 /// Inserts an owned copy of the given `value` into the set if it is not
676 /// present, then returns a reference to the value in the set.
681 /// #![feature(hash_set_entry)]
683 /// use std::collections::HashSet;
685 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
686 /// .iter().map(|&pet| pet.to_owned()).collect();
688 /// assert_eq!(set.len(), 3);
689 /// for &pet in &["cat", "dog", "fish"] {
690 /// let value = set.get_or_insert_owned(pet);
691 /// assert_eq!(value, pet);
693 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
696 #[unstable(feature = "hash_set_entry", issue = "60896")]
697 pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
700 Q: Hash + Eq + ToOwned<Owned = T>,
702 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
703 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
704 self.base.get_or_insert_owned(value)
707 /// Inserts a value computed from `f` into the set if the given `value` is
708 /// not present, then returns a reference to the value in the set.
713 /// #![feature(hash_set_entry)]
715 /// use std::collections::HashSet;
717 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
718 /// .iter().map(|&pet| pet.to_owned()).collect();
720 /// assert_eq!(set.len(), 3);
721 /// for &pet in &["cat", "dog", "fish"] {
722 /// let value = set.get_or_insert_with(pet, str::to_owned);
723 /// assert_eq!(value, pet);
725 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
728 #[unstable(feature = "hash_set_entry", issue = "60896")]
729 pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
735 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
736 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
737 self.base.get_or_insert_with(value, f)
740 /// Returns `true` if `self` has no elements in common with `other`.
741 /// This is equivalent to checking for an empty intersection.
746 /// use std::collections::HashSet;
748 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
749 /// let mut b = HashSet::new();
751 /// assert_eq!(a.is_disjoint(&b), true);
753 /// assert_eq!(a.is_disjoint(&b), true);
755 /// assert_eq!(a.is_disjoint(&b), false);
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
759 if self.len() <= other.len() {
760 self.iter().all(|v| !other.contains(v))
762 other.iter().all(|v| !self.contains(v))
766 /// Returns `true` if the set is a subset of another,
767 /// i.e., `other` contains at least all the values in `self`.
772 /// use std::collections::HashSet;
774 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
775 /// let mut set = HashSet::new();
777 /// assert_eq!(set.is_subset(&sup), true);
779 /// assert_eq!(set.is_subset(&sup), true);
781 /// assert_eq!(set.is_subset(&sup), false);
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
785 if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
788 /// Returns `true` if the set is a superset of another,
789 /// i.e., `self` contains at least all the values in `other`.
794 /// use std::collections::HashSet;
796 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
797 /// let mut set = HashSet::new();
799 /// assert_eq!(set.is_superset(&sub), false);
803 /// assert_eq!(set.is_superset(&sub), false);
806 /// assert_eq!(set.is_superset(&sub), true);
809 #[stable(feature = "rust1", since = "1.0.0")]
810 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
811 other.is_subset(self)
814 /// Adds a value to the set.
816 /// If the set did not have this value present, `true` is returned.
818 /// If the set did have this value present, `false` is returned.
823 /// use std::collections::HashSet;
825 /// let mut set = HashSet::new();
827 /// assert_eq!(set.insert(2), true);
828 /// assert_eq!(set.insert(2), false);
829 /// assert_eq!(set.len(), 1);
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub fn insert(&mut self, value: T) -> bool {
834 self.base.insert(value)
837 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
838 /// one. Returns the replaced value.
843 /// use std::collections::HashSet;
845 /// let mut set = HashSet::new();
846 /// set.insert(Vec::<i32>::new());
848 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
849 /// set.replace(Vec::with_capacity(10));
850 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
853 #[stable(feature = "set_recovery", since = "1.9.0")]
854 pub fn replace(&mut self, value: T) -> Option<T> {
855 self.base.replace(value)
858 /// Removes a value from the set. Returns whether the value was
859 /// present in the set.
861 /// The value may be any borrowed form of the set's value type, but
862 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
868 /// use std::collections::HashSet;
870 /// let mut set = HashSet::new();
873 /// assert_eq!(set.remove(&2), true);
874 /// assert_eq!(set.remove(&2), false);
876 #[doc(alias = "delete")]
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
884 self.base.remove(value)
887 /// Removes and returns the value in the set, if any, that is equal to the given one.
889 /// The value may be any borrowed form of the set's value type, but
890 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
896 /// use std::collections::HashSet;
898 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
899 /// assert_eq!(set.take(&2), Some(2));
900 /// assert_eq!(set.take(&2), None);
903 #[stable(feature = "set_recovery", since = "1.9.0")]
904 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
909 self.base.take(value)
912 /// Retains only the elements specified by the predicate.
914 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
919 /// use std::collections::HashSet;
921 /// let xs = [1, 2, 3, 4, 5, 6];
922 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
923 /// set.retain(|&k| k % 2 == 0);
924 /// assert_eq!(set.len(), 3);
926 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
927 pub fn retain<F>(&mut self, f: F)
929 F: FnMut(&T) -> bool,
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<T, S> Clone for HashSet<T, S>
942 fn clone(&self) -> Self {
943 Self { base: self.base.clone() }
947 fn clone_from(&mut self, other: &Self) {
948 self.base.clone_from(&other.base);
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<T, S> PartialEq for HashSet<T, S>
958 fn eq(&self, other: &HashSet<T, S>) -> bool {
959 if self.len() != other.len() {
963 self.iter().all(|key| other.contains(key))
967 #[stable(feature = "rust1", since = "1.0.0")]
968 impl<T, S> Eq for HashSet<T, S>
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<T, S> fmt::Debug for HashSet<T, S>
980 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981 f.debug_set().entries(self.iter()).finish()
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<T, S> FromIterator<T> for HashSet<T, S>
989 S: BuildHasher + Default,
992 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
993 let mut set = HashSet::with_hasher(Default::default());
999 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1000 // Note: as what is currently the most convenient built-in way to construct
1001 // a HashSet, a simple usage of this function must not *require* the user
1002 // to provide a type annotation in order to infer the third type parameter
1003 // (the hasher parameter, conventionally "S").
1004 // To that end, this impl is defined using RandomState as the concrete
1005 // type of S, rather than being generic over `S: BuildHasher + Default`.
1006 // It is expected that users who want to specify a hasher will manually use
1007 // `with_capacity_and_hasher`.
1008 // If type parameter defaults worked on impls, and if type parameter
1009 // defaults could be mixed with const generics, then perhaps
1010 // this could be generalized.
1011 // See also the equivalent impl on HashMap.
1012 impl<T, const N: usize> From<[T; N]> for HashSet<T, RandomState>
1019 /// use std::collections::HashSet;
1021 /// let set1 = HashSet::from([1, 2, 3, 4]);
1022 /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1023 /// assert_eq!(set1, set2);
1025 fn from(arr: [T; N]) -> Self {
1026 crate::array::IntoIter::new(arr).collect()
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<T, S> Extend<T> for HashSet<T, S>
1037 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1038 self.base.extend(iter);
1042 fn extend_one(&mut self, item: T) {
1043 self.base.insert(item);
1047 fn extend_reserve(&mut self, additional: usize) {
1048 self.base.extend_reserve(additional);
1052 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1053 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1055 T: 'a + Eq + Hash + Copy,
1059 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1060 self.extend(iter.into_iter().cloned());
1064 fn extend_one(&mut self, &item: &'a T) {
1065 self.base.insert(item);
1069 fn extend_reserve(&mut self, additional: usize) {
1070 Extend::<T>::extend_reserve(self, additional)
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 impl<T, S> Default for HashSet<T, S>
1079 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1081 fn default() -> HashSet<T, S> {
1082 HashSet { base: Default::default() }
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1089 T: Eq + Hash + Clone,
1090 S: BuildHasher + Default,
1092 type Output = HashSet<T, S>;
1094 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1099 /// use std::collections::HashSet;
1101 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1102 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1104 /// let set = &a | &b;
1107 /// let expected = [1, 2, 3, 4, 5];
1109 /// assert!(expected.contains(x));
1112 /// assert_eq!(i, expected.len());
1114 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1115 self.union(rhs).cloned().collect()
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1122 T: Eq + Hash + Clone,
1123 S: BuildHasher + Default,
1125 type Output = HashSet<T, S>;
1127 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1132 /// use std::collections::HashSet;
1134 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1135 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1137 /// let set = &a & &b;
1140 /// let expected = [2, 3];
1142 /// assert!(expected.contains(x));
1145 /// assert_eq!(i, expected.len());
1147 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1148 self.intersection(rhs).cloned().collect()
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1155 T: Eq + Hash + Clone,
1156 S: BuildHasher + Default,
1158 type Output = HashSet<T, S>;
1160 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1165 /// use std::collections::HashSet;
1167 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1168 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1170 /// let set = &a ^ &b;
1173 /// let expected = [1, 2, 4, 5];
1175 /// assert!(expected.contains(x));
1178 /// assert_eq!(i, expected.len());
1180 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1181 self.symmetric_difference(rhs).cloned().collect()
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1188 T: Eq + Hash + Clone,
1189 S: BuildHasher + Default,
1191 type Output = HashSet<T, S>;
1193 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1198 /// use std::collections::HashSet;
1200 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1201 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1203 /// let set = &a - &b;
1206 /// let expected = [1, 2];
1208 /// assert!(expected.contains(x));
1211 /// assert_eq!(i, expected.len());
1213 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1214 self.difference(rhs).cloned().collect()
1218 /// An iterator over the items of a `HashSet`.
1220 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1221 /// See its documentation for more.
1223 /// [`iter`]: HashSet::iter
1228 /// use std::collections::HashSet;
1230 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1232 /// let mut iter = a.iter();
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 pub struct Iter<'a, K: 'a> {
1236 base: base::Iter<'a, K>,
1239 /// An owning iterator over the items of a `HashSet`.
1241 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1242 /// (provided by the `IntoIterator` trait). See its documentation for more.
1244 /// [`into_iter`]: IntoIterator::into_iter
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.pad("DrainFilter { .. }")
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> {