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)
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl<T, S> PartialEq for HashSet<T, S>
640 fn eq(&self, other: &HashSet<T, S>) -> bool {
641 if self.len() != other.len() {
645 self.iter().all(|key| other.contains(key))
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl<T, S> Eq for HashSet<T, S>
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl<T, S> fmt::Debug for HashSet<T, S>
658 where T: Eq + Hash + fmt::Debug,
661 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662 f.debug_set().entries(self.iter()).finish()
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<T, S> FromIterator<T> for HashSet<T, S>
669 S: BuildHasher + Default
671 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
672 let mut set = HashSet::with_hasher(Default::default());
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T, S> Extend<T> for HashSet<T, S>
683 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
684 self.map.extend(iter.into_iter().map(|k| (k, ())));
688 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
689 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
690 where T: 'a + Eq + Hash + Copy,
693 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
694 self.extend(iter.into_iter().cloned());
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T, S> Default for HashSet<T, S>
701 S: BuildHasher + Default
703 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
704 fn default() -> HashSet<T, S> {
705 HashSet { map: HashMap::default() }
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
711 where T: Eq + Hash + Clone,
712 S: BuildHasher + Default
714 type Output = HashSet<T, S>;
716 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
721 /// use std::collections::HashSet;
723 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
724 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
726 /// let set = &a | &b;
729 /// let expected = [1, 2, 3, 4, 5];
731 /// assert!(expected.contains(x));
734 /// assert_eq!(i, expected.len());
736 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
737 self.union(rhs).cloned().collect()
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
743 where T: Eq + Hash + Clone,
744 S: BuildHasher + Default
746 type Output = HashSet<T, S>;
748 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
753 /// use std::collections::HashSet;
755 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
756 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
758 /// let set = &a & &b;
761 /// let expected = [2, 3];
763 /// assert!(expected.contains(x));
766 /// assert_eq!(i, expected.len());
768 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
769 self.intersection(rhs).cloned().collect()
773 #[stable(feature = "rust1", since = "1.0.0")]
774 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
775 where T: Eq + Hash + Clone,
776 S: BuildHasher + Default
778 type Output = HashSet<T, S>;
780 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
785 /// use std::collections::HashSet;
787 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
788 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
790 /// let set = &a ^ &b;
793 /// let expected = [1, 2, 4, 5];
795 /// assert!(expected.contains(x));
798 /// assert_eq!(i, expected.len());
800 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
801 self.symmetric_difference(rhs).cloned().collect()
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
807 where T: Eq + Hash + Clone,
808 S: BuildHasher + Default
810 type Output = HashSet<T, S>;
812 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
817 /// use std::collections::HashSet;
819 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
820 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
822 /// let set = &a - &b;
825 /// let expected = [1, 2];
827 /// assert!(expected.contains(x));
830 /// assert_eq!(i, expected.len());
832 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
833 self.difference(rhs).cloned().collect()
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub struct Iter<'a, K: 'a> {
840 iter: Keys<'a, K, ()>,
843 /// HashSet move iterator
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub struct IntoIter<K> {
846 iter: map::IntoIter<K, ()>,
849 /// HashSet drain iterator
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub struct Drain<'a, K: 'a> {
852 iter: map::Drain<'a, K, ()>,
855 /// Intersection iterator
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub struct Intersection<'a, T: 'a, S: 'a> {
858 // iterator of the first set
861 other: &'a HashSet<T, S>,
864 /// Difference iterator
865 #[stable(feature = "rust1", since = "1.0.0")]
866 pub struct Difference<'a, T: 'a, S: 'a> {
867 // iterator of the first set
870 other: &'a HashSet<T, S>,
873 /// Symmetric difference iterator.
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
876 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
879 /// Set union iterator.
880 #[stable(feature = "rust1", since = "1.0.0")]
881 pub struct Union<'a, T: 'a, S: 'a> {
882 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
891 type IntoIter = Iter<'a, T>;
893 fn into_iter(self) -> Iter<'a, T> {
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<T, S> IntoIterator for HashSet<T, S>
904 type IntoIter = IntoIter<T>;
906 /// Creates a consuming iterator, that is, one that moves each value out
907 /// of the set in arbitrary order. The set cannot be used after calling
913 /// use std::collections::HashSet;
914 /// let mut set = HashSet::new();
915 /// set.insert("a".to_string());
916 /// set.insert("b".to_string());
918 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
919 /// let v: Vec<String> = set.into_iter().collect();
921 /// // Will print in an arbitrary order.
923 /// println!("{}", x);
926 fn into_iter(self) -> IntoIter<T> {
927 IntoIter { iter: self.map.into_iter() }
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<'a, K> Clone for Iter<'a, K> {
933 fn clone(&self) -> Iter<'a, K> {
934 Iter { iter: self.iter.clone() }
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, K> Iterator for Iter<'a, K> {
941 fn next(&mut self) -> Option<&'a K> {
944 fn size_hint(&self) -> (usize, Option<usize>) {
945 self.iter.size_hint()
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
950 fn len(&self) -> usize {
954 #[unstable(feature = "fused", issue = "35602")]
955 impl<'a, K> FusedIterator for Iter<'a, K> {}
957 #[stable(feature = "std_debug", since = "1.16.0")]
958 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
959 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961 .entries(self.clone())
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<K> Iterator for IntoIter<K> {
970 fn next(&mut self) -> Option<K> {
971 self.iter.next().map(|(k, _)| k)
973 fn size_hint(&self) -> (usize, Option<usize>) {
974 self.iter.size_hint()
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<K> ExactSizeIterator for IntoIter<K> {
979 fn len(&self) -> usize {
983 #[unstable(feature = "fused", issue = "35602")]
984 impl<K> FusedIterator for IntoIter<K> {}
986 #[stable(feature = "std_debug", since = "1.16.0")]
987 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
988 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
989 let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
991 .entries(entries_iter)
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl<'a, K> Iterator for Drain<'a, K> {
1000 fn next(&mut self) -> Option<K> {
1001 self.iter.next().map(|(k, _)| k)
1003 fn size_hint(&self) -> (usize, Option<usize>) {
1004 self.iter.size_hint()
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1009 fn len(&self) -> usize {
1013 #[unstable(feature = "fused", issue = "35602")]
1014 impl<'a, K> FusedIterator for Drain<'a, K> {}
1016 #[stable(feature = "std_debug", since = "1.16.0")]
1017 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1018 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1019 let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
1021 .entries(entries_iter)
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1028 fn clone(&self) -> Intersection<'a, T, S> {
1029 Intersection { iter: self.iter.clone(), ..*self }
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1040 fn next(&mut self) -> Option<&'a T> {
1042 match self.iter.next() {
1043 None => return None,
1045 if self.other.contains(elt) {
1053 fn size_hint(&self) -> (usize, Option<usize>) {
1054 let (_, upper) = self.iter.size_hint();
1059 #[stable(feature = "std_debug", since = "1.16.0")]
1060 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1061 where T: fmt::Debug + Eq + Hash,
1064 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1066 .entries(self.clone())
1071 #[unstable(feature = "fused", issue = "35602")]
1072 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<'a, T, S> Clone for Difference<'a, T, S> {
1080 fn clone(&self) -> Difference<'a, T, S> {
1081 Difference { iter: self.iter.clone(), ..*self }
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<'a, T, S> Iterator for Difference<'a, T, S>
1092 fn next(&mut self) -> Option<&'a T> {
1094 match self.iter.next() {
1095 None => return None,
1097 if !self.other.contains(elt) {
1105 fn size_hint(&self) -> (usize, Option<usize>) {
1106 let (_, upper) = self.iter.size_hint();
1111 #[unstable(feature = "fused", issue = "35602")]
1112 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1118 #[stable(feature = "std_debug", since = "1.16.0")]
1119 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1120 where T: fmt::Debug + Eq + Hash,
1123 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1125 .entries(self.clone())
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1132 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1133 SymmetricDifference { iter: self.iter.clone() }
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1144 fn next(&mut self) -> Option<&'a T> {
1147 fn size_hint(&self) -> (usize, Option<usize>) {
1148 self.iter.size_hint()
1152 #[unstable(feature = "fused", issue = "35602")]
1153 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1159 #[stable(feature = "std_debug", since = "1.16.0")]
1160 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1161 where T: fmt::Debug + Eq + Hash,
1164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1166 .entries(self.clone())
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<'a, T, S> Clone for Union<'a, T, S> {
1173 fn clone(&self) -> Union<'a, T, S> {
1174 Union { iter: self.iter.clone() }
1178 #[unstable(feature = "fused", issue = "35602")]
1179 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1185 #[stable(feature = "std_debug", since = "1.16.0")]
1186 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1187 where T: fmt::Debug + Eq + Hash,
1190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1192 .entries(self.clone())
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<'a, T, S> Iterator for Union<'a, T, S>
1204 fn next(&mut self) -> Option<&'a T> {
1207 fn size_hint(&self) -> (usize, Option<usize>) {
1208 self.iter.size_hint()
1213 fn assert_covariance() {
1214 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1217 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1220 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1223 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1224 -> Difference<'a, &'new str, RandomState> {
1227 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1228 -> SymmetricDifference<'a, &'new str, RandomState> {
1231 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1232 -> Intersection<'a, &'new str, RandomState> {
1235 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1236 -> Union<'a, &'new str, RandomState> {
1239 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1247 use super::super::map::RandomState;
1250 fn test_zero_capacities() {
1251 type HS = HashSet<i32>;
1254 assert_eq!(s.capacity(), 0);
1256 let s = HS::default();
1257 assert_eq!(s.capacity(), 0);
1259 let s = HS::with_hasher(RandomState::new());
1260 assert_eq!(s.capacity(), 0);
1262 let s = HS::with_capacity(0);
1263 assert_eq!(s.capacity(), 0);
1265 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1266 assert_eq!(s.capacity(), 0);
1268 let mut s = HS::new();
1274 assert_eq!(s.capacity(), 0);
1276 let mut s = HS::new();
1278 assert_eq!(s.capacity(), 0);
1282 fn test_disjoint() {
1283 let mut xs = HashSet::new();
1284 let mut ys = HashSet::new();
1285 assert!(xs.is_disjoint(&ys));
1286 assert!(ys.is_disjoint(&xs));
1287 assert!(xs.insert(5));
1288 assert!(ys.insert(11));
1289 assert!(xs.is_disjoint(&ys));
1290 assert!(ys.is_disjoint(&xs));
1291 assert!(xs.insert(7));
1292 assert!(xs.insert(19));
1293 assert!(xs.insert(4));
1294 assert!(ys.insert(2));
1295 assert!(ys.insert(-11));
1296 assert!(xs.is_disjoint(&ys));
1297 assert!(ys.is_disjoint(&xs));
1298 assert!(ys.insert(7));
1299 assert!(!xs.is_disjoint(&ys));
1300 assert!(!ys.is_disjoint(&xs));
1304 fn test_subset_and_superset() {
1305 let mut a = HashSet::new();
1306 assert!(a.insert(0));
1307 assert!(a.insert(5));
1308 assert!(a.insert(11));
1309 assert!(a.insert(7));
1311 let mut b = HashSet::new();
1312 assert!(b.insert(0));
1313 assert!(b.insert(7));
1314 assert!(b.insert(19));
1315 assert!(b.insert(250));
1316 assert!(b.insert(11));
1317 assert!(b.insert(200));
1319 assert!(!a.is_subset(&b));
1320 assert!(!a.is_superset(&b));
1321 assert!(!b.is_subset(&a));
1322 assert!(!b.is_superset(&a));
1324 assert!(b.insert(5));
1326 assert!(a.is_subset(&b));
1327 assert!(!a.is_superset(&b));
1328 assert!(!b.is_subset(&a));
1329 assert!(b.is_superset(&a));
1334 let mut a = HashSet::new();
1336 assert!(a.insert(i));
1338 let mut observed: u32 = 0;
1340 observed |= 1 << *k;
1342 assert_eq!(observed, 0xFFFF_FFFF);
1346 fn test_intersection() {
1347 let mut a = HashSet::new();
1348 let mut b = HashSet::new();
1350 assert!(a.insert(11));
1351 assert!(a.insert(1));
1352 assert!(a.insert(3));
1353 assert!(a.insert(77));
1354 assert!(a.insert(103));
1355 assert!(a.insert(5));
1356 assert!(a.insert(-5));
1358 assert!(b.insert(2));
1359 assert!(b.insert(11));
1360 assert!(b.insert(77));
1361 assert!(b.insert(-9));
1362 assert!(b.insert(-42));
1363 assert!(b.insert(5));
1364 assert!(b.insert(3));
1367 let expected = [3, 5, 11, 77];
1368 for x in a.intersection(&b) {
1369 assert!(expected.contains(x));
1372 assert_eq!(i, expected.len());
1376 fn test_difference() {
1377 let mut a = HashSet::new();
1378 let mut b = HashSet::new();
1380 assert!(a.insert(1));
1381 assert!(a.insert(3));
1382 assert!(a.insert(5));
1383 assert!(a.insert(9));
1384 assert!(a.insert(11));
1386 assert!(b.insert(3));
1387 assert!(b.insert(9));
1390 let expected = [1, 5, 11];
1391 for x in a.difference(&b) {
1392 assert!(expected.contains(x));
1395 assert_eq!(i, expected.len());
1399 fn test_symmetric_difference() {
1400 let mut a = HashSet::new();
1401 let mut b = HashSet::new();
1403 assert!(a.insert(1));
1404 assert!(a.insert(3));
1405 assert!(a.insert(5));
1406 assert!(a.insert(9));
1407 assert!(a.insert(11));
1409 assert!(b.insert(-2));
1410 assert!(b.insert(3));
1411 assert!(b.insert(9));
1412 assert!(b.insert(14));
1413 assert!(b.insert(22));
1416 let expected = [-2, 1, 5, 11, 14, 22];
1417 for x in a.symmetric_difference(&b) {
1418 assert!(expected.contains(x));
1421 assert_eq!(i, expected.len());
1426 let mut a = HashSet::new();
1427 let mut b = HashSet::new();
1429 assert!(a.insert(1));
1430 assert!(a.insert(3));
1431 assert!(a.insert(5));
1432 assert!(a.insert(9));
1433 assert!(a.insert(11));
1434 assert!(a.insert(16));
1435 assert!(a.insert(19));
1436 assert!(a.insert(24));
1438 assert!(b.insert(-2));
1439 assert!(b.insert(1));
1440 assert!(b.insert(5));
1441 assert!(b.insert(9));
1442 assert!(b.insert(13));
1443 assert!(b.insert(19));
1446 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1447 for x in a.union(&b) {
1448 assert!(expected.contains(x));
1451 assert_eq!(i, expected.len());
1455 fn test_from_iter() {
1456 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1458 let set: HashSet<_> = xs.iter().cloned().collect();
1461 assert!(set.contains(x));
1466 fn test_move_iter() {
1468 let mut hs = HashSet::new();
1476 let v = hs.into_iter().collect::<Vec<char>>();
1477 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1482 // These constants once happened to expose a bug in insert().
1483 // I'm keeping them around to prevent a regression.
1484 let mut s1 = HashSet::new();
1490 let mut s2 = HashSet::new();
1504 let mut set = HashSet::new();
1505 let empty = HashSet::<i32>::new();
1510 let set_str = format!("{:?}", set);
1512 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1513 assert_eq!(format!("{:?}", empty), "{}");
1517 fn test_trivial_drain() {
1518 let mut s = HashSet::<i32>::new();
1519 for _ in s.drain() {}
1520 assert!(s.is_empty());
1523 let mut s = HashSet::<i32>::new();
1525 assert!(s.is_empty());
1530 let mut s: HashSet<_> = (1..100).collect();
1532 // try this a bunch of times to make sure we don't screw up internal state.
1534 assert_eq!(s.len(), 99);
1538 let mut d = s.drain();
1539 for (i, x) in d.by_ref().take(50).enumerate() {
1543 assert_eq!(last_i, 49);
1547 panic!("s should be empty!");
1550 // reset to try again.
1560 struct Foo(&'static str, i32);
1562 impl PartialEq for Foo {
1563 fn eq(&self, other: &Self) -> bool {
1570 impl hash::Hash for Foo {
1571 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1576 let mut s = HashSet::new();
1577 assert_eq!(s.replace(Foo("a", 1)), None);
1578 assert_eq!(s.len(), 1);
1579 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1580 assert_eq!(s.len(), 1);
1582 let mut it = s.iter();
1583 assert_eq!(it.next(), Some(&Foo("a", 2)));
1584 assert_eq!(it.next(), None);
1588 fn test_extend_ref() {
1589 let mut a = HashSet::new();
1592 a.extend(&[2, 3, 4]);
1594 assert_eq!(a.len(), 4);
1595 assert!(a.contains(&1));
1596 assert!(a.contains(&2));
1597 assert!(a.contains(&3));
1598 assert!(a.contains(&4));
1600 let mut b = HashSet::new();
1606 assert_eq!(a.len(), 6);
1607 assert!(a.contains(&1));
1608 assert!(a.contains(&2));
1609 assert!(a.contains(&3));
1610 assert!(a.contains(&4));
1611 assert!(a.contains(&5));
1612 assert!(a.contains(&6));