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
45 /// use std::collections::HashSet;
46 /// // Type inference lets us omit an explicit type signature (which
47 /// // would be `HashSet<String>` in this example).
48 /// let mut books = HashSet::new();
50 /// // Add some books.
51 /// books.insert("A Dance With Dragons".to_string());
52 /// books.insert("To Kill a Mockingbird".to_string());
53 /// books.insert("The Odyssey".to_string());
54 /// books.insert("The Great Gatsby".to_string());
56 /// // Check for a specific one.
57 /// if !books.contains("The Winds of Winter") {
58 /// println!("We have {} books, but The Winds of Winter ain't one.",
63 /// books.remove("The Odyssey");
65 /// // Iterate over everything.
66 /// for book in &books {
67 /// println!("{}", book);
71 /// The easiest way to use `HashSet` with a custom type is to derive
72 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
73 /// future be implied by [`Eq`].
76 /// use std::collections::HashSet;
77 /// #[derive(Hash, Eq, PartialEq, Debug)]
83 /// let mut vikings = HashSet::new();
85 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
86 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
87 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
88 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
90 /// // Use derived implementation to print the vikings.
91 /// for x in &vikings {
92 /// println!("{:?}", x);
96 /// A `HashSet` with fixed list of elements can be initialized from an array:
99 /// use std::collections::HashSet;
101 /// let viking_names: HashSet<&'static str> =
102 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
103 /// // use the values stored in the set
106 /// [`HashMap`]: crate::collections::HashMap
107 /// [`RefCell`]: crate::cell::RefCell
108 /// [`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);
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 /// #![feature(try_reserve)]
427 /// use std::collections::HashSet;
428 /// let mut set: HashSet<i32> = HashSet::new();
429 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
432 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
433 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
434 self.base.try_reserve(additional).map_err(map_try_reserve_error)
437 /// Shrinks the capacity of the set as much as possible. It will drop
438 /// down as much as possible while maintaining the internal rules
439 /// and possibly leaving some space in accordance with the resize policy.
444 /// use std::collections::HashSet;
446 /// let mut set = HashSet::with_capacity(100);
449 /// assert!(set.capacity() >= 100);
450 /// set.shrink_to_fit();
451 /// assert!(set.capacity() >= 2);
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn shrink_to_fit(&mut self) {
456 self.base.shrink_to_fit()
459 /// Shrinks the capacity of the set with a lower limit. It will drop
460 /// down no lower than the supplied limit while maintaining the internal rules
461 /// and possibly leaving some space in accordance with the resize policy.
463 /// Panics if the current capacity is smaller than the supplied
464 /// minimum capacity.
469 /// #![feature(shrink_to)]
470 /// use std::collections::HashSet;
472 /// let mut set = HashSet::with_capacity(100);
475 /// assert!(set.capacity() >= 100);
476 /// set.shrink_to(10);
477 /// assert!(set.capacity() >= 10);
478 /// set.shrink_to(0);
479 /// assert!(set.capacity() >= 2);
482 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
483 pub fn shrink_to(&mut self, min_capacity: usize) {
484 self.base.shrink_to(min_capacity)
487 /// Visits the values representing the difference,
488 /// i.e., the values that are in `self` but not in `other`.
493 /// use std::collections::HashSet;
494 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
495 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
497 /// // Can be seen as `a - b`.
498 /// for x in a.difference(&b) {
499 /// println!("{}", x); // Print 1
502 /// let diff: HashSet<_> = a.difference(&b).collect();
503 /// assert_eq!(diff, [1].iter().collect());
505 /// // Note that difference is not symmetric,
506 /// // and `b - a` means something else:
507 /// let diff: HashSet<_> = b.difference(&a).collect();
508 /// assert_eq!(diff, [4].iter().collect());
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
513 Difference { iter: self.iter(), other }
516 /// Visits the values representing the symmetric difference,
517 /// i.e., the values that are in `self` or in `other` but not in both.
522 /// use std::collections::HashSet;
523 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
524 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
526 /// // Print 1, 4 in arbitrary order.
527 /// for x in a.symmetric_difference(&b) {
528 /// println!("{}", x);
531 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
532 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
534 /// assert_eq!(diff1, diff2);
535 /// assert_eq!(diff1, [1, 4].iter().collect());
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn symmetric_difference<'a>(
541 other: &'a HashSet<T, S>,
542 ) -> SymmetricDifference<'a, T, S> {
543 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
546 /// Visits the values representing the intersection,
547 /// i.e., the values that are both in `self` and `other`.
552 /// use std::collections::HashSet;
553 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
554 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
556 /// // Print 2, 3 in arbitrary order.
557 /// for x in a.intersection(&b) {
558 /// println!("{}", x);
561 /// let intersection: HashSet<_> = a.intersection(&b).collect();
562 /// assert_eq!(intersection, [2, 3].iter().collect());
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
567 if self.len() <= other.len() {
568 Intersection { iter: self.iter(), other }
570 Intersection { iter: other.iter(), other: self }
574 /// Visits the values representing the union,
575 /// i.e., all the values in `self` or `other`, without duplicates.
580 /// use std::collections::HashSet;
581 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
582 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
584 /// // Print 1, 2, 3, 4 in arbitrary order.
585 /// for x in a.union(&b) {
586 /// println!("{}", x);
589 /// let union: HashSet<_> = a.union(&b).collect();
590 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
593 #[stable(feature = "rust1", since = "1.0.0")]
594 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
595 if self.len() >= other.len() {
596 Union { iter: self.iter().chain(other.difference(self)) }
598 Union { iter: other.iter().chain(self.difference(other)) }
602 /// Returns `true` if the set contains a value.
604 /// The value may be any borrowed form of the set's value type, but
605 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
611 /// use std::collections::HashSet;
613 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
614 /// assert_eq!(set.contains(&1), true);
615 /// assert_eq!(set.contains(&4), false);
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
624 self.base.contains(value)
627 /// Returns a reference to the value in the set, if any, that is equal to the given value.
629 /// The value may be any borrowed form of the set's value type, but
630 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
636 /// use std::collections::HashSet;
638 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
639 /// assert_eq!(set.get(&2), Some(&2));
640 /// assert_eq!(set.get(&4), None);
643 #[stable(feature = "set_recovery", since = "1.9.0")]
644 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
652 /// Inserts the given `value` into the set if it is not present, then
653 /// returns a reference to the value in the set.
658 /// #![feature(hash_set_entry)]
660 /// use std::collections::HashSet;
662 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
663 /// assert_eq!(set.len(), 3);
664 /// assert_eq!(set.get_or_insert(2), &2);
665 /// assert_eq!(set.get_or_insert(100), &100);
666 /// assert_eq!(set.len(), 4); // 100 was inserted
669 #[unstable(feature = "hash_set_entry", issue = "60896")]
670 pub fn get_or_insert(&mut self, value: T) -> &T {
671 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
672 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
673 self.base.get_or_insert(value)
676 /// Inserts an owned copy of the given `value` into the set if it is not
677 /// present, then returns a reference to the value in the set.
682 /// #![feature(hash_set_entry)]
684 /// use std::collections::HashSet;
686 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
687 /// .iter().map(|&pet| pet.to_owned()).collect();
689 /// assert_eq!(set.len(), 3);
690 /// for &pet in &["cat", "dog", "fish"] {
691 /// let value = set.get_or_insert_owned(pet);
692 /// assert_eq!(value, pet);
694 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
697 #[unstable(feature = "hash_set_entry", issue = "60896")]
698 pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
701 Q: Hash + Eq + ToOwned<Owned = T>,
703 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
704 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
705 self.base.get_or_insert_owned(value)
708 /// Inserts a value computed from `f` into the set if the given `value` is
709 /// not present, then returns a reference to the value in the set.
714 /// #![feature(hash_set_entry)]
716 /// use std::collections::HashSet;
718 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
719 /// .iter().map(|&pet| pet.to_owned()).collect();
721 /// assert_eq!(set.len(), 3);
722 /// for &pet in &["cat", "dog", "fish"] {
723 /// let value = set.get_or_insert_with(pet, str::to_owned);
724 /// assert_eq!(value, pet);
726 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
729 #[unstable(feature = "hash_set_entry", issue = "60896")]
730 pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
736 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
737 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
738 self.base.get_or_insert_with(value, f)
741 /// Returns `true` if `self` has no elements in common with `other`.
742 /// This is equivalent to checking for an empty intersection.
747 /// use std::collections::HashSet;
749 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
750 /// let mut b = HashSet::new();
752 /// assert_eq!(a.is_disjoint(&b), true);
754 /// assert_eq!(a.is_disjoint(&b), true);
756 /// assert_eq!(a.is_disjoint(&b), false);
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
760 if self.len() <= other.len() {
761 self.iter().all(|v| !other.contains(v))
763 other.iter().all(|v| !self.contains(v))
767 /// Returns `true` if the set is a subset of another,
768 /// i.e., `other` contains at least all the values in `self`.
773 /// use std::collections::HashSet;
775 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
776 /// let mut set = HashSet::new();
778 /// assert_eq!(set.is_subset(&sup), true);
780 /// assert_eq!(set.is_subset(&sup), true);
782 /// assert_eq!(set.is_subset(&sup), false);
784 #[stable(feature = "rust1", since = "1.0.0")]
785 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
786 if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
789 /// Returns `true` if the set is a superset of another,
790 /// i.e., `self` contains at least all the values in `other`.
795 /// use std::collections::HashSet;
797 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
798 /// let mut set = HashSet::new();
800 /// assert_eq!(set.is_superset(&sub), false);
804 /// assert_eq!(set.is_superset(&sub), false);
807 /// assert_eq!(set.is_superset(&sub), true);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
812 other.is_subset(self)
815 /// Adds a value to the set.
817 /// If the set did not have this value present, `true` is returned.
819 /// If the set did have this value present, `false` is returned.
824 /// use std::collections::HashSet;
826 /// let mut set = HashSet::new();
828 /// assert_eq!(set.insert(2), true);
829 /// assert_eq!(set.insert(2), false);
830 /// assert_eq!(set.len(), 1);
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn insert(&mut self, value: T) -> bool {
835 self.base.insert(value)
838 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
839 /// one. Returns the replaced value.
844 /// use std::collections::HashSet;
846 /// let mut set = HashSet::new();
847 /// set.insert(Vec::<i32>::new());
849 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
850 /// set.replace(Vec::with_capacity(10));
851 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
854 #[stable(feature = "set_recovery", since = "1.9.0")]
855 pub fn replace(&mut self, value: T) -> Option<T> {
856 self.base.replace(value)
859 /// Removes a value from the set. Returns whether the value was
860 /// present in the set.
862 /// The value may be any borrowed form of the set's value type, but
863 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
869 /// use std::collections::HashSet;
871 /// let mut set = HashSet::new();
874 /// assert_eq!(set.remove(&2), true);
875 /// assert_eq!(set.remove(&2), false);
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> PartialEq for HashSet<T, S>
941 fn eq(&self, other: &HashSet<T, S>) -> bool {
942 if self.len() != other.len() {
946 self.iter().all(|key| other.contains(key))
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl<T, S> Eq for HashSet<T, S>
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl<T, S> fmt::Debug for HashSet<T, S>
963 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
964 f.debug_set().entries(self.iter()).finish()
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<T, S> FromIterator<T> for HashSet<T, S>
972 S: BuildHasher + Default,
975 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
976 let mut set = HashSet::with_hasher(Default::default());
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T, S> Extend<T> for HashSet<T, S>
989 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
990 self.base.extend(iter);
994 fn extend_one(&mut self, item: T) {
995 self.base.insert(item);
999 fn extend_reserve(&mut self, additional: usize) {
1000 self.base.extend_reserve(additional);
1004 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1005 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1007 T: 'a + Eq + Hash + Copy,
1011 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1012 self.extend(iter.into_iter().cloned());
1016 fn extend_one(&mut self, &item: &'a T) {
1017 self.base.insert(item);
1021 fn extend_reserve(&mut self, additional: usize) {
1022 Extend::<T>::extend_reserve(self, additional)
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<T, S> Default for HashSet<T, S>
1031 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1033 fn default() -> HashSet<T, S> {
1034 HashSet { base: Default::default() }
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1041 T: Eq + Hash + Clone,
1042 S: BuildHasher + Default,
1044 type Output = HashSet<T, S>;
1046 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1051 /// use std::collections::HashSet;
1053 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1054 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1056 /// let set = &a | &b;
1059 /// let expected = [1, 2, 3, 4, 5];
1061 /// assert!(expected.contains(x));
1064 /// assert_eq!(i, expected.len());
1066 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1067 self.union(rhs).cloned().collect()
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1074 T: Eq + Hash + Clone,
1075 S: BuildHasher + Default,
1077 type Output = HashSet<T, S>;
1079 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1084 /// use std::collections::HashSet;
1086 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1087 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1089 /// let set = &a & &b;
1092 /// let expected = [2, 3];
1094 /// assert!(expected.contains(x));
1097 /// assert_eq!(i, expected.len());
1099 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1100 self.intersection(rhs).cloned().collect()
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1107 T: Eq + Hash + Clone,
1108 S: BuildHasher + Default,
1110 type Output = HashSet<T, S>;
1112 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1117 /// use std::collections::HashSet;
1119 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1120 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1122 /// let set = &a ^ &b;
1125 /// let expected = [1, 2, 4, 5];
1127 /// assert!(expected.contains(x));
1130 /// assert_eq!(i, expected.len());
1132 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1133 self.symmetric_difference(rhs).cloned().collect()
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1140 T: Eq + Hash + Clone,
1141 S: BuildHasher + Default,
1143 type Output = HashSet<T, S>;
1145 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1150 /// use std::collections::HashSet;
1152 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1153 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1155 /// let set = &a - &b;
1158 /// let expected = [1, 2];
1160 /// assert!(expected.contains(x));
1163 /// assert_eq!(i, expected.len());
1165 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1166 self.difference(rhs).cloned().collect()
1170 /// An iterator over the items of a `HashSet`.
1172 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1173 /// See its documentation for more.
1175 /// [`iter`]: HashSet::iter
1180 /// use std::collections::HashSet;
1182 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1184 /// let mut iter = a.iter();
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 pub struct Iter<'a, K: 'a> {
1188 base: base::Iter<'a, K>,
1191 /// An owning iterator over the items of a `HashSet`.
1193 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1194 /// (provided by the `IntoIterator` trait). See its documentation for more.
1196 /// [`into_iter`]: IntoIterator::into_iter
1201 /// use std::collections::HashSet;
1203 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1205 /// let mut iter = a.into_iter();
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 pub struct IntoIter<K> {
1209 base: base::IntoIter<K>,
1212 /// A draining iterator over the items of a `HashSet`.
1214 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1215 /// See its documentation for more.
1217 /// [`drain`]: HashSet::drain
1222 /// use std::collections::HashSet;
1224 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1226 /// let mut drain = a.drain();
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub struct Drain<'a, K: 'a> {
1230 base: base::Drain<'a, K>,
1233 /// A draining, filtering iterator over the items of a `HashSet`.
1235 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1237 /// [`drain_filter`]: HashSet::drain_filter
1242 /// #![feature(hash_drain_filter)]
1244 /// use std::collections::HashSet;
1246 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1248 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1250 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1251 pub struct DrainFilter<'a, K, F>
1253 F: FnMut(&K) -> bool,
1255 base: base::DrainFilter<'a, K, F>,
1258 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1260 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1261 /// See its documentation for more.
1263 /// [`intersection`]: HashSet::intersection
1268 /// use std::collections::HashSet;
1270 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1271 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1273 /// let mut intersection = a.intersection(&b);
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub struct Intersection<'a, T: 'a, S: 'a> {
1277 // iterator of the first set
1280 other: &'a HashSet<T, S>,
1283 /// A lazy iterator producing elements in the difference of `HashSet`s.
1285 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1286 /// See its documentation for more.
1288 /// [`difference`]: HashSet::difference
1293 /// use std::collections::HashSet;
1295 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1296 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1298 /// let mut difference = a.difference(&b);
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub struct Difference<'a, T: 'a, S: 'a> {
1302 // iterator of the first set
1305 other: &'a HashSet<T, S>,
1308 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1310 /// This `struct` is created by the [`symmetric_difference`] method on
1311 /// [`HashSet`]. See its documentation for more.
1313 /// [`symmetric_difference`]: HashSet::symmetric_difference
1318 /// use std::collections::HashSet;
1320 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1321 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1323 /// let mut intersection = a.symmetric_difference(&b);
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1327 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1330 /// A lazy iterator producing elements in the union of `HashSet`s.
1332 /// This `struct` is created by the [`union`] method on [`HashSet`].
1333 /// See its documentation for more.
1335 /// [`union`]: HashSet::union
1340 /// use std::collections::HashSet;
1342 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1343 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1345 /// let mut union_iter = a.union(&b);
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub struct Union<'a, T: 'a, S: 'a> {
1349 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1355 type IntoIter = Iter<'a, T>;
1358 fn into_iter(self) -> Iter<'a, T> {
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 impl<T, S> IntoIterator for HashSet<T, S> {
1366 type IntoIter = IntoIter<T>;
1368 /// Creates a consuming iterator, that is, one that moves each value out
1369 /// of the set in arbitrary order. The set cannot be used after calling
1375 /// use std::collections::HashSet;
1376 /// let mut set = HashSet::new();
1377 /// set.insert("a".to_string());
1378 /// set.insert("b".to_string());
1380 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1381 /// let v: Vec<String> = set.into_iter().collect();
1383 /// // Will print in an arbitrary order.
1385 /// println!("{}", x);
1389 fn into_iter(self) -> IntoIter<T> {
1390 IntoIter { base: self.base.into_iter() }
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 impl<K> Clone for Iter<'_, K> {
1397 fn clone(&self) -> Self {
1398 Iter { base: self.base.clone() }
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<'a, K> Iterator for Iter<'a, K> {
1406 fn next(&mut self) -> Option<&'a K> {
1410 fn size_hint(&self) -> (usize, Option<usize>) {
1411 self.base.size_hint()
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl<K> ExactSizeIterator for Iter<'_, K> {
1417 fn len(&self) -> usize {
1421 #[stable(feature = "fused", since = "1.26.0")]
1422 impl<K> FusedIterator for Iter<'_, K> {}
1424 #[stable(feature = "std_debug", since = "1.16.0")]
1425 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427 f.debug_list().entries(self.clone()).finish()
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<K> Iterator for IntoIter<K> {
1436 fn next(&mut self) -> Option<K> {
1440 fn size_hint(&self) -> (usize, Option<usize>) {
1441 self.base.size_hint()
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<K> ExactSizeIterator for IntoIter<K> {
1447 fn len(&self) -> usize {
1451 #[stable(feature = "fused", since = "1.26.0")]
1452 impl<K> FusedIterator for IntoIter<K> {}
1454 #[stable(feature = "std_debug", since = "1.16.0")]
1455 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1457 fmt::Debug::fmt(&self.base, f)
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<'a, K> Iterator for Drain<'a, K> {
1466 fn next(&mut self) -> Option<K> {
1470 fn size_hint(&self) -> (usize, Option<usize>) {
1471 self.base.size_hint()
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<K> ExactSizeIterator for Drain<'_, K> {
1477 fn len(&self) -> usize {
1481 #[stable(feature = "fused", since = "1.26.0")]
1482 impl<K> FusedIterator for Drain<'_, K> {}
1484 #[stable(feature = "std_debug", since = "1.16.0")]
1485 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1487 fmt::Debug::fmt(&self.base, f)
1491 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1492 impl<K, F> Iterator for DrainFilter<'_, K, F>
1494 F: FnMut(&K) -> bool,
1499 fn next(&mut self) -> Option<K> {
1503 fn size_hint(&self) -> (usize, Option<usize>) {
1504 self.base.size_hint()
1508 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1509 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1511 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1512 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1514 F: FnMut(&K) -> bool,
1516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1517 f.pad("DrainFilter { .. }")
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl<T, S> Clone for Intersection<'_, T, S> {
1524 fn clone(&self) -> Self {
1525 Intersection { iter: self.iter.clone(), ..*self }
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1538 fn next(&mut self) -> Option<&'a T> {
1540 let elt = self.iter.next()?;
1541 if self.other.contains(elt) {
1548 fn size_hint(&self) -> (usize, Option<usize>) {
1549 let (_, upper) = self.iter.size_hint();
1554 #[stable(feature = "std_debug", since = "1.16.0")]
1555 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1557 T: fmt::Debug + Eq + Hash,
1560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1561 f.debug_list().entries(self.clone()).finish()
1565 #[stable(feature = "fused", since = "1.26.0")]
1566 impl<T, S> FusedIterator for Intersection<'_, T, S>
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl<T, S> Clone for Difference<'_, T, S> {
1576 fn clone(&self) -> Self {
1577 Difference { iter: self.iter.clone(), ..*self }
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<'a, T, S> Iterator for Difference<'a, T, S>
1590 fn next(&mut self) -> Option<&'a T> {
1592 let elt = self.iter.next()?;
1593 if !self.other.contains(elt) {
1600 fn size_hint(&self) -> (usize, Option<usize>) {
1601 let (_, upper) = self.iter.size_hint();
1606 #[stable(feature = "fused", since = "1.26.0")]
1607 impl<T, S> FusedIterator for Difference<'_, T, S>
1614 #[stable(feature = "std_debug", since = "1.16.0")]
1615 impl<T, S> fmt::Debug for Difference<'_, T, S>
1617 T: fmt::Debug + Eq + Hash,
1620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 f.debug_list().entries(self.clone()).finish()
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1628 fn clone(&self) -> Self {
1629 SymmetricDifference { iter: self.iter.clone() }
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1642 fn next(&mut self) -> Option<&'a T> {
1646 fn size_hint(&self) -> (usize, Option<usize>) {
1647 self.iter.size_hint()
1651 #[stable(feature = "fused", since = "1.26.0")]
1652 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1659 #[stable(feature = "std_debug", since = "1.16.0")]
1660 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1662 T: fmt::Debug + Eq + Hash,
1665 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1666 f.debug_list().entries(self.clone()).finish()
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<T, S> Clone for Union<'_, T, S> {
1673 fn clone(&self) -> Self {
1674 Union { iter: self.iter.clone() }
1678 #[stable(feature = "fused", since = "1.26.0")]
1679 impl<T, S> FusedIterator for Union<'_, T, S>
1686 #[stable(feature = "std_debug", since = "1.16.0")]
1687 impl<T, S> fmt::Debug for Union<'_, T, S>
1689 T: fmt::Debug + Eq + Hash,
1692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1693 f.debug_list().entries(self.clone()).finish()
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<'a, T, S> Iterator for Union<'a, T, S>
1706 fn next(&mut self) -> Option<&'a T> {
1710 fn size_hint(&self) -> (usize, Option<usize>) {
1711 self.iter.size_hint()
1716 fn assert_covariance() {
1717 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1720 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1723 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1726 fn difference<'a, 'new>(
1727 v: Difference<'a, &'static str, RandomState>,
1728 ) -> Difference<'a, &'new str, RandomState> {
1731 fn symmetric_difference<'a, 'new>(
1732 v: SymmetricDifference<'a, &'static str, RandomState>,
1733 ) -> SymmetricDifference<'a, &'new str, RandomState> {
1736 fn intersection<'a, 'new>(
1737 v: Intersection<'a, &'static str, RandomState>,
1738 ) -> Intersection<'a, &'new str, RandomState> {
1742 v: Union<'a, &'static str, RandomState>,
1743 ) -> Union<'a, &'new str, RandomState> {
1746 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {