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.
299 /// use std::collections::HashSet;
300 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
301 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
303 /// // Can be seen as `a - b`.
304 /// for x in a.difference(&b) {
305 /// println!("{}", x); // Print 1
308 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
309 /// assert_eq!(diff, [1].iter().cloned().collect());
311 /// // Note that difference is not symmetric,
312 /// // and `b - a` means something else:
313 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
314 /// assert_eq!(diff, [4].iter().cloned().collect());
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
324 /// Visit the values representing the symmetric difference.
329 /// use std::collections::HashSet;
330 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
331 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
333 /// // Print 1, 4 in arbitrary order.
334 /// for x in a.symmetric_difference(&b) {
335 /// println!("{}", x);
338 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
339 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
341 /// assert_eq!(diff1, diff2);
342 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn symmetric_difference<'a>(&'a self,
346 other: &'a HashSet<T, S>)
347 -> SymmetricDifference<'a, T, S> {
348 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
351 /// Visit the values representing the intersection.
356 /// use std::collections::HashSet;
357 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
358 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
360 /// // Print 2, 3 in arbitrary order.
361 /// for x in a.intersection(&b) {
362 /// println!("{}", x);
365 /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
366 /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
376 /// Visit the values representing the union.
381 /// use std::collections::HashSet;
382 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
383 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
385 /// // Print 1, 2, 3, 4 in arbitrary order.
386 /// for x in a.union(&b) {
387 /// println!("{}", x);
390 /// let union: HashSet<_> = a.union(&b).cloned().collect();
391 /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
395 Union { iter: self.iter().chain(other.difference(self)) }
398 /// Returns the number of elements in the set.
403 /// use std::collections::HashSet;
405 /// let mut v = HashSet::new();
406 /// assert_eq!(v.len(), 0);
408 /// assert_eq!(v.len(), 1);
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn len(&self) -> usize {
415 /// Returns true if the set contains no elements.
420 /// use std::collections::HashSet;
422 /// let mut v = HashSet::new();
423 /// assert!(v.is_empty());
425 /// assert!(!v.is_empty());
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn is_empty(&self) -> bool {
432 /// Clears the set, returning all elements in an iterator.
434 #[stable(feature = "drain", since = "1.6.0")]
435 pub fn drain(&mut self) -> Drain<T> {
436 Drain { iter: self.map.drain() }
439 /// Clears the set, removing all values.
444 /// use std::collections::HashSet;
446 /// let mut v = HashSet::new();
449 /// assert!(v.is_empty());
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn clear(&mut self) {
456 /// Returns `true` if the set contains a value.
458 /// The value may be any borrowed form of the set's value type, but
459 /// `Hash` and `Eq` on the borrowed form *must* match those for
465 /// use std::collections::HashSet;
467 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
468 /// assert_eq!(set.contains(&1), true);
469 /// assert_eq!(set.contains(&4), false);
471 #[stable(feature = "rust1", since = "1.0.0")]
472 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
476 self.map.contains_key(value)
479 /// Returns a reference to the value in the set, if any, that is equal to the given value.
481 /// The value may be any borrowed form of the set's value type, but
482 /// `Hash` and `Eq` on the borrowed form *must* match those for
484 #[stable(feature = "set_recovery", since = "1.9.0")]
485 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
489 Recover::get(&self.map, value)
492 /// Returns `true` if the set has no elements in common with `other`.
493 /// This is equivalent to checking for an empty intersection.
498 /// use std::collections::HashSet;
500 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
501 /// let mut b = HashSet::new();
503 /// assert_eq!(a.is_disjoint(&b), true);
505 /// assert_eq!(a.is_disjoint(&b), true);
507 /// assert_eq!(a.is_disjoint(&b), false);
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
511 self.iter().all(|v| !other.contains(v))
514 /// Returns `true` if the set is a subset of another.
519 /// use std::collections::HashSet;
521 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
522 /// let mut set = HashSet::new();
524 /// assert_eq!(set.is_subset(&sup), true);
526 /// assert_eq!(set.is_subset(&sup), true);
528 /// assert_eq!(set.is_subset(&sup), false);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
532 self.iter().all(|v| other.contains(v))
535 /// Returns `true` if the set is a superset of another.
540 /// use std::collections::HashSet;
542 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
543 /// let mut set = HashSet::new();
545 /// assert_eq!(set.is_superset(&sub), false);
549 /// assert_eq!(set.is_superset(&sub), false);
552 /// assert_eq!(set.is_superset(&sub), true);
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
557 other.is_subset(self)
560 /// Adds a value to the set.
562 /// If the set did not have this value present, `true` is returned.
564 /// If the set did have this value present, `false` is returned.
569 /// use std::collections::HashSet;
571 /// let mut set = HashSet::new();
573 /// assert_eq!(set.insert(2), true);
574 /// assert_eq!(set.insert(2), false);
575 /// assert_eq!(set.len(), 1);
577 #[stable(feature = "rust1", since = "1.0.0")]
578 pub fn insert(&mut self, value: T) -> bool {
579 self.map.insert(value, ()).is_none()
582 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
583 /// one. Returns the replaced value.
584 #[stable(feature = "set_recovery", since = "1.9.0")]
585 pub fn replace(&mut self, value: T) -> Option<T> {
586 Recover::replace(&mut self.map, value)
589 /// Removes a value from the set. Returns `true` if the value was
590 /// present in the set.
592 /// The value may be any borrowed form of the set's value type, but
593 /// `Hash` and `Eq` on the borrowed form *must* match those for
599 /// use std::collections::HashSet;
601 /// let mut set = HashSet::new();
604 /// assert_eq!(set.remove(&2), true);
605 /// assert_eq!(set.remove(&2), false);
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
612 self.map.remove(value).is_some()
615 /// Removes and returns the value in the set, if any, that is equal to the given one.
617 /// The value may be any borrowed form of the set's value type, but
618 /// `Hash` and `Eq` on the borrowed form *must* match those for
620 #[stable(feature = "set_recovery", since = "1.9.0")]
621 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
625 Recover::take(&mut self.map, value)
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<T, S> PartialEq for HashSet<T, S>
634 fn eq(&self, other: &HashSet<T, S>) -> bool {
635 if self.len() != other.len() {
639 self.iter().all(|key| other.contains(key))
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T, S> Eq for HashSet<T, S>
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T, S> fmt::Debug for HashSet<T, S>
652 where T: Eq + Hash + fmt::Debug,
655 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
656 f.debug_set().entries(self.iter()).finish()
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<T, S> FromIterator<T> for HashSet<T, S>
663 S: BuildHasher + Default
665 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
666 let mut set = HashSet::with_hasher(Default::default());
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<T, S> Extend<T> for HashSet<T, S>
677 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
678 self.map.extend(iter.into_iter().map(|k| (k, ())));
682 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
683 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
684 where T: 'a + Eq + Hash + Copy,
687 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
688 self.extend(iter.into_iter().cloned());
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<T, S> Default for HashSet<T, S>
695 S: BuildHasher + Default
697 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
698 fn default() -> HashSet<T, S> {
699 HashSet { map: HashMap::default() }
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
705 where T: Eq + Hash + Clone,
706 S: BuildHasher + Default
708 type Output = HashSet<T, S>;
710 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
715 /// use std::collections::HashSet;
717 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
718 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
720 /// let set = &a | &b;
723 /// let expected = [1, 2, 3, 4, 5];
725 /// assert!(expected.contains(x));
728 /// assert_eq!(i, expected.len());
730 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
731 self.union(rhs).cloned().collect()
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
737 where T: Eq + Hash + Clone,
738 S: BuildHasher + Default
740 type Output = HashSet<T, S>;
742 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
747 /// use std::collections::HashSet;
749 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
750 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
752 /// let set = &a & &b;
755 /// let expected = [2, 3];
757 /// assert!(expected.contains(x));
760 /// assert_eq!(i, expected.len());
762 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
763 self.intersection(rhs).cloned().collect()
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
769 where T: Eq + Hash + Clone,
770 S: BuildHasher + Default
772 type Output = HashSet<T, S>;
774 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
779 /// use std::collections::HashSet;
781 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
782 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
784 /// let set = &a ^ &b;
787 /// let expected = [1, 2, 4, 5];
789 /// assert!(expected.contains(x));
792 /// assert_eq!(i, expected.len());
794 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
795 self.symmetric_difference(rhs).cloned().collect()
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
801 where T: Eq + Hash + Clone,
802 S: BuildHasher + Default
804 type Output = HashSet<T, S>;
806 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
811 /// use std::collections::HashSet;
813 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
814 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
816 /// let set = &a - &b;
819 /// let expected = [1, 2];
821 /// assert!(expected.contains(x));
824 /// assert_eq!(i, expected.len());
826 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
827 self.difference(rhs).cloned().collect()
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub struct Iter<'a, K: 'a> {
834 iter: Keys<'a, K, ()>,
837 /// HashSet move iterator
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub struct IntoIter<K> {
840 iter: map::IntoIter<K, ()>,
843 /// HashSet drain iterator
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub struct Drain<'a, K: 'a> {
846 iter: map::Drain<'a, K, ()>,
849 /// Intersection iterator
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub struct Intersection<'a, T: 'a, S: 'a> {
852 // iterator of the first set
855 other: &'a HashSet<T, S>,
858 /// Difference iterator
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub struct Difference<'a, T: 'a, S: 'a> {
861 // iterator of the first set
864 other: &'a HashSet<T, S>,
867 /// Symmetric difference iterator.
868 #[stable(feature = "rust1", since = "1.0.0")]
869 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
870 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
873 /// Set union iterator.
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub struct Union<'a, T: 'a, S: 'a> {
876 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
885 type IntoIter = Iter<'a, T>;
887 fn into_iter(self) -> Iter<'a, T> {
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<T, S> IntoIterator for HashSet<T, S>
898 type IntoIter = IntoIter<T>;
900 /// Creates a consuming iterator, that is, one that moves each value out
901 /// of the set in arbitrary order. The set cannot be used after calling
907 /// use std::collections::HashSet;
908 /// let mut set = HashSet::new();
909 /// set.insert("a".to_string());
910 /// set.insert("b".to_string());
912 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
913 /// let v: Vec<String> = set.into_iter().collect();
915 /// // Will print in an arbitrary order.
917 /// println!("{}", x);
920 fn into_iter(self) -> IntoIter<T> {
921 IntoIter { iter: self.map.into_iter() }
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<'a, K> Clone for Iter<'a, K> {
927 fn clone(&self) -> Iter<'a, K> {
928 Iter { iter: self.iter.clone() }
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<'a, K> Iterator for Iter<'a, K> {
935 fn next(&mut self) -> Option<&'a K> {
938 fn size_hint(&self) -> (usize, Option<usize>) {
939 self.iter.size_hint()
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
944 fn len(&self) -> usize {
948 #[unstable(feature = "fused", issue = "35602")]
949 impl<'a, K> FusedIterator for Iter<'a, K> {}
951 #[stable(feature = "std_debug", since = "1.15.0")]
952 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
953 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
955 .entries(self.clone())
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<K> Iterator for IntoIter<K> {
964 fn next(&mut self) -> Option<K> {
965 self.iter.next().map(|(k, _)| k)
967 fn size_hint(&self) -> (usize, Option<usize>) {
968 self.iter.size_hint()
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<K> ExactSizeIterator for IntoIter<K> {
973 fn len(&self) -> usize {
977 #[unstable(feature = "fused", issue = "35602")]
978 impl<K> FusedIterator for IntoIter<K> {}
980 #[stable(feature = "std_debug", since = "1.15.0")]
981 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
983 let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
985 .entries(entries_iter)
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<'a, K> Iterator for Drain<'a, K> {
994 fn next(&mut self) -> Option<K> {
995 self.iter.next().map(|(k, _)| k)
997 fn size_hint(&self) -> (usize, Option<usize>) {
998 self.iter.size_hint()
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1003 fn len(&self) -> usize {
1007 #[unstable(feature = "fused", issue = "35602")]
1008 impl<'a, K> FusedIterator for Drain<'a, K> {}
1010 #[stable(feature = "std_debug", since = "1.15.0")]
1011 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1012 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1013 let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
1015 .entries(entries_iter)
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1022 fn clone(&self) -> Intersection<'a, T, S> {
1023 Intersection { iter: self.iter.clone(), ..*self }
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1034 fn next(&mut self) -> Option<&'a T> {
1036 match self.iter.next() {
1037 None => return None,
1039 if self.other.contains(elt) {
1047 fn size_hint(&self) -> (usize, Option<usize>) {
1048 let (_, upper) = self.iter.size_hint();
1053 #[stable(feature = "std_debug", since = "1.15.0")]
1054 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1055 where T: fmt::Debug + Eq + Hash,
1058 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1060 .entries(self.clone())
1065 #[unstable(feature = "fused", issue = "35602")]
1066 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<'a, T, S> Clone for Difference<'a, T, S> {
1074 fn clone(&self) -> Difference<'a, T, S> {
1075 Difference { iter: self.iter.clone(), ..*self }
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<'a, T, S> Iterator for Difference<'a, T, S>
1086 fn next(&mut self) -> Option<&'a T> {
1088 match self.iter.next() {
1089 None => return None,
1091 if !self.other.contains(elt) {
1099 fn size_hint(&self) -> (usize, Option<usize>) {
1100 let (_, upper) = self.iter.size_hint();
1105 #[unstable(feature = "fused", issue = "35602")]
1106 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1112 #[stable(feature = "std_debug", since = "1.15.0")]
1113 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1114 where T: fmt::Debug + Eq + Hash,
1117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1119 .entries(self.clone())
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1126 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1127 SymmetricDifference { iter: self.iter.clone() }
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1138 fn next(&mut self) -> Option<&'a T> {
1141 fn size_hint(&self) -> (usize, Option<usize>) {
1142 self.iter.size_hint()
1146 #[unstable(feature = "fused", issue = "35602")]
1147 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1153 #[stable(feature = "std_debug", since = "1.15.0")]
1154 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1155 where T: fmt::Debug + Eq + Hash,
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1160 .entries(self.clone())
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<'a, T, S> Clone for Union<'a, T, S> {
1167 fn clone(&self) -> Union<'a, T, S> {
1168 Union { iter: self.iter.clone() }
1172 #[unstable(feature = "fused", issue = "35602")]
1173 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1179 #[stable(feature = "std_debug", since = "1.15.0")]
1180 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1181 where T: fmt::Debug + Eq + Hash,
1184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1186 .entries(self.clone())
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<'a, T, S> Iterator for Union<'a, T, S>
1198 fn next(&mut self) -> Option<&'a T> {
1201 fn size_hint(&self) -> (usize, Option<usize>) {
1202 self.iter.size_hint()
1207 fn assert_covariance() {
1208 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1211 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1214 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1217 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1218 -> Difference<'a, &'new str, RandomState> {
1221 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1222 -> SymmetricDifference<'a, &'new str, RandomState> {
1225 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1226 -> Intersection<'a, &'new str, RandomState> {
1229 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1230 -> Union<'a, &'new str, RandomState> {
1233 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1241 use super::super::map::RandomState;
1244 fn test_zero_capacities() {
1245 type HS = HashSet<i32>;
1248 assert_eq!(s.capacity(), 0);
1250 let s = HS::default();
1251 assert_eq!(s.capacity(), 0);
1253 let s = HS::with_hasher(RandomState::new());
1254 assert_eq!(s.capacity(), 0);
1256 let s = HS::with_capacity(0);
1257 assert_eq!(s.capacity(), 0);
1259 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1260 assert_eq!(s.capacity(), 0);
1262 let mut s = HS::new();
1268 assert_eq!(s.capacity(), 0);
1270 let mut s = HS::new();
1272 assert_eq!(s.capacity(), 0);
1276 fn test_disjoint() {
1277 let mut xs = HashSet::new();
1278 let mut ys = HashSet::new();
1279 assert!(xs.is_disjoint(&ys));
1280 assert!(ys.is_disjoint(&xs));
1281 assert!(xs.insert(5));
1282 assert!(ys.insert(11));
1283 assert!(xs.is_disjoint(&ys));
1284 assert!(ys.is_disjoint(&xs));
1285 assert!(xs.insert(7));
1286 assert!(xs.insert(19));
1287 assert!(xs.insert(4));
1288 assert!(ys.insert(2));
1289 assert!(ys.insert(-11));
1290 assert!(xs.is_disjoint(&ys));
1291 assert!(ys.is_disjoint(&xs));
1292 assert!(ys.insert(7));
1293 assert!(!xs.is_disjoint(&ys));
1294 assert!(!ys.is_disjoint(&xs));
1298 fn test_subset_and_superset() {
1299 let mut a = HashSet::new();
1300 assert!(a.insert(0));
1301 assert!(a.insert(5));
1302 assert!(a.insert(11));
1303 assert!(a.insert(7));
1305 let mut b = HashSet::new();
1306 assert!(b.insert(0));
1307 assert!(b.insert(7));
1308 assert!(b.insert(19));
1309 assert!(b.insert(250));
1310 assert!(b.insert(11));
1311 assert!(b.insert(200));
1313 assert!(!a.is_subset(&b));
1314 assert!(!a.is_superset(&b));
1315 assert!(!b.is_subset(&a));
1316 assert!(!b.is_superset(&a));
1318 assert!(b.insert(5));
1320 assert!(a.is_subset(&b));
1321 assert!(!a.is_superset(&b));
1322 assert!(!b.is_subset(&a));
1323 assert!(b.is_superset(&a));
1328 let mut a = HashSet::new();
1330 assert!(a.insert(i));
1332 let mut observed: u32 = 0;
1334 observed |= 1 << *k;
1336 assert_eq!(observed, 0xFFFF_FFFF);
1340 fn test_intersection() {
1341 let mut a = HashSet::new();
1342 let mut b = HashSet::new();
1344 assert!(a.insert(11));
1345 assert!(a.insert(1));
1346 assert!(a.insert(3));
1347 assert!(a.insert(77));
1348 assert!(a.insert(103));
1349 assert!(a.insert(5));
1350 assert!(a.insert(-5));
1352 assert!(b.insert(2));
1353 assert!(b.insert(11));
1354 assert!(b.insert(77));
1355 assert!(b.insert(-9));
1356 assert!(b.insert(-42));
1357 assert!(b.insert(5));
1358 assert!(b.insert(3));
1361 let expected = [3, 5, 11, 77];
1362 for x in a.intersection(&b) {
1363 assert!(expected.contains(x));
1366 assert_eq!(i, expected.len());
1370 fn test_difference() {
1371 let mut a = HashSet::new();
1372 let mut b = HashSet::new();
1374 assert!(a.insert(1));
1375 assert!(a.insert(3));
1376 assert!(a.insert(5));
1377 assert!(a.insert(9));
1378 assert!(a.insert(11));
1380 assert!(b.insert(3));
1381 assert!(b.insert(9));
1384 let expected = [1, 5, 11];
1385 for x in a.difference(&b) {
1386 assert!(expected.contains(x));
1389 assert_eq!(i, expected.len());
1393 fn test_symmetric_difference() {
1394 let mut a = HashSet::new();
1395 let mut b = HashSet::new();
1397 assert!(a.insert(1));
1398 assert!(a.insert(3));
1399 assert!(a.insert(5));
1400 assert!(a.insert(9));
1401 assert!(a.insert(11));
1403 assert!(b.insert(-2));
1404 assert!(b.insert(3));
1405 assert!(b.insert(9));
1406 assert!(b.insert(14));
1407 assert!(b.insert(22));
1410 let expected = [-2, 1, 5, 11, 14, 22];
1411 for x in a.symmetric_difference(&b) {
1412 assert!(expected.contains(x));
1415 assert_eq!(i, expected.len());
1420 let mut a = HashSet::new();
1421 let mut b = HashSet::new();
1423 assert!(a.insert(1));
1424 assert!(a.insert(3));
1425 assert!(a.insert(5));
1426 assert!(a.insert(9));
1427 assert!(a.insert(11));
1428 assert!(a.insert(16));
1429 assert!(a.insert(19));
1430 assert!(a.insert(24));
1432 assert!(b.insert(-2));
1433 assert!(b.insert(1));
1434 assert!(b.insert(5));
1435 assert!(b.insert(9));
1436 assert!(b.insert(13));
1437 assert!(b.insert(19));
1440 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1441 for x in a.union(&b) {
1442 assert!(expected.contains(x));
1445 assert_eq!(i, expected.len());
1449 fn test_from_iter() {
1450 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1452 let set: HashSet<_> = xs.iter().cloned().collect();
1455 assert!(set.contains(x));
1460 fn test_move_iter() {
1462 let mut hs = HashSet::new();
1470 let v = hs.into_iter().collect::<Vec<char>>();
1471 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1476 // These constants once happened to expose a bug in insert().
1477 // I'm keeping them around to prevent a regression.
1478 let mut s1 = HashSet::new();
1484 let mut s2 = HashSet::new();
1498 let mut set = HashSet::new();
1499 let empty = HashSet::<i32>::new();
1504 let set_str = format!("{:?}", set);
1506 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1507 assert_eq!(format!("{:?}", empty), "{}");
1511 fn test_trivial_drain() {
1512 let mut s = HashSet::<i32>::new();
1513 for _ in s.drain() {}
1514 assert!(s.is_empty());
1517 let mut s = HashSet::<i32>::new();
1519 assert!(s.is_empty());
1524 let mut s: HashSet<_> = (1..100).collect();
1526 // try this a bunch of times to make sure we don't screw up internal state.
1528 assert_eq!(s.len(), 99);
1532 let mut d = s.drain();
1533 for (i, x) in d.by_ref().take(50).enumerate() {
1537 assert_eq!(last_i, 49);
1541 panic!("s should be empty!");
1544 // reset to try again.
1554 struct Foo(&'static str, i32);
1556 impl PartialEq for Foo {
1557 fn eq(&self, other: &Self) -> bool {
1564 impl hash::Hash for Foo {
1565 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1570 let mut s = HashSet::new();
1571 assert_eq!(s.replace(Foo("a", 1)), None);
1572 assert_eq!(s.len(), 1);
1573 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1574 assert_eq!(s.len(), 1);
1576 let mut it = s.iter();
1577 assert_eq!(it.next(), Some(&Foo("a", 2)));
1578 assert_eq!(it.next(), None);
1582 fn test_extend_ref() {
1583 let mut a = HashSet::new();
1586 a.extend(&[2, 3, 4]);
1588 assert_eq!(a.len(), 4);
1589 assert!(a.contains(&1));
1590 assert!(a.contains(&2));
1591 assert!(a.contains(&3));
1592 assert!(a.contains(&4));
1594 let mut b = HashSet::new();
1600 assert_eq!(a.len(), 6);
1601 assert!(a.contains(&1));
1602 assert!(a.contains(&2));
1603 assert!(a.contains(&3));
1604 assert!(a.contains(&4));
1605 assert!(a.contains(&5));
1606 assert!(a.contains(&6));