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.
11 // ignore-lexer-test FIXME #15883
15 use cmp
::{Eq, PartialEq}
;
16 use core
::marker
::Sized
;
21 use iter
::{Iterator, IntoIterator, ExactSizeIterator, FromIterator, Map, Chain, Extend}
;
22 use ops
::{BitOr, BitAnd, BitXor, Sub}
;
23 use option
::Option
::{Some, None, self}
;
25 use super::map
::{self, HashMap, Keys, INITIAL_CAPACITY, RandomState}
;
26 use super::state
::HashState
;
28 // Future Optimization (FIXME!)
29 // =============================
31 // Iteration over zero sized values is a noop. There is no need
32 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
33 // to get rid of it properly.
35 /// An implementation of a hash set using the underlying representation of a
36 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
37 /// requires that the elements implement the `Eq` and `Hash` traits. This can
38 /// frequently be achieved by using `#[derive(Eq, Hash)]`. If you implement
39 /// these yourself, it is important that the following property holds:
42 /// k1 == k2 -> hash(k1) == hash(k2)
45 /// In other words, if two keys are equal, their hashes must be equal.
48 /// It is a logic error for an item to be modified in such a way that the
49 /// item's hash, as determined by the `Hash` trait, or its equality, as
50 /// determined by the `Eq` trait, changes while it is in the set. This is
51 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or
57 /// use std::collections::HashSet;
58 /// // Type inference lets us omit an explicit type signature (which
59 /// // would be `HashSet<&str>` in this example).
60 /// let mut books = HashSet::new();
62 /// // Add some books.
63 /// books.insert("A Dance With Dragons");
64 /// books.insert("To Kill a Mockingbird");
65 /// books.insert("The Odyssey");
66 /// books.insert("The Great Gatsby");
68 /// // Check for a specific one.
69 /// if !books.contains(&("The Winds of Winter")) {
70 /// println!("We have {} books, but The Winds of Winter ain't one.",
75 /// books.remove(&"The Odyssey");
77 /// // Iterate over everything.
78 /// for book in books.iter() {
79 /// println!("{}", *book);
83 /// The easiest way to use `HashSet` with a custom type is to derive
84 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
85 /// future be implied by `Eq`.
88 /// use std::collections::HashSet;
89 /// #[derive(Hash, Eq, PartialEq, Debug)]
90 /// struct Viking<'a> {
95 /// let mut vikings = HashSet::new();
97 /// vikings.insert(Viking { name: "Einar", power: 9 });
98 /// vikings.insert(Viking { name: "Einar", power: 9 });
99 /// vikings.insert(Viking { name: "Olaf", power: 4 });
100 /// vikings.insert(Viking { name: "Harald", power: 8 });
102 /// // Use derived implementation to print the vikings.
103 /// for x in vikings.iter() {
104 /// println!("{:?}", x);
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.
119 /// use std::collections::HashSet;
120 /// let mut set: HashSet<i32> = HashSet::new();
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub fn new() -> HashSet
<T
, RandomState
> {
125 HashSet
::with_capacity(INITIAL_CAPACITY
)
128 /// Creates an empty HashSet with space for at least `n` elements in
134 /// use std::collections::HashSet;
135 /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn with_capacity(capacity
: usize) -> HashSet
<T
, RandomState
> {
140 HashSet { map: HashMap::with_capacity(capacity) }
144 impl<T
, S
> HashSet
<T
, S
>
145 where T
: Eq
+ Hash
, S
: HashState
147 /// Creates a new empty hash set which will use the given hasher to hash
150 /// The hash set is also created with the default initial capacity.
155 /// # #![feature(std_misc)]
156 /// use std::collections::HashSet;
157 /// use std::collections::hash_map::RandomState;
159 /// let s = RandomState::new();
160 /// let mut set = HashSet::with_hash_state(s);
164 #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
165 pub fn with_hash_state(hash_state
: S
) -> HashSet
<T
, S
> {
166 HashSet
::with_capacity_and_hash_state(INITIAL_CAPACITY
, hash_state
)
169 /// Creates an empty HashSet with space for at least `capacity`
170 /// elements in the hash table, using `hasher` to hash the keys.
172 /// Warning: `hasher` is normally randomly generated, and
173 /// is designed to allow `HashSet`s to be resistant to attacks that
174 /// cause many collisions and very poor performance. Setting it
175 /// manually using this function can expose a DoS attack vector.
180 /// # #![feature(std_misc)]
181 /// use std::collections::HashSet;
182 /// use std::collections::hash_map::RandomState;
184 /// let s = RandomState::new();
185 /// let mut set = HashSet::with_capacity_and_hash_state(10, s);
189 #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
190 pub fn with_capacity_and_hash_state(capacity
: usize, hash_state
: S
)
193 map
: HashMap
::with_capacity_and_hash_state(capacity
, hash_state
),
197 /// Returns the number of elements the set can hold without reallocating.
202 /// use std::collections::HashSet;
203 /// let set: HashSet<i32> = HashSet::with_capacity(100);
204 /// assert!(set.capacity() >= 100);
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn capacity(&self) -> usize {
212 /// Reserves capacity for at least `additional` more elements to be inserted
213 /// in the `HashSet`. The collection may reserve more space to avoid
214 /// frequent reallocations.
218 /// Panics if the new allocation size overflows `usize`.
223 /// use std::collections::HashSet;
224 /// let mut set: HashSet<i32> = HashSet::new();
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn reserve(&mut self, additional
: usize) {
229 self.map
.reserve(additional
)
232 /// Shrinks the capacity of the set as much as possible. It will drop
233 /// down as much as possible while maintaining the internal rules
234 /// and possibly leaving some space in accordance with the resize policy.
239 /// use std::collections::HashSet;
241 /// let mut set = HashSet::with_capacity(100);
244 /// assert!(set.capacity() >= 100);
245 /// set.shrink_to_fit();
246 /// assert!(set.capacity() >= 2);
248 #[stable(feature = "rust1", since = "1.0.0")]
249 pub fn shrink_to_fit(&mut self) {
250 self.map
.shrink_to_fit()
253 /// An iterator visiting all elements in arbitrary order.
254 /// Iterator element type is &'a T.
259 /// use std::collections::HashSet;
260 /// let mut set = HashSet::new();
264 /// // Will print in an arbitrary order.
265 /// for x in set.iter() {
266 /// println!("{}", x);
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn iter(&self) -> Iter
<T
> {
271 Iter { iter: self.map.keys() }
274 /// Visit the values representing the difference.
279 /// use std::collections::HashSet;
280 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
281 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
283 /// // Can be seen as `a - b`.
284 /// for x in a.difference(&b) {
285 /// println!("{}", x); // Print 1
288 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
289 /// assert_eq!(diff, [1].iter().cloned().collect());
291 /// // Note that difference is not symmetric,
292 /// // and `b - a` means something else:
293 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
294 /// assert_eq!(diff, [4].iter().cloned().collect());
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn difference
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Difference
<'a
, T
, S
> {
304 /// Visit the values representing the symmetric difference.
309 /// use std::collections::HashSet;
310 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
311 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
313 /// // Print 1, 4 in arbitrary order.
314 /// for x in a.symmetric_difference(&b) {
315 /// println!("{}", x);
318 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
319 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
321 /// assert_eq!(diff1, diff2);
322 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn symmetric_difference
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>)
326 -> SymmetricDifference
<'a
, T
, S
> {
327 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
330 /// Visit the values representing the intersection.
335 /// use std::collections::HashSet;
336 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
337 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
339 /// // Print 2, 3 in arbitrary order.
340 /// for x in a.intersection(&b) {
341 /// println!("{}", x);
344 /// let diff: HashSet<_> = a.intersection(&b).cloned().collect();
345 /// assert_eq!(diff, [2, 3].iter().cloned().collect());
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn intersection
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Intersection
<'a
, T
, S
> {
355 /// Visit the values representing the union.
360 /// use std::collections::HashSet;
361 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
362 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
364 /// // Print 1, 2, 3, 4 in arbitrary order.
365 /// for x in a.union(&b) {
366 /// println!("{}", x);
369 /// let diff: HashSet<_> = a.union(&b).cloned().collect();
370 /// assert_eq!(diff, [1, 2, 3, 4].iter().cloned().collect());
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn union<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Union
<'a
, T
, S
> {
374 Union { iter: self.iter().chain(other.difference(self)) }
377 /// Returns the number of elements in the set.
382 /// use std::collections::HashSet;
384 /// let mut v = HashSet::new();
385 /// assert_eq!(v.len(), 0);
387 /// assert_eq!(v.len(), 1);
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn len(&self) -> usize { self.map.len() }
392 /// Returns true if the set contains no elements.
397 /// use std::collections::HashSet;
399 /// let mut v = HashSet::new();
400 /// assert!(v.is_empty());
402 /// assert!(!v.is_empty());
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn is_empty(&self) -> bool { self.map.is_empty() }
407 /// Clears the set, returning all elements in an iterator.
409 #[unstable(feature = "std_misc",
410 reason
= "matches collection reform specification, waiting for dust to settle")]
411 pub fn drain(&mut self) -> Drain
<T
> {
412 fn first
<A
, B
>((a
, _
): (A
, B
)) -> A { a }
413 let first
: fn((T
, ())) -> T
= first
; // coerce to fn pointer
415 Drain { iter: self.map.drain().map(first) }
418 /// Clears the set, removing all values.
423 /// use std::collections::HashSet;
425 /// let mut v = HashSet::new();
428 /// assert!(v.is_empty());
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn clear(&mut self) { self.map.clear() }
433 /// Returns `true` if the set contains a value.
435 /// The value may be any borrowed form of the set's value type, but
436 /// `Hash` and `Eq` on the borrowed form *must* match those for
442 /// use std::collections::HashSet;
444 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
445 /// assert_eq!(set.contains(&1), true);
446 /// assert_eq!(set.contains(&4), false);
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn contains
<Q
: ?Sized
>(&self, value
: &Q
) -> bool
450 where T
: Borrow
<Q
>, Q
: Hash
+ Eq
452 self.map
.contains_key(value
)
455 /// Returns `true` if the set has no elements in common with `other`.
456 /// This is equivalent to checking for an empty intersection.
461 /// use std::collections::HashSet;
463 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
464 /// let mut b = HashSet::new();
466 /// assert_eq!(a.is_disjoint(&b), true);
468 /// assert_eq!(a.is_disjoint(&b), true);
470 /// assert_eq!(a.is_disjoint(&b), false);
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn is_disjoint(&self, other
: &HashSet
<T
, S
>) -> bool
{
474 self.iter().all(|v
| !other
.contains(v
))
477 /// Returns `true` if the set is a subset of another.
482 /// use std::collections::HashSet;
484 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
485 /// let mut set = HashSet::new();
487 /// assert_eq!(set.is_subset(&sup), true);
489 /// assert_eq!(set.is_subset(&sup), true);
491 /// assert_eq!(set.is_subset(&sup), false);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn is_subset(&self, other
: &HashSet
<T
, S
>) -> bool
{
495 self.iter().all(|v
| other
.contains(v
))
498 /// Returns `true` if the set is a superset of another.
503 /// use std::collections::HashSet;
505 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
506 /// let mut set = HashSet::new();
508 /// assert_eq!(set.is_superset(&sub), false);
512 /// assert_eq!(set.is_superset(&sub), false);
515 /// assert_eq!(set.is_superset(&sub), true);
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn is_superset(&self, other
: &HashSet
<T
, S
>) -> bool
{
520 other
.is_subset(self)
523 /// Adds a value to the set. Returns `true` if the value was not already
524 /// present in the set.
529 /// use std::collections::HashSet;
531 /// let mut set = HashSet::new();
533 /// assert_eq!(set.insert(2), true);
534 /// assert_eq!(set.insert(2), false);
535 /// assert_eq!(set.len(), 1);
537 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn insert(&mut self, value
: T
) -> bool { self.map.insert(value, ()).is_none() }
540 /// Removes a value from the set. Returns `true` if the value was
541 /// present in the set.
543 /// The value may be any borrowed form of the set's value type, but
544 /// `Hash` and `Eq` on the borrowed form *must* match those for
550 /// use std::collections::HashSet;
552 /// let mut set = HashSet::new();
555 /// assert_eq!(set.remove(&2), true);
556 /// assert_eq!(set.remove(&2), false);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn remove
<Q
: ?Sized
>(&mut self, value
: &Q
) -> bool
560 where T
: Borrow
<Q
>, Q
: Hash
+ Eq
562 self.map
.remove(value
).is_some()
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<T
, S
> PartialEq
for HashSet
<T
, S
>
568 where T
: Eq
+ Hash
, S
: HashState
570 fn eq(&self, other
: &HashSet
<T
, S
>) -> bool
{
571 if self.len() != other
.len() { return false; }
573 self.iter().all(|key
| other
.contains(key
))
577 #[stable(feature = "rust1", since = "1.0.0")]
578 impl<T
, S
> Eq
for HashSet
<T
, S
>
579 where T
: Eq
+ Hash
, S
: HashState
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<T
, S
> fmt
::Debug
for HashSet
<T
, S
>
584 where T
: Eq
+ Hash
+ fmt
::Debug
,
587 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
588 self.iter().fold(f
.debug_set(), |b
, e
| b
.entry(e
)).finish()
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl<T
, S
> FromIterator
<T
> for HashSet
<T
, S
>
595 S
: HashState
+ Default
,
597 fn from_iter
<I
: IntoIterator
<Item
=T
>>(iterable
: I
) -> HashSet
<T
, S
> {
598 let iter
= iterable
.into_iter();
599 let lower
= iter
.size_hint().0;
600 let mut set
= HashSet
::with_capacity_and_hash_state(lower
, Default
::default());
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl<T
, S
> Extend
<T
> for HashSet
<T
, S
>
611 fn extend
<I
: IntoIterator
<Item
=T
>>(&mut self, iter
: I
) {
618 #[stable(feature = "rust1", since = "1.0.0")]
619 impl<T
, S
> Default
for HashSet
<T
, S
>
621 S
: HashState
+ Default
,
623 #[stable(feature = "rust1", since = "1.0.0")]
624 fn default() -> HashSet
<T
, S
> {
625 HashSet
::with_hash_state(Default
::default())
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<'a
, 'b
, T
, S
> BitOr
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
631 where T
: Eq
+ Hash
+ Clone
,
632 S
: HashState
+ Default
,
634 type Output
= HashSet
<T
, S
>;
636 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
641 /// use std::collections::HashSet;
643 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
644 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
646 /// let set = &a | &b;
649 /// let expected = [1, 2, 3, 4, 5];
650 /// for x in set.iter() {
651 /// assert!(expected.contains(x));
654 /// assert_eq!(i, expected.len());
656 fn bitor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
657 self.union(rhs
).cloned().collect()
661 #[stable(feature = "rust1", since = "1.0.0")]
662 impl<'a
, 'b
, T
, S
> BitAnd
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
663 where T
: Eq
+ Hash
+ Clone
,
664 S
: HashState
+ Default
,
666 type Output
= HashSet
<T
, S
>;
668 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
673 /// use std::collections::HashSet;
675 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
676 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
678 /// let set = &a & &b;
681 /// let expected = [2, 3];
682 /// for x in set.iter() {
683 /// assert!(expected.contains(x));
686 /// assert_eq!(i, expected.len());
688 fn bitand(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
689 self.intersection(rhs
).cloned().collect()
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<'a
, 'b
, T
, S
> BitXor
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
695 where T
: Eq
+ Hash
+ Clone
,
696 S
: HashState
+ Default
,
698 type Output
= HashSet
<T
, S
>;
700 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
705 /// use std::collections::HashSet;
707 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
708 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
710 /// let set = &a ^ &b;
713 /// let expected = [1, 2, 4, 5];
714 /// for x in set.iter() {
715 /// assert!(expected.contains(x));
718 /// assert_eq!(i, expected.len());
720 fn bitxor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
721 self.symmetric_difference(rhs
).cloned().collect()
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl<'a
, 'b
, T
, S
> Sub
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
727 where T
: Eq
+ Hash
+ Clone
,
728 S
: HashState
+ Default
,
730 type Output
= HashSet
<T
, S
>;
732 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
737 /// use std::collections::HashSet;
739 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
740 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
742 /// let set = &a - &b;
745 /// let expected = [1, 2];
746 /// for x in set.iter() {
747 /// assert!(expected.contains(x));
750 /// assert_eq!(i, expected.len());
752 fn sub(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
753 self.difference(rhs
).cloned().collect()
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub struct Iter
<'a
, K
: 'a
> {
760 iter
: Keys
<'a
, K
, ()>
763 /// HashSet move iterator
764 #[stable(feature = "rust1", since = "1.0.0")]
765 pub struct IntoIter
<K
> {
766 iter
: Map
<map
::IntoIter
<K
, ()>, fn((K
, ())) -> K
>
769 /// HashSet drain iterator
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub struct Drain
<'a
, K
: 'a
> {
772 iter
: Map
<map
::Drain
<'a
, K
, ()>, fn((K
, ())) -> K
>,
775 /// Intersection iterator
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub struct Intersection
<'a
, T
: 'a
, S
: 'a
> {
778 // iterator of the first set
781 other
: &'a HashSet
<T
, S
>,
784 /// Difference iterator
785 #[stable(feature = "rust1", since = "1.0.0")]
786 pub struct Difference
<'a
, T
: 'a
, S
: 'a
> {
787 // iterator of the first set
790 other
: &'a HashSet
<T
, S
>,
793 /// Symmetric difference iterator.
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub struct SymmetricDifference
<'a
, T
: 'a
, S
: 'a
> {
796 iter
: Chain
<Difference
<'a
, T
, S
>, Difference
<'a
, T
, S
>>
799 /// Set union iterator.
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub struct Union
<'a
, T
: 'a
, S
: 'a
> {
802 iter
: Chain
<Iter
<'a
, T
>, Difference
<'a
, T
, S
>>
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<'a
, T
, S
> IntoIterator
for &'a HashSet
<T
, S
>
807 where T
: Eq
+ Hash
, S
: HashState
810 type IntoIter
= Iter
<'a
, T
>;
812 fn into_iter(self) -> Iter
<'a
, T
> {
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<T
, S
> IntoIterator
for HashSet
<T
, S
>
823 type IntoIter
= IntoIter
<T
>;
825 /// Creates a consuming iterator, that is, one that moves each value out
826 /// of the set in arbitrary order. The set cannot be used after calling
832 /// use std::collections::HashSet;
833 /// let mut set = HashSet::new();
834 /// set.insert("a".to_string());
835 /// set.insert("b".to_string());
837 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
838 /// let v: Vec<String> = set.into_iter().collect();
840 /// // Will print in an arbitrary order.
841 /// for x in v.iter() {
842 /// println!("{}", x);
845 fn into_iter(self) -> IntoIter
<T
> {
846 fn first
<A
, B
>((a
, _
): (A
, B
)) -> A { a }
847 let first
: fn((T
, ())) -> T
= first
;
849 IntoIter { iter: self.map.into_iter().map(first) }
853 impl<'a
, K
> Clone
for Iter
<'a
, K
> {
854 fn clone(&self) -> Iter
<'a
, K
> { Iter { iter: self.iter.clone() }
}
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl<'a
, K
> Iterator
for Iter
<'a
, K
> {
860 fn next(&mut self) -> Option
<&'a K
> { self.iter.next() }
861 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<'a
, K
> ExactSizeIterator
for Iter
<'a
, K
> {
865 fn len(&self) -> usize { self.iter.len() }
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<K
> Iterator
for IntoIter
<K
> {
872 fn next(&mut self) -> Option
<K
> { self.iter.next() }
873 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl<K
> ExactSizeIterator
for IntoIter
<K
> {
877 fn len(&self) -> usize { self.iter.len() }
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<'a
, K
> Iterator
for Drain
<'a
, K
> {
884 fn next(&mut self) -> Option
<K
> { self.iter.next() }
885 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl<'a
, K
> ExactSizeIterator
for Drain
<'a
, K
> {
889 fn len(&self) -> usize { self.iter.len() }
892 impl<'a
, T
, S
> Clone
for Intersection
<'a
, T
, S
> {
893 fn clone(&self) -> Intersection
<'a
, T
, S
> {
894 Intersection { iter: self.iter.clone(), ..*self }
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a
, T
, S
> Iterator
for Intersection
<'a
, T
, S
>
900 where T
: Eq
+ Hash
, S
: HashState
904 fn next(&mut self) -> Option
<&'a T
> {
906 match self.iter
.next() {
908 Some(elt
) => if self.other
.contains(elt
) {
915 fn size_hint(&self) -> (usize, Option
<usize>) {
916 let (_
, upper
) = self.iter
.size_hint();
921 impl<'a
, T
, S
> Clone
for Difference
<'a
, T
, S
> {
922 fn clone(&self) -> Difference
<'a
, T
, S
> {
923 Difference { iter: self.iter.clone(), ..*self }
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl<'a
, T
, S
> Iterator
for Difference
<'a
, T
, S
>
929 where T
: Eq
+ Hash
, S
: HashState
933 fn next(&mut self) -> Option
<&'a T
> {
935 match self.iter
.next() {
937 Some(elt
) => if !self.other
.contains(elt
) {
944 fn size_hint(&self) -> (usize, Option
<usize>) {
945 let (_
, upper
) = self.iter
.size_hint();
950 impl<'a
, T
, S
> Clone
for SymmetricDifference
<'a
, T
, S
> {
951 fn clone(&self) -> SymmetricDifference
<'a
, T
, S
> {
952 SymmetricDifference { iter: self.iter.clone() }
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<'a
, T
, S
> Iterator
for SymmetricDifference
<'a
, T
, S
>
958 where T
: Eq
+ Hash
, S
: HashState
962 fn next(&mut self) -> Option
<&'a T
> { self.iter.next() }
963 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
966 impl<'a
, T
, S
> Clone
for Union
<'a
, T
, S
> {
967 fn clone(&self) -> Union
<'a
, T
, S
> { Union { iter: self.iter.clone() }
}
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<'a
, T
, S
> Iterator
for Union
<'a
, T
, S
>
972 where T
: Eq
+ Hash
, S
: HashState
976 fn next(&mut self) -> Option
<&'a T
> { self.iter.next() }
977 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
988 let mut xs
= HashSet
::new();
989 let mut ys
= HashSet
::new();
990 assert
!(xs
.is_disjoint(&ys
));
991 assert
!(ys
.is_disjoint(&xs
));
992 assert
!(xs
.insert(5));
993 assert
!(ys
.insert(11));
994 assert
!(xs
.is_disjoint(&ys
));
995 assert
!(ys
.is_disjoint(&xs
));
996 assert
!(xs
.insert(7));
997 assert
!(xs
.insert(19));
998 assert
!(xs
.insert(4));
999 assert
!(ys
.insert(2));
1000 assert
!(ys
.insert(-11));
1001 assert
!(xs
.is_disjoint(&ys
));
1002 assert
!(ys
.is_disjoint(&xs
));
1003 assert
!(ys
.insert(7));
1004 assert
!(!xs
.is_disjoint(&ys
));
1005 assert
!(!ys
.is_disjoint(&xs
));
1009 fn test_subset_and_superset() {
1010 let mut a
= HashSet
::new();
1011 assert
!(a
.insert(0));
1012 assert
!(a
.insert(5));
1013 assert
!(a
.insert(11));
1014 assert
!(a
.insert(7));
1016 let mut b
= HashSet
::new();
1017 assert
!(b
.insert(0));
1018 assert
!(b
.insert(7));
1019 assert
!(b
.insert(19));
1020 assert
!(b
.insert(250));
1021 assert
!(b
.insert(11));
1022 assert
!(b
.insert(200));
1024 assert
!(!a
.is_subset(&b
));
1025 assert
!(!a
.is_superset(&b
));
1026 assert
!(!b
.is_subset(&a
));
1027 assert
!(!b
.is_superset(&a
));
1029 assert
!(b
.insert(5));
1031 assert
!(a
.is_subset(&b
));
1032 assert
!(!a
.is_superset(&b
));
1033 assert
!(!b
.is_subset(&a
));
1034 assert
!(b
.is_superset(&a
));
1039 let mut a
= HashSet
::new();
1041 assert
!(a
.insert(i
));
1043 let mut observed
: u32 = 0;
1045 observed
|= 1 << *k
;
1047 assert_eq
!(observed
, 0xFFFF_FFFF);
1051 fn test_intersection() {
1052 let mut a
= HashSet
::new();
1053 let mut b
= HashSet
::new();
1055 assert
!(a
.insert(11));
1056 assert
!(a
.insert(1));
1057 assert
!(a
.insert(3));
1058 assert
!(a
.insert(77));
1059 assert
!(a
.insert(103));
1060 assert
!(a
.insert(5));
1061 assert
!(a
.insert(-5));
1063 assert
!(b
.insert(2));
1064 assert
!(b
.insert(11));
1065 assert
!(b
.insert(77));
1066 assert
!(b
.insert(-9));
1067 assert
!(b
.insert(-42));
1068 assert
!(b
.insert(5));
1069 assert
!(b
.insert(3));
1072 let expected
= [3, 5, 11, 77];
1073 for x
in a
.intersection(&b
) {
1074 assert
!(expected
.contains(x
));
1077 assert_eq
!(i
, expected
.len());
1081 fn test_difference() {
1082 let mut a
= HashSet
::new();
1083 let mut b
= HashSet
::new();
1085 assert
!(a
.insert(1));
1086 assert
!(a
.insert(3));
1087 assert
!(a
.insert(5));
1088 assert
!(a
.insert(9));
1089 assert
!(a
.insert(11));
1091 assert
!(b
.insert(3));
1092 assert
!(b
.insert(9));
1095 let expected
= [1, 5, 11];
1096 for x
in a
.difference(&b
) {
1097 assert
!(expected
.contains(x
));
1100 assert_eq
!(i
, expected
.len());
1104 fn test_symmetric_difference() {
1105 let mut a
= HashSet
::new();
1106 let mut b
= HashSet
::new();
1108 assert
!(a
.insert(1));
1109 assert
!(a
.insert(3));
1110 assert
!(a
.insert(5));
1111 assert
!(a
.insert(9));
1112 assert
!(a
.insert(11));
1114 assert
!(b
.insert(-2));
1115 assert
!(b
.insert(3));
1116 assert
!(b
.insert(9));
1117 assert
!(b
.insert(14));
1118 assert
!(b
.insert(22));
1121 let expected
= [-2, 1, 5, 11, 14, 22];
1122 for x
in a
.symmetric_difference(&b
) {
1123 assert
!(expected
.contains(x
));
1126 assert_eq
!(i
, expected
.len());
1131 let mut a
= HashSet
::new();
1132 let mut b
= HashSet
::new();
1134 assert
!(a
.insert(1));
1135 assert
!(a
.insert(3));
1136 assert
!(a
.insert(5));
1137 assert
!(a
.insert(9));
1138 assert
!(a
.insert(11));
1139 assert
!(a
.insert(16));
1140 assert
!(a
.insert(19));
1141 assert
!(a
.insert(24));
1143 assert
!(b
.insert(-2));
1144 assert
!(b
.insert(1));
1145 assert
!(b
.insert(5));
1146 assert
!(b
.insert(9));
1147 assert
!(b
.insert(13));
1148 assert
!(b
.insert(19));
1151 let expected
= [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1152 for x
in a
.union(&b
) {
1153 assert
!(expected
.contains(x
));
1156 assert_eq
!(i
, expected
.len());
1160 fn test_from_iter() {
1161 let xs
= [1, 2, 3, 4, 5, 6, 7, 8, 9];
1163 let set
: HashSet
<_
> = xs
.iter().cloned().collect();
1166 assert
!(set
.contains(x
));
1171 fn test_move_iter() {
1173 let mut hs
= HashSet
::new();
1181 let v
= hs
.into_iter().collect
::<Vec
<char>>();
1182 assert
!(v
== ['a'
, 'b'
] || v
== ['b'
, 'a'
]);
1187 // These constants once happened to expose a bug in insert().
1188 // I'm keeping them around to prevent a regression.
1189 let mut s1
= HashSet
::new();
1195 let mut s2
= HashSet
::new();
1209 let mut set
= HashSet
::new();
1210 let empty
= HashSet
::<i32>::new();
1215 let set_str
= format
!("{:?}", set
);
1217 assert
!(set_str
== "{1, 2}" || set_str
== "{2, 1}");
1218 assert_eq
!(format
!("{:?}", empty
), "{}");
1222 fn test_trivial_drain() {
1223 let mut s
= HashSet
::<i32>::new();
1224 for _
in s
.drain() {}
1225 assert
!(s
.is_empty());
1228 let mut s
= HashSet
::<i32>::new();
1230 assert
!(s
.is_empty());
1235 let mut s
: HashSet
<_
> = (1..100).collect();
1237 // try this a bunch of times to make sure we don't screw up internal state.
1239 assert_eq
!(s
.len(), 99);
1243 let mut d
= s
.drain();
1244 for (i
, x
) in d
.by_ref().take(50).enumerate() {
1248 assert_eq
!(last_i
, 49);
1251 for _
in &s { panic!("s should be empty!"); }
1253 // reset to try again.