1 use crate::borrow
::Borrow
;
2 use crate::collections
::TryReserveError
;
4 use crate::hash
::{Hash, BuildHasher}
;
5 use crate::iter
::{Chain, FromIterator, FusedIterator}
;
6 use crate::ops
::{BitOr, BitAnd, BitXor, Sub}
;
8 use super::map
::{self, HashMap, Keys, RandomState}
;
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
40 /// use std::collections::HashSet;
41 /// // Type inference lets us omit an explicit type signature (which
42 /// // would be `HashSet<String>` in this example).
43 /// let mut books = HashSet::new();
45 /// // Add some books.
46 /// books.insert("A Dance With Dragons".to_string());
47 /// books.insert("To Kill a Mockingbird".to_string());
48 /// books.insert("The Odyssey".to_string());
49 /// books.insert("The Great Gatsby".to_string());
51 /// // Check for a specific one.
52 /// if !books.contains("The Winds of Winter") {
53 /// println!("We have {} books, but The Winds of Winter ain't one.",
58 /// books.remove("The Odyssey");
60 /// // Iterate over everything.
61 /// for book in &books {
62 /// println!("{}", book);
66 /// The easiest way to use `HashSet` with a custom type is to derive
67 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
68 /// future be implied by [`Eq`].
71 /// use std::collections::HashSet;
72 /// #[derive(Hash, Eq, PartialEq, Debug)]
78 /// let mut vikings = HashSet::new();
80 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
81 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
82 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
83 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
85 /// // Use derived implementation to print the vikings.
86 /// for x in &vikings {
87 /// println!("{:?}", x);
91 /// A `HashSet` with fixed list of elements can be initialized from an array:
94 /// use std::collections::HashSet;
96 /// let viking_names: HashSet<&'static str> =
97 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
98 /// // use the values stored in the set
101 /// [`Cell`]: ../../std/cell/struct.Cell.html
102 /// [`Eq`]: ../../std/cmp/trait.Eq.html
103 /// [`Hash`]: ../../std/hash/trait.Hash.html
104 /// [`HashMap`]: struct.HashMap.html
105 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
106 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct HashSet
<T
, S
= RandomState
> {
110 map
: HashMap
<T
, (), S
>,
113 impl<T
: Hash
+ Eq
> HashSet
<T
, RandomState
> {
114 /// Creates an empty `HashSet`.
116 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
117 /// is first inserted into.
122 /// use std::collections::HashSet;
123 /// let set: HashSet<i32> = HashSet::new();
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub fn new() -> HashSet
<T
, RandomState
> {
128 HashSet { map: HashMap::new() }
131 /// Creates an empty `HashSet` with the specified capacity.
133 /// The hash set will be able to hold at least `capacity` elements without
134 /// reallocating. If `capacity` is 0, the hash set will not allocate.
139 /// use std::collections::HashSet;
140 /// let set: HashSet<i32> = HashSet::with_capacity(10);
141 /// assert!(set.capacity() >= 10);
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn with_capacity(capacity
: usize) -> HashSet
<T
, RandomState
> {
146 HashSet { map: HashMap::with_capacity(capacity) }
150 impl<T
, S
> HashSet
<T
, S
> {
151 /// Returns the number of elements the set can hold without reallocating.
156 /// use std::collections::HashSet;
157 /// let set: HashSet<i32> = HashSet::with_capacity(100);
158 /// assert!(set.capacity() >= 100);
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub fn capacity(&self) -> usize {
166 /// An iterator visiting all elements in arbitrary order.
167 /// The iterator element type is `&'a T`.
172 /// use std::collections::HashSet;
173 /// let mut set = HashSet::new();
177 /// // Will print in an arbitrary order.
178 /// for x in set.iter() {
179 /// println!("{}", x);
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn iter(&self) -> Iter
<'_
, T
> {
185 Iter { iter: self.map.keys() }
188 /// Returns the number of elements in the set.
193 /// use std::collections::HashSet;
195 /// let mut v = HashSet::new();
196 /// assert_eq!(v.len(), 0);
198 /// assert_eq!(v.len(), 1);
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub fn len(&self) -> usize {
206 /// Returns `true` if the set contains no elements.
211 /// use std::collections::HashSet;
213 /// let mut v = HashSet::new();
214 /// assert!(v.is_empty());
216 /// assert!(!v.is_empty());
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn is_empty(&self) -> bool
{
224 /// Clears the set, returning all elements in an iterator.
229 /// use std::collections::HashSet;
231 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
232 /// assert!(!set.is_empty());
234 /// // print 1, 2, 3 in an arbitrary order
235 /// for i in set.drain() {
236 /// println!("{}", i);
239 /// assert!(set.is_empty());
242 #[stable(feature = "drain", since = "1.6.0")]
243 pub fn drain(&mut self) -> Drain
<'_
, T
> {
244 Drain { iter: self.map.drain() }
247 /// Clears the set, removing all values.
252 /// use std::collections::HashSet;
254 /// let mut v = HashSet::new();
257 /// assert!(v.is_empty());
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn clear(&mut self) {
266 impl<T
, S
> HashSet
<T
, S
>
270 /// Creates a new empty hash set which will use the given hasher to hash
273 /// The hash set is also created with the default initial capacity.
275 /// Warning: `hasher` is normally randomly generated, and
276 /// is designed to allow `HashSet`s to be resistant to attacks that
277 /// cause many collisions and very poor performance. Setting it
278 /// manually using this function can expose a DoS attack vector.
283 /// use std::collections::HashSet;
284 /// use std::collections::hash_map::RandomState;
286 /// let s = RandomState::new();
287 /// let mut set = HashSet::with_hasher(s);
291 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
292 pub fn with_hasher(hasher
: S
) -> HashSet
<T
, S
> {
293 HashSet { map: HashMap::with_hasher(hasher) }
296 /// Creates an empty `HashSet` with the specified capacity, using
297 /// `hasher` to hash the keys.
299 /// The hash set will be able to hold at least `capacity` elements without
300 /// reallocating. If `capacity` is 0, the hash set will not allocate.
302 /// Warning: `hasher` is normally randomly generated, and
303 /// is designed to allow `HashSet`s to be resistant to attacks that
304 /// cause many collisions and very poor performance. Setting it
305 /// manually using this function can expose a DoS attack vector.
310 /// use std::collections::HashSet;
311 /// use std::collections::hash_map::RandomState;
313 /// let s = RandomState::new();
314 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
318 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
319 pub fn with_capacity_and_hasher(capacity
: usize, hasher
: S
) -> HashSet
<T
, S
> {
320 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
323 /// Returns a reference to the set's [`BuildHasher`].
325 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
330 /// use std::collections::HashSet;
331 /// use std::collections::hash_map::RandomState;
333 /// let hasher = RandomState::new();
334 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
335 /// let hasher: &RandomState = set.hasher();
338 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
339 pub fn hasher(&self) -> &S
{
343 /// Reserves capacity for at least `additional` more elements to be inserted
344 /// in the `HashSet`. The collection may reserve more space to avoid
345 /// frequent reallocations.
349 /// Panics if the new allocation size overflows `usize`.
354 /// use std::collections::HashSet;
355 /// let mut set: HashSet<i32> = HashSet::new();
357 /// assert!(set.capacity() >= 10);
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn reserve(&mut self, additional
: usize) {
362 self.map
.reserve(additional
)
365 /// Tries to reserve capacity for at least `additional` more elements to be inserted
366 /// in the given `HashSet<K,V>`. The collection may reserve more space to avoid
367 /// frequent reallocations.
371 /// If the capacity overflows, or the allocator reports a failure, then an error
377 /// #![feature(try_reserve)]
378 /// use std::collections::HashSet;
379 /// let mut set: HashSet<i32> = HashSet::new();
380 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
383 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
384 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
385 self.map
.try_reserve(additional
)
388 /// Shrinks the capacity of the set as much as possible. It will drop
389 /// down as much as possible while maintaining the internal rules
390 /// and possibly leaving some space in accordance with the resize policy.
395 /// use std::collections::HashSet;
397 /// let mut set = HashSet::with_capacity(100);
400 /// assert!(set.capacity() >= 100);
401 /// set.shrink_to_fit();
402 /// assert!(set.capacity() >= 2);
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn shrink_to_fit(&mut self) {
407 self.map
.shrink_to_fit()
410 /// Shrinks the capacity of the set with a lower limit. It will drop
411 /// down no lower than the supplied limit while maintaining the internal rules
412 /// and possibly leaving some space in accordance with the resize policy.
414 /// Panics if the current capacity is smaller than the supplied
415 /// minimum capacity.
420 /// #![feature(shrink_to)]
421 /// use std::collections::HashSet;
423 /// let mut set = HashSet::with_capacity(100);
426 /// assert!(set.capacity() >= 100);
427 /// set.shrink_to(10);
428 /// assert!(set.capacity() >= 10);
429 /// set.shrink_to(0);
430 /// assert!(set.capacity() >= 2);
433 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
434 pub fn shrink_to(&mut self, min_capacity
: usize) {
435 self.map
.shrink_to(min_capacity
)
438 /// Visits the values representing the difference,
439 /// i.e., the values that are in `self` but not in `other`.
444 /// use std::collections::HashSet;
445 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
446 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
448 /// // Can be seen as `a - b`.
449 /// for x in a.difference(&b) {
450 /// println!("{}", x); // Print 1
453 /// let diff: HashSet<_> = a.difference(&b).collect();
454 /// assert_eq!(diff, [1].iter().collect());
456 /// // Note that difference is not symmetric,
457 /// // and `b - a` means something else:
458 /// let diff: HashSet<_> = b.difference(&a).collect();
459 /// assert_eq!(diff, [4].iter().collect());
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn difference
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Difference
<'a
, T
, S
> {
470 /// Visits the values representing the symmetric difference,
471 /// i.e., the values that are in `self` or in `other` but not in both.
476 /// use std::collections::HashSet;
477 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
478 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
480 /// // Print 1, 4 in arbitrary order.
481 /// for x in a.symmetric_difference(&b) {
482 /// println!("{}", x);
485 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
486 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
488 /// assert_eq!(diff1, diff2);
489 /// assert_eq!(diff1, [1, 4].iter().collect());
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn symmetric_difference
<'a
>(&'a
self,
494 other
: &'a HashSet
<T
, S
>)
495 -> SymmetricDifference
<'a
, T
, S
> {
496 SymmetricDifference { 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 std::collections::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 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn intersection
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Intersection
<'a
, T
, S
> {
520 if self.len() <= other
.len() {
533 /// Visits the values representing the union,
534 /// i.e., all the values in `self` or `other`, without duplicates.
539 /// use std::collections::HashSet;
540 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
541 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
543 /// // Print 1, 2, 3, 4 in arbitrary order.
544 /// for x in a.union(&b) {
545 /// println!("{}", x);
548 /// let union: HashSet<_> = a.union(&b).collect();
549 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn union<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Union
<'a
, T
, S
> {
554 if self.len() >= other
.len() {
556 iter
: self.iter().chain(other
.difference(self)),
560 iter
: other
.iter().chain(self.difference(other
)),
565 /// Returns `true` if the set contains a value.
567 /// The value may be any borrowed form of the set's value type, but
568 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
574 /// use std::collections::HashSet;
576 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
577 /// assert_eq!(set.contains(&1), true);
578 /// assert_eq!(set.contains(&4), false);
581 /// [`Eq`]: ../../std/cmp/trait.Eq.html
582 /// [`Hash`]: ../../std/hash/trait.Hash.html
584 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn contains
<Q
: ?Sized
>(&self, value
: &Q
) -> bool
589 self.map
.contains_key(value
)
592 /// Returns a reference to the value in the set, if any, that is equal to the given value.
594 /// The value may be any borrowed form of the set's value type, but
595 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
601 /// use std::collections::HashSet;
603 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
604 /// assert_eq!(set.get(&2), Some(&2));
605 /// assert_eq!(set.get(&4), None);
608 /// [`Eq`]: ../../std/cmp/trait.Eq.html
609 /// [`Hash`]: ../../std/hash/trait.Hash.html
611 #[stable(feature = "set_recovery", since = "1.9.0")]
612 pub fn get
<Q
: ?Sized
>(&self, value
: &Q
) -> Option
<&T
>
616 self.map
.get_key_value(value
).map(|(k
, _
)| k
)
619 /// Inserts the given `value` into the set if it is not present, then
620 /// returns a reference to the value in the set.
625 /// #![feature(hash_set_entry)]
627 /// use std::collections::HashSet;
629 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
630 /// assert_eq!(set.len(), 3);
631 /// assert_eq!(set.get_or_insert(2), &2);
632 /// assert_eq!(set.get_or_insert(100), &100);
633 /// assert_eq!(set.len(), 4); // 100 was inserted
636 #[unstable(feature = "hash_set_entry", issue = "60896")]
637 pub fn get_or_insert(&mut self, value
: T
) -> &T
{
638 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
639 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
640 self.map
.raw_entry_mut().from_key(&value
).or_insert(value
, ()).0
643 /// Inserts a value computed from `f` into the set if the given `value` is
644 /// not present, then returns a reference to the value in the set.
649 /// #![feature(hash_set_entry)]
651 /// use std::collections::HashSet;
653 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
654 /// .iter().map(|&pet| pet.to_owned()).collect();
656 /// assert_eq!(set.len(), 3);
657 /// for &pet in &["cat", "dog", "fish"] {
658 /// let value = set.get_or_insert_with(pet, str::to_owned);
659 /// assert_eq!(value, pet);
661 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
664 #[unstable(feature = "hash_set_entry", issue = "60896")]
665 pub fn get_or_insert_with
<Q
: ?Sized
, F
>(&mut self, value
: &Q
, f
: F
) -> &T
670 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
671 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
672 self.map
.raw_entry_mut().from_key(value
).or_insert_with(|| (f(value
), ())).0
675 /// Returns `true` if `self` has no elements in common with `other`.
676 /// This is equivalent to checking for an empty intersection.
681 /// use std::collections::HashSet;
683 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
684 /// let mut b = HashSet::new();
686 /// assert_eq!(a.is_disjoint(&b), true);
688 /// assert_eq!(a.is_disjoint(&b), true);
690 /// assert_eq!(a.is_disjoint(&b), false);
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn is_disjoint(&self, other
: &HashSet
<T
, S
>) -> bool
{
694 if self.len() <= other
.len() {
695 self.iter().all(|v
| !other
.contains(v
))
697 other
.iter().all(|v
| !self.contains(v
))
701 /// Returns `true` if the set is a subset of another,
702 /// i.e., `other` contains at least all the values in `self`.
707 /// use std::collections::HashSet;
709 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
710 /// let mut set = HashSet::new();
712 /// assert_eq!(set.is_subset(&sup), true);
714 /// assert_eq!(set.is_subset(&sup), true);
716 /// assert_eq!(set.is_subset(&sup), false);
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn is_subset(&self, other
: &HashSet
<T
, S
>) -> bool
{
720 if self.len() <= other
.len() {
721 self.iter().all(|v
| other
.contains(v
))
727 /// Returns `true` if the set is a superset of another,
728 /// i.e., `self` contains at least all the values in `other`.
733 /// use std::collections::HashSet;
735 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
736 /// let mut set = HashSet::new();
738 /// assert_eq!(set.is_superset(&sub), false);
742 /// assert_eq!(set.is_superset(&sub), false);
745 /// assert_eq!(set.is_superset(&sub), true);
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn is_superset(&self, other
: &HashSet
<T
, S
>) -> bool
{
750 other
.is_subset(self)
753 /// Adds a value to the set.
755 /// If the set did not have this value present, `true` is returned.
757 /// If the set did have this value present, `false` is returned.
762 /// use std::collections::HashSet;
764 /// let mut set = HashSet::new();
766 /// assert_eq!(set.insert(2), true);
767 /// assert_eq!(set.insert(2), false);
768 /// assert_eq!(set.len(), 1);
771 #[stable(feature = "rust1", since = "1.0.0")]
772 pub fn insert(&mut self, value
: T
) -> bool
{
773 self.map
.insert(value
, ()).is_none()
776 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
777 /// one. Returns the replaced value.
782 /// use std::collections::HashSet;
784 /// let mut set = HashSet::new();
785 /// set.insert(Vec::<i32>::new());
787 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
788 /// set.replace(Vec::with_capacity(10));
789 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
792 #[stable(feature = "set_recovery", since = "1.9.0")]
793 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
794 match self.map
.entry(value
) {
795 map
::Entry
::Occupied(occupied
) => Some(occupied
.replace_key()),
796 map
::Entry
::Vacant(vacant
) => {
803 /// Removes a value from the set. Returns whether the value was
804 /// present in the set.
806 /// The value may be any borrowed form of the set's value type, but
807 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
813 /// use std::collections::HashSet;
815 /// let mut set = HashSet::new();
818 /// assert_eq!(set.remove(&2), true);
819 /// assert_eq!(set.remove(&2), false);
822 /// [`Eq`]: ../../std/cmp/trait.Eq.html
823 /// [`Hash`]: ../../std/hash/trait.Hash.html
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn remove
<Q
: ?Sized
>(&mut self, value
: &Q
) -> bool
830 self.map
.remove(value
).is_some()
833 /// Removes and returns the value in the set, if any, that is equal to the given one.
835 /// The value may be any borrowed form of the set's value type, but
836 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
842 /// use std::collections::HashSet;
844 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
845 /// assert_eq!(set.take(&2), Some(2));
846 /// assert_eq!(set.take(&2), None);
849 /// [`Eq`]: ../../std/cmp/trait.Eq.html
850 /// [`Hash`]: ../../std/hash/trait.Hash.html
852 #[stable(feature = "set_recovery", since = "1.9.0")]
853 pub fn take
<Q
: ?Sized
>(&mut self, value
: &Q
) -> Option
<T
>
857 self.map
.remove_entry(value
).map(|(k
, _
)| k
)
860 /// Retains only the elements specified by the predicate.
862 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
867 /// use std::collections::HashSet;
869 /// let xs = [1,2,3,4,5,6];
870 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
871 /// set.retain(|&k| k % 2 == 0);
872 /// assert_eq!(set.len(), 3);
874 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
875 pub fn retain
<F
>(&mut self, mut f
: F
)
876 where F
: FnMut(&T
) -> bool
878 self.map
.retain(|k
, _
| f(k
));
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<T
, S
> PartialEq
for HashSet
<T
, S
>
887 fn eq(&self, other
: &HashSet
<T
, S
>) -> bool
{
888 if self.len() != other
.len() {
892 self.iter().all(|key
| other
.contains(key
))
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl<T
, S
> Eq
for HashSet
<T
, S
>
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl<T
, S
> fmt
::Debug
for HashSet
<T
, S
>
905 where T
: Eq
+ Hash
+ fmt
::Debug
,
908 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
909 f
.debug_set().entries(self.iter()).finish()
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl<T
, S
> FromIterator
<T
> for HashSet
<T
, S
>
916 S
: BuildHasher
+ Default
919 fn from_iter
<I
: IntoIterator
<Item
= T
>>(iter
: I
) -> HashSet
<T
, S
> {
920 let mut set
= HashSet
::with_hasher(Default
::default());
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl<T
, S
> Extend
<T
> for HashSet
<T
, S
>
932 fn extend
<I
: IntoIterator
<Item
= T
>>(&mut self, iter
: I
) {
933 self.map
.extend(iter
.into_iter().map(|k
| (k
, ())));
937 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
938 impl<'a
, T
, S
> Extend
<&'a T
> for HashSet
<T
, S
>
939 where T
: 'a
+ Eq
+ Hash
+ Copy
,
943 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
944 self.extend(iter
.into_iter().cloned());
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<T
, S
> Default
for HashSet
<T
, S
>
951 S
: BuildHasher
+ Default
953 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
955 fn default() -> HashSet
<T
, S
> {
956 HashSet { map: HashMap::default() }
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<T
, S
> BitOr
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
962 where T
: Eq
+ Hash
+ Clone
,
963 S
: BuildHasher
+ Default
965 type Output
= HashSet
<T
, S
>;
967 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
972 /// use std::collections::HashSet;
974 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
975 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
977 /// let set = &a | &b;
980 /// let expected = [1, 2, 3, 4, 5];
982 /// assert!(expected.contains(x));
985 /// assert_eq!(i, expected.len());
987 fn bitor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
988 self.union(rhs
).cloned().collect()
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<T
, S
> BitAnd
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
994 where T
: Eq
+ Hash
+ Clone
,
995 S
: BuildHasher
+ Default
997 type Output
= HashSet
<T
, S
>;
999 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1004 /// use std::collections::HashSet;
1006 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1007 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1009 /// let set = &a & &b;
1012 /// let expected = [2, 3];
1014 /// assert!(expected.contains(x));
1017 /// assert_eq!(i, expected.len());
1019 fn bitand(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1020 self.intersection(rhs
).cloned().collect()
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<T
, S
> BitXor
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
1026 where T
: Eq
+ Hash
+ Clone
,
1027 S
: BuildHasher
+ Default
1029 type Output
= HashSet
<T
, S
>;
1031 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1036 /// use std::collections::HashSet;
1038 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1039 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1041 /// let set = &a ^ &b;
1044 /// let expected = [1, 2, 4, 5];
1046 /// assert!(expected.contains(x));
1049 /// assert_eq!(i, expected.len());
1051 fn bitxor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1052 self.symmetric_difference(rhs
).cloned().collect()
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<T
, S
> Sub
<&HashSet
<T
, S
>> for &HashSet
<T
, S
>
1058 where T
: Eq
+ Hash
+ Clone
,
1059 S
: BuildHasher
+ Default
1061 type Output
= HashSet
<T
, S
>;
1063 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1068 /// use std::collections::HashSet;
1070 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1071 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1073 /// let set = &a - &b;
1076 /// let expected = [1, 2];
1078 /// assert!(expected.contains(x));
1081 /// assert_eq!(i, expected.len());
1083 fn sub(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
1084 self.difference(rhs
).cloned().collect()
1088 /// An iterator over the items of a `HashSet`.
1090 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1091 /// See its documentation for more.
1093 /// [`HashSet`]: struct.HashSet.html
1094 /// [`iter`]: struct.HashSet.html#method.iter
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 pub struct Iter
<'a
, K
: 'a
> {
1097 iter
: Keys
<'a
, K
, ()>,
1100 /// An owning iterator over the items of a `HashSet`.
1102 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
1103 /// (provided by the `IntoIterator` trait). See its documentation for more.
1105 /// [`HashSet`]: struct.HashSet.html
1106 /// [`into_iter`]: struct.HashSet.html#method.into_iter
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub struct IntoIter
<K
> {
1109 iter
: map
::IntoIter
<K
, ()>,
1112 /// A draining iterator over the items of a `HashSet`.
1114 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1115 /// See its documentation for more.
1117 /// [`HashSet`]: struct.HashSet.html
1118 /// [`drain`]: struct.HashSet.html#method.drain
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub struct Drain
<'a
, K
: 'a
> {
1121 iter
: map
::Drain
<'a
, K
, ()>,
1124 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1126 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1127 /// See its documentation for more.
1129 /// [`HashSet`]: struct.HashSet.html
1130 /// [`intersection`]: struct.HashSet.html#method.intersection
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub struct Intersection
<'a
, T
: 'a
, S
: 'a
> {
1133 // iterator of the first set
1136 other
: &'a HashSet
<T
, S
>,
1139 /// A lazy iterator producing elements in the difference of `HashSet`s.
1141 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1142 /// See its documentation for more.
1144 /// [`HashSet`]: struct.HashSet.html
1145 /// [`difference`]: struct.HashSet.html#method.difference
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub struct Difference
<'a
, T
: 'a
, S
: 'a
> {
1148 // iterator of the first set
1151 other
: &'a HashSet
<T
, S
>,
1154 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1156 /// This `struct` is created by the [`symmetric_difference`] method on
1157 /// [`HashSet`]. See its documentation for more.
1159 /// [`HashSet`]: struct.HashSet.html
1160 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 pub struct SymmetricDifference
<'a
, T
: 'a
, S
: 'a
> {
1163 iter
: Chain
<Difference
<'a
, T
, S
>, Difference
<'a
, T
, S
>>,
1166 /// A lazy iterator producing elements in the union of `HashSet`s.
1168 /// This `struct` is created by the [`union`] method on [`HashSet`].
1169 /// See its documentation for more.
1171 /// [`HashSet`]: struct.HashSet.html
1172 /// [`union`]: struct.HashSet.html#method.union
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub struct Union
<'a
, T
: 'a
, S
: 'a
> {
1175 iter
: Chain
<Iter
<'a
, T
>, Difference
<'a
, T
, S
>>,
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<'a
, T
, S
> IntoIterator
for &'a HashSet
<T
, S
> {
1181 type IntoIter
= Iter
<'a
, T
>;
1184 fn into_iter(self) -> Iter
<'a
, T
> {
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<T
, S
> IntoIterator
for HashSet
<T
, S
> {
1192 type IntoIter
= IntoIter
<T
>;
1194 /// Creates a consuming iterator, that is, one that moves each value out
1195 /// of the set in arbitrary order. The set cannot be used after calling
1201 /// use std::collections::HashSet;
1202 /// let mut set = HashSet::new();
1203 /// set.insert("a".to_string());
1204 /// set.insert("b".to_string());
1206 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1207 /// let v: Vec<String> = set.into_iter().collect();
1209 /// // Will print in an arbitrary order.
1211 /// println!("{}", x);
1215 fn into_iter(self) -> IntoIter
<T
> {
1216 IntoIter { iter: self.map.into_iter() }
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl<K
> Clone
for Iter
<'_
, K
> {
1223 fn clone(&self) -> Self {
1224 Iter { iter: self.iter.clone() }
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<'a
, K
> Iterator
for Iter
<'a
, K
> {
1232 fn next(&mut self) -> Option
<&'a K
> {
1236 fn size_hint(&self) -> (usize, Option
<usize>) {
1237 self.iter
.size_hint()
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 impl<K
> ExactSizeIterator
for Iter
<'_
, K
> {
1243 fn len(&self) -> usize {
1247 #[stable(feature = "fused", since = "1.26.0")]
1248 impl<K
> FusedIterator
for Iter
<'_
, K
> {}
1250 #[stable(feature = "std_debug", since = "1.16.0")]
1251 impl<K
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, K
> {
1252 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1253 f
.debug_list().entries(self.clone()).finish()
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 impl<K
> Iterator
for IntoIter
<K
> {
1262 fn next(&mut self) -> Option
<K
> {
1263 self.iter
.next().map(|(k
, _
)| k
)
1266 fn size_hint(&self) -> (usize, Option
<usize>) {
1267 self.iter
.size_hint()
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl<K
> ExactSizeIterator
for IntoIter
<K
> {
1273 fn len(&self) -> usize {
1277 #[stable(feature = "fused", since = "1.26.0")]
1278 impl<K
> FusedIterator
for IntoIter
<K
> {}
1280 #[stable(feature = "std_debug", since = "1.16.0")]
1281 impl<K
: fmt
::Debug
> fmt
::Debug
for IntoIter
<K
> {
1282 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1283 let entries_iter
= self.iter
1286 f
.debug_list().entries(entries_iter
).finish()
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 impl<'a
, K
> Iterator
for Drain
<'a
, K
> {
1295 fn next(&mut self) -> Option
<K
> {
1296 self.iter
.next().map(|(k
, _
)| k
)
1299 fn size_hint(&self) -> (usize, Option
<usize>) {
1300 self.iter
.size_hint()
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<K
> ExactSizeIterator
for Drain
<'_
, K
> {
1306 fn len(&self) -> usize {
1310 #[stable(feature = "fused", since = "1.26.0")]
1311 impl<K
> FusedIterator
for Drain
<'_
, K
> {}
1313 #[stable(feature = "std_debug", since = "1.16.0")]
1314 impl<K
: fmt
::Debug
> fmt
::Debug
for Drain
<'_
, K
> {
1315 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1316 let entries_iter
= self.iter
1319 f
.debug_list().entries(entries_iter
).finish()
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<T
, S
> Clone
for Intersection
<'_
, T
, S
> {
1326 fn clone(&self) -> Self {
1327 Intersection { iter: self.iter.clone(), ..*self }
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<'a
, T
, S
> Iterator
for Intersection
<'a
, T
, S
>
1339 fn next(&mut self) -> Option
<&'a T
> {
1341 let elt
= self.iter
.next()?
;
1342 if self.other
.contains(elt
) {
1349 fn size_hint(&self) -> (usize, Option
<usize>) {
1350 let (_
, upper
) = self.iter
.size_hint();
1355 #[stable(feature = "std_debug", since = "1.16.0")]
1356 impl<T
, S
> fmt
::Debug
for Intersection
<'_
, T
, S
>
1357 where T
: fmt
::Debug
+ Eq
+ Hash
,
1360 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1361 f
.debug_list().entries(self.clone()).finish()
1365 #[stable(feature = "fused", since = "1.26.0")]
1366 impl<T
, S
> FusedIterator
for Intersection
<'_
, T
, S
>
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<T
, S
> Clone
for Difference
<'_
, T
, S
> {
1375 fn clone(&self) -> Self {
1376 Difference { iter: self.iter.clone(), ..*self }
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<'a
, T
, S
> Iterator
for Difference
<'a
, T
, S
>
1388 fn next(&mut self) -> Option
<&'a T
> {
1390 let elt
= self.iter
.next()?
;
1391 if !self.other
.contains(elt
) {
1398 fn size_hint(&self) -> (usize, Option
<usize>) {
1399 let (_
, upper
) = self.iter
.size_hint();
1404 #[stable(feature = "fused", since = "1.26.0")]
1405 impl<T
, S
> FusedIterator
for Difference
<'_
, T
, S
>
1411 #[stable(feature = "std_debug", since = "1.16.0")]
1412 impl<T
, S
> fmt
::Debug
for Difference
<'_
, T
, S
>
1413 where T
: fmt
::Debug
+ Eq
+ Hash
,
1416 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1417 f
.debug_list().entries(self.clone()).finish()
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<T
, S
> Clone
for SymmetricDifference
<'_
, T
, S
> {
1424 fn clone(&self) -> Self {
1425 SymmetricDifference { iter: self.iter.clone() }
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl<'a
, T
, S
> Iterator
for SymmetricDifference
<'a
, T
, S
>
1437 fn next(&mut self) -> Option
<&'a T
> {
1441 fn size_hint(&self) -> (usize, Option
<usize>) {
1442 self.iter
.size_hint()
1446 #[stable(feature = "fused", since = "1.26.0")]
1447 impl<T
, S
> FusedIterator
for SymmetricDifference
<'_
, T
, S
>
1453 #[stable(feature = "std_debug", since = "1.16.0")]
1454 impl<T
, S
> fmt
::Debug
for SymmetricDifference
<'_
, T
, S
>
1455 where T
: fmt
::Debug
+ Eq
+ Hash
,
1458 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1459 f
.debug_list().entries(self.clone()).finish()
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 impl<T
, S
> Clone
for Union
<'_
, T
, S
> {
1466 fn clone(&self) -> Self {
1467 Union { iter: self.iter.clone() }
1471 #[stable(feature = "fused", since = "1.26.0")]
1472 impl<T
, S
> FusedIterator
for Union
<'_
, T
, S
>
1478 #[stable(feature = "std_debug", since = "1.16.0")]
1479 impl<T
, S
> fmt
::Debug
for Union
<'_
, T
, S
>
1480 where T
: fmt
::Debug
+ Eq
+ Hash
,
1483 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1484 f
.debug_list().entries(self.clone()).finish()
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<'a
, T
, S
> Iterator
for Union
<'a
, T
, S
>
1496 fn next(&mut self) -> Option
<&'a T
> {
1500 fn size_hint(&self) -> (usize, Option
<usize>) {
1501 self.iter
.size_hint()
1506 fn assert_covariance() {
1507 fn set
<'new
>(v
: HashSet
<&'
static str>) -> HashSet
<&'new
str> {
1510 fn iter
<'a
, 'new
>(v
: Iter
<'a
, &'
static str>) -> Iter
<'a
, &'new
str> {
1513 fn into_iter
<'new
>(v
: IntoIter
<&'
static str>) -> IntoIter
<&'new
str> {
1516 fn difference
<'a
, 'new
>(v
: Difference
<'a
, &'
static str, RandomState
>)
1517 -> Difference
<'a
, &'new
str, RandomState
> {
1520 fn symmetric_difference
<'a
, 'new
>(v
: SymmetricDifference
<'a
, &'
static str, RandomState
>)
1521 -> SymmetricDifference
<'a
, &'new
str, RandomState
> {
1524 fn intersection
<'a
, 'new
>(v
: Intersection
<'a
, &'
static str, RandomState
>)
1525 -> Intersection
<'a
, &'new
str, RandomState
> {
1528 fn union<'a
, 'new
>(v
: Union
<'a
, &'
static str, RandomState
>)
1529 -> Union
<'a
, &'new
str, RandomState
> {
1532 fn drain
<'new
>(d
: Drain
<'
static, &'
static str>) -> Drain
<'new
, &'new
str> {
1540 use super::super::map
::RandomState
;
1543 fn test_zero_capacities() {
1544 type HS
= HashSet
<i32>;
1547 assert_eq
!(s
.capacity(), 0);
1549 let s
= HS
::default();
1550 assert_eq
!(s
.capacity(), 0);
1552 let s
= HS
::with_hasher(RandomState
::new());
1553 assert_eq
!(s
.capacity(), 0);
1555 let s
= HS
::with_capacity(0);
1556 assert_eq
!(s
.capacity(), 0);
1558 let s
= HS
::with_capacity_and_hasher(0, RandomState
::new());
1559 assert_eq
!(s
.capacity(), 0);
1561 let mut s
= HS
::new();
1567 assert_eq
!(s
.capacity(), 0);
1569 let mut s
= HS
::new();
1571 assert_eq
!(s
.capacity(), 0);
1575 fn test_disjoint() {
1576 let mut xs
= HashSet
::new();
1577 let mut ys
= HashSet
::new();
1578 assert
!(xs
.is_disjoint(&ys
));
1579 assert
!(ys
.is_disjoint(&xs
));
1580 assert
!(xs
.insert(5));
1581 assert
!(ys
.insert(11));
1582 assert
!(xs
.is_disjoint(&ys
));
1583 assert
!(ys
.is_disjoint(&xs
));
1584 assert
!(xs
.insert(7));
1585 assert
!(xs
.insert(19));
1586 assert
!(xs
.insert(4));
1587 assert
!(ys
.insert(2));
1588 assert
!(ys
.insert(-11));
1589 assert
!(xs
.is_disjoint(&ys
));
1590 assert
!(ys
.is_disjoint(&xs
));
1591 assert
!(ys
.insert(7));
1592 assert
!(!xs
.is_disjoint(&ys
));
1593 assert
!(!ys
.is_disjoint(&xs
));
1597 fn test_subset_and_superset() {
1598 let mut a
= HashSet
::new();
1599 assert
!(a
.insert(0));
1600 assert
!(a
.insert(5));
1601 assert
!(a
.insert(11));
1602 assert
!(a
.insert(7));
1604 let mut b
= HashSet
::new();
1605 assert
!(b
.insert(0));
1606 assert
!(b
.insert(7));
1607 assert
!(b
.insert(19));
1608 assert
!(b
.insert(250));
1609 assert
!(b
.insert(11));
1610 assert
!(b
.insert(200));
1612 assert
!(!a
.is_subset(&b
));
1613 assert
!(!a
.is_superset(&b
));
1614 assert
!(!b
.is_subset(&a
));
1615 assert
!(!b
.is_superset(&a
));
1617 assert
!(b
.insert(5));
1619 assert
!(a
.is_subset(&b
));
1620 assert
!(!a
.is_superset(&b
));
1621 assert
!(!b
.is_subset(&a
));
1622 assert
!(b
.is_superset(&a
));
1627 let mut a
= HashSet
::new();
1629 assert
!(a
.insert(i
));
1631 let mut observed
: u32 = 0;
1633 observed
|= 1 << *k
;
1635 assert_eq
!(observed
, 0xFFFF_FFFF);
1639 fn test_intersection() {
1640 let mut a
= HashSet
::new();
1641 let mut b
= HashSet
::new();
1642 assert
!(a
.intersection(&b
).next().is_none());
1644 assert
!(a
.insert(11));
1645 assert
!(a
.insert(1));
1646 assert
!(a
.insert(3));
1647 assert
!(a
.insert(77));
1648 assert
!(a
.insert(103));
1649 assert
!(a
.insert(5));
1650 assert
!(a
.insert(-5));
1652 assert
!(b
.insert(2));
1653 assert
!(b
.insert(11));
1654 assert
!(b
.insert(77));
1655 assert
!(b
.insert(-9));
1656 assert
!(b
.insert(-42));
1657 assert
!(b
.insert(5));
1658 assert
!(b
.insert(3));
1661 let expected
= [3, 5, 11, 77];
1662 for x
in a
.intersection(&b
) {
1663 assert
!(expected
.contains(x
));
1666 assert_eq
!(i
, expected
.len());
1668 assert
!(a
.insert(9)); // make a bigger than b
1671 for x
in a
.intersection(&b
) {
1672 assert
!(expected
.contains(x
));
1675 assert_eq
!(i
, expected
.len());
1678 for x
in b
.intersection(&a
) {
1679 assert
!(expected
.contains(x
));
1682 assert_eq
!(i
, expected
.len());
1686 fn test_difference() {
1687 let mut a
= HashSet
::new();
1688 let mut b
= HashSet
::new();
1690 assert
!(a
.insert(1));
1691 assert
!(a
.insert(3));
1692 assert
!(a
.insert(5));
1693 assert
!(a
.insert(9));
1694 assert
!(a
.insert(11));
1696 assert
!(b
.insert(3));
1697 assert
!(b
.insert(9));
1700 let expected
= [1, 5, 11];
1701 for x
in a
.difference(&b
) {
1702 assert
!(expected
.contains(x
));
1705 assert_eq
!(i
, expected
.len());
1709 fn test_symmetric_difference() {
1710 let mut a
= HashSet
::new();
1711 let mut b
= HashSet
::new();
1713 assert
!(a
.insert(1));
1714 assert
!(a
.insert(3));
1715 assert
!(a
.insert(5));
1716 assert
!(a
.insert(9));
1717 assert
!(a
.insert(11));
1719 assert
!(b
.insert(-2));
1720 assert
!(b
.insert(3));
1721 assert
!(b
.insert(9));
1722 assert
!(b
.insert(14));
1723 assert
!(b
.insert(22));
1726 let expected
= [-2, 1, 5, 11, 14, 22];
1727 for x
in a
.symmetric_difference(&b
) {
1728 assert
!(expected
.contains(x
));
1731 assert_eq
!(i
, expected
.len());
1736 let mut a
= HashSet
::new();
1737 let mut b
= HashSet
::new();
1738 assert
!(a
.union(&b
).next().is_none());
1739 assert
!(b
.union(&a
).next().is_none());
1741 assert
!(a
.insert(1));
1742 assert
!(a
.insert(3));
1743 assert
!(a
.insert(11));
1744 assert
!(a
.insert(16));
1745 assert
!(a
.insert(19));
1746 assert
!(a
.insert(24));
1748 assert
!(b
.insert(-2));
1749 assert
!(b
.insert(1));
1750 assert
!(b
.insert(5));
1751 assert
!(b
.insert(9));
1752 assert
!(b
.insert(13));
1753 assert
!(b
.insert(19));
1756 let expected
= [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1757 for x
in a
.union(&b
) {
1758 assert
!(expected
.contains(x
));
1761 assert_eq
!(i
, expected
.len());
1763 assert
!(a
.insert(9)); // make a bigger than b
1764 assert
!(a
.insert(5));
1767 for x
in a
.union(&b
) {
1768 assert
!(expected
.contains(x
));
1771 assert_eq
!(i
, expected
.len());
1774 for x
in b
.union(&a
) {
1775 assert
!(expected
.contains(x
));
1778 assert_eq
!(i
, expected
.len());
1782 fn test_from_iter() {
1783 let xs
= [1, 2, 2, 3, 4, 5, 6, 7, 8, 9];
1785 let set
: HashSet
<_
> = xs
.iter().cloned().collect();
1788 assert
!(set
.contains(x
));
1791 assert_eq
!(set
.iter().len(), xs
.len() - 1);
1795 fn test_move_iter() {
1797 let mut hs
= HashSet
::new();
1805 let v
= hs
.into_iter().collect
::<Vec
<char>>();
1806 assert
!(v
== ['a'
, 'b'
] || v
== ['b'
, 'a'
]);
1811 // These constants once happened to expose a bug in insert().
1812 // I'm keeping them around to prevent a regression.
1813 let mut s1
= HashSet
::new();
1819 let mut s2
= HashSet
::new();
1833 let mut set
= HashSet
::new();
1834 let empty
= HashSet
::<i32>::new();
1839 let set_str
= format
!("{:?}", set
);
1841 assert
!(set_str
== "{1, 2}" || set_str
== "{2, 1}");
1842 assert_eq
!(format
!("{:?}", empty
), "{}");
1846 fn test_trivial_drain() {
1847 let mut s
= HashSet
::<i32>::new();
1848 for _
in s
.drain() {}
1849 assert
!(s
.is_empty());
1852 let mut s
= HashSet
::<i32>::new();
1854 assert
!(s
.is_empty());
1859 let mut s
: HashSet
<_
> = (1..100).collect();
1861 // try this a bunch of times to make sure we don't screw up internal state.
1863 assert_eq
!(s
.len(), 99);
1867 let mut d
= s
.drain();
1868 for (i
, x
) in d
.by_ref().take(50).enumerate() {
1872 assert_eq
!(last_i
, 49);
1876 panic
!("s should be empty!");
1879 // reset to try again.
1889 struct Foo(&'
static str, i32);
1891 impl PartialEq
for Foo
{
1892 fn eq(&self, other
: &Self) -> bool
{
1899 impl hash
::Hash
for Foo
{
1900 fn hash
<H
: hash
::Hasher
>(&self, h
: &mut H
) {
1905 let mut s
= HashSet
::new();
1906 assert_eq
!(s
.replace(Foo("a", 1)), None
);
1907 assert_eq
!(s
.len(), 1);
1908 assert_eq
!(s
.replace(Foo("a", 2)), Some(Foo("a", 1)));
1909 assert_eq
!(s
.len(), 1);
1911 let mut it
= s
.iter();
1912 assert_eq
!(it
.next(), Some(&Foo("a", 2)));
1913 assert_eq
!(it
.next(), None
);
1917 fn test_extend_ref() {
1918 let mut a
= HashSet
::new();
1921 a
.extend(&[2, 3, 4]);
1923 assert_eq
!(a
.len(), 4);
1924 assert
!(a
.contains(&1));
1925 assert
!(a
.contains(&2));
1926 assert
!(a
.contains(&3));
1927 assert
!(a
.contains(&4));
1929 let mut b
= HashSet
::new();
1935 assert_eq
!(a
.len(), 6);
1936 assert
!(a
.contains(&1));
1937 assert
!(a
.contains(&2));
1938 assert
!(a
.contains(&3));
1939 assert
!(a
.contains(&4));
1940 assert
!(a
.contains(&5));
1941 assert
!(a
.contains(&6));
1946 let xs
= [1, 2, 3, 4, 5, 6];
1947 let mut set
: HashSet
<i32> = xs
.iter().cloned().collect();
1948 set
.retain(|&k
| k
% 2 == 0);
1949 assert_eq
!(set
.len(), 3);
1950 assert
!(set
.contains(&2));
1951 assert
!(set
.contains(&4));
1952 assert
!(set
.contains(&6));