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 fixed list of elements can be initialized from an array:
101 /// use std::collections::HashSet;
103 /// let viking_names: HashSet<&'static str> =
104 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
105 /// // use the values stored in the set
108 /// [`HashMap`]: crate::collections::HashMap
109 /// [`RefCell`]: crate::cell::RefCell
110 /// [`Cell`]: crate::cell::Cell
111 #[cfg_attr(not(test), rustc_diagnostic_item = "hashset_type")]
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct HashSet<T, S = RandomState> {
114 base: base::HashSet<T, S>,
117 impl<T> HashSet<T, RandomState> {
118 /// Creates an empty `HashSet`.
120 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
121 /// is first inserted into.
126 /// use std::collections::HashSet;
127 /// let set: HashSet<i32> = HashSet::new();
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub fn new() -> HashSet<T, RandomState> {
135 /// Creates an empty `HashSet` with the specified capacity.
137 /// The hash set will be able to hold at least `capacity` elements without
138 /// reallocating. If `capacity` is 0, the hash set will not allocate.
143 /// use std::collections::HashSet;
144 /// let set: HashSet<i32> = HashSet::with_capacity(10);
145 /// assert!(set.capacity() >= 10);
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
150 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
154 impl<T, S> HashSet<T, S> {
155 /// Returns the number of elements the set can hold without reallocating.
160 /// use std::collections::HashSet;
161 /// let set: HashSet<i32> = HashSet::with_capacity(100);
162 /// assert!(set.capacity() >= 100);
165 #[stable(feature = "rust1", since = "1.0.0")]
166 pub fn capacity(&self) -> usize {
170 /// An iterator visiting all elements in arbitrary order.
171 /// The iterator element type is `&'a T`.
176 /// use std::collections::HashSet;
177 /// let mut set = HashSet::new();
181 /// // Will print in an arbitrary order.
182 /// for x in set.iter() {
183 /// println!("{}", x);
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn iter(&self) -> Iter<'_, T> {
189 Iter { base: self.base.iter() }
192 /// Returns the number of elements in the set.
197 /// use std::collections::HashSet;
199 /// let mut v = HashSet::new();
200 /// assert_eq!(v.len(), 0);
202 /// assert_eq!(v.len(), 1);
204 #[doc(alias = "length")]
206 #[stable(feature = "rust1", since = "1.0.0")]
207 pub fn len(&self) -> usize {
211 /// Returns `true` if the set contains no elements.
216 /// use std::collections::HashSet;
218 /// let mut v = HashSet::new();
219 /// assert!(v.is_empty());
221 /// assert!(!v.is_empty());
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn is_empty(&self) -> bool {
229 /// Clears the set, returning all elements in an iterator.
234 /// use std::collections::HashSet;
236 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
237 /// assert!(!set.is_empty());
239 /// // print 1, 2, 3 in an arbitrary order
240 /// for i in set.drain() {
241 /// println!("{}", i);
244 /// assert!(set.is_empty());
247 #[stable(feature = "drain", since = "1.6.0")]
248 pub fn drain(&mut self) -> Drain<'_, T> {
249 Drain { base: self.base.drain() }
252 /// Creates an iterator which uses a closure to determine if a value should be removed.
254 /// If the closure returns true, then the value is removed and yielded.
255 /// If the closure returns false, the value will remain in the list and will not be yielded
258 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
259 /// values will still be subjected to the closure and removed and dropped if it returns true.
261 /// It is unspecified how many more values will be subjected to the closure
262 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
263 /// `DrainFilter` itself is leaked.
267 /// Splitting a set into even and odd values, reusing the original set:
270 /// #![feature(hash_drain_filter)]
271 /// use std::collections::HashSet;
273 /// let mut set: HashSet<i32> = (0..8).collect();
274 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
276 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
277 /// let mut odds = set.into_iter().collect::<Vec<_>>();
281 /// assert_eq!(evens, vec![0, 2, 4, 6]);
282 /// assert_eq!(odds, vec![1, 3, 5, 7]);
285 #[unstable(feature = "hash_drain_filter", issue = "59618")]
286 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
288 F: FnMut(&T) -> bool,
290 DrainFilter { base: self.base.drain_filter(pred) }
293 /// Clears the set, removing all values.
298 /// use std::collections::HashSet;
300 /// let mut v = HashSet::new();
303 /// assert!(v.is_empty());
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn clear(&mut self) {
311 /// Creates a new empty hash set which will use the given hasher to hash
314 /// The hash set is also created with the default initial capacity.
316 /// Warning: `hasher` is normally randomly generated, and
317 /// is designed to allow `HashSet`s to be resistant to attacks that
318 /// cause many collisions and very poor performance. Setting it
319 /// manually using this function can expose a DoS attack vector.
321 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
322 /// the HashMap to be useful, see its documentation for details.
327 /// use std::collections::HashSet;
328 /// use std::collections::hash_map::RandomState;
330 /// let s = RandomState::new();
331 /// let mut set = HashSet::with_hasher(s);
335 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
336 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
337 HashSet { base: base::HashSet::with_hasher(hasher) }
340 /// Creates an empty `HashSet` with the specified capacity, using
341 /// `hasher` to hash the keys.
343 /// The hash set will be able to hold at least `capacity` elements without
344 /// reallocating. If `capacity` is 0, the hash set will not allocate.
346 /// Warning: `hasher` is normally randomly generated, and
347 /// is designed to allow `HashSet`s to be resistant to attacks that
348 /// cause many collisions and very poor performance. Setting it
349 /// manually using this function can expose a DoS attack vector.
351 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
352 /// the HashMap to be useful, see its documentation for details.
357 /// use std::collections::HashSet;
358 /// use std::collections::hash_map::RandomState;
360 /// let s = RandomState::new();
361 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
365 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
366 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
367 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
370 /// Returns a reference to the set's [`BuildHasher`].
375 /// use std::collections::HashSet;
376 /// use std::collections::hash_map::RandomState;
378 /// let hasher = RandomState::new();
379 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
380 /// let hasher: &RandomState = set.hasher();
383 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
384 pub fn hasher(&self) -> &S {
389 impl<T, S> HashSet<T, S>
394 /// Reserves capacity for at least `additional` more elements to be inserted
395 /// in the `HashSet`. The collection may reserve more space to avoid
396 /// frequent reallocations.
400 /// Panics if the new allocation size overflows `usize`.
405 /// use std::collections::HashSet;
406 /// let mut set: HashSet<i32> = HashSet::new();
408 /// assert!(set.capacity() >= 10);
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn reserve(&mut self, additional: usize) {
413 self.base.reserve(additional)
416 /// Tries to reserve capacity for at least `additional` more elements to be inserted
417 /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
418 /// frequent reallocations.
422 /// If the capacity overflows, or the allocator reports a failure, then an error
428 /// #![feature(try_reserve)]
429 /// use std::collections::HashSet;
430 /// let mut set: HashSet<i32> = HashSet::new();
431 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
434 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
435 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
436 self.base.try_reserve(additional).map_err(map_try_reserve_error)
439 /// Shrinks the capacity of the set as much as possible. It will drop
440 /// down as much as possible while maintaining the internal rules
441 /// and possibly leaving some space in accordance with the resize policy.
446 /// use std::collections::HashSet;
448 /// let mut set = HashSet::with_capacity(100);
451 /// assert!(set.capacity() >= 100);
452 /// set.shrink_to_fit();
453 /// assert!(set.capacity() >= 2);
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn shrink_to_fit(&mut self) {
458 self.base.shrink_to_fit()
461 /// Shrinks the capacity of the set with a lower limit. It will drop
462 /// down no lower than the supplied limit while maintaining the internal rules
463 /// and possibly leaving some space in accordance with the resize policy.
465 /// If the current capacity is less than the lower limit, this is a no-op.
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);
877 #[doc(alias = "delete")]
879 #[stable(feature = "rust1", since = "1.0.0")]
880 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
885 self.base.remove(value)
888 /// Removes and returns the value in the set, if any, that is equal to the given one.
890 /// The value may be any borrowed form of the set's value type, but
891 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
897 /// use std::collections::HashSet;
899 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
900 /// assert_eq!(set.take(&2), Some(2));
901 /// assert_eq!(set.take(&2), None);
904 #[stable(feature = "set_recovery", since = "1.9.0")]
905 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
910 self.base.take(value)
913 /// Retains only the elements specified by the predicate.
915 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
920 /// use std::collections::HashSet;
922 /// let xs = [1, 2, 3, 4, 5, 6];
923 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
924 /// set.retain(|&k| k % 2 == 0);
925 /// assert_eq!(set.len(), 3);
927 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
928 pub fn retain<F>(&mut self, f: F)
930 F: FnMut(&T) -> bool,
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<T, S> Clone for HashSet<T, S>
943 fn clone(&self) -> Self {
944 Self { base: self.base.clone() }
948 fn clone_from(&mut self, other: &Self) {
949 self.base.clone_from(&other.base);
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<T, S> PartialEq for HashSet<T, S>
959 fn eq(&self, other: &HashSet<T, S>) -> bool {
960 if self.len() != other.len() {
964 self.iter().all(|key| other.contains(key))
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<T, S> Eq for HashSet<T, S>
976 #[stable(feature = "rust1", since = "1.0.0")]
977 impl<T, S> fmt::Debug for HashSet<T, S>
981 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982 f.debug_set().entries(self.iter()).finish()
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<T, S> FromIterator<T> for HashSet<T, S>
990 S: BuildHasher + Default,
993 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
994 let mut set = HashSet::with_hasher(Default::default());
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 impl<T, S> Extend<T> for HashSet<T, S>
1007 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1008 self.base.extend(iter);
1012 fn extend_one(&mut self, item: T) {
1013 self.base.insert(item);
1017 fn extend_reserve(&mut self, additional: usize) {
1018 self.base.extend_reserve(additional);
1022 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1023 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1025 T: 'a + Eq + Hash + Copy,
1029 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1030 self.extend(iter.into_iter().cloned());
1034 fn extend_one(&mut self, &item: &'a T) {
1035 self.base.insert(item);
1039 fn extend_reserve(&mut self, additional: usize) {
1040 Extend::<T>::extend_reserve(self, additional)
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 impl<T, S> Default for HashSet<T, S>
1049 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1051 fn default() -> HashSet<T, S> {
1052 HashSet { base: Default::default() }
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1059 T: Eq + Hash + Clone,
1060 S: BuildHasher + Default,
1062 type Output = HashSet<T, S>;
1064 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1069 /// use std::collections::HashSet;
1071 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1072 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1074 /// let set = &a | &b;
1077 /// let expected = [1, 2, 3, 4, 5];
1079 /// assert!(expected.contains(x));
1082 /// assert_eq!(i, expected.len());
1084 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1085 self.union(rhs).cloned().collect()
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1092 T: Eq + Hash + Clone,
1093 S: BuildHasher + Default,
1095 type Output = HashSet<T, S>;
1097 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1102 /// use std::collections::HashSet;
1104 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1105 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1107 /// let set = &a & &b;
1110 /// let expected = [2, 3];
1112 /// assert!(expected.contains(x));
1115 /// assert_eq!(i, expected.len());
1117 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1118 self.intersection(rhs).cloned().collect()
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1125 T: Eq + Hash + Clone,
1126 S: BuildHasher + Default,
1128 type Output = HashSet<T, S>;
1130 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1135 /// use std::collections::HashSet;
1137 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1138 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1140 /// let set = &a ^ &b;
1143 /// let expected = [1, 2, 4, 5];
1145 /// assert!(expected.contains(x));
1148 /// assert_eq!(i, expected.len());
1150 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1151 self.symmetric_difference(rhs).cloned().collect()
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1158 T: Eq + Hash + Clone,
1159 S: BuildHasher + Default,
1161 type Output = HashSet<T, S>;
1163 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1168 /// use std::collections::HashSet;
1170 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1171 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1173 /// let set = &a - &b;
1176 /// let expected = [1, 2];
1178 /// assert!(expected.contains(x));
1181 /// assert_eq!(i, expected.len());
1183 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1184 self.difference(rhs).cloned().collect()
1188 /// An iterator over the items of a `HashSet`.
1190 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1191 /// See its documentation for more.
1193 /// [`iter`]: HashSet::iter
1198 /// use std::collections::HashSet;
1200 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1202 /// let mut iter = a.iter();
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub struct Iter<'a, K: 'a> {
1206 base: base::Iter<'a, K>,
1209 /// An owning iterator over the items of a `HashSet`.
1211 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1212 /// (provided by the `IntoIterator` trait). See its documentation for more.
1214 /// [`into_iter`]: IntoIterator::into_iter
1219 /// use std::collections::HashSet;
1221 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1223 /// let mut iter = a.into_iter();
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub struct IntoIter<K> {
1227 base: base::IntoIter<K>,
1230 /// A draining iterator over the items of a `HashSet`.
1232 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1233 /// See its documentation for more.
1235 /// [`drain`]: HashSet::drain
1240 /// use std::collections::HashSet;
1242 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1244 /// let mut drain = a.drain();
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 pub struct Drain<'a, K: 'a> {
1248 base: base::Drain<'a, K>,
1251 /// A draining, filtering iterator over the items of a `HashSet`.
1253 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1255 /// [`drain_filter`]: HashSet::drain_filter
1260 /// #![feature(hash_drain_filter)]
1262 /// use std::collections::HashSet;
1264 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1266 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1268 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1269 pub struct DrainFilter<'a, K, F>
1271 F: FnMut(&K) -> bool,
1273 base: base::DrainFilter<'a, K, F>,
1276 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1278 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1279 /// See its documentation for more.
1281 /// [`intersection`]: HashSet::intersection
1286 /// use std::collections::HashSet;
1288 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1289 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1291 /// let mut intersection = a.intersection(&b);
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 pub struct Intersection<'a, T: 'a, S: 'a> {
1295 // iterator of the first set
1298 other: &'a HashSet<T, S>,
1301 /// A lazy iterator producing elements in the difference of `HashSet`s.
1303 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1304 /// See its documentation for more.
1306 /// [`difference`]: HashSet::difference
1311 /// use std::collections::HashSet;
1313 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1314 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1316 /// let mut difference = a.difference(&b);
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub struct Difference<'a, T: 'a, S: 'a> {
1320 // iterator of the first set
1323 other: &'a HashSet<T, S>,
1326 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1328 /// This `struct` is created by the [`symmetric_difference`] method on
1329 /// [`HashSet`]. See its documentation for more.
1331 /// [`symmetric_difference`]: HashSet::symmetric_difference
1336 /// use std::collections::HashSet;
1338 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1339 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1341 /// let mut intersection = a.symmetric_difference(&b);
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1345 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1348 /// A lazy iterator producing elements in the union of `HashSet`s.
1350 /// This `struct` is created by the [`union`] method on [`HashSet`].
1351 /// See its documentation for more.
1353 /// [`union`]: HashSet::union
1358 /// use std::collections::HashSet;
1360 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1361 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1363 /// let mut union_iter = a.union(&b);
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub struct Union<'a, T: 'a, S: 'a> {
1367 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1373 type IntoIter = Iter<'a, T>;
1376 fn into_iter(self) -> Iter<'a, T> {
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<T, S> IntoIterator for HashSet<T, S> {
1384 type IntoIter = IntoIter<T>;
1386 /// Creates a consuming iterator, that is, one that moves each value out
1387 /// of the set in arbitrary order. The set cannot be used after calling
1393 /// use std::collections::HashSet;
1394 /// let mut set = HashSet::new();
1395 /// set.insert("a".to_string());
1396 /// set.insert("b".to_string());
1398 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1399 /// let v: Vec<String> = set.into_iter().collect();
1401 /// // Will print in an arbitrary order.
1403 /// println!("{}", x);
1407 fn into_iter(self) -> IntoIter<T> {
1408 IntoIter { base: self.base.into_iter() }
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 impl<K> Clone for Iter<'_, K> {
1415 fn clone(&self) -> Self {
1416 Iter { base: self.base.clone() }
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<'a, K> Iterator for Iter<'a, K> {
1424 fn next(&mut self) -> Option<&'a K> {
1428 fn size_hint(&self) -> (usize, Option<usize>) {
1429 self.base.size_hint()
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<K> ExactSizeIterator for Iter<'_, K> {
1435 fn len(&self) -> usize {
1439 #[stable(feature = "fused", since = "1.26.0")]
1440 impl<K> FusedIterator for Iter<'_, K> {}
1442 #[stable(feature = "std_debug", since = "1.16.0")]
1443 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1445 f.debug_list().entries(self.clone()).finish()
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 impl<K> Iterator for IntoIter<K> {
1454 fn next(&mut self) -> Option<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 IntoIter<K> {
1465 fn len(&self) -> usize {
1469 #[stable(feature = "fused", since = "1.26.0")]
1470 impl<K> FusedIterator for IntoIter<K> {}
1472 #[stable(feature = "std_debug", since = "1.16.0")]
1473 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 fmt::Debug::fmt(&self.base, f)
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<'a, K> Iterator for Drain<'a, 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 Drain<'_, K> {
1495 fn len(&self) -> usize {
1499 #[stable(feature = "fused", since = "1.26.0")]
1500 impl<K> FusedIterator for Drain<'_, K> {}
1502 #[stable(feature = "std_debug", since = "1.16.0")]
1503 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1505 fmt::Debug::fmt(&self.base, f)
1509 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1510 impl<K, F> Iterator for DrainFilter<'_, K, F>
1512 F: FnMut(&K) -> bool,
1517 fn next(&mut self) -> Option<K> {
1521 fn size_hint(&self) -> (usize, Option<usize>) {
1522 self.base.size_hint()
1526 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1527 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1529 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1530 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1532 F: FnMut(&K) -> bool,
1534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535 f.pad("DrainFilter { .. }")
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<T, S> Clone for Intersection<'_, T, S> {
1542 fn clone(&self) -> Self {
1543 Intersection { iter: self.iter.clone(), ..*self }
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1556 fn next(&mut self) -> Option<&'a T> {
1558 let elt = self.iter.next()?;
1559 if self.other.contains(elt) {
1566 fn size_hint(&self) -> (usize, Option<usize>) {
1567 let (_, upper) = self.iter.size_hint();
1572 #[stable(feature = "std_debug", since = "1.16.0")]
1573 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1575 T: fmt::Debug + Eq + Hash,
1578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1579 f.debug_list().entries(self.clone()).finish()
1583 #[stable(feature = "fused", since = "1.26.0")]
1584 impl<T, S> FusedIterator for Intersection<'_, T, S>
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<T, S> Clone for Difference<'_, T, S> {
1594 fn clone(&self) -> Self {
1595 Difference { iter: self.iter.clone(), ..*self }
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<'a, T, S> Iterator for Difference<'a, T, S>
1608 fn next(&mut self) -> Option<&'a T> {
1610 let elt = self.iter.next()?;
1611 if !self.other.contains(elt) {
1618 fn size_hint(&self) -> (usize, Option<usize>) {
1619 let (_, upper) = self.iter.size_hint();
1624 #[stable(feature = "fused", since = "1.26.0")]
1625 impl<T, S> FusedIterator for Difference<'_, T, S>
1632 #[stable(feature = "std_debug", since = "1.16.0")]
1633 impl<T, S> fmt::Debug for Difference<'_, T, S>
1635 T: fmt::Debug + Eq + Hash,
1638 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1639 f.debug_list().entries(self.clone()).finish()
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1646 fn clone(&self) -> Self {
1647 SymmetricDifference { iter: self.iter.clone() }
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1660 fn next(&mut self) -> Option<&'a T> {
1664 fn size_hint(&self) -> (usize, Option<usize>) {
1665 self.iter.size_hint()
1669 #[stable(feature = "fused", since = "1.26.0")]
1670 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1677 #[stable(feature = "std_debug", since = "1.16.0")]
1678 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1680 T: fmt::Debug + Eq + Hash,
1683 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1684 f.debug_list().entries(self.clone()).finish()
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<T, S> Clone for Union<'_, T, S> {
1691 fn clone(&self) -> Self {
1692 Union { iter: self.iter.clone() }
1696 #[stable(feature = "fused", since = "1.26.0")]
1697 impl<T, S> FusedIterator for Union<'_, T, S>
1704 #[stable(feature = "std_debug", since = "1.16.0")]
1705 impl<T, S> fmt::Debug for Union<'_, T, S>
1707 T: fmt::Debug + Eq + Hash,
1710 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1711 f.debug_list().entries(self.clone()).finish()
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<'a, T, S> Iterator for Union<'a, T, S>
1724 fn next(&mut self) -> Option<&'a T> {
1728 fn size_hint(&self) -> (usize, Option<usize>) {
1729 self.iter.size_hint()
1734 fn assert_covariance() {
1735 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1738 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1741 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1744 fn difference<'a, 'new>(
1745 v: Difference<'a, &'static str, RandomState>,
1746 ) -> Difference<'a, &'new str, RandomState> {
1749 fn symmetric_difference<'a, 'new>(
1750 v: SymmetricDifference<'a, &'static str, RandomState>,
1751 ) -> SymmetricDifference<'a, &'new str, RandomState> {
1754 fn intersection<'a, 'new>(
1755 v: Intersection<'a, &'static str, RandomState>,
1756 ) -> Intersection<'a, &'new str, RandomState> {
1760 v: Union<'a, &'static str, RandomState>,
1761 ) -> Union<'a, &'new str, RandomState> {
1764 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {