1 use crate::TryReserveError
;
2 use alloc
::borrow
::ToOwned
;
3 use core
::borrow
::Borrow
;
5 use core
::hash
::{BuildHasher, Hash}
;
6 use core
::iter
::{Chain, FromIterator, FusedIterator}
;
8 use core
::ops
::{BitAnd, BitOr, BitXor, Sub}
;
10 use super::map
::{self, ConsumeAllOnDrop, DefaultHashBuilder, DrainFilterInner, HashMap, Keys}
;
12 // Future Optimization (FIXME!)
13 // =============================
15 // Iteration over zero sized values is a noop. There is no need
16 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
17 // to get rid of it properly.
19 /// A hash set implemented as a `HashMap` where the value is `()`.
21 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
22 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
23 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
24 /// it is important that the following property holds:
27 /// k1 == k2 -> hash(k1) == hash(k2)
30 /// In other words, if two keys are equal, their hashes must be equal.
33 /// It is a logic error for an item to be modified in such a way that the
34 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
35 /// determined by the [`Eq`] trait, changes while it is in the set. This is
36 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
39 /// It is also a logic error for the [`Hash`] implementation of a key to panic.
40 /// This is generally only possible if the trait is implemented manually. If a
41 /// panic does occur then the contents of the `HashSet` may become corrupted and
42 /// some items may be dropped from the table.
47 /// use hashbrown::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 hashbrown::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 hashbrown::HashSet;
103 /// let viking_names: HashSet<&'static str> =
104 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
105 /// // 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
114 pub struct HashSet
<T
, S
= DefaultHashBuilder
> {
115 pub(crate) map
: HashMap
<T
, (), S
>,
118 impl<T
: Clone
, S
: Clone
> Clone
for HashSet
<T
, S
> {
119 fn clone(&self) -> Self {
121 map
: self.map
.clone(),
125 fn clone_from(&mut self, source
: &Self) {
126 self.map
.clone_from(&source
.map
);
130 #[cfg(feature = "ahash")]
131 impl<T
> HashSet
<T
, DefaultHashBuilder
> {
132 /// Creates an empty `HashSet`.
134 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
135 /// is first inserted into.
140 /// use hashbrown::HashSet;
141 /// let set: HashSet<i32> = HashSet::new();
143 #[cfg_attr(feature = "inline-more", inline)]
144 pub fn new() -> Self {
150 /// Creates an empty `HashSet` with the specified capacity.
152 /// The hash set will be able to hold at least `capacity` elements without
153 /// reallocating. If `capacity` is 0, the hash set will not allocate.
158 /// use hashbrown::HashSet;
159 /// let set: HashSet<i32> = HashSet::with_capacity(10);
160 /// assert!(set.capacity() >= 10);
162 #[cfg_attr(feature = "inline-more", inline)]
163 pub fn with_capacity(capacity
: usize) -> Self {
165 map
: HashMap
::with_capacity(capacity
),
170 impl<T
, S
> HashSet
<T
, S
> {
171 /// Creates a new empty hash set which will use the given hasher to hash
174 /// The hash set is also created with the default initial capacity.
176 /// Warning: `hasher` is normally randomly generated, and
177 /// is designed to allow `HashSet`s to be resistant to attacks that
178 /// cause many collisions and very poor performance. Setting it
179 /// manually using this function can expose a DoS attack vector.
181 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
182 /// the HashMap to be useful, see its documentation for details.
188 /// use hashbrown::HashSet;
189 /// use hashbrown::hash_map::DefaultHashBuilder;
191 /// let s = DefaultHashBuilder::default();
192 /// let mut set = HashSet::with_hasher(s);
196 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
197 #[cfg_attr(feature = "inline-more", inline)]
198 pub const fn with_hasher(hasher
: S
) -> Self {
200 map
: HashMap
::with_hasher(hasher
),
204 /// Creates an empty `HashSet` with the specified capacity, using
205 /// `hasher` to hash the keys.
207 /// The hash set will be able to hold at least `capacity` elements without
208 /// reallocating. If `capacity` is 0, the hash set will not allocate.
210 /// Warning: `hasher` is normally randomly generated, and
211 /// is designed to allow `HashSet`s to be resistant to attacks that
212 /// cause many collisions and very poor performance. Setting it
213 /// manually using this function can expose a DoS attack vector.
215 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
216 /// the HashMap to be useful, see its documentation for details.
221 /// use hashbrown::HashSet;
222 /// use hashbrown::hash_map::DefaultHashBuilder;
224 /// let s = DefaultHashBuilder::default();
225 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
229 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
230 #[cfg_attr(feature = "inline-more", inline)]
231 pub fn with_capacity_and_hasher(capacity
: usize, hasher
: S
) -> Self {
233 map
: HashMap
::with_capacity_and_hasher(capacity
, hasher
),
237 /// Returns the number of elements the set can hold without reallocating.
242 /// use hashbrown::HashSet;
243 /// let set: HashSet<i32> = HashSet::with_capacity(100);
244 /// assert!(set.capacity() >= 100);
246 #[cfg_attr(feature = "inline-more", inline)]
247 pub fn capacity(&self) -> usize {
251 /// An iterator visiting all elements in arbitrary order.
252 /// The iterator element type is `&'a T`.
257 /// use hashbrown::HashSet;
258 /// let mut set = HashSet::new();
262 /// // Will print in an arbitrary order.
263 /// for x in set.iter() {
264 /// println!("{}", x);
267 #[cfg_attr(feature = "inline-more", inline)]
268 pub fn iter(&self) -> Iter
<'_
, T
> {
270 iter
: self.map
.keys(),
274 /// Returns the number of elements in the set.
279 /// use hashbrown::HashSet;
281 /// let mut v = HashSet::new();
282 /// assert_eq!(v.len(), 0);
284 /// assert_eq!(v.len(), 1);
286 #[cfg_attr(feature = "inline-more", inline)]
287 pub fn len(&self) -> usize {
291 /// Returns `true` if the set contains no elements.
296 /// use hashbrown::HashSet;
298 /// let mut v = HashSet::new();
299 /// assert!(v.is_empty());
301 /// assert!(!v.is_empty());
303 #[cfg_attr(feature = "inline-more", inline)]
304 pub fn is_empty(&self) -> bool
{
308 /// Clears the set, returning all elements in an iterator.
313 /// use hashbrown::HashSet;
315 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
316 /// assert!(!set.is_empty());
318 /// // print 1, 2, 3 in an arbitrary order
319 /// for i in set.drain() {
320 /// println!("{}", i);
323 /// assert!(set.is_empty());
325 #[cfg_attr(feature = "inline-more", inline)]
326 pub fn drain(&mut self) -> Drain
<'_
, T
> {
328 iter
: self.map
.drain(),
332 /// Retains only the elements specified by the predicate.
334 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
339 /// use hashbrown::HashSet;
341 /// let xs = [1,2,3,4,5,6];
342 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
343 /// set.retain(|&k| k % 2 == 0);
344 /// assert_eq!(set.len(), 3);
346 pub fn retain
<F
>(&mut self, mut f
: F
)
348 F
: FnMut(&T
) -> bool
,
350 self.map
.retain(|k
, _
| f(k
));
353 /// Drains elements which are true under the given predicate,
354 /// and returns an iterator over the removed items.
356 /// In other words, move all elements `e` such that `f(&e)` returns `true` out
357 /// into another iterator.
359 /// When the returned DrainedFilter is dropped, any remaining elements that satisfy
360 /// the predicate are dropped from the set.
365 /// use hashbrown::HashSet;
367 /// let mut set: HashSet<i32> = (0..8).collect();
368 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
370 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
371 /// let mut odds = set.into_iter().collect::<Vec<_>>();
375 /// assert_eq!(evens, vec![0, 2, 4, 6]);
376 /// assert_eq!(odds, vec![1, 3, 5, 7]);
378 #[cfg_attr(feature = "inline-more", inline)]
379 pub fn drain_filter
<F
>(&mut self, f
: F
) -> DrainFilter
<'_
, T
, F
>
381 F
: FnMut(&T
) -> bool
,
385 inner
: DrainFilterInner
{
386 iter
: unsafe { self.map.table.iter() }
,
387 table
: &mut self.map
.table
,
392 /// Clears the set, removing all values.
397 /// use hashbrown::HashSet;
399 /// let mut v = HashSet::new();
402 /// assert!(v.is_empty());
404 #[cfg_attr(feature = "inline-more", inline)]
405 pub fn clear(&mut self) {
409 /// Returns a reference to the set's [`BuildHasher`].
411 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
416 /// use hashbrown::HashSet;
417 /// use hashbrown::hash_map::DefaultHashBuilder;
419 /// let hasher = DefaultHashBuilder::default();
420 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
421 /// let hasher: &DefaultHashBuilder = set.hasher();
423 #[cfg_attr(feature = "inline-more", inline)]
424 pub fn hasher(&self) -> &S
{
429 impl<T
, S
> HashSet
<T
, S
>
434 /// Reserves capacity for at least `additional` more elements to be inserted
435 /// in the `HashSet`. The collection may reserve more space to avoid
436 /// frequent reallocations.
440 /// Panics if the new allocation size overflows `usize`.
445 /// use hashbrown::HashSet;
446 /// let mut set: HashSet<i32> = HashSet::new();
448 /// assert!(set.capacity() >= 10);
450 #[cfg_attr(feature = "inline-more", inline)]
451 pub fn reserve(&mut self, additional
: usize) {
452 self.map
.reserve(additional
)
455 /// Tries to reserve capacity for at least `additional` more elements to be inserted
456 /// in the given `HashSet<K,V>`. The collection may reserve more space to avoid
457 /// frequent reallocations.
461 /// If the capacity overflows, or the allocator reports a failure, then an error
467 /// use hashbrown::HashSet;
468 /// let mut set: HashSet<i32> = HashSet::new();
469 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
471 #[cfg_attr(feature = "inline-more", inline)]
472 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
473 self.map
.try_reserve(additional
)
476 /// Shrinks the capacity of the set as much as possible. It will drop
477 /// down as much as possible while maintaining the internal rules
478 /// and possibly leaving some space in accordance with the resize policy.
483 /// use hashbrown::HashSet;
485 /// let mut set = HashSet::with_capacity(100);
488 /// assert!(set.capacity() >= 100);
489 /// set.shrink_to_fit();
490 /// assert!(set.capacity() >= 2);
492 #[cfg_attr(feature = "inline-more", inline)]
493 pub fn shrink_to_fit(&mut self) {
494 self.map
.shrink_to_fit()
497 /// Shrinks the capacity of the set with a lower limit. It will drop
498 /// down no lower than the supplied limit while maintaining the internal rules
499 /// and possibly leaving some space in accordance with the resize policy.
501 /// Panics if the current capacity is smaller than the supplied
502 /// minimum capacity.
507 /// use hashbrown::HashSet;
509 /// let mut set = HashSet::with_capacity(100);
512 /// assert!(set.capacity() >= 100);
513 /// set.shrink_to(10);
514 /// assert!(set.capacity() >= 10);
515 /// set.shrink_to(0);
516 /// assert!(set.capacity() >= 2);
518 #[cfg_attr(feature = "inline-more", inline)]
519 pub fn shrink_to(&mut self, min_capacity
: usize) {
520 self.map
.shrink_to(min_capacity
)
523 /// Visits the values representing the difference,
524 /// i.e., the values that are in `self` but not in `other`.
529 /// use hashbrown::HashSet;
530 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
531 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
533 /// // Can be seen as `a - b`.
534 /// for x in a.difference(&b) {
535 /// println!("{}", x); // Print 1
538 /// let diff: HashSet<_> = a.difference(&b).collect();
539 /// assert_eq!(diff, [1].iter().collect());
541 /// // Note that difference is not symmetric,
542 /// // and `b - a` means something else:
543 /// let diff: HashSet<_> = b.difference(&a).collect();
544 /// assert_eq!(diff, [4].iter().collect());
546 #[cfg_attr(feature = "inline-more", inline)]
547 pub fn difference
<'a
>(&'a
self, other
: &'a
Self) -> Difference
<'a
, T
, S
> {
554 /// Visits the values representing the symmetric difference,
555 /// i.e., the values that are in `self` or in `other` but not in both.
560 /// use hashbrown::HashSet;
561 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
562 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
564 /// // Print 1, 4 in arbitrary order.
565 /// for x in a.symmetric_difference(&b) {
566 /// println!("{}", x);
569 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
570 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
572 /// assert_eq!(diff1, diff2);
573 /// assert_eq!(diff1, [1, 4].iter().collect());
575 #[cfg_attr(feature = "inline-more", inline)]
576 pub fn symmetric_difference
<'a
>(&'a
self, other
: &'a
Self) -> SymmetricDifference
<'a
, T
, S
> {
577 SymmetricDifference
{
578 iter
: self.difference(other
).chain(other
.difference(self)),
582 /// Visits the values representing the intersection,
583 /// i.e., the values that are both in `self` and `other`.
588 /// use hashbrown::HashSet;
589 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
590 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
592 /// // Print 2, 3 in arbitrary order.
593 /// for x in a.intersection(&b) {
594 /// println!("{}", x);
597 /// let intersection: HashSet<_> = a.intersection(&b).collect();
598 /// assert_eq!(intersection, [2, 3].iter().collect());
600 #[cfg_attr(feature = "inline-more", inline)]
601 pub fn intersection
<'a
>(&'a
self, other
: &'a
Self) -> Intersection
<'a
, T
, S
> {
602 let (smaller
, larger
) = if self.len() <= other
.len() {
608 iter
: smaller
.iter(),
613 /// Visits the values representing the union,
614 /// i.e., all the values in `self` or `other`, without duplicates.
619 /// use hashbrown::HashSet;
620 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
621 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
623 /// // Print 1, 2, 3, 4 in arbitrary order.
624 /// for x in a.union(&b) {
625 /// println!("{}", x);
628 /// let union: HashSet<_> = a.union(&b).collect();
629 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
631 #[cfg_attr(feature = "inline-more", inline)]
632 pub fn union<'a
>(&'a
self, other
: &'a
Self) -> Union
<'a
, T
, S
> {
633 let (smaller
, larger
) = if self.len() >= other
.len() {
639 iter
: larger
.iter().chain(smaller
.difference(larger
)),
643 /// Returns `true` if the set contains a value.
645 /// The value may be any borrowed form of the set's value type, but
646 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
652 /// use hashbrown::HashSet;
654 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
655 /// assert_eq!(set.contains(&1), true);
656 /// assert_eq!(set.contains(&4), false);
659 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
660 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
661 #[cfg_attr(feature = "inline-more", inline)]
662 pub fn contains
<Q
: ?Sized
>(&self, value
: &Q
) -> bool
667 self.map
.contains_key(value
)
670 /// Returns a reference to the value in the set, if any, that is equal to the given value.
672 /// The value may be any borrowed form of the set's value type, but
673 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
679 /// use hashbrown::HashSet;
681 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
682 /// assert_eq!(set.get(&2), Some(&2));
683 /// assert_eq!(set.get(&4), None);
686 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
687 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
688 #[cfg_attr(feature = "inline-more", inline)]
689 pub fn get
<Q
: ?Sized
>(&self, value
: &Q
) -> Option
<&T
>
694 // Avoid `Option::map` because it bloats LLVM IR.
695 match self.map
.get_key_value(value
) {
696 Some((k
, _
)) => Some(k
),
701 /// Inserts the given `value` into the set if it is not present, then
702 /// returns a reference to the value in the set.
707 /// use hashbrown::HashSet;
709 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
710 /// assert_eq!(set.len(), 3);
711 /// assert_eq!(set.get_or_insert(2), &2);
712 /// assert_eq!(set.get_or_insert(100), &100);
713 /// assert_eq!(set.len(), 4); // 100 was inserted
715 #[cfg_attr(feature = "inline-more", inline)]
716 pub fn get_or_insert(&mut self, value
: T
) -> &T
{
717 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
718 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
722 .or_insert(value
, ())
726 /// Inserts an owned copy of the given `value` into the set if it is not
727 /// present, then returns a reference to the value in the set.
732 /// use hashbrown::HashSet;
734 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
735 /// .iter().map(|&pet| pet.to_owned()).collect();
737 /// assert_eq!(set.len(), 3);
738 /// for &pet in &["cat", "dog", "fish"] {
739 /// let value = set.get_or_insert_owned(pet);
740 /// assert_eq!(value, pet);
742 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
745 pub fn get_or_insert_owned
<Q
: ?Sized
>(&mut self, value
: &Q
) -> &T
748 Q
: Hash
+ Eq
+ ToOwned
<Owned
= T
>,
750 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
751 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
755 .or_insert_with(|| (value
.to_owned(), ()))
759 /// Inserts a value computed from `f` into the set if the given `value` is
760 /// not present, then returns a reference to the value in the set.
765 /// use hashbrown::HashSet;
767 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
768 /// .iter().map(|&pet| pet.to_owned()).collect();
770 /// assert_eq!(set.len(), 3);
771 /// for &pet in &["cat", "dog", "fish"] {
772 /// let value = set.get_or_insert_with(pet, str::to_owned);
773 /// assert_eq!(value, pet);
775 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
777 #[cfg_attr(feature = "inline-more", inline)]
778 pub fn get_or_insert_with
<Q
: ?Sized
, F
>(&mut self, value
: &Q
, f
: F
) -> &T
784 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
785 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
789 .or_insert_with(|| (f(value
), ()))
793 /// Returns `true` if `self` has no elements in common with `other`.
794 /// This is equivalent to checking for an empty intersection.
799 /// use hashbrown::HashSet;
801 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
802 /// let mut b = HashSet::new();
804 /// assert_eq!(a.is_disjoint(&b), true);
806 /// assert_eq!(a.is_disjoint(&b), true);
808 /// assert_eq!(a.is_disjoint(&b), false);
810 pub fn is_disjoint(&self, other
: &Self) -> bool
{
811 self.iter().all(|v
| !other
.contains(v
))
814 /// Returns `true` if the set is a subset of another,
815 /// i.e., `other` contains at least all the values in `self`.
820 /// use hashbrown::HashSet;
822 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
823 /// let mut set = HashSet::new();
825 /// assert_eq!(set.is_subset(&sup), true);
827 /// assert_eq!(set.is_subset(&sup), true);
829 /// assert_eq!(set.is_subset(&sup), false);
831 pub fn is_subset(&self, other
: &Self) -> bool
{
832 self.len() <= other
.len() && self.iter().all(|v
| other
.contains(v
))
835 /// Returns `true` if the set is a superset of another,
836 /// i.e., `self` contains at least all the values in `other`.
841 /// use hashbrown::HashSet;
843 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
844 /// let mut set = HashSet::new();
846 /// assert_eq!(set.is_superset(&sub), false);
850 /// assert_eq!(set.is_superset(&sub), false);
853 /// assert_eq!(set.is_superset(&sub), true);
855 #[cfg_attr(feature = "inline-more", inline)]
856 pub fn is_superset(&self, other
: &Self) -> bool
{
857 other
.is_subset(self)
860 /// Adds a value to the set.
862 /// If the set did not have this value present, `true` is returned.
864 /// If the set did have this value present, `false` is returned.
869 /// use hashbrown::HashSet;
871 /// let mut set = HashSet::new();
873 /// assert_eq!(set.insert(2), true);
874 /// assert_eq!(set.insert(2), false);
875 /// assert_eq!(set.len(), 1);
877 #[cfg_attr(feature = "inline-more", inline)]
878 pub fn insert(&mut self, value
: T
) -> bool
{
879 self.map
.insert(value
, ()).is_none()
882 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
883 /// one. Returns the replaced value.
888 /// use hashbrown::HashSet;
890 /// let mut set = HashSet::new();
891 /// set.insert(Vec::<i32>::new());
893 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
894 /// set.replace(Vec::with_capacity(10));
895 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
897 #[cfg_attr(feature = "inline-more", inline)]
898 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
899 match self.map
.entry(value
) {
900 map
::Entry
::Occupied(occupied
) => Some(occupied
.replace_key()),
901 map
::Entry
::Vacant(vacant
) => {
908 /// Removes a value from the set. Returns whether the value was
909 /// present in the set.
911 /// The value may be any borrowed form of the set's value type, but
912 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
918 /// use hashbrown::HashSet;
920 /// let mut set = HashSet::new();
923 /// assert_eq!(set.remove(&2), true);
924 /// assert_eq!(set.remove(&2), false);
927 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
928 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
929 #[cfg_attr(feature = "inline-more", inline)]
930 pub fn remove
<Q
: ?Sized
>(&mut self, value
: &Q
) -> bool
935 self.map
.remove(value
).is_some()
938 /// Removes and returns the value in the set, if any, that is equal to the given one.
940 /// The value may be any borrowed form of the set's value type, but
941 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
947 /// use hashbrown::HashSet;
949 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
950 /// assert_eq!(set.take(&2), Some(2));
951 /// assert_eq!(set.take(&2), None);
954 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
955 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
956 #[cfg_attr(feature = "inline-more", inline)]
957 pub fn take
<Q
: ?Sized
>(&mut self, value
: &Q
) -> Option
<T
>
962 // Avoid `Option::map` because it bloats LLVM IR.
963 match self.map
.remove_entry(value
) {
964 Some((k
, _
)) => Some(k
),
970 impl<T
, S
> PartialEq
for HashSet
<T
, S
>
975 fn eq(&self, other
: &Self) -> bool
{
976 if self.len() != other
.len() {
980 self.iter().all(|key
| other
.contains(key
))
984 impl<T
, S
> Eq
for HashSet
<T
, S
>
991 impl<T
, S
> fmt
::Debug
for HashSet
<T
, S
>
993 T
: Eq
+ Hash
+ fmt
::Debug
,
996 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
997 f
.debug_set().entries(self.iter()).finish()
1001 impl<T
, S
> FromIterator
<T
> for HashSet
<T
, S
>
1004 S
: BuildHasher
+ Default
,
1006 #[cfg_attr(feature = "inline-more", inline)]
1007 fn from_iter
<I
: IntoIterator
<Item
= T
>>(iter
: I
) -> Self {
1008 let mut set
= Self::with_hasher(Default
::default());
1014 impl<T
, S
> Extend
<T
> for HashSet
<T
, S
>
1019 #[cfg_attr(feature = "inline-more", inline)]
1020 fn extend
<I
: IntoIterator
<Item
= T
>>(&mut self, iter
: I
) {
1021 self.map
.extend(iter
.into_iter().map(|k
| (k
, ())));
1025 #[cfg(feature = "nightly")]
1026 fn extend_one(&mut self, k
: T
) {
1027 self.map
.insert(k
, ());
1031 #[cfg(feature = "nightly")]
1032 fn extend_reserve(&mut self, additional
: usize) {
1033 Extend
::<(T
, ())>::extend_reserve(&mut self.map
, additional
);
1037 impl<'a
, T
, S
> Extend
<&'a T
> for HashSet
<T
, S
>
1039 T
: 'a
+ Eq
+ Hash
+ Copy
,
1042 #[cfg_attr(feature = "inline-more", inline)]
1043 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
1044 self.extend(iter
.into_iter().cloned());
1048 #[cfg(feature = "nightly")]
1049 fn extend_one(&mut self, k
: &'a T
) {
1050 self.map
.insert(*k
, ());
1054 #[cfg(feature = "nightly")]
1055 fn extend_reserve(&mut self, additional
: usize) {
1056 Extend
::<(T
, ())>::extend_reserve(&mut self.map
, additional
);
1060 impl<T
, S
> Default
for HashSet
<T
, S
>
1064 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1065 #[cfg_attr(feature = "inline-more", inline)]
1066 fn default() -> Self {
1068 map
: HashMap
::default(),
1073 impl<T
, S
> BitOr
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
1075 T
: Eq
+ Hash
+ Clone
,
1076 S
: BuildHasher
+ Default
,
1078 type Output
= HashSet
<T
, S
>;
1080 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1085 /// use hashbrown::HashSet;
1087 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1088 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1090 /// let set = &a | &b;
1093 /// let expected = [1, 2, 3, 4, 5];
1095 /// assert!(expected.contains(x));
1098 /// assert_eq!(i, expected.len());
1100 fn bitor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1101 self.union(rhs
).cloned().collect()
1105 impl<T
, S
> BitAnd
<&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 intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1117 /// use hashbrown::HashSet;
1119 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1120 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1122 /// let set = &a & &b;
1125 /// let expected = [2, 3];
1127 /// assert!(expected.contains(x));
1130 /// assert_eq!(i, expected.len());
1132 fn bitand(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1133 self.intersection(rhs
).cloned().collect()
1137 impl<T
, S
> BitXor
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
1139 T
: Eq
+ Hash
+ Clone
,
1140 S
: BuildHasher
+ Default
,
1142 type Output
= HashSet
<T
, S
>;
1144 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1149 /// use hashbrown::HashSet;
1151 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1152 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1154 /// let set = &a ^ &b;
1157 /// let expected = [1, 2, 4, 5];
1159 /// assert!(expected.contains(x));
1162 /// assert_eq!(i, expected.len());
1164 fn bitxor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1165 self.symmetric_difference(rhs
).cloned().collect()
1169 impl<T
, S
> Sub
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
1171 T
: Eq
+ Hash
+ Clone
,
1172 S
: BuildHasher
+ Default
,
1174 type Output
= HashSet
<T
, S
>;
1176 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1181 /// use hashbrown::HashSet;
1183 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1184 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1186 /// let set = &a - &b;
1189 /// let expected = [1, 2];
1191 /// assert!(expected.contains(x));
1194 /// assert_eq!(i, expected.len());
1196 fn sub(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1197 self.difference(rhs
).cloned().collect()
1201 /// An iterator over the items of a `HashSet`.
1203 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1204 /// See its documentation for more.
1206 /// [`HashSet`]: struct.HashSet.html
1207 /// [`iter`]: struct.HashSet.html#method.iter
1208 pub struct Iter
<'a
, K
> {
1209 iter
: Keys
<'a
, K
, ()>,
1212 /// An owning iterator over the items of a `HashSet`.
1214 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1215 /// (provided by the `IntoIterator` trait). See its documentation for more.
1217 /// [`HashSet`]: struct.HashSet.html
1218 /// [`into_iter`]: struct.HashSet.html#method.into_iter
1219 pub struct IntoIter
<K
> {
1220 iter
: map
::IntoIter
<K
, ()>,
1223 /// A draining iterator over the items of a `HashSet`.
1225 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1226 /// See its documentation for more.
1228 /// [`HashSet`]: struct.HashSet.html
1229 /// [`drain`]: struct.HashSet.html#method.drain
1230 pub struct Drain
<'a
, K
> {
1231 iter
: map
::Drain
<'a
, K
, ()>,
1234 /// A draining iterator over entries of a `HashSet` which don't satisfy the predicate `f`.
1236 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`]. See its
1237 /// documentation for more.
1239 /// [`drain_filter`]: struct.HashSet.html#method.drain_filter
1240 /// [`HashSet`]: struct.HashSet.html
1241 pub struct DrainFilter
<'a
, K
, F
>
1243 F
: FnMut(&K
) -> bool
,
1246 inner
: DrainFilterInner
<'a
, K
, ()>,
1249 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1251 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1252 /// See its documentation for more.
1254 /// [`HashSet`]: struct.HashSet.html
1255 /// [`intersection`]: struct.HashSet.html#method.intersection
1256 pub struct Intersection
<'a
, T
, S
> {
1257 // iterator of the first set
1260 other
: &'a HashSet
<T
, S
>,
1263 /// A lazy iterator producing elements in the difference of `HashSet`s.
1265 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1266 /// See its documentation for more.
1268 /// [`HashSet`]: struct.HashSet.html
1269 /// [`difference`]: struct.HashSet.html#method.difference
1270 pub struct Difference
<'a
, T
, S
> {
1271 // iterator of the first set
1274 other
: &'a HashSet
<T
, S
>,
1277 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1279 /// This `struct` is created by the [`symmetric_difference`] method on
1280 /// [`HashSet`]. See its documentation for more.
1282 /// [`HashSet`]: struct.HashSet.html
1283 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1284 pub struct SymmetricDifference
<'a
, T
, S
> {
1285 iter
: Chain
<Difference
<'a
, T
, S
>, Difference
<'a
, T
, S
>>,
1288 /// A lazy iterator producing elements in the union of `HashSet`s.
1290 /// This `struct` is created by the [`union`] method on [`HashSet`].
1291 /// See its documentation for more.
1293 /// [`HashSet`]: struct.HashSet.html
1294 /// [`union`]: struct.HashSet.html#method.union
1295 pub struct Union
<'a
, T
, S
> {
1296 iter
: Chain
<Iter
<'a
, T
>, Difference
<'a
, T
, S
>>,
1299 impl<'a
, T
, S
> IntoIterator
for &'a HashSet
<T
, S
> {
1301 type IntoIter
= Iter
<'a
, T
>;
1303 #[cfg_attr(feature = "inline-more", inline)]
1304 fn into_iter(self) -> Iter
<'a
, T
> {
1309 impl<T
, S
> IntoIterator
for HashSet
<T
, S
> {
1311 type IntoIter
= IntoIter
<T
>;
1313 /// Creates a consuming iterator, that is, one that moves each value out
1314 /// of the set in arbitrary order. The set cannot be used after calling
1320 /// use hashbrown::HashSet;
1321 /// let mut set = HashSet::new();
1322 /// set.insert("a".to_string());
1323 /// set.insert("b".to_string());
1325 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1326 /// let v: Vec<String> = set.into_iter().collect();
1328 /// // Will print in an arbitrary order.
1330 /// println!("{}", x);
1333 #[cfg_attr(feature = "inline-more", inline)]
1334 fn into_iter(self) -> IntoIter
<T
> {
1336 iter
: self.map
.into_iter(),
1341 impl<K
> Clone
for Iter
<'_
, K
> {
1342 #[cfg_attr(feature = "inline-more", inline)]
1343 fn clone(&self) -> Self {
1345 iter
: self.iter
.clone(),
1349 impl<'a
, K
> Iterator
for Iter
<'a
, K
> {
1352 #[cfg_attr(feature = "inline-more", inline)]
1353 fn next(&mut self) -> Option
<&'a K
> {
1356 #[cfg_attr(feature = "inline-more", inline)]
1357 fn size_hint(&self) -> (usize, Option
<usize>) {
1358 self.iter
.size_hint()
1361 impl<'a
, K
> ExactSizeIterator
for Iter
<'a
, K
> {
1362 #[cfg_attr(feature = "inline-more", inline)]
1363 fn len(&self) -> usize {
1367 impl<K
> FusedIterator
for Iter
<'_
, K
> {}
1369 impl<K
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, K
> {
1370 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1371 f
.debug_list().entries(self.clone()).finish()
1375 impl<K
> Iterator
for IntoIter
<K
> {
1378 #[cfg_attr(feature = "inline-more", inline)]
1379 fn next(&mut self) -> Option
<K
> {
1380 // Avoid `Option::map` because it bloats LLVM IR.
1381 match self.iter
.next() {
1382 Some((k
, _
)) => Some(k
),
1386 #[cfg_attr(feature = "inline-more", inline)]
1387 fn size_hint(&self) -> (usize, Option
<usize>) {
1388 self.iter
.size_hint()
1391 impl<K
> ExactSizeIterator
for IntoIter
<K
> {
1392 #[cfg_attr(feature = "inline-more", inline)]
1393 fn len(&self) -> usize {
1397 impl<K
> FusedIterator
for IntoIter
<K
> {}
1399 impl<K
: fmt
::Debug
> fmt
::Debug
for IntoIter
<K
> {
1400 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1401 let entries_iter
= self.iter
.iter().map(|(k
, _
)| k
);
1402 f
.debug_list().entries(entries_iter
).finish()
1406 impl<K
> Iterator
for Drain
<'_
, K
> {
1409 #[cfg_attr(feature = "inline-more", inline)]
1410 fn next(&mut self) -> Option
<K
> {
1411 // Avoid `Option::map` because it bloats LLVM IR.
1412 match self.iter
.next() {
1413 Some((k
, _
)) => Some(k
),
1417 #[cfg_attr(feature = "inline-more", inline)]
1418 fn size_hint(&self) -> (usize, Option
<usize>) {
1419 self.iter
.size_hint()
1422 impl<K
> ExactSizeIterator
for Drain
<'_
, K
> {
1423 #[cfg_attr(feature = "inline-more", inline)]
1424 fn len(&self) -> usize {
1428 impl<K
> FusedIterator
for Drain
<'_
, K
> {}
1430 impl<K
: fmt
::Debug
> fmt
::Debug
for Drain
<'_
, K
> {
1431 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1432 let entries_iter
= self.iter
.iter().map(|(k
, _
)| k
);
1433 f
.debug_list().entries(entries_iter
).finish()
1437 impl<'a
, K
, F
> Drop
for DrainFilter
<'a
, K
, F
>
1439 F
: FnMut(&K
) -> bool
,
1441 #[cfg_attr(feature = "inline-more", inline)]
1442 fn drop(&mut self) {
1443 while let Some(item
) = self.next() {
1444 let guard
= ConsumeAllOnDrop(self);
1451 impl<K
, F
> Iterator
for DrainFilter
<'_
, K
, F
>
1453 F
: FnMut(&K
) -> bool
,
1457 #[cfg_attr(feature = "inline-more", inline)]
1458 fn next(&mut self) -> Option
<Self::Item
> {
1459 let f
= &mut self.f
;
1460 let (k
, _
) = self.inner
.next(&mut |k
, _
| f(k
))?
;
1465 fn size_hint(&self) -> (usize, Option
<usize>) {
1466 (0, self.inner
.iter
.size_hint().1)
1470 impl<K
, F
> FusedIterator
for DrainFilter
<'_
, K
, F
> where F
: FnMut(&K
) -> bool {}
1472 impl<T
, S
> Clone
for Intersection
<'_
, T
, S
> {
1473 #[cfg_attr(feature = "inline-more", inline)]
1474 fn clone(&self) -> Self {
1476 iter
: self.iter
.clone(),
1482 impl<'a
, T
, S
> Iterator
for Intersection
<'a
, T
, S
>
1489 #[cfg_attr(feature = "inline-more", inline)]
1490 fn next(&mut self) -> Option
<&'a T
> {
1492 let elt
= self.iter
.next()?
;
1493 if self.other
.contains(elt
) {
1499 #[cfg_attr(feature = "inline-more", inline)]
1500 fn size_hint(&self) -> (usize, Option
<usize>) {
1501 let (_
, upper
) = self.iter
.size_hint();
1506 impl<T
, S
> fmt
::Debug
for Intersection
<'_
, T
, S
>
1508 T
: fmt
::Debug
+ Eq
+ Hash
,
1511 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1512 f
.debug_list().entries(self.clone()).finish()
1516 impl<T
, S
> FusedIterator
for Intersection
<'_
, T
, S
>
1523 impl<T
, S
> Clone
for Difference
<'_
, T
, S
> {
1524 #[cfg_attr(feature = "inline-more", inline)]
1525 fn clone(&self) -> Self {
1527 iter
: self.iter
.clone(),
1533 impl<'a
, T
, S
> Iterator
for Difference
<'a
, T
, S
>
1540 #[cfg_attr(feature = "inline-more", inline)]
1541 fn next(&mut self) -> Option
<&'a T
> {
1543 let elt
= self.iter
.next()?
;
1544 if !self.other
.contains(elt
) {
1550 #[cfg_attr(feature = "inline-more", inline)]
1551 fn size_hint(&self) -> (usize, Option
<usize>) {
1552 let (_
, upper
) = self.iter
.size_hint();
1557 impl<T
, S
> FusedIterator
for Difference
<'_
, T
, S
>
1564 impl<T
, S
> fmt
::Debug
for Difference
<'_
, T
, S
>
1566 T
: fmt
::Debug
+ Eq
+ Hash
,
1569 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1570 f
.debug_list().entries(self.clone()).finish()
1574 impl<T
, S
> Clone
for SymmetricDifference
<'_
, T
, S
> {
1575 #[cfg_attr(feature = "inline-more", inline)]
1576 fn clone(&self) -> Self {
1577 SymmetricDifference
{
1578 iter
: self.iter
.clone(),
1583 impl<'a
, T
, S
> Iterator
for SymmetricDifference
<'a
, T
, S
>
1590 #[cfg_attr(feature = "inline-more", inline)]
1591 fn next(&mut self) -> Option
<&'a T
> {
1594 #[cfg_attr(feature = "inline-more", inline)]
1595 fn size_hint(&self) -> (usize, Option
<usize>) {
1596 self.iter
.size_hint()
1600 impl<T
, S
> FusedIterator
for SymmetricDifference
<'_
, T
, S
>
1607 impl<T
, S
> fmt
::Debug
for SymmetricDifference
<'_
, T
, S
>
1609 T
: fmt
::Debug
+ Eq
+ Hash
,
1612 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1613 f
.debug_list().entries(self.clone()).finish()
1617 impl<T
, S
> Clone
for Union
<'_
, T
, S
> {
1618 #[cfg_attr(feature = "inline-more", inline)]
1619 fn clone(&self) -> Self {
1621 iter
: self.iter
.clone(),
1626 impl<T
, S
> FusedIterator
for Union
<'_
, T
, S
>
1633 impl<T
, S
> fmt
::Debug
for Union
<'_
, 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 impl<'a
, T
, S
> Iterator
for Union
<'a
, T
, S
>
1650 #[cfg_attr(feature = "inline-more", inline)]
1651 fn next(&mut self) -> Option
<&'a T
> {
1654 #[cfg_attr(feature = "inline-more", inline)]
1655 fn size_hint(&self) -> (usize, Option
<usize>) {
1656 self.iter
.size_hint()
1661 fn assert_covariance() {
1662 fn set
<'new
>(v
: HashSet
<&'
static str>) -> HashSet
<&'new
str> {
1665 fn iter
<'a
, 'new
>(v
: Iter
<'a
, &'
static str>) -> Iter
<'a
, &'new
str> {
1668 fn into_iter
<'new
>(v
: IntoIter
<&'
static str>) -> IntoIter
<&'new
str> {
1671 fn difference
<'a
, 'new
>(
1672 v
: Difference
<'a
, &'
static str, DefaultHashBuilder
>,
1673 ) -> Difference
<'a
, &'new
str, DefaultHashBuilder
> {
1676 fn symmetric_difference
<'a
, 'new
>(
1677 v
: SymmetricDifference
<'a
, &'
static str, DefaultHashBuilder
>,
1678 ) -> SymmetricDifference
<'a
, &'new
str, DefaultHashBuilder
> {
1681 fn intersection
<'a
, 'new
>(
1682 v
: Intersection
<'a
, &'
static str, DefaultHashBuilder
>,
1683 ) -> Intersection
<'a
, &'new
str, DefaultHashBuilder
> {
1687 v
: Union
<'a
, &'
static str, DefaultHashBuilder
>,
1688 ) -> Union
<'a
, &'new
str, DefaultHashBuilder
> {
1691 fn drain
<'new
>(d
: Drain
<'
static, &'
static str>) -> Drain
<'new
, &'new
str> {
1698 use super::super::map
::DefaultHashBuilder
;
1703 fn test_zero_capacities() {
1704 type HS
= HashSet
<i32>;
1707 assert_eq
!(s
.capacity(), 0);
1709 let s
= HS
::default();
1710 assert_eq
!(s
.capacity(), 0);
1712 let s
= HS
::with_hasher(DefaultHashBuilder
::default());
1713 assert_eq
!(s
.capacity(), 0);
1715 let s
= HS
::with_capacity(0);
1716 assert_eq
!(s
.capacity(), 0);
1718 let s
= HS
::with_capacity_and_hasher(0, DefaultHashBuilder
::default());
1719 assert_eq
!(s
.capacity(), 0);
1721 let mut s
= HS
::new();
1727 assert_eq
!(s
.capacity(), 0);
1729 let mut s
= HS
::new();
1731 assert_eq
!(s
.capacity(), 0);
1735 fn test_disjoint() {
1736 let mut xs
= HashSet
::new();
1737 let mut ys
= HashSet
::new();
1738 assert
!(xs
.is_disjoint(&ys
));
1739 assert
!(ys
.is_disjoint(&xs
));
1740 assert
!(xs
.insert(5));
1741 assert
!(ys
.insert(11));
1742 assert
!(xs
.is_disjoint(&ys
));
1743 assert
!(ys
.is_disjoint(&xs
));
1744 assert
!(xs
.insert(7));
1745 assert
!(xs
.insert(19));
1746 assert
!(xs
.insert(4));
1747 assert
!(ys
.insert(2));
1748 assert
!(ys
.insert(-11));
1749 assert
!(xs
.is_disjoint(&ys
));
1750 assert
!(ys
.is_disjoint(&xs
));
1751 assert
!(ys
.insert(7));
1752 assert
!(!xs
.is_disjoint(&ys
));
1753 assert
!(!ys
.is_disjoint(&xs
));
1757 fn test_subset_and_superset() {
1758 let mut a
= HashSet
::new();
1759 assert
!(a
.insert(0));
1760 assert
!(a
.insert(5));
1761 assert
!(a
.insert(11));
1762 assert
!(a
.insert(7));
1764 let mut b
= HashSet
::new();
1765 assert
!(b
.insert(0));
1766 assert
!(b
.insert(7));
1767 assert
!(b
.insert(19));
1768 assert
!(b
.insert(250));
1769 assert
!(b
.insert(11));
1770 assert
!(b
.insert(200));
1772 assert
!(!a
.is_subset(&b
));
1773 assert
!(!a
.is_superset(&b
));
1774 assert
!(!b
.is_subset(&a
));
1775 assert
!(!b
.is_superset(&a
));
1777 assert
!(b
.insert(5));
1779 assert
!(a
.is_subset(&b
));
1780 assert
!(!a
.is_superset(&b
));
1781 assert
!(!b
.is_subset(&a
));
1782 assert
!(b
.is_superset(&a
));
1787 let mut a
= HashSet
::new();
1789 assert
!(a
.insert(i
));
1791 let mut observed
: u32 = 0;
1793 observed
|= 1 << *k
;
1795 assert_eq
!(observed
, 0xFFFF_FFFF);
1799 fn test_intersection() {
1800 let mut a
= HashSet
::new();
1801 let mut b
= HashSet
::new();
1803 assert
!(a
.insert(11));
1804 assert
!(a
.insert(1));
1805 assert
!(a
.insert(3));
1806 assert
!(a
.insert(77));
1807 assert
!(a
.insert(103));
1808 assert
!(a
.insert(5));
1809 assert
!(a
.insert(-5));
1811 assert
!(b
.insert(2));
1812 assert
!(b
.insert(11));
1813 assert
!(b
.insert(77));
1814 assert
!(b
.insert(-9));
1815 assert
!(b
.insert(-42));
1816 assert
!(b
.insert(5));
1817 assert
!(b
.insert(3));
1820 let expected
= [3, 5, 11, 77];
1821 for x
in a
.intersection(&b
) {
1822 assert
!(expected
.contains(x
));
1825 assert_eq
!(i
, expected
.len());
1829 fn test_difference() {
1830 let mut a
= HashSet
::new();
1831 let mut b
= HashSet
::new();
1833 assert
!(a
.insert(1));
1834 assert
!(a
.insert(3));
1835 assert
!(a
.insert(5));
1836 assert
!(a
.insert(9));
1837 assert
!(a
.insert(11));
1839 assert
!(b
.insert(3));
1840 assert
!(b
.insert(9));
1843 let expected
= [1, 5, 11];
1844 for x
in a
.difference(&b
) {
1845 assert
!(expected
.contains(x
));
1848 assert_eq
!(i
, expected
.len());
1852 fn test_symmetric_difference() {
1853 let mut a
= HashSet
::new();
1854 let mut b
= HashSet
::new();
1856 assert
!(a
.insert(1));
1857 assert
!(a
.insert(3));
1858 assert
!(a
.insert(5));
1859 assert
!(a
.insert(9));
1860 assert
!(a
.insert(11));
1862 assert
!(b
.insert(-2));
1863 assert
!(b
.insert(3));
1864 assert
!(b
.insert(9));
1865 assert
!(b
.insert(14));
1866 assert
!(b
.insert(22));
1869 let expected
= [-2, 1, 5, 11, 14, 22];
1870 for x
in a
.symmetric_difference(&b
) {
1871 assert
!(expected
.contains(x
));
1874 assert_eq
!(i
, expected
.len());
1879 let mut a
= HashSet
::new();
1880 let mut b
= HashSet
::new();
1882 assert
!(a
.insert(1));
1883 assert
!(a
.insert(3));
1884 assert
!(a
.insert(5));
1885 assert
!(a
.insert(9));
1886 assert
!(a
.insert(11));
1887 assert
!(a
.insert(16));
1888 assert
!(a
.insert(19));
1889 assert
!(a
.insert(24));
1891 assert
!(b
.insert(-2));
1892 assert
!(b
.insert(1));
1893 assert
!(b
.insert(5));
1894 assert
!(b
.insert(9));
1895 assert
!(b
.insert(13));
1896 assert
!(b
.insert(19));
1899 let expected
= [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1900 for x
in a
.union(&b
) {
1901 assert
!(expected
.contains(x
));
1904 assert_eq
!(i
, expected
.len());
1908 fn test_from_iter() {
1909 let xs
= [1, 2, 2, 3, 4, 5, 6, 7, 8, 9];
1911 let set
: HashSet
<_
> = xs
.iter().cloned().collect();
1914 assert
!(set
.contains(x
));
1917 assert_eq
!(set
.iter().len(), xs
.len() - 1);
1921 fn test_move_iter() {
1923 let mut hs
= HashSet
::new();
1931 let v
= hs
.into_iter().collect
::<Vec
<char>>();
1932 assert
!(v
== ['a'
, 'b'
] || v
== ['b'
, 'a'
]);
1937 // These constants once happened to expose a bug in insert().
1938 // I'm keeping them around to prevent a regression.
1939 let mut s1
= HashSet
::new();
1945 let mut s2
= HashSet
::new();
1959 let mut set
= HashSet
::new();
1960 let empty
= HashSet
::<i32>::new();
1965 let set_str
= format
!("{:?}", set
);
1967 assert
!(set_str
== "{1, 2}" || set_str
== "{2, 1}");
1968 assert_eq
!(format
!("{:?}", empty
), "{}");
1972 fn test_trivial_drain() {
1973 let mut s
= HashSet
::<i32>::new();
1974 for _
in s
.drain() {}
1975 assert
!(s
.is_empty());
1978 let mut s
= HashSet
::<i32>::new();
1980 assert
!(s
.is_empty());
1985 let mut s
: HashSet
<_
> = (1..100).collect();
1987 // try this a bunch of times to make sure we don't screw up internal state.
1989 assert_eq
!(s
.len(), 99);
1993 let mut d
= s
.drain();
1994 for (i
, x
) in d
.by_ref().take(50).enumerate() {
1998 assert_eq
!(last_i
, 49);
2002 panic
!("s should be empty!");
2005 // reset to try again.
2015 struct Foo(&'
static str, i32);
2017 impl PartialEq
for Foo
{
2018 fn eq(&self, other
: &Self) -> bool
{
2025 impl hash
::Hash
for Foo
{
2026 fn hash
<H
: hash
::Hasher
>(&self, h
: &mut H
) {
2031 let mut s
= HashSet
::new();
2032 assert_eq
!(s
.replace(Foo("a", 1)), None
);
2033 assert_eq
!(s
.len(), 1);
2034 assert_eq
!(s
.replace(Foo("a", 2)), Some(Foo("a", 1)));
2035 assert_eq
!(s
.len(), 1);
2037 let mut it
= s
.iter();
2038 assert_eq
!(it
.next(), Some(&Foo("a", 2)));
2039 assert_eq
!(it
.next(), None
);
2043 fn test_extend_ref() {
2044 let mut a
= HashSet
::new();
2047 a
.extend(&[2, 3, 4]);
2049 assert_eq
!(a
.len(), 4);
2050 assert
!(a
.contains(&1));
2051 assert
!(a
.contains(&2));
2052 assert
!(a
.contains(&3));
2053 assert
!(a
.contains(&4));
2055 let mut b
= HashSet
::new();
2061 assert_eq
!(a
.len(), 6);
2062 assert
!(a
.contains(&1));
2063 assert
!(a
.contains(&2));
2064 assert
!(a
.contains(&3));
2065 assert
!(a
.contains(&4));
2066 assert
!(a
.contains(&5));
2067 assert
!(a
.contains(&6));
2072 let xs
= [1, 2, 3, 4, 5, 6];
2073 let mut set
: HashSet
<i32> = xs
.iter().cloned().collect();
2074 set
.retain(|&k
| k
% 2 == 0);
2075 assert_eq
!(set
.len(), 3);
2076 assert
!(set
.contains(&2));
2077 assert
!(set
.contains(&4));
2078 assert
!(set
.contains(&6));
2082 fn test_drain_filter() {
2084 let mut set
: HashSet
<i32> = (0..8).collect();
2085 let drained
= set
.drain_filter(|&k
| k
% 2 == 0);
2086 let mut out
= drained
.collect
::<Vec
<_
>>();
2087 out
.sort_unstable();
2088 assert_eq
!(vec
![0, 2, 4, 6], out
);
2089 assert_eq
!(set
.len(), 4);
2092 let mut set
: HashSet
<i32> = (0..8).collect();
2093 drop(set
.drain_filter(|&k
| k
% 2 == 0));
2094 assert_eq
!(set
.len(), 4, "Removes non-matching items on drop");
2099 fn test_const_with_hasher() {
2100 use core
::hash
::BuildHasher
;
2101 use std
::collections
::hash_map
::DefaultHasher
;
2105 impl BuildHasher
for MyHasher
{
2106 type Hasher
= DefaultHasher
;
2108 fn build_hasher(&self) -> DefaultHasher
{
2109 DefaultHasher
::new()
2113 const EMPTY_SET
: HashSet
<u32, MyHasher
> = HashSet
::with_hasher(MyHasher
);
2115 let mut set
= EMPTY_SET
.clone();
2117 assert
!(set
.contains(&19));