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 cmp
::{Eq, PartialEq}
;
14 use core
::marker
::Sized
;
19 use iter
::{Iterator, IntoIterator, ExactSizeIterator, FromIterator, Map, Chain, Extend}
;
20 use ops
::{BitOr, BitAnd, BitXor, Sub}
;
21 use option
::Option
::{Some, None, self}
;
24 use super::map
::{self, HashMap, Keys, RandomState}
;
25 use super::state
::HashState
;
27 const INITIAL_CAPACITY
: usize = 32;
29 // Future Optimization (FIXME!)
30 // =============================
32 // Iteration over zero sized values is a noop. There is no need
33 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
34 // to get rid of it properly.
36 /// An implementation of a hash set using the underlying representation of a
37 /// HashMap where the value is ().
39 /// As with the `HashMap` type, a `HashSet` requires that the elements
40 /// implement the `Eq` and `Hash` traits. This can frequently be achieved by
41 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
42 /// it is important that the following property holds:
45 /// k1 == k2 -> hash(k1) == hash(k2)
48 /// In other words, if two keys are equal, their hashes must be equal.
51 /// It is a logic error for an item to be modified in such a way that the
52 /// item's hash, as determined by the `Hash` trait, or its equality, as
53 /// determined by the `Eq` trait, changes while it is in the set. This is
54 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or
60 /// use std::collections::HashSet;
61 /// // Type inference lets us omit an explicit type signature (which
62 /// // would be `HashSet<&str>` in this example).
63 /// let mut books = HashSet::new();
65 /// // Add some books.
66 /// books.insert("A Dance With Dragons");
67 /// books.insert("To Kill a Mockingbird");
68 /// books.insert("The Odyssey");
69 /// books.insert("The Great Gatsby");
71 /// // Check for a specific one.
72 /// if !books.contains("The Winds of Winter") {
73 /// println!("We have {} books, but The Winds of Winter ain't one.",
78 /// books.remove("The Odyssey");
80 /// // Iterate over everything.
81 /// for book in &books {
82 /// println!("{}", book);
86 /// The easiest way to use `HashSet` with a custom type is to derive
87 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
88 /// future be implied by `Eq`.
91 /// use std::collections::HashSet;
92 /// #[derive(Hash, Eq, PartialEq, Debug)]
93 /// struct Viking<'a> {
98 /// let mut vikings = HashSet::new();
100 /// vikings.insert(Viking { name: "Einar", power: 9 });
101 /// vikings.insert(Viking { name: "Einar", power: 9 });
102 /// vikings.insert(Viking { name: "Olaf", power: 4 });
103 /// vikings.insert(Viking { name: "Harald", power: 8 });
105 /// // Use derived implementation to print the vikings.
106 /// for x in &vikings {
107 /// println!("{:?}", x);
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct HashSet
<T
, S
= RandomState
> {
113 map
: HashMap
<T
, (), S
>
116 impl<T
: Hash
+ Eq
> HashSet
<T
, RandomState
> {
117 /// Creates an empty HashSet.
122 /// use std::collections::HashSet;
123 /// let mut set: HashSet<i32> = HashSet::new();
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub fn new() -> HashSet
<T
, RandomState
> {
128 HashSet
::with_capacity(INITIAL_CAPACITY
)
131 /// Creates an empty HashSet with space for at least `n` elements in
137 /// use std::collections::HashSet;
138 /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub fn with_capacity(capacity
: usize) -> HashSet
<T
, RandomState
> {
143 HashSet { map: HashMap::with_capacity(capacity) }
147 impl<T
, S
> HashSet
<T
, S
>
148 where T
: Eq
+ Hash
, S
: HashState
150 /// Creates a new empty hash set which will use the given hasher to hash
153 /// The hash set is also created with the default initial capacity.
158 /// #![feature(hashmap_hasher)]
160 /// use std::collections::HashSet;
161 /// use std::collections::hash_map::RandomState;
163 /// let s = RandomState::new();
164 /// let mut set = HashSet::with_hash_state(s);
168 #[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
170 pub fn with_hash_state(hash_state
: S
) -> HashSet
<T
, S
> {
171 HashSet
::with_capacity_and_hash_state(INITIAL_CAPACITY
, hash_state
)
174 /// Creates an empty HashSet with space for at least `capacity`
175 /// elements in the hash table, using `hasher` to hash the keys.
177 /// Warning: `hasher` is normally randomly generated, and
178 /// is designed to allow `HashSet`s to be resistant to attacks that
179 /// cause many collisions and very poor performance. Setting it
180 /// manually using this function can expose a DoS attack vector.
185 /// #![feature(hashmap_hasher)]
187 /// use std::collections::HashSet;
188 /// use std::collections::hash_map::RandomState;
190 /// let s = RandomState::new();
191 /// let mut set = HashSet::with_capacity_and_hash_state(10, s);
195 #[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
197 pub fn with_capacity_and_hash_state(capacity
: usize, hash_state
: S
)
200 map
: HashMap
::with_capacity_and_hash_state(capacity
, hash_state
),
204 /// Returns the number of elements the set can hold without reallocating.
209 /// use std::collections::HashSet;
210 /// let set: HashSet<i32> = HashSet::with_capacity(100);
211 /// assert!(set.capacity() >= 100);
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn capacity(&self) -> usize {
219 /// Reserves capacity for at least `additional` more elements to be inserted
220 /// in the `HashSet`. The collection may reserve more space to avoid
221 /// frequent reallocations.
225 /// Panics if the new allocation size overflows `usize`.
230 /// use std::collections::HashSet;
231 /// let mut set: HashSet<i32> = HashSet::new();
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn reserve(&mut self, additional
: usize) {
236 self.map
.reserve(additional
)
239 /// Shrinks the capacity of the set as much as possible. It will drop
240 /// down as much as possible while maintaining the internal rules
241 /// and possibly leaving some space in accordance with the resize policy.
246 /// use std::collections::HashSet;
248 /// let mut set = HashSet::with_capacity(100);
251 /// assert!(set.capacity() >= 100);
252 /// set.shrink_to_fit();
253 /// assert!(set.capacity() >= 2);
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn shrink_to_fit(&mut self) {
257 self.map
.shrink_to_fit()
260 /// An iterator visiting all elements in arbitrary order.
261 /// Iterator element type is &'a T.
266 /// use std::collections::HashSet;
267 /// let mut set = HashSet::new();
271 /// // Will print in an arbitrary order.
272 /// for x in set.iter() {
273 /// println!("{}", x);
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn iter(&self) -> Iter
<T
> {
278 Iter { iter: self.map.keys() }
281 /// Visit the values representing the difference.
286 /// use std::collections::HashSet;
287 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
288 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
290 /// // Can be seen as `a - b`.
291 /// for x in a.difference(&b) {
292 /// println!("{}", x); // Print 1
295 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
296 /// assert_eq!(diff, [1].iter().cloned().collect());
298 /// // Note that difference is not symmetric,
299 /// // and `b - a` means something else:
300 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
301 /// assert_eq!(diff, [4].iter().cloned().collect());
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn difference
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Difference
<'a
, T
, S
> {
311 /// Visit the values representing the symmetric difference.
316 /// use std::collections::HashSet;
317 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
318 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
320 /// // Print 1, 4 in arbitrary order.
321 /// for x in a.symmetric_difference(&b) {
322 /// println!("{}", x);
325 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
326 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
328 /// assert_eq!(diff1, diff2);
329 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn symmetric_difference
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>)
333 -> SymmetricDifference
<'a
, T
, S
> {
334 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
337 /// Visit the values representing the intersection.
342 /// use std::collections::HashSet;
343 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
344 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
346 /// // Print 2, 3 in arbitrary order.
347 /// for x in a.intersection(&b) {
348 /// println!("{}", x);
351 /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
352 /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn intersection
<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Intersection
<'a
, T
, S
> {
362 /// Visit the values representing the union.
367 /// use std::collections::HashSet;
368 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
369 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
371 /// // Print 1, 2, 3, 4 in arbitrary order.
372 /// for x in a.union(&b) {
373 /// println!("{}", x);
376 /// let union: HashSet<_> = a.union(&b).cloned().collect();
377 /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn union<'a
>(&'a
self, other
: &'a HashSet
<T
, S
>) -> Union
<'a
, T
, S
> {
381 Union { iter: self.iter().chain(other.difference(self)) }
384 /// Returns the number of elements in the set.
389 /// use std::collections::HashSet;
391 /// let mut v = HashSet::new();
392 /// assert_eq!(v.len(), 0);
394 /// assert_eq!(v.len(), 1);
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn len(&self) -> usize { self.map.len() }
399 /// Returns true if the set contains no elements.
404 /// use std::collections::HashSet;
406 /// let mut v = HashSet::new();
407 /// assert!(v.is_empty());
409 /// assert!(!v.is_empty());
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn is_empty(&self) -> bool { self.map.is_empty() }
414 /// Clears the set, returning all elements in an iterator.
416 #[stable(feature = "drain", since = "1.6.0")]
417 pub fn drain(&mut self) -> Drain
<T
> {
418 fn first
<A
, B
>((a
, _
): (A
, B
)) -> A { a }
419 let first
: fn((T
, ())) -> T
= first
; // coerce to fn pointer
421 Drain { iter: self.map.drain().map(first) }
424 /// Clears the set, removing all values.
429 /// use std::collections::HashSet;
431 /// let mut v = HashSet::new();
434 /// assert!(v.is_empty());
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn clear(&mut self) { self.map.clear() }
439 /// Returns `true` if the set contains a value.
441 /// The value may be any borrowed form of the set's value type, but
442 /// `Hash` and `Eq` on the borrowed form *must* match those for
448 /// use std::collections::HashSet;
450 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
451 /// assert_eq!(set.contains(&1), true);
452 /// assert_eq!(set.contains(&4), false);
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn contains
<Q
: ?Sized
>(&self, value
: &Q
) -> bool
456 where T
: Borrow
<Q
>, Q
: Hash
+ Eq
458 self.map
.contains_key(value
)
461 /// Returns a reference to the value in the set, if any, that is equal to the given value.
463 /// The value may be any borrowed form of the set's value type, but
464 /// `Hash` and `Eq` on the borrowed form *must* match those for
466 #[unstable(feature = "set_recovery", issue = "28050")]
467 pub fn get
<Q
: ?Sized
>(&self, value
: &Q
) -> Option
<&T
>
468 where T
: Borrow
<Q
>, Q
: Hash
+ Eq
470 Recover
::get(&self.map
, value
)
473 /// Returns `true` if the set has no elements in common with `other`.
474 /// This is equivalent to checking for an empty intersection.
479 /// use std::collections::HashSet;
481 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
482 /// let mut b = HashSet::new();
484 /// assert_eq!(a.is_disjoint(&b), true);
486 /// assert_eq!(a.is_disjoint(&b), true);
488 /// assert_eq!(a.is_disjoint(&b), false);
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn is_disjoint(&self, other
: &HashSet
<T
, S
>) -> bool
{
492 self.iter().all(|v
| !other
.contains(v
))
495 /// Returns `true` if the set is a subset of another.
500 /// use std::collections::HashSet;
502 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
503 /// let mut set = HashSet::new();
505 /// assert_eq!(set.is_subset(&sup), true);
507 /// assert_eq!(set.is_subset(&sup), true);
509 /// assert_eq!(set.is_subset(&sup), false);
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn is_subset(&self, other
: &HashSet
<T
, S
>) -> bool
{
513 self.iter().all(|v
| other
.contains(v
))
516 /// Returns `true` if the set is a superset of another.
521 /// use std::collections::HashSet;
523 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
524 /// let mut set = HashSet::new();
526 /// assert_eq!(set.is_superset(&sub), false);
530 /// assert_eq!(set.is_superset(&sub), false);
533 /// assert_eq!(set.is_superset(&sub), true);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn is_superset(&self, other
: &HashSet
<T
, S
>) -> bool
{
538 other
.is_subset(self)
541 /// Adds a value to the set.
543 /// If the set did not have a value present, `true` is returned.
545 /// If the set did have this key present, `false` is returned.
550 /// use std::collections::HashSet;
552 /// let mut set = HashSet::new();
554 /// assert_eq!(set.insert(2), true);
555 /// assert_eq!(set.insert(2), false);
556 /// assert_eq!(set.len(), 1);
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn insert(&mut self, value
: T
) -> bool { self.map.insert(value, ()).is_none() }
561 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
562 /// one. Returns the replaced value.
563 #[unstable(feature = "set_recovery", issue = "28050")]
564 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
565 Recover
::replace(&mut self.map
, value
)
568 /// Removes a value from the set. Returns `true` if the value was
569 /// present in the set.
571 /// The value may be any borrowed form of the set's value type, but
572 /// `Hash` and `Eq` on the borrowed form *must* match those for
578 /// use std::collections::HashSet;
580 /// let mut set = HashSet::new();
583 /// assert_eq!(set.remove(&2), true);
584 /// assert_eq!(set.remove(&2), false);
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn remove
<Q
: ?Sized
>(&mut self, value
: &Q
) -> bool
588 where T
: Borrow
<Q
>, Q
: Hash
+ Eq
590 self.map
.remove(value
).is_some()
593 /// Removes and returns the value in the set, if any, that is equal to the given one.
595 /// The value may be any borrowed form of the set's value type, but
596 /// `Hash` and `Eq` on the borrowed form *must* match those for
598 #[unstable(feature = "set_recovery", issue = "28050")]
599 pub fn take
<Q
: ?Sized
>(&mut self, value
: &Q
) -> Option
<T
>
600 where T
: Borrow
<Q
>, Q
: Hash
+ Eq
602 Recover
::take(&mut self.map
, value
)
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl<T
, S
> PartialEq
for HashSet
<T
, S
>
608 where T
: Eq
+ Hash
, S
: HashState
610 fn eq(&self, other
: &HashSet
<T
, S
>) -> bool
{
611 if self.len() != other
.len() { return false; }
613 self.iter().all(|key
| other
.contains(key
))
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<T
, S
> Eq
for HashSet
<T
, S
>
619 where T
: Eq
+ Hash
, S
: HashState
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<T
, S
> fmt
::Debug
for HashSet
<T
, S
>
624 where T
: Eq
+ Hash
+ fmt
::Debug
,
627 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
628 f
.debug_set().entries(self.iter()).finish()
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl<T
, S
> FromIterator
<T
> for HashSet
<T
, S
>
635 S
: HashState
+ Default
,
637 fn from_iter
<I
: IntoIterator
<Item
=T
>>(iterable
: I
) -> HashSet
<T
, S
> {
638 let iter
= iterable
.into_iter();
639 let lower
= iter
.size_hint().0;
640 let mut set
= HashSet
::with_capacity_and_hash_state(lower
, Default
::default());
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl<T
, S
> Extend
<T
> for HashSet
<T
, S
>
651 fn extend
<I
: IntoIterator
<Item
=T
>>(&mut self, iter
: I
) {
658 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
659 impl<'a
, T
, S
> Extend
<&'a T
> for HashSet
<T
, S
>
660 where T
: 'a
+ Eq
+ Hash
+ Copy
,
663 fn extend
<I
: IntoIterator
<Item
=&'a T
>>(&mut self, iter
: I
) {
664 self.extend(iter
.into_iter().cloned());
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl<T
, S
> Default
for HashSet
<T
, S
>
671 S
: HashState
+ Default
,
673 fn default() -> HashSet
<T
, S
> {
674 HashSet
::with_hash_state(Default
::default())
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<'a
, 'b
, T
, S
> BitOr
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
680 where T
: Eq
+ Hash
+ Clone
,
681 S
: HashState
+ Default
,
683 type Output
= HashSet
<T
, S
>;
685 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
690 /// use std::collections::HashSet;
692 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
693 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
695 /// let set = &a | &b;
698 /// let expected = [1, 2, 3, 4, 5];
700 /// assert!(expected.contains(x));
703 /// assert_eq!(i, expected.len());
705 fn bitor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
706 self.union(rhs
).cloned().collect()
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl<'a
, 'b
, T
, S
> BitAnd
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
712 where T
: Eq
+ Hash
+ Clone
,
713 S
: HashState
+ Default
,
715 type Output
= HashSet
<T
, S
>;
717 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
722 /// use std::collections::HashSet;
724 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
725 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
727 /// let set = &a & &b;
730 /// let expected = [2, 3];
732 /// assert!(expected.contains(x));
735 /// assert_eq!(i, expected.len());
737 fn bitand(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
738 self.intersection(rhs
).cloned().collect()
742 #[stable(feature = "rust1", since = "1.0.0")]
743 impl<'a
, 'b
, T
, S
> BitXor
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
744 where T
: Eq
+ Hash
+ Clone
,
745 S
: HashState
+ Default
,
747 type Output
= HashSet
<T
, S
>;
749 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
754 /// use std::collections::HashSet;
756 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
757 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
759 /// let set = &a ^ &b;
762 /// let expected = [1, 2, 4, 5];
764 /// assert!(expected.contains(x));
767 /// assert_eq!(i, expected.len());
769 fn bitxor(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
770 self.symmetric_difference(rhs
).cloned().collect()
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl<'a
, 'b
, T
, S
> Sub
<&'b HashSet
<T
, S
>> for &'a HashSet
<T
, S
>
776 where T
: Eq
+ Hash
+ Clone
,
777 S
: HashState
+ Default
,
779 type Output
= HashSet
<T
, S
>;
781 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
786 /// use std::collections::HashSet;
788 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
789 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
791 /// let set = &a - &b;
794 /// let expected = [1, 2];
796 /// assert!(expected.contains(x));
799 /// assert_eq!(i, expected.len());
801 fn sub(self, rhs
: &HashSet
<T
, S
>) -> HashSet
<T
, S
> {
802 self.difference(rhs
).cloned().collect()
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub struct Iter
<'a
, K
: 'a
> {
809 iter
: Keys
<'a
, K
, ()>
812 /// HashSet move iterator
813 #[stable(feature = "rust1", since = "1.0.0")]
814 pub struct IntoIter
<K
> {
815 iter
: Map
<map
::IntoIter
<K
, ()>, fn((K
, ())) -> K
>
818 /// HashSet drain iterator
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub struct Drain
<'a
, K
: 'a
> {
821 iter
: Map
<map
::Drain
<'a
, K
, ()>, fn((K
, ())) -> K
>,
824 /// Intersection iterator
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub struct Intersection
<'a
, T
: 'a
, S
: 'a
> {
827 // iterator of the first set
830 other
: &'a HashSet
<T
, S
>,
833 /// Difference iterator
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub struct Difference
<'a
, T
: 'a
, S
: 'a
> {
836 // iterator of the first set
839 other
: &'a HashSet
<T
, S
>,
842 /// Symmetric difference iterator.
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub struct SymmetricDifference
<'a
, T
: 'a
, S
: 'a
> {
845 iter
: Chain
<Difference
<'a
, T
, S
>, Difference
<'a
, T
, S
>>
848 /// Set union iterator.
849 #[stable(feature = "rust1", since = "1.0.0")]
850 pub struct Union
<'a
, T
: 'a
, S
: 'a
> {
851 iter
: Chain
<Iter
<'a
, T
>, Difference
<'a
, T
, S
>>
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<'a
, T
, S
> IntoIterator
for &'a HashSet
<T
, S
>
856 where T
: Eq
+ Hash
, S
: HashState
859 type IntoIter
= Iter
<'a
, T
>;
861 fn into_iter(self) -> Iter
<'a
, T
> {
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<T
, S
> IntoIterator
for HashSet
<T
, S
>
872 type IntoIter
= IntoIter
<T
>;
874 /// Creates a consuming iterator, that is, one that moves each value out
875 /// of the set in arbitrary order. The set cannot be used after calling
881 /// use std::collections::HashSet;
882 /// let mut set = HashSet::new();
883 /// set.insert("a".to_string());
884 /// set.insert("b".to_string());
886 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
887 /// let v: Vec<String> = set.into_iter().collect();
889 /// // Will print in an arbitrary order.
891 /// println!("{}", x);
894 fn into_iter(self) -> IntoIter
<T
> {
895 fn first
<A
, B
>((a
, _
): (A
, B
)) -> A { a }
896 let first
: fn((T
, ())) -> T
= first
;
898 IntoIter { iter: self.map.into_iter().map(first) }
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a
, K
> Clone
for Iter
<'a
, K
> {
904 fn clone(&self) -> Iter
<'a
, K
> { Iter { iter: self.iter.clone() }
}
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl<'a
, K
> Iterator
for Iter
<'a
, K
> {
910 fn next(&mut self) -> Option
<&'a K
> { self.iter.next() }
911 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl<'a
, K
> ExactSizeIterator
for Iter
<'a
, K
> {
915 fn len(&self) -> usize { self.iter.len() }
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<K
> Iterator
for IntoIter
<K
> {
922 fn next(&mut self) -> Option
<K
> { self.iter.next() }
923 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<K
> ExactSizeIterator
for IntoIter
<K
> {
927 fn len(&self) -> usize { self.iter.len() }
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<'a
, K
> Iterator
for Drain
<'a
, K
> {
934 fn next(&mut self) -> Option
<K
> { self.iter.next() }
935 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a
, K
> ExactSizeIterator
for Drain
<'a
, K
> {
939 fn len(&self) -> usize { self.iter.len() }
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<'a
, T
, S
> Clone
for Intersection
<'a
, T
, S
> {
944 fn clone(&self) -> Intersection
<'a
, T
, S
> {
945 Intersection { iter: self.iter.clone(), ..*self }
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a
, T
, S
> Iterator
for Intersection
<'a
, T
, S
>
951 where T
: Eq
+ Hash
, S
: HashState
955 fn next(&mut self) -> Option
<&'a T
> {
957 match self.iter
.next() {
959 Some(elt
) => if self.other
.contains(elt
) {
966 fn size_hint(&self) -> (usize, Option
<usize>) {
967 let (_
, upper
) = self.iter
.size_hint();
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl<'a
, T
, S
> Clone
for Difference
<'a
, T
, S
> {
974 fn clone(&self) -> Difference
<'a
, T
, S
> {
975 Difference { iter: self.iter.clone(), ..*self }
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<'a
, T
, S
> Iterator
for Difference
<'a
, T
, S
>
981 where T
: Eq
+ Hash
, S
: HashState
985 fn next(&mut self) -> Option
<&'a T
> {
987 match self.iter
.next() {
989 Some(elt
) => if !self.other
.contains(elt
) {
996 fn size_hint(&self) -> (usize, Option
<usize>) {
997 let (_
, upper
) = self.iter
.size_hint();
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<'a
, T
, S
> Clone
for SymmetricDifference
<'a
, T
, S
> {
1004 fn clone(&self) -> SymmetricDifference
<'a
, T
, S
> {
1005 SymmetricDifference { iter: self.iter.clone() }
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl<'a
, T
, S
> Iterator
for SymmetricDifference
<'a
, T
, S
>
1011 where T
: Eq
+ Hash
, S
: HashState
1015 fn next(&mut self) -> Option
<&'a T
> { self.iter.next() }
1016 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl<'a
, T
, S
> Clone
for Union
<'a
, T
, S
> {
1021 fn clone(&self) -> Union
<'a
, T
, S
> { Union { iter: self.iter.clone() }
}
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a
, T
, S
> Iterator
for Union
<'a
, T
, S
>
1026 where T
: Eq
+ Hash
, S
: HashState
1030 fn next(&mut self) -> Option
<&'a T
> { self.iter.next() }
1031 fn size_hint(&self) -> (usize, Option
<usize>) { self.iter.size_hint() }
1041 fn test_disjoint() {
1042 let mut xs
= HashSet
::new();
1043 let mut ys
= HashSet
::new();
1044 assert
!(xs
.is_disjoint(&ys
));
1045 assert
!(ys
.is_disjoint(&xs
));
1046 assert
!(xs
.insert(5));
1047 assert
!(ys
.insert(11));
1048 assert
!(xs
.is_disjoint(&ys
));
1049 assert
!(ys
.is_disjoint(&xs
));
1050 assert
!(xs
.insert(7));
1051 assert
!(xs
.insert(19));
1052 assert
!(xs
.insert(4));
1053 assert
!(ys
.insert(2));
1054 assert
!(ys
.insert(-11));
1055 assert
!(xs
.is_disjoint(&ys
));
1056 assert
!(ys
.is_disjoint(&xs
));
1057 assert
!(ys
.insert(7));
1058 assert
!(!xs
.is_disjoint(&ys
));
1059 assert
!(!ys
.is_disjoint(&xs
));
1063 fn test_subset_and_superset() {
1064 let mut a
= HashSet
::new();
1065 assert
!(a
.insert(0));
1066 assert
!(a
.insert(5));
1067 assert
!(a
.insert(11));
1068 assert
!(a
.insert(7));
1070 let mut b
= HashSet
::new();
1071 assert
!(b
.insert(0));
1072 assert
!(b
.insert(7));
1073 assert
!(b
.insert(19));
1074 assert
!(b
.insert(250));
1075 assert
!(b
.insert(11));
1076 assert
!(b
.insert(200));
1078 assert
!(!a
.is_subset(&b
));
1079 assert
!(!a
.is_superset(&b
));
1080 assert
!(!b
.is_subset(&a
));
1081 assert
!(!b
.is_superset(&a
));
1083 assert
!(b
.insert(5));
1085 assert
!(a
.is_subset(&b
));
1086 assert
!(!a
.is_superset(&b
));
1087 assert
!(!b
.is_subset(&a
));
1088 assert
!(b
.is_superset(&a
));
1093 let mut a
= HashSet
::new();
1095 assert
!(a
.insert(i
));
1097 let mut observed
: u32 = 0;
1099 observed
|= 1 << *k
;
1101 assert_eq
!(observed
, 0xFFFF_FFFF);
1105 fn test_intersection() {
1106 let mut a
= HashSet
::new();
1107 let mut b
= HashSet
::new();
1109 assert
!(a
.insert(11));
1110 assert
!(a
.insert(1));
1111 assert
!(a
.insert(3));
1112 assert
!(a
.insert(77));
1113 assert
!(a
.insert(103));
1114 assert
!(a
.insert(5));
1115 assert
!(a
.insert(-5));
1117 assert
!(b
.insert(2));
1118 assert
!(b
.insert(11));
1119 assert
!(b
.insert(77));
1120 assert
!(b
.insert(-9));
1121 assert
!(b
.insert(-42));
1122 assert
!(b
.insert(5));
1123 assert
!(b
.insert(3));
1126 let expected
= [3, 5, 11, 77];
1127 for x
in a
.intersection(&b
) {
1128 assert
!(expected
.contains(x
));
1131 assert_eq
!(i
, expected
.len());
1135 fn test_difference() {
1136 let mut a
= HashSet
::new();
1137 let mut b
= HashSet
::new();
1139 assert
!(a
.insert(1));
1140 assert
!(a
.insert(3));
1141 assert
!(a
.insert(5));
1142 assert
!(a
.insert(9));
1143 assert
!(a
.insert(11));
1145 assert
!(b
.insert(3));
1146 assert
!(b
.insert(9));
1149 let expected
= [1, 5, 11];
1150 for x
in a
.difference(&b
) {
1151 assert
!(expected
.contains(x
));
1154 assert_eq
!(i
, expected
.len());
1158 fn test_symmetric_difference() {
1159 let mut a
= HashSet
::new();
1160 let mut b
= HashSet
::new();
1162 assert
!(a
.insert(1));
1163 assert
!(a
.insert(3));
1164 assert
!(a
.insert(5));
1165 assert
!(a
.insert(9));
1166 assert
!(a
.insert(11));
1168 assert
!(b
.insert(-2));
1169 assert
!(b
.insert(3));
1170 assert
!(b
.insert(9));
1171 assert
!(b
.insert(14));
1172 assert
!(b
.insert(22));
1175 let expected
= [-2, 1, 5, 11, 14, 22];
1176 for x
in a
.symmetric_difference(&b
) {
1177 assert
!(expected
.contains(x
));
1180 assert_eq
!(i
, expected
.len());
1185 let mut a
= HashSet
::new();
1186 let mut b
= HashSet
::new();
1188 assert
!(a
.insert(1));
1189 assert
!(a
.insert(3));
1190 assert
!(a
.insert(5));
1191 assert
!(a
.insert(9));
1192 assert
!(a
.insert(11));
1193 assert
!(a
.insert(16));
1194 assert
!(a
.insert(19));
1195 assert
!(a
.insert(24));
1197 assert
!(b
.insert(-2));
1198 assert
!(b
.insert(1));
1199 assert
!(b
.insert(5));
1200 assert
!(b
.insert(9));
1201 assert
!(b
.insert(13));
1202 assert
!(b
.insert(19));
1205 let expected
= [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1206 for x
in a
.union(&b
) {
1207 assert
!(expected
.contains(x
));
1210 assert_eq
!(i
, expected
.len());
1214 fn test_from_iter() {
1215 let xs
= [1, 2, 3, 4, 5, 6, 7, 8, 9];
1217 let set
: HashSet
<_
> = xs
.iter().cloned().collect();
1220 assert
!(set
.contains(x
));
1225 fn test_move_iter() {
1227 let mut hs
= HashSet
::new();
1235 let v
= hs
.into_iter().collect
::<Vec
<char>>();
1236 assert
!(v
== ['a'
, 'b'
] || v
== ['b'
, 'a'
]);
1241 // These constants once happened to expose a bug in insert().
1242 // I'm keeping them around to prevent a regression.
1243 let mut s1
= HashSet
::new();
1249 let mut s2
= HashSet
::new();
1263 let mut set
= HashSet
::new();
1264 let empty
= HashSet
::<i32>::new();
1269 let set_str
= format
!("{:?}", set
);
1271 assert
!(set_str
== "{1, 2}" || set_str
== "{2, 1}");
1272 assert_eq
!(format
!("{:?}", empty
), "{}");
1276 fn test_trivial_drain() {
1277 let mut s
= HashSet
::<i32>::new();
1278 for _
in s
.drain() {}
1279 assert
!(s
.is_empty());
1282 let mut s
= HashSet
::<i32>::new();
1284 assert
!(s
.is_empty());
1289 let mut s
: HashSet
<_
> = (1..100).collect();
1291 // try this a bunch of times to make sure we don't screw up internal state.
1293 assert_eq
!(s
.len(), 99);
1297 let mut d
= s
.drain();
1298 for (i
, x
) in d
.by_ref().take(50).enumerate() {
1302 assert_eq
!(last_i
, 49);
1305 for _
in &s { panic!("s should be empty!"); }
1307 // reset to try again.
1317 struct Foo(&'
static str, i32);
1319 impl PartialEq
for Foo
{
1320 fn eq(&self, other
: &Self) -> bool
{
1327 impl hash
::Hash
for Foo
{
1328 fn hash
<H
: hash
::Hasher
>(&self, h
: &mut H
) {
1333 let mut s
= HashSet
::new();
1334 assert_eq
!(s
.replace(Foo("a", 1)), None
);
1335 assert_eq
!(s
.len(), 1);
1336 assert_eq
!(s
.replace(Foo("a", 2)), Some(Foo("a", 1)));
1337 assert_eq
!(s
.len(), 1);
1339 let mut it
= s
.iter();
1340 assert_eq
!(it
.next(), Some(&Foo("a", 2)));
1341 assert_eq
!(it
.next(), None
);
1345 fn test_extend_ref() {
1346 let mut a
= HashSet
::new();
1349 a
.extend(&[2, 3, 4]);
1351 assert_eq
!(a
.len(), 4);
1352 assert
!(a
.contains(&1));
1353 assert
!(a
.contains(&2));
1354 assert
!(a
.contains(&3));
1355 assert
!(a
.contains(&4));
1357 let mut b
= HashSet
::new();
1363 assert_eq
!(a
.len(), 6);
1364 assert
!(a
.contains(&1));
1365 assert
!(a
.contains(&2));
1366 assert
!(a
.contains(&3));
1367 assert
!(a
.contains(&4));
1368 assert
!(a
.contains(&5));
1369 assert
!(a
.contains(&6));