1 use crate::CollectionAllocErr
;
2 use core
::borrow
::Borrow
;
4 use core
::hash
::{BuildHasher, Hash}
;
5 use core
::iter
::{Chain, FromIterator, FusedIterator}
;
6 use core
::ops
::{BitAnd, BitOr, BitXor, Sub}
;
8 use super::map
::{self, DefaultHashBuilder, HashMap, Keys}
;
10 // Future Optimization (FIXME!)
11 // =============================
13 // Iteration over zero sized values is a noop. There is no need
14 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
15 // to get rid of it properly.
17 /// A hash set implemented as a `HashMap` where the value is `()`.
19 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
20 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
21 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
22 /// it is important that the following property holds:
25 /// k1 == k2 -> hash(k1) == hash(k2)
28 /// In other words, if two keys are equal, their hashes must be equal.
31 /// It is a logic error for an item to be modified in such a way that the
32 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
33 /// determined by the [`Eq`] trait, changes while it is in the set. This is
34 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
37 /// It is also a logic error for the [`Hash`] implementation of a key to panic.
38 /// This is generally only possible if the trait is implemented manually. If a
39 /// panic does occur then the contents of the `HashSet` may become corrupted and
40 /// some items may be dropped from the table.
45 /// use hashbrown::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 hashbrown::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 hashbrown::HashSet;
102 /// let viking_names: HashSet<&'static str> =
103 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
104 /// // use the values stored in the set
108 /// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
109 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
110 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
111 /// [`HashMap`]: struct.HashMap.html
112 /// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
113 /// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
115 pub struct HashSet
<T
, S
= DefaultHashBuilder
> {
116 pub(crate) map
: HashMap
<T
, (), S
>,
119 impl<T
: Hash
+ Eq
> HashSet
<T
, DefaultHashBuilder
> {
120 /// Creates an empty `HashSet`.
122 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
123 /// is first inserted into.
128 /// use hashbrown::HashSet;
129 /// let set: HashSet<i32> = HashSet::new();
132 pub fn new() -> Self {
138 /// Creates an empty `HashSet` with the specified capacity.
140 /// The hash set will be able to hold at least `capacity` elements without
141 /// reallocating. If `capacity` is 0, the hash set will not allocate.
146 /// use hashbrown::HashSet;
147 /// let set: HashSet<i32> = HashSet::with_capacity(10);
148 /// assert!(set.capacity() >= 10);
151 pub fn with_capacity(capacity
: usize) -> Self {
153 map
: HashMap
::with_capacity(capacity
),
158 impl<T
, S
> HashSet
<T
, S
> {
159 /// Returns the number of elements the set can hold without reallocating.
164 /// use hashbrown::HashSet;
165 /// let set: HashSet<i32> = HashSet::with_capacity(100);
166 /// assert!(set.capacity() >= 100);
169 pub fn capacity(&self) -> usize {
173 /// An iterator visiting all elements in arbitrary order.
174 /// The iterator element type is `&'a T`.
179 /// use hashbrown::HashSet;
180 /// let mut set = HashSet::new();
184 /// // Will print in an arbitrary order.
185 /// for x in set.iter() {
186 /// println!("{}", x);
190 pub fn iter(&self) -> Iter
<'_
, T
> {
192 iter
: self.map
.keys(),
196 /// Returns the number of elements in the set.
201 /// use hashbrown::HashSet;
203 /// let mut v = HashSet::new();
204 /// assert_eq!(v.len(), 0);
206 /// assert_eq!(v.len(), 1);
209 pub fn len(&self) -> usize {
213 /// Returns `true` if the set contains no elements.
218 /// use hashbrown::HashSet;
220 /// let mut v = HashSet::new();
221 /// assert!(v.is_empty());
223 /// assert!(!v.is_empty());
226 pub fn is_empty(&self) -> bool
{
230 /// Clears the set, returning all elements in an iterator.
235 /// use hashbrown::HashSet;
237 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
238 /// assert!(!set.is_empty());
240 /// // print 1, 2, 3 in an arbitrary order
241 /// for i in set.drain() {
242 /// println!("{}", i);
245 /// assert!(set.is_empty());
248 pub fn drain(&mut self) -> Drain
<'_
, T
> {
250 iter
: self.map
.drain(),
254 /// Clears the set, removing all values.
259 /// use hashbrown::HashSet;
261 /// let mut v = HashSet::new();
264 /// assert!(v.is_empty());
267 pub fn clear(&mut self) {
272 impl<T
, S
> HashSet
<T
, S
>
277 /// Creates a new empty hash set which will use the given hasher to hash
280 /// The hash set is also created with the default initial capacity.
282 /// Warning: `hasher` is normally randomly generated, and
283 /// is designed to allow `HashSet`s to be resistant to attacks that
284 /// cause many collisions and very poor performance. Setting it
285 /// manually using this function can expose a DoS attack vector.
290 /// use hashbrown::HashSet;
291 /// use hashbrown::hash_map::DefaultHashBuilder;
293 /// let s = DefaultHashBuilder::default();
294 /// let mut set = HashSet::with_hasher(s);
298 pub fn with_hasher(hasher
: S
) -> Self {
300 map
: HashMap
::with_hasher(hasher
),
304 /// Creates an empty `HashSet` with the specified capacity, using
305 /// `hasher` to hash the keys.
307 /// The hash set will be able to hold at least `capacity` elements without
308 /// reallocating. If `capacity` is 0, the hash set will not allocate.
310 /// Warning: `hasher` is normally randomly generated, and
311 /// is designed to allow `HashSet`s to be resistant to attacks that
312 /// cause many collisions and very poor performance. Setting it
313 /// manually using this function can expose a DoS attack vector.
318 /// use hashbrown::HashSet;
319 /// use hashbrown::hash_map::DefaultHashBuilder;
321 /// let s = DefaultHashBuilder::default();
322 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
326 pub fn with_capacity_and_hasher(capacity
: usize, hasher
: S
) -> Self {
328 map
: HashMap
::with_capacity_and_hasher(capacity
, hasher
),
332 /// Returns a reference to the set's [`BuildHasher`].
334 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
339 /// use hashbrown::HashSet;
340 /// use hashbrown::hash_map::DefaultHashBuilder;
342 /// let hasher = DefaultHashBuilder::default();
343 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
344 /// let hasher: &DefaultHashBuilder = set.hasher();
347 pub fn hasher(&self) -> &S
{
351 /// Reserves capacity for at least `additional` more elements to be inserted
352 /// in the `HashSet`. The collection may reserve more space to avoid
353 /// frequent reallocations.
357 /// Panics if the new allocation size overflows `usize`.
362 /// use hashbrown::HashSet;
363 /// let mut set: HashSet<i32> = HashSet::new();
365 /// assert!(set.capacity() >= 10);
368 pub fn reserve(&mut self, additional
: usize) {
369 self.map
.reserve(additional
)
372 /// Tries to reserve capacity for at least `additional` more elements to be inserted
373 /// in the given `HashSet<K,V>`. The collection may reserve more space to avoid
374 /// frequent reallocations.
378 /// If the capacity overflows, or the allocator reports a failure, then an error
384 /// use hashbrown::HashSet;
385 /// let mut set: HashSet<i32> = HashSet::new();
386 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
389 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), CollectionAllocErr
> {
390 self.map
.try_reserve(additional
)
393 /// Shrinks the capacity of the set as much as possible. It will drop
394 /// down as much as possible while maintaining the internal rules
395 /// and possibly leaving some space in accordance with the resize policy.
400 /// use hashbrown::HashSet;
402 /// let mut set = HashSet::with_capacity(100);
405 /// assert!(set.capacity() >= 100);
406 /// set.shrink_to_fit();
407 /// assert!(set.capacity() >= 2);
410 pub fn shrink_to_fit(&mut self) {
411 self.map
.shrink_to_fit()
414 /// Shrinks the capacity of the set with a lower limit. It will drop
415 /// down no lower than the supplied limit while maintaining the internal rules
416 /// and possibly leaving some space in accordance with the resize policy.
418 /// Panics if the current capacity is smaller than the supplied
419 /// minimum capacity.
424 /// use hashbrown::HashSet;
426 /// let mut set = HashSet::with_capacity(100);
429 /// assert!(set.capacity() >= 100);
430 /// set.shrink_to(10);
431 /// assert!(set.capacity() >= 10);
432 /// set.shrink_to(0);
433 /// assert!(set.capacity() >= 2);
436 pub fn shrink_to(&mut self, min_capacity
: usize) {
437 self.map
.shrink_to(min_capacity
)
440 /// Visits the values representing the difference,
441 /// i.e., the values that are in `self` but not in `other`.
446 /// use hashbrown::HashSet;
447 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
448 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
450 /// // Can be seen as `a - b`.
451 /// for x in a.difference(&b) {
452 /// println!("{}", x); // Print 1
455 /// let diff: HashSet<_> = a.difference(&b).collect();
456 /// assert_eq!(diff, [1].iter().collect());
458 /// // Note that difference is not symmetric,
459 /// // and `b - a` means something else:
460 /// let diff: HashSet<_> = b.difference(&a).collect();
461 /// assert_eq!(diff, [4].iter().collect());
464 pub fn difference
<'a
>(&'a
self, other
: &'a
Self) -> Difference
<'a
, T
, S
> {
471 /// Visits the values representing the symmetric difference,
472 /// i.e., the values that are in `self` or in `other` but not in both.
477 /// use hashbrown::HashSet;
478 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
479 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
481 /// // Print 1, 4 in arbitrary order.
482 /// for x in a.symmetric_difference(&b) {
483 /// println!("{}", x);
486 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
487 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
489 /// assert_eq!(diff1, diff2);
490 /// assert_eq!(diff1, [1, 4].iter().collect());
493 pub fn symmetric_difference
<'a
>(&'a
self, other
: &'a
Self) -> SymmetricDifference
<'a
, T
, S
> {
494 SymmetricDifference
{
495 iter
: self.difference(other
).chain(other
.difference(self)),
499 /// Visits the values representing the intersection,
500 /// i.e., the values that are both in `self` and `other`.
505 /// use hashbrown::HashSet;
506 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
507 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
509 /// // Print 2, 3 in arbitrary order.
510 /// for x in a.intersection(&b) {
511 /// println!("{}", x);
514 /// let intersection: HashSet<_> = a.intersection(&b).collect();
515 /// assert_eq!(intersection, [2, 3].iter().collect());
518 pub fn intersection
<'a
>(&'a
self, other
: &'a
Self) -> Intersection
<'a
, T
, S
> {
525 /// Visits the values representing the union,
526 /// i.e., all the values in `self` or `other`, without duplicates.
531 /// use hashbrown::HashSet;
532 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
533 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
535 /// // Print 1, 2, 3, 4 in arbitrary order.
536 /// for x in a.union(&b) {
537 /// println!("{}", x);
540 /// let union: HashSet<_> = a.union(&b).collect();
541 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
544 pub fn union<'a
>(&'a
self, other
: &'a
Self) -> Union
<'a
, T
, S
> {
546 iter
: self.iter().chain(other
.difference(self)),
550 /// Returns `true` if the set contains a value.
552 /// The value may be any borrowed form of the set's value type, but
553 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
559 /// use hashbrown::HashSet;
561 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
562 /// assert_eq!(set.contains(&1), true);
563 /// assert_eq!(set.contains(&4), false);
566 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
567 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
569 pub fn contains
<Q
: ?Sized
>(&self, value
: &Q
) -> bool
574 self.map
.contains_key(value
)
577 /// Returns a reference to the value in the set, if any, that is equal to the given value.
579 /// The value may be any borrowed form of the set's value type, but
580 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
586 /// use hashbrown::HashSet;
588 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
589 /// assert_eq!(set.get(&2), Some(&2));
590 /// assert_eq!(set.get(&4), None);
593 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
594 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
596 pub fn get
<Q
: ?Sized
>(&self, value
: &Q
) -> Option
<&T
>
601 self.map
.get_key_value(value
).map(|(k
, _
)| k
)
604 /// Returns `true` if `self` has no elements in common with `other`.
605 /// This is equivalent to checking for an empty intersection.
610 /// use hashbrown::HashSet;
612 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
613 /// let mut b = HashSet::new();
615 /// assert_eq!(a.is_disjoint(&b), true);
617 /// assert_eq!(a.is_disjoint(&b), true);
619 /// assert_eq!(a.is_disjoint(&b), false);
621 pub fn is_disjoint(&self, other
: &Self) -> bool
{
622 self.iter().all(|v
| !other
.contains(v
))
625 /// Returns `true` if the set is a subset of another,
626 /// i.e., `other` contains at least all the values in `self`.
631 /// use hashbrown::HashSet;
633 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
634 /// let mut set = HashSet::new();
636 /// assert_eq!(set.is_subset(&sup), true);
638 /// assert_eq!(set.is_subset(&sup), true);
640 /// assert_eq!(set.is_subset(&sup), false);
642 pub fn is_subset(&self, other
: &Self) -> bool
{
643 if self.len() <= other
.len() {
644 self.iter().all(|v
| other
.contains(v
))
650 /// Returns `true` if the set is a superset of another,
651 /// i.e., `self` contains at least all the values in `other`.
656 /// use hashbrown::HashSet;
658 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
659 /// let mut set = HashSet::new();
661 /// assert_eq!(set.is_superset(&sub), false);
665 /// assert_eq!(set.is_superset(&sub), false);
668 /// assert_eq!(set.is_superset(&sub), true);
671 pub fn is_superset(&self, other
: &Self) -> bool
{
672 other
.is_subset(self)
675 /// Adds a value to the set.
677 /// If the set did not have this value present, `true` is returned.
679 /// If the set did have this value present, `false` is returned.
684 /// use hashbrown::HashSet;
686 /// let mut set = HashSet::new();
688 /// assert_eq!(set.insert(2), true);
689 /// assert_eq!(set.insert(2), false);
690 /// assert_eq!(set.len(), 1);
693 pub fn insert(&mut self, value
: T
) -> bool
{
694 self.map
.insert(value
, ()).is_none()
697 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
698 /// one. Returns the replaced value.
703 /// use hashbrown::HashSet;
705 /// let mut set = HashSet::new();
706 /// set.insert(Vec::<i32>::new());
708 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
709 /// set.replace(Vec::with_capacity(10));
710 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
713 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
714 match self.map
.entry(value
) {
715 map
::Entry
::Occupied(occupied
) => Some(occupied
.replace_key()),
716 map
::Entry
::Vacant(vacant
) => {
723 /// Removes a value from the set. Returns whether the value was
724 /// present in the set.
726 /// The value may be any borrowed form of the set's value type, but
727 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
733 /// use hashbrown::HashSet;
735 /// let mut set = HashSet::new();
738 /// assert_eq!(set.remove(&2), true);
739 /// assert_eq!(set.remove(&2), false);
742 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
743 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
745 pub fn remove
<Q
: ?Sized
>(&mut self, value
: &Q
) -> bool
750 self.map
.remove(value
).is_some()
753 /// Removes and returns the value in the set, if any, that is equal to the given one.
755 /// The value may be any borrowed form of the set's value type, but
756 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
762 /// use hashbrown::HashSet;
764 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
765 /// assert_eq!(set.take(&2), Some(2));
766 /// assert_eq!(set.take(&2), None);
769 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
770 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
772 pub fn take
<Q
: ?Sized
>(&mut self, value
: &Q
) -> Option
<T
>
777 self.map
.remove_entry(value
).map(|(k
, _
)| k
)
780 /// Retains only the elements specified by the predicate.
782 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
787 /// use hashbrown::HashSet;
789 /// let xs = [1,2,3,4,5,6];
790 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
791 /// set.retain(|&k| k % 2 == 0);
792 /// assert_eq!(set.len(), 3);
794 pub fn retain
<F
>(&mut self, mut f
: F
)
796 F
: FnMut(&T
) -> bool
,
798 self.map
.retain(|k
, _
| f(k
));
802 impl<T
, S
> PartialEq
for HashSet
<T
, S
>
807 fn eq(&self, other
: &Self) -> bool
{
808 if self.len() != other
.len() {
812 self.iter().all(|key
| other
.contains(key
))
816 impl<T
, S
> Eq
for HashSet
<T
, S
>
823 impl<T
, S
> fmt
::Debug
for HashSet
<T
, S
>
825 T
: Eq
+ Hash
+ fmt
::Debug
,
828 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
829 f
.debug_set().entries(self.iter()).finish()
833 impl<T
, S
> FromIterator
<T
> for HashSet
<T
, S
>
836 S
: BuildHasher
+ Default
,
839 fn from_iter
<I
: IntoIterator
<Item
= T
>>(iter
: I
) -> Self {
840 let mut set
= Self::with_hasher(Default
::default());
846 impl<T
, S
> Extend
<T
> for HashSet
<T
, S
>
852 fn extend
<I
: IntoIterator
<Item
= T
>>(&mut self, iter
: I
) {
853 self.map
.extend(iter
.into_iter().map(|k
| (k
, ())));
857 impl<'a
, T
, S
> Extend
<&'a T
> for HashSet
<T
, S
>
859 T
: 'a
+ Eq
+ Hash
+ Copy
,
863 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
864 self.extend(iter
.into_iter().cloned());
868 impl<T
, S
> Default
for HashSet
<T
, S
>
871 S
: BuildHasher
+ Default
,
873 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
875 fn default() -> Self {
877 map
: HashMap
::default(),
882 impl<T
, S
> BitOr
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
884 T
: Eq
+ Hash
+ Clone
,
885 S
: BuildHasher
+ Default
,
887 type Output
= HashSet
<T
, S
>;
889 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
894 /// use hashbrown::HashSet;
896 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
897 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
899 /// let set = &a | &b;
902 /// let expected = [1, 2, 3, 4, 5];
904 /// assert!(expected.contains(x));
907 /// assert_eq!(i, expected.len());
909 fn bitor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
910 self.union(rhs
).cloned().collect()
914 impl<T
, S
> BitAnd
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
916 T
: Eq
+ Hash
+ Clone
,
917 S
: BuildHasher
+ Default
,
919 type Output
= HashSet
<T
, S
>;
921 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
926 /// use hashbrown::HashSet;
928 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
929 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
931 /// let set = &a & &b;
934 /// let expected = [2, 3];
936 /// assert!(expected.contains(x));
939 /// assert_eq!(i, expected.len());
941 fn bitand(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
942 self.intersection(rhs
).cloned().collect()
946 impl<T
, S
> BitXor
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
948 T
: Eq
+ Hash
+ Clone
,
949 S
: BuildHasher
+ Default
,
951 type Output
= HashSet
<T
, S
>;
953 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
958 /// use hashbrown::HashSet;
960 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
961 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
963 /// let set = &a ^ &b;
966 /// let expected = [1, 2, 4, 5];
968 /// assert!(expected.contains(x));
971 /// assert_eq!(i, expected.len());
973 fn bitxor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
974 self.symmetric_difference(rhs
).cloned().collect()
978 impl<T
, S
> Sub
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
980 T
: Eq
+ Hash
+ Clone
,
981 S
: BuildHasher
+ Default
,
983 type Output
= HashSet
<T
, S
>;
985 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
990 /// use hashbrown::HashSet;
992 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
993 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
995 /// let set = &a - &b;
998 /// let expected = [1, 2];
1000 /// assert!(expected.contains(x));
1003 /// assert_eq!(i, expected.len());
1005 fn sub(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1006 self.difference(rhs
).cloned().collect()
1010 /// An iterator over the items of a `HashSet`.
1012 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1013 /// See its documentation for more.
1015 /// [`HashSet`]: struct.HashSet.html
1016 /// [`iter`]: struct.HashSet.html#method.iter
1017 pub struct Iter
<'a
, K
> {
1018 iter
: Keys
<'a
, K
, ()>,
1021 /// An owning iterator over the items of a `HashSet`.
1023 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
1024 /// (provided by the `IntoIterator` trait). See its documentation for more.
1026 /// [`HashSet`]: struct.HashSet.html
1027 /// [`into_iter`]: struct.HashSet.html#method.into_iter
1028 pub struct IntoIter
<K
> {
1029 iter
: map
::IntoIter
<K
, ()>,
1032 /// A draining iterator over the items of a `HashSet`.
1034 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1035 /// See its documentation for more.
1037 /// [`HashSet`]: struct.HashSet.html
1038 /// [`drain`]: struct.HashSet.html#method.drain
1039 pub struct Drain
<'a
, K
> {
1040 iter
: map
::Drain
<'a
, K
, ()>,
1043 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1045 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1046 /// See its documentation for more.
1048 /// [`HashSet`]: struct.HashSet.html
1049 /// [`intersection`]: struct.HashSet.html#method.intersection
1050 pub struct Intersection
<'a
, T
, S
> {
1051 // iterator of the first set
1054 other
: &'a HashSet
<T
, S
>,
1057 /// A lazy iterator producing elements in the difference of `HashSet`s.
1059 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1060 /// See its documentation for more.
1062 /// [`HashSet`]: struct.HashSet.html
1063 /// [`difference`]: struct.HashSet.html#method.difference
1064 pub struct Difference
<'a
, T
, S
> {
1065 // iterator of the first set
1068 other
: &'a HashSet
<T
, S
>,
1071 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1073 /// This `struct` is created by the [`symmetric_difference`] method on
1074 /// [`HashSet`]. See its documentation for more.
1076 /// [`HashSet`]: struct.HashSet.html
1077 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1078 pub struct SymmetricDifference
<'a
, T
, S
> {
1079 iter
: Chain
<Difference
<'a
, T
, S
>, Difference
<'a
, T
, S
>>,
1082 /// A lazy iterator producing elements in the union of `HashSet`s.
1084 /// This `struct` is created by the [`union`] method on [`HashSet`].
1085 /// See its documentation for more.
1087 /// [`HashSet`]: struct.HashSet.html
1088 /// [`union`]: struct.HashSet.html#method.union
1089 pub struct Union
<'a
, T
, S
> {
1090 iter
: Chain
<Iter
<'a
, T
>, Difference
<'a
, T
, S
>>,
1093 impl<'a
, T
, S
> IntoIterator
for &'a HashSet
<T
, S
> {
1095 type IntoIter
= Iter
<'a
, T
>;
1098 fn into_iter(self) -> Iter
<'a
, T
> {
1103 impl<T
, S
> IntoIterator
for HashSet
<T
, S
> {
1105 type IntoIter
= IntoIter
<T
>;
1107 /// Creates a consuming iterator, that is, one that moves each value out
1108 /// of the set in arbitrary order. The set cannot be used after calling
1114 /// use hashbrown::HashSet;
1115 /// let mut set = HashSet::new();
1116 /// set.insert("a".to_string());
1117 /// set.insert("b".to_string());
1119 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1120 /// let v: Vec<String> = set.into_iter().collect();
1122 /// // Will print in an arbitrary order.
1124 /// println!("{}", x);
1128 fn into_iter(self) -> IntoIter
<T
> {
1130 iter
: self.map
.into_iter(),
1135 impl<K
> Clone
for Iter
<'_
, K
> {
1137 fn clone(&self) -> Self {
1139 iter
: self.iter
.clone(),
1143 impl<'a
, K
> Iterator
for Iter
<'a
, K
> {
1147 fn next(&mut self) -> Option
<&'a K
> {
1151 fn size_hint(&self) -> (usize, Option
<usize>) {
1152 self.iter
.size_hint()
1155 impl<'a
, K
> ExactSizeIterator
for Iter
<'a
, K
> {
1157 fn len(&self) -> usize {
1161 impl<K
> FusedIterator
for Iter
<'_
, K
> {}
1163 impl<K
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, K
> {
1164 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1165 f
.debug_list().entries(self.clone()).finish()
1169 impl<K
> Iterator
for IntoIter
<K
> {
1173 fn next(&mut self) -> Option
<K
> {
1174 self.iter
.next().map(|(k
, _
)| k
)
1177 fn size_hint(&self) -> (usize, Option
<usize>) {
1178 self.iter
.size_hint()
1181 impl<K
> ExactSizeIterator
for IntoIter
<K
> {
1183 fn len(&self) -> usize {
1187 impl<K
> FusedIterator
for IntoIter
<K
> {}
1189 impl<K
: fmt
::Debug
> fmt
::Debug
for IntoIter
<K
> {
1190 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1191 let entries_iter
= self.iter
.iter().map(|(k
, _
)| k
);
1192 f
.debug_list().entries(entries_iter
).finish()
1196 impl<K
> Iterator
for Drain
<'_
, K
> {
1200 fn next(&mut self) -> Option
<K
> {
1201 self.iter
.next().map(|(k
, _
)| k
)
1204 fn size_hint(&self) -> (usize, Option
<usize>) {
1205 self.iter
.size_hint()
1208 impl<K
> ExactSizeIterator
for Drain
<'_
, K
> {
1210 fn len(&self) -> usize {
1214 impl<K
> FusedIterator
for Drain
<'_
, K
> {}
1216 impl<K
: fmt
::Debug
> fmt
::Debug
for Drain
<'_
, K
> {
1217 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1218 let entries_iter
= self.iter
.iter().map(|(k
, _
)| k
);
1219 f
.debug_list().entries(entries_iter
).finish()
1223 impl<T
, S
> Clone
for Intersection
<'_
, T
, S
> {
1225 fn clone(&self) -> Self {
1227 iter
: self.iter
.clone(),
1233 impl<'a
, T
, S
> Iterator
for Intersection
<'a
, T
, S
>
1241 fn next(&mut self) -> Option
<&'a T
> {
1243 let elt
= self.iter
.next()?
;
1244 if self.other
.contains(elt
) {
1251 fn size_hint(&self) -> (usize, Option
<usize>) {
1252 let (_
, upper
) = self.iter
.size_hint();
1257 impl<T
, S
> fmt
::Debug
for Intersection
<'_
, T
, S
>
1259 T
: fmt
::Debug
+ Eq
+ Hash
,
1262 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1263 f
.debug_list().entries(self.clone()).finish()
1267 impl<T
, S
> FusedIterator
for Intersection
<'_
, T
, S
>
1274 impl<T
, S
> Clone
for Difference
<'_
, T
, S
> {
1276 fn clone(&self) -> Self {
1278 iter
: self.iter
.clone(),
1284 impl<'a
, T
, S
> Iterator
for Difference
<'a
, T
, S
>
1292 fn next(&mut self) -> Option
<&'a T
> {
1294 let elt
= self.iter
.next()?
;
1295 if !self.other
.contains(elt
) {
1302 fn size_hint(&self) -> (usize, Option
<usize>) {
1303 let (_
, upper
) = self.iter
.size_hint();
1308 impl<T
, S
> FusedIterator
for Difference
<'_
, T
, S
>
1315 impl<T
, S
> fmt
::Debug
for Difference
<'_
, T
, S
>
1317 T
: fmt
::Debug
+ Eq
+ Hash
,
1320 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1321 f
.debug_list().entries(self.clone()).finish()
1325 impl<T
, S
> Clone
for SymmetricDifference
<'_
, T
, S
> {
1327 fn clone(&self) -> Self {
1328 SymmetricDifference
{
1329 iter
: self.iter
.clone(),
1334 impl<'a
, T
, S
> Iterator
for SymmetricDifference
<'a
, T
, S
>
1342 fn next(&mut self) -> Option
<&'a T
> {
1346 fn size_hint(&self) -> (usize, Option
<usize>) {
1347 self.iter
.size_hint()
1351 impl<T
, S
> FusedIterator
for SymmetricDifference
<'_
, T
, S
>
1358 impl<T
, S
> fmt
::Debug
for SymmetricDifference
<'_
, T
, S
>
1360 T
: fmt
::Debug
+ Eq
+ Hash
,
1363 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1364 f
.debug_list().entries(self.clone()).finish()
1368 impl<T
, S
> Clone
for Union
<'_
, T
, S
> {
1370 fn clone(&self) -> Self {
1372 iter
: self.iter
.clone(),
1377 impl<T
, S
> FusedIterator
for Union
<'_
, T
, S
>
1384 impl<T
, S
> fmt
::Debug
for Union
<'_
, T
, S
>
1386 T
: fmt
::Debug
+ Eq
+ Hash
,
1389 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1390 f
.debug_list().entries(self.clone()).finish()
1394 impl<'a
, T
, S
> Iterator
for Union
<'a
, T
, S
>
1402 fn next(&mut self) -> Option
<&'a T
> {
1406 fn size_hint(&self) -> (usize, Option
<usize>) {
1407 self.iter
.size_hint()
1412 fn assert_covariance() {
1413 fn set
<'new
>(v
: HashSet
<&'
static str>) -> HashSet
<&'new
str> {
1416 fn iter
<'a
, 'new
>(v
: Iter
<'a
, &'
static str>) -> Iter
<'a
, &'new
str> {
1419 fn into_iter
<'new
>(v
: IntoIter
<&'
static str>) -> IntoIter
<&'new
str> {
1422 fn difference
<'a
, 'new
>(
1423 v
: Difference
<'a
, &'
static str, DefaultHashBuilder
>,
1424 ) -> Difference
<'a
, &'new
str, DefaultHashBuilder
> {
1427 fn symmetric_difference
<'a
, 'new
>(
1428 v
: SymmetricDifference
<'a
, &'
static str, DefaultHashBuilder
>,
1429 ) -> SymmetricDifference
<'a
, &'new
str, DefaultHashBuilder
> {
1432 fn intersection
<'a
, 'new
>(
1433 v
: Intersection
<'a
, &'
static str, DefaultHashBuilder
>,
1434 ) -> Intersection
<'a
, &'new
str, DefaultHashBuilder
> {
1438 v
: Union
<'a
, &'
static str, DefaultHashBuilder
>,
1439 ) -> Union
<'a
, &'new
str, DefaultHashBuilder
> {
1442 fn drain
<'new
>(d
: Drain
<'
static, &'
static str>) -> Drain
<'new
, &'new
str> {
1449 use super::super::map
::DefaultHashBuilder
;
1454 fn test_zero_capacities() {
1455 type HS
= HashSet
<i32>;
1458 assert_eq
!(s
.capacity(), 0);
1460 let s
= HS
::default();
1461 assert_eq
!(s
.capacity(), 0);
1463 let s
= HS
::with_hasher(DefaultHashBuilder
::default());
1464 assert_eq
!(s
.capacity(), 0);
1466 let s
= HS
::with_capacity(0);
1467 assert_eq
!(s
.capacity(), 0);
1469 let s
= HS
::with_capacity_and_hasher(0, DefaultHashBuilder
::default());
1470 assert_eq
!(s
.capacity(), 0);
1472 let mut s
= HS
::new();
1478 assert_eq
!(s
.capacity(), 0);
1480 let mut s
= HS
::new();
1482 assert_eq
!(s
.capacity(), 0);
1486 fn test_disjoint() {
1487 let mut xs
= HashSet
::new();
1488 let mut ys
= HashSet
::new();
1489 assert
!(xs
.is_disjoint(&ys
));
1490 assert
!(ys
.is_disjoint(&xs
));
1491 assert
!(xs
.insert(5));
1492 assert
!(ys
.insert(11));
1493 assert
!(xs
.is_disjoint(&ys
));
1494 assert
!(ys
.is_disjoint(&xs
));
1495 assert
!(xs
.insert(7));
1496 assert
!(xs
.insert(19));
1497 assert
!(xs
.insert(4));
1498 assert
!(ys
.insert(2));
1499 assert
!(ys
.insert(-11));
1500 assert
!(xs
.is_disjoint(&ys
));
1501 assert
!(ys
.is_disjoint(&xs
));
1502 assert
!(ys
.insert(7));
1503 assert
!(!xs
.is_disjoint(&ys
));
1504 assert
!(!ys
.is_disjoint(&xs
));
1508 fn test_subset_and_superset() {
1509 let mut a
= HashSet
::new();
1510 assert
!(a
.insert(0));
1511 assert
!(a
.insert(5));
1512 assert
!(a
.insert(11));
1513 assert
!(a
.insert(7));
1515 let mut b
= HashSet
::new();
1516 assert
!(b
.insert(0));
1517 assert
!(b
.insert(7));
1518 assert
!(b
.insert(19));
1519 assert
!(b
.insert(250));
1520 assert
!(b
.insert(11));
1521 assert
!(b
.insert(200));
1523 assert
!(!a
.is_subset(&b
));
1524 assert
!(!a
.is_superset(&b
));
1525 assert
!(!b
.is_subset(&a
));
1526 assert
!(!b
.is_superset(&a
));
1528 assert
!(b
.insert(5));
1530 assert
!(a
.is_subset(&b
));
1531 assert
!(!a
.is_superset(&b
));
1532 assert
!(!b
.is_subset(&a
));
1533 assert
!(b
.is_superset(&a
));
1538 let mut a
= HashSet
::new();
1540 assert
!(a
.insert(i
));
1542 let mut observed
: u32 = 0;
1544 observed
|= 1 << *k
;
1546 assert_eq
!(observed
, 0xFFFF_FFFF);
1550 fn test_intersection() {
1551 let mut a
= HashSet
::new();
1552 let mut b
= HashSet
::new();
1554 assert
!(a
.insert(11));
1555 assert
!(a
.insert(1));
1556 assert
!(a
.insert(3));
1557 assert
!(a
.insert(77));
1558 assert
!(a
.insert(103));
1559 assert
!(a
.insert(5));
1560 assert
!(a
.insert(-5));
1562 assert
!(b
.insert(2));
1563 assert
!(b
.insert(11));
1564 assert
!(b
.insert(77));
1565 assert
!(b
.insert(-9));
1566 assert
!(b
.insert(-42));
1567 assert
!(b
.insert(5));
1568 assert
!(b
.insert(3));
1571 let expected
= [3, 5, 11, 77];
1572 for x
in a
.intersection(&b
) {
1573 assert
!(expected
.contains(x
));
1576 assert_eq
!(i
, expected
.len());
1580 fn test_difference() {
1581 let mut a
= HashSet
::new();
1582 let mut b
= HashSet
::new();
1584 assert
!(a
.insert(1));
1585 assert
!(a
.insert(3));
1586 assert
!(a
.insert(5));
1587 assert
!(a
.insert(9));
1588 assert
!(a
.insert(11));
1590 assert
!(b
.insert(3));
1591 assert
!(b
.insert(9));
1594 let expected
= [1, 5, 11];
1595 for x
in a
.difference(&b
) {
1596 assert
!(expected
.contains(x
));
1599 assert_eq
!(i
, expected
.len());
1603 fn test_symmetric_difference() {
1604 let mut a
= HashSet
::new();
1605 let mut b
= HashSet
::new();
1607 assert
!(a
.insert(1));
1608 assert
!(a
.insert(3));
1609 assert
!(a
.insert(5));
1610 assert
!(a
.insert(9));
1611 assert
!(a
.insert(11));
1613 assert
!(b
.insert(-2));
1614 assert
!(b
.insert(3));
1615 assert
!(b
.insert(9));
1616 assert
!(b
.insert(14));
1617 assert
!(b
.insert(22));
1620 let expected
= [-2, 1, 5, 11, 14, 22];
1621 for x
in a
.symmetric_difference(&b
) {
1622 assert
!(expected
.contains(x
));
1625 assert_eq
!(i
, expected
.len());
1630 let mut a
= HashSet
::new();
1631 let mut b
= HashSet
::new();
1633 assert
!(a
.insert(1));
1634 assert
!(a
.insert(3));
1635 assert
!(a
.insert(5));
1636 assert
!(a
.insert(9));
1637 assert
!(a
.insert(11));
1638 assert
!(a
.insert(16));
1639 assert
!(a
.insert(19));
1640 assert
!(a
.insert(24));
1642 assert
!(b
.insert(-2));
1643 assert
!(b
.insert(1));
1644 assert
!(b
.insert(5));
1645 assert
!(b
.insert(9));
1646 assert
!(b
.insert(13));
1647 assert
!(b
.insert(19));
1650 let expected
= [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1651 for x
in a
.union(&b
) {
1652 assert
!(expected
.contains(x
));
1655 assert_eq
!(i
, expected
.len());
1659 fn test_from_iter() {
1660 let xs
= [1, 2, 3, 4, 5, 6, 7, 8, 9];
1662 let set
: HashSet
<_
> = xs
.iter().cloned().collect();
1665 assert
!(set
.contains(x
));
1670 fn test_move_iter() {
1672 let mut hs
= HashSet
::new();
1680 let v
= hs
.into_iter().collect
::<Vec
<char>>();
1681 assert
!(v
== ['a'
, 'b'
] || v
== ['b'
, 'a'
]);
1686 // These constants once happened to expose a bug in insert().
1687 // I'm keeping them around to prevent a regression.
1688 let mut s1
= HashSet
::new();
1694 let mut s2
= HashSet
::new();
1708 let mut set
= HashSet
::new();
1709 let empty
= HashSet
::<i32>::new();
1714 let set_str
= format
!("{:?}", set
);
1716 assert
!(set_str
== "{1, 2}" || set_str
== "{2, 1}");
1717 assert_eq
!(format
!("{:?}", empty
), "{}");
1721 fn test_trivial_drain() {
1722 let mut s
= HashSet
::<i32>::new();
1723 for _
in s
.drain() {}
1724 assert
!(s
.is_empty());
1727 let mut s
= HashSet
::<i32>::new();
1729 assert
!(s
.is_empty());
1734 let mut s
: HashSet
<_
> = (1..100).collect();
1736 // try this a bunch of times to make sure we don't screw up internal state.
1738 assert_eq
!(s
.len(), 99);
1742 let mut d
= s
.drain();
1743 for (i
, x
) in d
.by_ref().take(50).enumerate() {
1747 assert_eq
!(last_i
, 49);
1751 panic
!("s should be empty!");
1754 // reset to try again.
1764 struct Foo(&'
static str, i32);
1766 impl PartialEq
for Foo
{
1767 fn eq(&self, other
: &Self) -> bool
{
1774 impl hash
::Hash
for Foo
{
1775 fn hash
<H
: hash
::Hasher
>(&self, h
: &mut H
) {
1780 let mut s
= HashSet
::new();
1781 assert_eq
!(s
.replace(Foo("a", 1)), None
);
1782 assert_eq
!(s
.len(), 1);
1783 assert_eq
!(s
.replace(Foo("a", 2)), Some(Foo("a", 1)));
1784 assert_eq
!(s
.len(), 1);
1786 let mut it
= s
.iter();
1787 assert_eq
!(it
.next(), Some(&Foo("a", 2)));
1788 assert_eq
!(it
.next(), None
);
1792 fn test_extend_ref() {
1793 let mut a
= HashSet
::new();
1796 a
.extend(&[2, 3, 4]);
1798 assert_eq
!(a
.len(), 4);
1799 assert
!(a
.contains(&1));
1800 assert
!(a
.contains(&2));
1801 assert
!(a
.contains(&3));
1802 assert
!(a
.contains(&4));
1804 let mut b
= HashSet
::new();
1810 assert_eq
!(a
.len(), 6);
1811 assert
!(a
.contains(&1));
1812 assert
!(a
.contains(&2));
1813 assert
!(a
.contains(&3));
1814 assert
!(a
.contains(&4));
1815 assert
!(a
.contains(&5));
1816 assert
!(a
.contains(&6));
1821 let xs
= [1, 2, 3, 4, 5, 6];
1822 let mut set
: HashSet
<i32> = xs
.iter().cloned().collect();
1823 set
.retain(|&k
| k
% 2 == 0);
1824 assert_eq
!(set
.len(), 3);
1825 assert
!(set
.contains(&2));
1826 assert
!(set
.contains(&4));
1827 assert
!(set
.contains(&6));