1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use hash
::{Hash, BuildHasher}
;
14 use iter
::{Chain, FromIterator, FusedIterator}
;
15 use ops
::{BitOr, BitAnd, BitXor, Sub}
;
18 use super::map
::{self, HashMap, Keys, RandomState}
;
20 // Future Optimization (FIXME!)
21 // =============================
23 // Iteration over zero sized values is a noop. There is no need
24 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
25 // to get rid of it properly.
27 /// An implementation of a hash set using the underlying representation of a
28 /// HashMap where the value is ().
30 /// As with the `HashMap` type, a `HashSet` requires that the elements
31 /// implement the `Eq` and `Hash` traits. This can frequently be achieved by
32 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
33 /// it is important that the following property holds:
36 /// k1 == k2 -> hash(k1) == hash(k2)
39 /// In other words, if two keys are equal, their hashes must be equal.
42 /// It is a logic error for an item to be modified in such a way that the
43 /// item's hash, as determined by the `Hash` trait, or its equality, as
44 /// determined by the `Eq` trait, changes while it is in the set. This is
45 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or
51 /// use std::collections::HashSet;
52 /// // Type inference lets us omit an explicit type signature (which
53 /// // would be `HashSet<&str>` in this example).
54 /// let mut books = HashSet::new();
56 /// // Add some books.
57 /// books.insert("A Dance With Dragons");
58 /// books.insert("To Kill a Mockingbird");
59 /// books.insert("The Odyssey");
60 /// books.insert("The Great Gatsby");
62 /// // Check for a specific one.
63 /// if !books.contains("The Winds of Winter") {
64 /// println!("We have {} books, but The Winds of Winter ain't one.",
69 /// books.remove("The Odyssey");
71 /// // Iterate over everything.
72 /// for book in &books {
73 /// println!("{}", book);
77 /// The easiest way to use `HashSet` with a custom type is to derive
78 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
79 /// future be implied by `Eq`.
82 /// use std::collections::HashSet;
83 /// #[derive(Hash, Eq, PartialEq, Debug)]
84 /// struct Viking<'a> {
89 /// let mut vikings = HashSet::new();
91 /// vikings.insert(Viking { name: "Einar", power: 9 });
92 /// vikings.insert(Viking { name: "Einar", power: 9 });
93 /// vikings.insert(Viking { name: "Olaf", power: 4 });
94 /// vikings.insert(Viking { name: "Harald", power: 8 });
96 /// // Use derived implementation to print the vikings.
97 /// for x in &vikings {
98 /// println!("{:?}", x);
102 /// HashSet with fixed list of elements can be initialized from an array:
105 /// use std::collections::HashSet;
108 /// let viking_names: HashSet<&str> =
109 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
110 /// // use the values stored in the set
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub struct HashSet
<T
, S
= RandomState
> {
118 map
: HashMap
<T
, (), S
>,
121 impl<T
: Hash
+ Eq
> HashSet
<T
, RandomState
> {
122 /// Creates an empty HashSet.
127 /// use std::collections::HashSet;
128 /// let mut set: HashSet<i32> = HashSet::new();
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn new() -> HashSet
<T
, RandomState
> {
133 HashSet { map: HashMap::new() }
136 /// Creates an empty `HashSet` with the specified capacity.
138 /// The hash set will be able to hold at least `capacity` elements without
139 /// reallocating. If `capacity` is 0, the hash set will not allocate.
144 /// use std::collections::HashSet;
145 /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub fn with_capacity(capacity
: usize) -> HashSet
<T
, RandomState
> {
150 HashSet { map: HashMap::with_capacity(capacity) }
154 impl<T
, S
> HashSet
<T
, S
>
158 /// Creates a new empty hash set which will use the given hasher to hash
161 /// The hash set is also created with the default initial capacity.
163 /// Warning: `hasher` is normally randomly generated, and
164 /// is designed to allow `HashSet`s to be resistant to attacks that
165 /// cause many collisions and very poor performance. Setting it
166 /// manually using this function can expose a DoS attack vector.
171 /// use std::collections::HashSet;
172 /// use std::collections::hash_map::RandomState;
174 /// let s = RandomState::new();
175 /// let mut set = HashSet::with_hasher(s);
179 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
180 pub fn with_hasher(hasher
: S
) -> HashSet
<T
, S
> {
181 HashSet { map: HashMap::with_hasher(hasher) }
184 /// Creates an empty HashSet with with the specified capacity, using
185 /// `hasher` to hash the keys.
187 /// The hash set will be able to hold at least `capacity` elements without
188 /// reallocating. If `capacity` is 0, the hash set will not allocate.
190 /// Warning: `hasher` is normally randomly generated, and
191 /// is designed to allow `HashSet`s to be resistant to attacks that
192 /// cause many collisions and very poor performance. Setting it
193 /// manually using this function can expose a DoS attack vector.
198 /// use std::collections::HashSet;
199 /// use std::collections::hash_map::RandomState;
201 /// let s = RandomState::new();
202 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
206 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
207 pub fn with_capacity_and_hasher(capacity
: usize, hasher
: S
) -> HashSet
<T
, S
> {
208 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
211 /// Returns a reference to the set's hasher.
212 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
213 pub fn hasher(&self) -> &S
{
217 /// Returns the number of elements the set can hold without reallocating.
222 /// use std::collections::HashSet;
223 /// let set: HashSet<i32> = HashSet::with_capacity(100);
224 /// assert!(set.capacity() >= 100);
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn capacity(&self) -> usize {
232 /// Reserves capacity for at least `additional` more elements to be inserted
233 /// in the `HashSet`. The collection may reserve more space to avoid
234 /// frequent reallocations.
238 /// Panics if the new allocation size overflows `usize`.
243 /// use std::collections::HashSet;
244 /// let mut set: HashSet<i32> = HashSet::new();
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn reserve(&mut self, additional
: usize) {
249 self.map
.reserve(additional
)
252 /// Shrinks the capacity of the set as much as possible. It will drop
253 /// down as much as possible while maintaining the internal rules
254 /// and possibly leaving some space in accordance with the resize policy.
259 /// use std::collections::HashSet;
261 /// let mut set = HashSet::with_capacity(100);
264 /// assert!(set.capacity() >= 100);
265 /// set.shrink_to_fit();
266 /// assert!(set.capacity() >= 2);
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub fn shrink_to_fit(&mut self) {
270 self.map
.shrink_to_fit()
273 /// An iterator visiting all elements in arbitrary order.
274 /// Iterator element type is &'a T.
279 /// use std::collections::HashSet;
280 /// let mut set = HashSet::new();
284 /// // Will print in an arbitrary order.
285 /// for x in set.iter() {
286 /// println!("{}", x);
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn iter(&self) -> Iter
<T
> {
291 Iter { iter: self.map.keys() }
294 /// Visit the values representing the difference,
295 /// i.e. the values that are in `self` but not in `other`.
300 /// use std::collections::HashSet;
301 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
302 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
304 /// // Can be seen as `a - b`.
305 /// for x in a.difference(&b) {
306 /// println!("{}", x); // Print 1
309 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
310 /// assert_eq!(diff, [1].iter().cloned().collect());
312 /// // Note that difference is not symmetric,
313 /// // and `b - a` means something else:
314 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
315 /// assert_eq!(diff, [4].iter().cloned().collect());
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn difference
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Difference
<'a
, T
, S
> {
325 /// Visit the values representing the symmetric difference,
326 /// i.e. the values that are in `self` or in `other` but not in both.
331 /// use std::collections::HashSet;
332 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
333 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
335 /// // Print 1, 4 in arbitrary order.
336 /// for x in a.symmetric_difference(&b) {
337 /// println!("{}", x);
340 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
341 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
343 /// assert_eq!(diff1, diff2);
344 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub fn symmetric_difference
<'a
>(&'a
self,
348 other
: &'a HashSet
<T
, S
>)
349 -> SymmetricDifference
<'a
, T
, S
> {
350 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
353 /// Visit the values representing the intersection,
354 /// i.e. the values that are both in `self` and `other`.
359 /// use std::collections::HashSet;
360 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
361 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
363 /// // Print 2, 3 in arbitrary order.
364 /// for x in a.intersection(&b) {
365 /// println!("{}", x);
368 /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
369 /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn intersection
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Intersection
<'a
, T
, S
> {
379 /// Visit the values representing the union,
380 /// i.e. all the values in `self` or `other`, without duplicates.
385 /// use std::collections::HashSet;
386 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
387 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
389 /// // Print 1, 2, 3, 4 in arbitrary order.
390 /// for x in a.union(&b) {
391 /// println!("{}", x);
394 /// let union: HashSet<_> = a.union(&b).cloned().collect();
395 /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
397 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn union<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Union
<'a
, T
, S
> {
399 Union { iter: self.iter().chain(other.difference(self)) }
402 /// Returns the number of elements in the set.
407 /// use std::collections::HashSet;
409 /// let mut v = HashSet::new();
410 /// assert_eq!(v.len(), 0);
412 /// assert_eq!(v.len(), 1);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn len(&self) -> usize {
419 /// Returns true if the set contains no elements.
424 /// use std::collections::HashSet;
426 /// let mut v = HashSet::new();
427 /// assert!(v.is_empty());
429 /// assert!(!v.is_empty());
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn is_empty(&self) -> bool
{
436 /// Clears the set, returning all elements in an iterator.
438 #[stable(feature = "drain", since = "1.6.0")]
439 pub fn drain(&mut self) -> Drain
<T
> {
440 Drain { iter: self.map.drain() }
443 /// Clears the set, removing all values.
448 /// use std::collections::HashSet;
450 /// let mut v = HashSet::new();
453 /// assert!(v.is_empty());
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn clear(&mut self) {
460 /// Returns `true` if the set contains a value.
462 /// The value may be any borrowed form of the set's value type, but
463 /// `Hash` and `Eq` on the borrowed form *must* match those for
469 /// use std::collections::HashSet;
471 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
472 /// assert_eq!(set.contains(&1), true);
473 /// assert_eq!(set.contains(&4), false);
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn contains
<Q
: ?Sized
>(&self, value
: &Q
) -> bool
480 self.map
.contains_key(value
)
483 /// Returns a reference to the value in the set, if any, that is equal to the given value.
485 /// The value may be any borrowed form of the set's value type, but
486 /// `Hash` and `Eq` on the borrowed form *must* match those for
488 #[stable(feature = "set_recovery", since = "1.9.0")]
489 pub fn get
<Q
: ?Sized
>(&self, value
: &Q
) -> Option
<&T
>
493 Recover
::get(&self.map
, value
)
496 /// Returns `true` if `self` has no elements in common with `other`.
497 /// This is equivalent to checking for an empty intersection.
502 /// use std::collections::HashSet;
504 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
505 /// let mut b = HashSet::new();
507 /// assert_eq!(a.is_disjoint(&b), true);
509 /// assert_eq!(a.is_disjoint(&b), true);
511 /// assert_eq!(a.is_disjoint(&b), false);
513 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn is_disjoint(&self, other
: &HashSet
<T
, S
>) -> bool
{
515 self.iter().all(|v
| !other
.contains(v
))
518 /// Returns `true` if the set is a subset of another,
519 /// i.e. `other` contains at least all the values in `self`.
524 /// use std::collections::HashSet;
526 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
527 /// let mut set = HashSet::new();
529 /// assert_eq!(set.is_subset(&sup), true);
531 /// assert_eq!(set.is_subset(&sup), true);
533 /// assert_eq!(set.is_subset(&sup), false);
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn is_subset(&self, other
: &HashSet
<T
, S
>) -> bool
{
537 self.iter().all(|v
| other
.contains(v
))
540 /// Returns `true` if the set is a superset of another,
541 /// i.e. `self` contains at least all the values in `other`.
546 /// use std::collections::HashSet;
548 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
549 /// let mut set = HashSet::new();
551 /// assert_eq!(set.is_superset(&sub), false);
555 /// assert_eq!(set.is_superset(&sub), false);
558 /// assert_eq!(set.is_superset(&sub), true);
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn is_superset(&self, other
: &HashSet
<T
, S
>) -> bool
{
563 other
.is_subset(self)
566 /// Adds a value to the set.
568 /// If the set did not have this value present, `true` is returned.
570 /// If the set did have this value present, `false` is returned.
575 /// use std::collections::HashSet;
577 /// let mut set = HashSet::new();
579 /// assert_eq!(set.insert(2), true);
580 /// assert_eq!(set.insert(2), false);
581 /// assert_eq!(set.len(), 1);
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn insert(&mut self, value
: T
) -> bool
{
585 self.map
.insert(value
, ()).is_none()
588 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
589 /// one. Returns the replaced value.
590 #[stable(feature = "set_recovery", since = "1.9.0")]
591 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
592 Recover
::replace(&mut self.map
, value
)
595 /// Removes a value from the set. Returns `true` if the value was
596 /// present in the set.
598 /// The value may be any borrowed form of the set's value type, but
599 /// `Hash` and `Eq` on the borrowed form *must* match those for
605 /// use std::collections::HashSet;
607 /// let mut set = HashSet::new();
610 /// assert_eq!(set.remove(&2), true);
611 /// assert_eq!(set.remove(&2), false);
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn remove
<Q
: ?Sized
>(&mut self, value
: &Q
) -> bool
618 self.map
.remove(value
).is_some()
621 /// Removes and returns the value in the set, if any, that is equal to the given one.
623 /// The value may be any borrowed form of the set's value type, but
624 /// `Hash` and `Eq` on the borrowed form *must* match those for
626 #[stable(feature = "set_recovery", since = "1.9.0")]
627 pub fn take
<Q
: ?Sized
>(&mut self, value
: &Q
) -> Option
<T
>
631 Recover
::take(&mut self.map
, value
)
634 /// Retains only the elements specified by the predicate.
636 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
641 /// #![feature(retain_hash_collection)]
642 /// use std::collections::HashSet;
644 /// let xs = [1,2,3,4,5,6];
645 /// let mut set: HashSet<isize> = xs.iter().cloned().collect();
646 /// set.retain(|&k| k % 2 == 0);
647 /// assert_eq!(set.len(), 3);
649 #[unstable(feature = "retain_hash_collection", issue = "36648")]
650 pub fn retain
<F
>(&mut self, mut f
: F
)
651 where F
: FnMut(&T
) -> bool
653 self.map
.retain(|k
, _
| f(k
));
657 #[stable(feature = "rust1", since = "1.0.0")]
658 impl<T
, S
> PartialEq
for HashSet
<T
, S
>
662 fn eq(&self, other
: &HashSet
<T
, S
>) -> bool
{
663 if self.len() != other
.len() {
667 self.iter().all(|key
| other
.contains(key
))
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl<T
, S
> Eq
for HashSet
<T
, S
>
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T
, S
> fmt
::Debug
for HashSet
<T
, S
>
680 where T
: Eq
+ Hash
+ fmt
::Debug
,
683 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
684 f
.debug_set().entries(self.iter()).finish()
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl<T
, S
> FromIterator
<T
> for HashSet
<T
, S
>
691 S
: BuildHasher
+ Default
693 fn from_iter
<I
: IntoIterator
<Item
= T
>>(iter
: I
) -> HashSet
<T
, S
> {
694 let mut set
= HashSet
::with_hasher(Default
::default());
700 #[stable(feature = "rust1", since = "1.0.0")]
701 impl<T
, S
> Extend
<T
> for HashSet
<T
, S
>
705 fn extend
<I
: IntoIterator
<Item
= T
>>(&mut self, iter
: I
) {
706 self.map
.extend(iter
.into_iter().map(|k
| (k
, ())));
710 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
711 impl<'a
, T
, S
> Extend
<&'a T
> for HashSet
<T
, S
>
712 where T
: 'a
+ Eq
+ Hash
+ Copy
,
715 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
716 self.extend(iter
.into_iter().cloned());
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl<T
, S
> Default
for HashSet
<T
, S
>
723 S
: BuildHasher
+ Default
725 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
726 fn default() -> HashSet
<T
, S
> {
727 HashSet { map: HashMap::default() }
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl<'a
, 'b
, T
, S
> BitOr
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
733 where T
: Eq
+ Hash
+ Clone
,
734 S
: BuildHasher
+ Default
736 type Output
= HashSet
<T
, S
>;
738 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
743 /// use std::collections::HashSet;
745 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
746 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
748 /// let set = &a | &b;
751 /// let expected = [1, 2, 3, 4, 5];
753 /// assert!(expected.contains(x));
756 /// assert_eq!(i, expected.len());
758 fn bitor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
759 self.union(rhs
).cloned().collect()
763 #[stable(feature = "rust1", since = "1.0.0")]
764 impl<'a
, 'b
, T
, S
> BitAnd
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
765 where T
: Eq
+ Hash
+ Clone
,
766 S
: BuildHasher
+ Default
768 type Output
= HashSet
<T
, S
>;
770 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
775 /// use std::collections::HashSet;
777 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
778 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
780 /// let set = &a & &b;
783 /// let expected = [2, 3];
785 /// assert!(expected.contains(x));
788 /// assert_eq!(i, expected.len());
790 fn bitand(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
791 self.intersection(rhs
).cloned().collect()
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl<'a
, 'b
, T
, S
> BitXor
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
797 where T
: Eq
+ Hash
+ Clone
,
798 S
: BuildHasher
+ Default
800 type Output
= HashSet
<T
, S
>;
802 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
807 /// use std::collections::HashSet;
809 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
810 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
812 /// let set = &a ^ &b;
815 /// let expected = [1, 2, 4, 5];
817 /// assert!(expected.contains(x));
820 /// assert_eq!(i, expected.len());
822 fn bitxor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
823 self.symmetric_difference(rhs
).cloned().collect()
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl<'a
, 'b
, T
, S
> Sub
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
829 where T
: Eq
+ Hash
+ Clone
,
830 S
: BuildHasher
+ Default
832 type Output
= HashSet
<T
, S
>;
834 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
839 /// use std::collections::HashSet;
841 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
842 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
844 /// let set = &a - &b;
847 /// let expected = [1, 2];
849 /// assert!(expected.contains(x));
852 /// assert_eq!(i, expected.len());
854 fn sub(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
855 self.difference(rhs
).cloned().collect()
860 #[stable(feature = "rust1", since = "1.0.0")]
861 pub struct Iter
<'a
, K
: 'a
> {
862 iter
: Keys
<'a
, K
, ()>,
865 /// HashSet move iterator
866 #[stable(feature = "rust1", since = "1.0.0")]
867 pub struct IntoIter
<K
> {
868 iter
: map
::IntoIter
<K
, ()>,
871 /// HashSet drain iterator
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub struct Drain
<'a
, K
: 'a
> {
874 iter
: map
::Drain
<'a
, K
, ()>,
877 /// Intersection iterator
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub struct Intersection
<'a
, T
: 'a
, S
: 'a
> {
880 // iterator of the first set
883 other
: &'a HashSet
<T
, S
>,
886 /// Difference iterator
887 #[stable(feature = "rust1", since = "1.0.0")]
888 pub struct Difference
<'a
, T
: 'a
, S
: 'a
> {
889 // iterator of the first set
892 other
: &'a HashSet
<T
, S
>,
895 /// Symmetric difference iterator.
896 #[stable(feature = "rust1", since = "1.0.0")]
897 pub struct SymmetricDifference
<'a
, T
: 'a
, S
: 'a
> {
898 iter
: Chain
<Difference
<'a
, T
, S
>, Difference
<'a
, T
, S
>>,
901 /// Set union iterator.
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub struct Union
<'a
, T
: 'a
, S
: 'a
> {
904 iter
: Chain
<Iter
<'a
, T
>, Difference
<'a
, T
, S
>>,
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<'a
, T
, S
> IntoIterator
for &'a HashSet
<T
, S
>
913 type IntoIter
= Iter
<'a
, T
>;
915 fn into_iter(self) -> Iter
<'a
, T
> {
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl<T
, S
> IntoIterator
for HashSet
<T
, S
>
926 type IntoIter
= IntoIter
<T
>;
928 /// Creates a consuming iterator, that is, one that moves each value out
929 /// of the set in arbitrary order. The set cannot be used after calling
935 /// use std::collections::HashSet;
936 /// let mut set = HashSet::new();
937 /// set.insert("a".to_string());
938 /// set.insert("b".to_string());
940 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
941 /// let v: Vec<String> = set.into_iter().collect();
943 /// // Will print in an arbitrary order.
945 /// println!("{}", x);
948 fn into_iter(self) -> IntoIter
<T
> {
949 IntoIter { iter: self.map.into_iter() }
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<'a
, K
> Clone
for Iter
<'a
, K
> {
955 fn clone(&self) -> Iter
<'a
, K
> {
956 Iter { iter: self.iter.clone() }
959 #[stable(feature = "rust1", since = "1.0.0")]
960 impl<'a
, K
> Iterator
for Iter
<'a
, K
> {
963 fn next(&mut self) -> Option
<&'a K
> {
966 fn size_hint(&self) -> (usize, Option
<usize>) {
967 self.iter
.size_hint()
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<'a
, K
> ExactSizeIterator
for Iter
<'a
, K
> {
972 fn len(&self) -> usize {
976 #[unstable(feature = "fused", issue = "35602")]
977 impl<'a
, K
> FusedIterator
for Iter
<'a
, K
> {}
979 #[stable(feature = "std_debug", since = "1.16.0")]
980 impl<'a
, K
: fmt
::Debug
> fmt
::Debug
for Iter
<'a
, K
> {
981 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
983 .entries(self.clone())
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<K
> Iterator
for IntoIter
<K
> {
992 fn next(&mut self) -> Option
<K
> {
993 self.iter
.next().map(|(k
, _
)| k
)
995 fn size_hint(&self) -> (usize, Option
<usize>) {
996 self.iter
.size_hint()
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl<K
> ExactSizeIterator
for IntoIter
<K
> {
1001 fn len(&self) -> usize {
1005 #[unstable(feature = "fused", issue = "35602")]
1006 impl<K
> FusedIterator
for IntoIter
<K
> {}
1008 #[stable(feature = "std_debug", since = "1.16.0")]
1009 impl<K
: fmt
::Debug
> fmt
::Debug
for IntoIter
<K
> {
1010 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1011 let entries_iter
= self.iter
.inner
.iter().map(|(k
, _
)| k
);
1013 .entries(entries_iter
)
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 impl<'a
, K
> Iterator
for Drain
<'a
, K
> {
1022 fn next(&mut self) -> Option
<K
> {
1023 self.iter
.next().map(|(k
, _
)| k
)
1025 fn size_hint(&self) -> (usize, Option
<usize>) {
1026 self.iter
.size_hint()
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 impl<'a
, K
> ExactSizeIterator
for Drain
<'a
, K
> {
1031 fn len(&self) -> usize {
1035 #[unstable(feature = "fused", issue = "35602")]
1036 impl<'a
, K
> FusedIterator
for Drain
<'a
, K
> {}
1038 #[stable(feature = "std_debug", since = "1.16.0")]
1039 impl<'a
, K
: fmt
::Debug
> fmt
::Debug
for Drain
<'a
, K
> {
1040 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1041 let entries_iter
= self.iter
.inner
.iter().map(|(k
, _
)| k
);
1043 .entries(entries_iter
)
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 impl<'a
, T
, S
> Clone
for Intersection
<'a
, T
, S
> {
1050 fn clone(&self) -> Intersection
<'a
, T
, S
> {
1051 Intersection { iter: self.iter.clone(), ..*self }
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<'a
, T
, S
> Iterator
for Intersection
<'a
, T
, S
>
1062 fn next(&mut self) -> Option
<&'a T
> {
1064 match self.iter
.next() {
1065 None
=> return None
,
1067 if self.other
.contains(elt
) {
1075 fn size_hint(&self) -> (usize, Option
<usize>) {
1076 let (_
, upper
) = self.iter
.size_hint();
1081 #[stable(feature = "std_debug", since = "1.16.0")]
1082 impl<'a
, T
, S
> fmt
::Debug
for Intersection
<'a
, T
, S
>
1083 where T
: fmt
::Debug
+ Eq
+ Hash
,
1086 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1088 .entries(self.clone())
1093 #[unstable(feature = "fused", issue = "35602")]
1094 impl<'a
, T
, S
> FusedIterator
for Intersection
<'a
, T
, S
>
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<'a
, T
, S
> Clone
for Difference
<'a
, T
, S
> {
1102 fn clone(&self) -> Difference
<'a
, T
, S
> {
1103 Difference { iter: self.iter.clone(), ..*self }
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 impl<'a
, T
, S
> Iterator
for Difference
<'a
, T
, S
>
1114 fn next(&mut self) -> Option
<&'a T
> {
1116 match self.iter
.next() {
1117 None
=> return None
,
1119 if !self.other
.contains(elt
) {
1127 fn size_hint(&self) -> (usize, Option
<usize>) {
1128 let (_
, upper
) = self.iter
.size_hint();
1133 #[unstable(feature = "fused", issue = "35602")]
1134 impl<'a
, T
, S
> FusedIterator
for Difference
<'a
, T
, S
>
1140 #[stable(feature = "std_debug", since = "1.16.0")]
1141 impl<'a
, T
, S
> fmt
::Debug
for Difference
<'a
, T
, S
>
1142 where T
: fmt
::Debug
+ Eq
+ Hash
,
1145 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1147 .entries(self.clone())
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 impl<'a
, T
, S
> Clone
for SymmetricDifference
<'a
, T
, S
> {
1154 fn clone(&self) -> SymmetricDifference
<'a
, T
, S
> {
1155 SymmetricDifference { iter: self.iter.clone() }
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<'a
, T
, S
> Iterator
for SymmetricDifference
<'a
, T
, S
>
1166 fn next(&mut self) -> Option
<&'a T
> {
1169 fn size_hint(&self) -> (usize, Option
<usize>) {
1170 self.iter
.size_hint()
1174 #[unstable(feature = "fused", issue = "35602")]
1175 impl<'a
, T
, S
> FusedIterator
for SymmetricDifference
<'a
, T
, S
>
1181 #[stable(feature = "std_debug", since = "1.16.0")]
1182 impl<'a
, T
, S
> fmt
::Debug
for SymmetricDifference
<'a
, T
, S
>
1183 where T
: fmt
::Debug
+ Eq
+ Hash
,
1186 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1188 .entries(self.clone())
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<'a
, T
, S
> Clone
for Union
<'a
, T
, S
> {
1195 fn clone(&self) -> Union
<'a
, T
, S
> {
1196 Union { iter: self.iter.clone() }
1200 #[unstable(feature = "fused", issue = "35602")]
1201 impl<'a
, T
, S
> FusedIterator
for Union
<'a
, T
, S
>
1207 #[stable(feature = "std_debug", since = "1.16.0")]
1208 impl<'a
, T
, S
> fmt
::Debug
for Union
<'a
, T
, S
>
1209 where T
: fmt
::Debug
+ Eq
+ Hash
,
1212 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1214 .entries(self.clone())
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 impl<'a
, T
, S
> Iterator
for Union
<'a
, T
, S
>
1226 fn next(&mut self) -> Option
<&'a T
> {
1229 fn size_hint(&self) -> (usize, Option
<usize>) {
1230 self.iter
.size_hint()
1235 fn assert_covariance() {
1236 fn set
<'new
>(v
: HashSet
<&'
static str>) -> HashSet
<&'new
str> {
1239 fn iter
<'a
, 'new
>(v
: Iter
<'a
, &'
static str>) -> Iter
<'a
, &'new
str> {
1242 fn into_iter
<'new
>(v
: IntoIter
<&'
static str>) -> IntoIter
<&'new
str> {
1245 fn difference
<'a
, 'new
>(v
: Difference
<'a
, &'
static str, RandomState
>)
1246 -> Difference
<'a
, &'new
str, RandomState
> {
1249 fn symmetric_difference
<'a
, 'new
>(v
: SymmetricDifference
<'a
, &'
static str, RandomState
>)
1250 -> SymmetricDifference
<'a
, &'new
str, RandomState
> {
1253 fn intersection
<'a
, 'new
>(v
: Intersection
<'a
, &'
static str, RandomState
>)
1254 -> Intersection
<'a
, &'new
str, RandomState
> {
1257 fn union<'a
, 'new
>(v
: Union
<'a
, &'
static str, RandomState
>)
1258 -> Union
<'a
, &'new
str, RandomState
> {
1261 fn drain
<'new
>(d
: Drain
<'
static, &'
static str>) -> Drain
<'new
, &'new
str> {
1269 use super::super::map
::RandomState
;
1272 fn test_zero_capacities() {
1273 type HS
= HashSet
<i32>;
1276 assert_eq
!(s
.capacity(), 0);
1278 let s
= HS
::default();
1279 assert_eq
!(s
.capacity(), 0);
1281 let s
= HS
::with_hasher(RandomState
::new());
1282 assert_eq
!(s
.capacity(), 0);
1284 let s
= HS
::with_capacity(0);
1285 assert_eq
!(s
.capacity(), 0);
1287 let s
= HS
::with_capacity_and_hasher(0, RandomState
::new());
1288 assert_eq
!(s
.capacity(), 0);
1290 let mut s
= HS
::new();
1296 assert_eq
!(s
.capacity(), 0);
1298 let mut s
= HS
::new();
1300 assert_eq
!(s
.capacity(), 0);
1304 fn test_disjoint() {
1305 let mut xs
= HashSet
::new();
1306 let mut ys
= HashSet
::new();
1307 assert
!(xs
.is_disjoint(&ys
));
1308 assert
!(ys
.is_disjoint(&xs
));
1309 assert
!(xs
.insert(5));
1310 assert
!(ys
.insert(11));
1311 assert
!(xs
.is_disjoint(&ys
));
1312 assert
!(ys
.is_disjoint(&xs
));
1313 assert
!(xs
.insert(7));
1314 assert
!(xs
.insert(19));
1315 assert
!(xs
.insert(4));
1316 assert
!(ys
.insert(2));
1317 assert
!(ys
.insert(-11));
1318 assert
!(xs
.is_disjoint(&ys
));
1319 assert
!(ys
.is_disjoint(&xs
));
1320 assert
!(ys
.insert(7));
1321 assert
!(!xs
.is_disjoint(&ys
));
1322 assert
!(!ys
.is_disjoint(&xs
));
1326 fn test_subset_and_superset() {
1327 let mut a
= HashSet
::new();
1328 assert
!(a
.insert(0));
1329 assert
!(a
.insert(5));
1330 assert
!(a
.insert(11));
1331 assert
!(a
.insert(7));
1333 let mut b
= HashSet
::new();
1334 assert
!(b
.insert(0));
1335 assert
!(b
.insert(7));
1336 assert
!(b
.insert(19));
1337 assert
!(b
.insert(250));
1338 assert
!(b
.insert(11));
1339 assert
!(b
.insert(200));
1341 assert
!(!a
.is_subset(&b
));
1342 assert
!(!a
.is_superset(&b
));
1343 assert
!(!b
.is_subset(&a
));
1344 assert
!(!b
.is_superset(&a
));
1346 assert
!(b
.insert(5));
1348 assert
!(a
.is_subset(&b
));
1349 assert
!(!a
.is_superset(&b
));
1350 assert
!(!b
.is_subset(&a
));
1351 assert
!(b
.is_superset(&a
));
1356 let mut a
= HashSet
::new();
1358 assert
!(a
.insert(i
));
1360 let mut observed
: u32 = 0;
1362 observed
|= 1 << *k
;
1364 assert_eq
!(observed
, 0xFFFF_FFFF);
1368 fn test_intersection() {
1369 let mut a
= HashSet
::new();
1370 let mut b
= HashSet
::new();
1372 assert
!(a
.insert(11));
1373 assert
!(a
.insert(1));
1374 assert
!(a
.insert(3));
1375 assert
!(a
.insert(77));
1376 assert
!(a
.insert(103));
1377 assert
!(a
.insert(5));
1378 assert
!(a
.insert(-5));
1380 assert
!(b
.insert(2));
1381 assert
!(b
.insert(11));
1382 assert
!(b
.insert(77));
1383 assert
!(b
.insert(-9));
1384 assert
!(b
.insert(-42));
1385 assert
!(b
.insert(5));
1386 assert
!(b
.insert(3));
1389 let expected
= [3, 5, 11, 77];
1390 for x
in a
.intersection(&b
) {
1391 assert
!(expected
.contains(x
));
1394 assert_eq
!(i
, expected
.len());
1398 fn test_difference() {
1399 let mut a
= HashSet
::new();
1400 let mut b
= HashSet
::new();
1402 assert
!(a
.insert(1));
1403 assert
!(a
.insert(3));
1404 assert
!(a
.insert(5));
1405 assert
!(a
.insert(9));
1406 assert
!(a
.insert(11));
1408 assert
!(b
.insert(3));
1409 assert
!(b
.insert(9));
1412 let expected
= [1, 5, 11];
1413 for x
in a
.difference(&b
) {
1414 assert
!(expected
.contains(x
));
1417 assert_eq
!(i
, expected
.len());
1421 fn test_symmetric_difference() {
1422 let mut a
= HashSet
::new();
1423 let mut b
= HashSet
::new();
1425 assert
!(a
.insert(1));
1426 assert
!(a
.insert(3));
1427 assert
!(a
.insert(5));
1428 assert
!(a
.insert(9));
1429 assert
!(a
.insert(11));
1431 assert
!(b
.insert(-2));
1432 assert
!(b
.insert(3));
1433 assert
!(b
.insert(9));
1434 assert
!(b
.insert(14));
1435 assert
!(b
.insert(22));
1438 let expected
= [-2, 1, 5, 11, 14, 22];
1439 for x
in a
.symmetric_difference(&b
) {
1440 assert
!(expected
.contains(x
));
1443 assert_eq
!(i
, expected
.len());
1448 let mut a
= HashSet
::new();
1449 let mut b
= HashSet
::new();
1451 assert
!(a
.insert(1));
1452 assert
!(a
.insert(3));
1453 assert
!(a
.insert(5));
1454 assert
!(a
.insert(9));
1455 assert
!(a
.insert(11));
1456 assert
!(a
.insert(16));
1457 assert
!(a
.insert(19));
1458 assert
!(a
.insert(24));
1460 assert
!(b
.insert(-2));
1461 assert
!(b
.insert(1));
1462 assert
!(b
.insert(5));
1463 assert
!(b
.insert(9));
1464 assert
!(b
.insert(13));
1465 assert
!(b
.insert(19));
1468 let expected
= [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1469 for x
in a
.union(&b
) {
1470 assert
!(expected
.contains(x
));
1473 assert_eq
!(i
, expected
.len());
1477 fn test_from_iter() {
1478 let xs
= [1, 2, 3, 4, 5, 6, 7, 8, 9];
1480 let set
: HashSet
<_
> = xs
.iter().cloned().collect();
1483 assert
!(set
.contains(x
));
1488 fn test_move_iter() {
1490 let mut hs
= HashSet
::new();
1498 let v
= hs
.into_iter().collect
::<Vec
<char>>();
1499 assert
!(v
== ['a'
, 'b'
] || v
== ['b'
, 'a'
]);
1504 // These constants once happened to expose a bug in insert().
1505 // I'm keeping them around to prevent a regression.
1506 let mut s1
= HashSet
::new();
1512 let mut s2
= HashSet
::new();
1526 let mut set
= HashSet
::new();
1527 let empty
= HashSet
::<i32>::new();
1532 let set_str
= format
!("{:?}", set
);
1534 assert
!(set_str
== "{1, 2}" || set_str
== "{2, 1}");
1535 assert_eq
!(format
!("{:?}", empty
), "{}");
1539 fn test_trivial_drain() {
1540 let mut s
= HashSet
::<i32>::new();
1541 for _
in s
.drain() {}
1542 assert
!(s
.is_empty());
1545 let mut s
= HashSet
::<i32>::new();
1547 assert
!(s
.is_empty());
1552 let mut s
: HashSet
<_
> = (1..100).collect();
1554 // try this a bunch of times to make sure we don't screw up internal state.
1556 assert_eq
!(s
.len(), 99);
1560 let mut d
= s
.drain();
1561 for (i
, x
) in d
.by_ref().take(50).enumerate() {
1565 assert_eq
!(last_i
, 49);
1569 panic
!("s should be empty!");
1572 // reset to try again.
1582 struct Foo(&'
static str, i32);
1584 impl PartialEq
for Foo
{
1585 fn eq(&self, other
: &Self) -> bool
{
1592 impl hash
::Hash
for Foo
{
1593 fn hash
<H
: hash
::Hasher
>(&self, h
: &mut H
) {
1598 let mut s
= HashSet
::new();
1599 assert_eq
!(s
.replace(Foo("a", 1)), None
);
1600 assert_eq
!(s
.len(), 1);
1601 assert_eq
!(s
.replace(Foo("a", 2)), Some(Foo("a", 1)));
1602 assert_eq
!(s
.len(), 1);
1604 let mut it
= s
.iter();
1605 assert_eq
!(it
.next(), Some(&Foo("a", 2)));
1606 assert_eq
!(it
.next(), None
);
1610 fn test_extend_ref() {
1611 let mut a
= HashSet
::new();
1614 a
.extend(&[2, 3, 4]);
1616 assert_eq
!(a
.len(), 4);
1617 assert
!(a
.contains(&1));
1618 assert
!(a
.contains(&2));
1619 assert
!(a
.contains(&3));
1620 assert
!(a
.contains(&4));
1622 let mut b
= HashSet
::new();
1628 assert_eq
!(a
.len(), 6);
1629 assert
!(a
.contains(&1));
1630 assert
!(a
.contains(&2));
1631 assert
!(a
.contains(&3));
1632 assert
!(a
.contains(&4));
1633 assert
!(a
.contains(&5));
1634 assert
!(a
.contains(&6));
1639 let xs
= [1,2,3,4,5,6];
1640 let mut set
: HashSet
<isize> = xs
.iter().cloned().collect();
1641 set
.retain(|&k
| k
% 2 == 0);
1642 assert_eq
!(set
.len(), 3);
1643 assert
!(set
.contains(&2));
1644 assert
!(set
.contains(&4));
1645 assert
!(set
.contains(&6));