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 /// A hash set implemented as a `HashMap` where the value is `()`.
29 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
30 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
31 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
32 /// it is important that the following property holds:
35 /// k1 == k2 -> hash(k1) == hash(k2)
38 /// In other words, if two keys are equal, their hashes must be equal.
41 /// It is a logic error for an item to be modified in such a way that the
42 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
43 /// determined by the [`Eq`] trait, changes while it is in the set. This is
44 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
50 /// use std::collections::HashSet;
51 /// // Type inference lets us omit an explicit type signature (which
52 /// // would be `HashSet<&str>` in this example).
53 /// let mut books = HashSet::new();
55 /// // Add some books.
56 /// books.insert("A Dance With Dragons");
57 /// books.insert("To Kill a Mockingbird");
58 /// books.insert("The Odyssey");
59 /// books.insert("The Great Gatsby");
61 /// // Check for a specific one.
62 /// if !books.contains("The Winds of Winter") {
63 /// println!("We have {} books, but The Winds of Winter ain't one.",
68 /// books.remove("The Odyssey");
70 /// // Iterate over everything.
71 /// for book in &books {
72 /// println!("{}", book);
76 /// The easiest way to use `HashSet` with a custom type is to derive
77 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
78 /// future be implied by [`Eq`].
81 /// use std::collections::HashSet;
82 /// #[derive(Hash, Eq, PartialEq, Debug)]
83 /// struct Viking<'a> {
88 /// let mut vikings = HashSet::new();
90 /// vikings.insert(Viking { name: "Einar", power: 9 });
91 /// vikings.insert(Viking { name: "Einar", power: 9 });
92 /// vikings.insert(Viking { name: "Olaf", power: 4 });
93 /// vikings.insert(Viking { name: "Harald", power: 8 });
95 /// // Use derived implementation to print the vikings.
96 /// for x in &vikings {
97 /// println!("{:?}", x);
101 /// A `HashSet` with fixed list of elements can be initialized from an array:
104 /// use std::collections::HashSet;
107 /// let viking_names: HashSet<&str> =
108 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
109 /// // use the values stored in the set
113 /// [`Cell`]: ../../std/cell/struct.Cell.html
114 /// [`Eq`]: ../../std/cmp/trait.Eq.html
115 /// [`Hash`]: ../../std/hash/trait.Hash.html
116 /// [`HashMap`]: struct.HashMap.html
117 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
118 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct HashSet<T, S = RandomState> {
122 map: HashMap<T, (), S>,
125 impl<T: Hash + Eq> HashSet<T, RandomState> {
126 /// Creates an empty `HashSet`.
128 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
129 /// is first inserted into.
134 /// use std::collections::HashSet;
135 /// let set: HashSet<i32> = HashSet::new();
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn new() -> HashSet<T, RandomState> {
140 HashSet { map: HashMap::new() }
143 /// Creates an empty `HashSet` with the specified capacity.
145 /// The hash set will be able to hold at least `capacity` elements without
146 /// reallocating. If `capacity` is 0, the hash set will not allocate.
151 /// use std::collections::HashSet;
152 /// let set: HashSet<i32> = HashSet::with_capacity(10);
153 /// assert!(set.capacity() >= 10);
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
158 HashSet { map: HashMap::with_capacity(capacity) }
162 impl<T, S> HashSet<T, S>
166 /// Creates a new empty hash set which will use the given hasher to hash
169 /// The hash set is also created with the default initial capacity.
171 /// Warning: `hasher` is normally randomly generated, and
172 /// is designed to allow `HashSet`s to be resistant to attacks that
173 /// cause many collisions and very poor performance. Setting it
174 /// manually using this function can expose a DoS attack vector.
179 /// use std::collections::HashSet;
180 /// use std::collections::hash_map::RandomState;
182 /// let s = RandomState::new();
183 /// let mut set = HashSet::with_hasher(s);
187 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
188 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
189 HashSet { map: HashMap::with_hasher(hasher) }
192 /// Creates an empty `HashSet` with with the specified capacity, using
193 /// `hasher` to hash the keys.
195 /// The hash set will be able to hold at least `capacity` elements without
196 /// reallocating. If `capacity` is 0, the hash set will not allocate.
198 /// Warning: `hasher` is normally randomly generated, and
199 /// is designed to allow `HashSet`s to be resistant to attacks that
200 /// cause many collisions and very poor performance. Setting it
201 /// manually using this function can expose a DoS attack vector.
206 /// use std::collections::HashSet;
207 /// use std::collections::hash_map::RandomState;
209 /// let s = RandomState::new();
210 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
214 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
215 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
216 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
219 /// Returns a reference to the set's [`BuildHasher`].
221 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
226 /// use std::collections::HashSet;
227 /// use std::collections::hash_map::RandomState;
229 /// let hasher = RandomState::new();
230 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
231 /// let hasher: &RandomState = set.hasher();
233 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
234 pub fn hasher(&self) -> &S {
238 /// Returns the number of elements the set can hold without reallocating.
243 /// use std::collections::HashSet;
244 /// let set: HashSet<i32> = HashSet::with_capacity(100);
245 /// assert!(set.capacity() >= 100);
248 #[stable(feature = "rust1", since = "1.0.0")]
249 pub fn capacity(&self) -> usize {
253 /// Reserves capacity for at least `additional` more elements to be inserted
254 /// in the `HashSet`. The collection may reserve more space to avoid
255 /// frequent reallocations.
259 /// Panics if the new allocation size overflows `usize`.
264 /// use std::collections::HashSet;
265 /// let mut set: HashSet<i32> = HashSet::new();
267 /// assert!(set.capacity() >= 10);
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn reserve(&mut self, additional: usize) {
271 self.map.reserve(additional)
274 /// Shrinks the capacity of the set as much as possible. It will drop
275 /// down as much as possible while maintaining the internal rules
276 /// and possibly leaving some space in accordance with the resize policy.
281 /// use std::collections::HashSet;
283 /// let mut set = HashSet::with_capacity(100);
286 /// assert!(set.capacity() >= 100);
287 /// set.shrink_to_fit();
288 /// assert!(set.capacity() >= 2);
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn shrink_to_fit(&mut self) {
292 self.map.shrink_to_fit()
295 /// Shrinks the capacity of the set with a lower limit. It will drop
296 /// down no lower than the supplied limit while maintaining the internal rules
297 /// and possibly leaving some space in accordance with the resize policy.
299 /// Panics if the current capacity is smaller than the supplied
300 /// minimum capacity.
305 /// #![feature(shrink_to)]
306 /// use std::collections::HashSet;
308 /// let mut set = HashSet::with_capacity(100);
311 /// assert!(set.capacity() >= 100);
312 /// set.shrink_to(10);
313 /// assert!(set.capacity() >= 10);
314 /// set.shrink_to(0);
315 /// assert!(set.capacity() >= 2);
318 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
319 pub fn shrink_to(&mut self, min_capacity: usize) {
320 self.map.shrink_to(min_capacity)
323 /// An iterator visiting all elements in arbitrary order.
324 /// The iterator element type is `&'a T`.
329 /// use std::collections::HashSet;
330 /// let mut set = HashSet::new();
334 /// // Will print in an arbitrary order.
335 /// for x in set.iter() {
336 /// println!("{}", x);
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn iter(&self) -> Iter<T> {
341 Iter { iter: self.map.keys() }
344 /// Visits the values representing the difference,
345 /// i.e. the values that are in `self` but not in `other`.
350 /// use std::collections::HashSet;
351 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
352 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
354 /// // Can be seen as `a - b`.
355 /// for x in a.difference(&b) {
356 /// println!("{}", x); // Print 1
359 /// let diff: HashSet<_> = a.difference(&b).collect();
360 /// assert_eq!(diff, [1].iter().collect());
362 /// // Note that difference is not symmetric,
363 /// // and `b - a` means something else:
364 /// let diff: HashSet<_> = b.difference(&a).collect();
365 /// assert_eq!(diff, [4].iter().collect());
367 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
375 /// Visits the values representing the symmetric difference,
376 /// i.e. the values that are in `self` or in `other` but not in both.
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, 4 in arbitrary order.
386 /// for x in a.symmetric_difference(&b) {
387 /// println!("{}", x);
390 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
391 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
393 /// assert_eq!(diff1, diff2);
394 /// assert_eq!(diff1, [1, 4].iter().collect());
396 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn symmetric_difference<'a>(&'a self,
398 other: &'a HashSet<T, S>)
399 -> SymmetricDifference<'a, T, S> {
400 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
403 /// Visits the values representing the intersection,
404 /// i.e. the values that are both in `self` and `other`.
409 /// use std::collections::HashSet;
410 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
411 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
413 /// // Print 2, 3 in arbitrary order.
414 /// for x in a.intersection(&b) {
415 /// println!("{}", x);
418 /// let intersection: HashSet<_> = a.intersection(&b).collect();
419 /// assert_eq!(intersection, [2, 3].iter().collect());
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
429 /// Visits the values representing the union,
430 /// i.e. all the values in `self` or `other`, without duplicates.
435 /// use std::collections::HashSet;
436 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
437 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
439 /// // Print 1, 2, 3, 4 in arbitrary order.
440 /// for x in a.union(&b) {
441 /// println!("{}", x);
444 /// let union: HashSet<_> = a.union(&b).collect();
445 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
447 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
449 Union { iter: self.iter().chain(other.difference(self)) }
452 /// Returns the number of elements in the set.
457 /// use std::collections::HashSet;
459 /// let mut v = HashSet::new();
460 /// assert_eq!(v.len(), 0);
462 /// assert_eq!(v.len(), 1);
464 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn len(&self) -> usize {
469 /// Returns true if the set contains no elements.
474 /// use std::collections::HashSet;
476 /// let mut v = HashSet::new();
477 /// assert!(v.is_empty());
479 /// assert!(!v.is_empty());
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn is_empty(&self) -> bool {
486 /// Clears the set, returning all elements in an iterator.
491 /// use std::collections::HashSet;
493 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
494 /// assert!(!set.is_empty());
496 /// // print 1, 2, 3 in an arbitrary order
497 /// for i in set.drain() {
498 /// println!("{}", i);
501 /// assert!(set.is_empty());
504 #[stable(feature = "drain", since = "1.6.0")]
505 pub fn drain(&mut self) -> Drain<T> {
506 Drain { iter: self.map.drain() }
509 /// Clears the set, removing all values.
514 /// use std::collections::HashSet;
516 /// let mut v = HashSet::new();
519 /// assert!(v.is_empty());
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn clear(&mut self) {
526 /// Returns `true` if the set contains a value.
528 /// The value may be any borrowed form of the set's value type, but
529 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
535 /// use std::collections::HashSet;
537 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
538 /// assert_eq!(set.contains(&1), true);
539 /// assert_eq!(set.contains(&4), false);
542 /// [`Eq`]: ../../std/cmp/trait.Eq.html
543 /// [`Hash`]: ../../std/hash/trait.Hash.html
544 #[stable(feature = "rust1", since = "1.0.0")]
545 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
549 self.map.contains_key(value)
552 /// Returns a reference to the value in the set, if any, that is equal to the given value.
554 /// The value may be any borrowed form of the set's value type, but
555 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
561 /// use std::collections::HashSet;
563 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
564 /// assert_eq!(set.get(&2), Some(&2));
565 /// assert_eq!(set.get(&4), None);
568 /// [`Eq`]: ../../std/cmp/trait.Eq.html
569 /// [`Hash`]: ../../std/hash/trait.Hash.html
570 #[stable(feature = "set_recovery", since = "1.9.0")]
571 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
575 Recover::get(&self.map, value)
578 /// Returns `true` if `self` has no elements in common with `other`.
579 /// This is equivalent to checking for an empty intersection.
584 /// use std::collections::HashSet;
586 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
587 /// let mut b = HashSet::new();
589 /// assert_eq!(a.is_disjoint(&b), true);
591 /// assert_eq!(a.is_disjoint(&b), true);
593 /// assert_eq!(a.is_disjoint(&b), false);
595 #[stable(feature = "rust1", since = "1.0.0")]
596 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
597 self.iter().all(|v| !other.contains(v))
600 /// Returns `true` if the set is a subset of another,
601 /// i.e. `other` contains at least all the values in `self`.
606 /// use std::collections::HashSet;
608 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
609 /// let mut set = HashSet::new();
611 /// assert_eq!(set.is_subset(&sup), true);
613 /// assert_eq!(set.is_subset(&sup), true);
615 /// assert_eq!(set.is_subset(&sup), false);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
619 self.iter().all(|v| other.contains(v))
622 /// Returns `true` if the set is a superset of another,
623 /// i.e. `self` contains at least all the values in `other`.
628 /// use std::collections::HashSet;
630 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
631 /// let mut set = HashSet::new();
633 /// assert_eq!(set.is_superset(&sub), false);
637 /// assert_eq!(set.is_superset(&sub), false);
640 /// assert_eq!(set.is_superset(&sub), true);
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
645 other.is_subset(self)
648 /// Adds a value to the set.
650 /// If the set did not have this value present, `true` is returned.
652 /// If the set did have this value present, `false` is returned.
657 /// use std::collections::HashSet;
659 /// let mut set = HashSet::new();
661 /// assert_eq!(set.insert(2), true);
662 /// assert_eq!(set.insert(2), false);
663 /// assert_eq!(set.len(), 1);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn insert(&mut self, value: T) -> bool {
667 self.map.insert(value, ()).is_none()
670 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
671 /// one. Returns the replaced value.
676 /// use std::collections::HashSet;
678 /// let mut set = HashSet::new();
679 /// set.insert(Vec::<i32>::new());
681 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
682 /// set.replace(Vec::with_capacity(10));
683 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
685 #[stable(feature = "set_recovery", since = "1.9.0")]
686 pub fn replace(&mut self, value: T) -> Option<T> {
687 Recover::replace(&mut self.map, value)
690 /// Removes a value from the set. Returns `true` if the value was
691 /// present in the set.
693 /// The value may be any borrowed form of the set's value type, but
694 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
700 /// use std::collections::HashSet;
702 /// let mut set = HashSet::new();
705 /// assert_eq!(set.remove(&2), true);
706 /// assert_eq!(set.remove(&2), false);
709 /// [`Eq`]: ../../std/cmp/trait.Eq.html
710 /// [`Hash`]: ../../std/hash/trait.Hash.html
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
716 self.map.remove(value).is_some()
719 /// Removes and returns the value in the set, if any, that is equal to the given one.
721 /// The value may be any borrowed form of the set's value type, but
722 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
728 /// use std::collections::HashSet;
730 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
731 /// assert_eq!(set.take(&2), Some(2));
732 /// assert_eq!(set.take(&2), None);
735 /// [`Eq`]: ../../std/cmp/trait.Eq.html
736 /// [`Hash`]: ../../std/hash/trait.Hash.html
737 #[stable(feature = "set_recovery", since = "1.9.0")]
738 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
742 Recover::take(&mut self.map, value)
745 /// Retains only the elements specified by the predicate.
747 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
752 /// use std::collections::HashSet;
754 /// let xs = [1,2,3,4,5,6];
755 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
756 /// set.retain(|&k| k % 2 == 0);
757 /// assert_eq!(set.len(), 3);
759 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
760 pub fn retain<F>(&mut self, mut f: F)
761 where F: FnMut(&T) -> bool
763 self.map.retain(|k, _| f(k));
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl<T, S> PartialEq for HashSet<T, S>
772 fn eq(&self, other: &HashSet<T, S>) -> bool {
773 if self.len() != other.len() {
777 self.iter().all(|key| other.contains(key))
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<T, S> Eq for HashSet<T, S>
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl<T, S> fmt::Debug for HashSet<T, S>
790 where T: Eq + Hash + fmt::Debug,
793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
794 f.debug_set().entries(self.iter()).finish()
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl<T, S> FromIterator<T> for HashSet<T, S>
801 S: BuildHasher + Default
803 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
804 let mut set = HashSet::with_hasher(Default::default());
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl<T, S> Extend<T> for HashSet<T, S>
815 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
816 self.map.extend(iter.into_iter().map(|k| (k, ())));
820 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
821 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
822 where T: 'a + Eq + Hash + Copy,
825 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
826 self.extend(iter.into_iter().cloned());
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<T, S> Default for HashSet<T, S>
833 S: BuildHasher + Default
835 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
836 fn default() -> HashSet<T, S> {
837 HashSet { map: HashMap::default() }
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
843 where T: Eq + Hash + Clone,
844 S: BuildHasher + Default
846 type Output = HashSet<T, S>;
848 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
853 /// use std::collections::HashSet;
855 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
856 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
858 /// let set = &a | &b;
861 /// let expected = [1, 2, 3, 4, 5];
863 /// assert!(expected.contains(x));
866 /// assert_eq!(i, expected.len());
868 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
869 self.union(rhs).cloned().collect()
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
875 where T: Eq + Hash + Clone,
876 S: BuildHasher + Default
878 type Output = HashSet<T, S>;
880 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
885 /// use std::collections::HashSet;
887 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
888 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
890 /// let set = &a & &b;
893 /// let expected = [2, 3];
895 /// assert!(expected.contains(x));
898 /// assert_eq!(i, expected.len());
900 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
901 self.intersection(rhs).cloned().collect()
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
907 where T: Eq + Hash + Clone,
908 S: BuildHasher + Default
910 type Output = HashSet<T, S>;
912 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
917 /// use std::collections::HashSet;
919 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
920 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
922 /// let set = &a ^ &b;
925 /// let expected = [1, 2, 4, 5];
927 /// assert!(expected.contains(x));
930 /// assert_eq!(i, expected.len());
932 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
933 self.symmetric_difference(rhs).cloned().collect()
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
939 where T: Eq + Hash + Clone,
940 S: BuildHasher + Default
942 type Output = HashSet<T, S>;
944 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
949 /// use std::collections::HashSet;
951 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
952 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
954 /// let set = &a - &b;
957 /// let expected = [1, 2];
959 /// assert!(expected.contains(x));
962 /// assert_eq!(i, expected.len());
964 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
965 self.difference(rhs).cloned().collect()
969 /// An iterator over the items of a `HashSet`.
971 /// This `struct` is created by the [`iter`] method on [`HashSet`].
972 /// See its documentation for more.
974 /// [`HashSet`]: struct.HashSet.html
975 /// [`iter`]: struct.HashSet.html#method.iter
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub struct Iter<'a, K: 'a> {
978 iter: Keys<'a, K, ()>,
981 /// An owning iterator over the items of a `HashSet`.
983 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
984 /// (provided by the `IntoIterator` trait). See its documentation for more.
986 /// [`HashSet`]: struct.HashSet.html
987 /// [`into_iter`]: struct.HashSet.html#method.into_iter
988 #[stable(feature = "rust1", since = "1.0.0")]
989 pub struct IntoIter<K> {
990 iter: map::IntoIter<K, ()>,
993 /// A draining iterator over the items of a `HashSet`.
995 /// This `struct` is created by the [`drain`] method on [`HashSet`].
996 /// See its documentation for more.
998 /// [`HashSet`]: struct.HashSet.html
999 /// [`drain`]: struct.HashSet.html#method.drain
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub struct Drain<'a, K: 'a> {
1002 iter: map::Drain<'a, K, ()>,
1005 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1007 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1008 /// See its documentation for more.
1010 /// [`HashSet`]: struct.HashSet.html
1011 /// [`intersection`]: struct.HashSet.html#method.intersection
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 pub struct Intersection<'a, T: 'a, S: 'a> {
1014 // iterator of the first set
1017 other: &'a HashSet<T, S>,
1020 /// A lazy iterator producing elements in the difference of `HashSet`s.
1022 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1023 /// See its documentation for more.
1025 /// [`HashSet`]: struct.HashSet.html
1026 /// [`difference`]: struct.HashSet.html#method.difference
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 pub struct Difference<'a, T: 'a, S: 'a> {
1029 // iterator of the first set
1032 other: &'a HashSet<T, S>,
1035 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1037 /// This `struct` is created by the [`symmetric_difference`] method on
1038 /// [`HashSet`]. See its documentation for more.
1040 /// [`HashSet`]: struct.HashSet.html
1041 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1044 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1047 /// A lazy iterator producing elements in the union of `HashSet`s.
1049 /// This `struct` is created by the [`union`] method on [`HashSet`].
1050 /// See its documentation for more.
1052 /// [`HashSet`]: struct.HashSet.html
1053 /// [`union`]: struct.HashSet.html#method.union
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub struct Union<'a, T: 'a, S: 'a> {
1056 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
1065 type IntoIter = Iter<'a, T>;
1067 fn into_iter(self) -> Iter<'a, T> {
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<T, S> IntoIterator for HashSet<T, S>
1078 type IntoIter = IntoIter<T>;
1080 /// Creates a consuming iterator, that is, one that moves each value out
1081 /// of the set in arbitrary order. The set cannot be used after calling
1087 /// use std::collections::HashSet;
1088 /// let mut set = HashSet::new();
1089 /// set.insert("a".to_string());
1090 /// set.insert("b".to_string());
1092 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1093 /// let v: Vec<String> = set.into_iter().collect();
1095 /// // Will print in an arbitrary order.
1097 /// println!("{}", x);
1100 fn into_iter(self) -> IntoIter<T> {
1101 IntoIter { iter: self.map.into_iter() }
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a, K> Clone for Iter<'a, K> {
1107 fn clone(&self) -> Iter<'a, K> {
1108 Iter { iter: self.iter.clone() }
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<'a, K> Iterator for Iter<'a, K> {
1115 fn next(&mut self) -> Option<&'a K> {
1118 fn size_hint(&self) -> (usize, Option<usize>) {
1119 self.iter.size_hint()
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
1124 fn len(&self) -> usize {
1128 #[stable(feature = "fused", since = "1.26.0")]
1129 impl<'a, K> FusedIterator for Iter<'a, K> {}
1131 #[stable(feature = "std_debug", since = "1.16.0")]
1132 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
1133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1134 f.debug_list().entries(self.clone()).finish()
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 impl<K> Iterator for IntoIter<K> {
1142 fn next(&mut self) -> Option<K> {
1143 self.iter.next().map(|(k, _)| k)
1145 fn size_hint(&self) -> (usize, Option<usize>) {
1146 self.iter.size_hint()
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<K> ExactSizeIterator for IntoIter<K> {
1151 fn len(&self) -> usize {
1155 #[stable(feature = "fused", since = "1.26.0")]
1156 impl<K> FusedIterator for IntoIter<K> {}
1158 #[stable(feature = "std_debug", since = "1.16.0")]
1159 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1161 let entries_iter = self.iter
1165 f.debug_list().entries(entries_iter).finish()
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl<'a, K> Iterator for Drain<'a, K> {
1173 fn next(&mut self) -> Option<K> {
1174 self.iter.next().map(|(k, _)| k)
1176 fn size_hint(&self) -> (usize, Option<usize>) {
1177 self.iter.size_hint()
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1182 fn len(&self) -> usize {
1186 #[stable(feature = "fused", since = "1.26.0")]
1187 impl<'a, K> FusedIterator for Drain<'a, K> {}
1189 #[stable(feature = "std_debug", since = "1.16.0")]
1190 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1192 let entries_iter = self.iter
1196 f.debug_list().entries(entries_iter).finish()
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1202 fn clone(&self) -> Intersection<'a, T, S> {
1203 Intersection { iter: self.iter.clone(), ..*self }
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1214 fn next(&mut self) -> Option<&'a T> {
1216 let elt = self.iter.next()?;
1217 if self.other.contains(elt) {
1223 fn size_hint(&self) -> (usize, Option<usize>) {
1224 let (_, upper) = self.iter.size_hint();
1229 #[stable(feature = "std_debug", since = "1.16.0")]
1230 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1231 where T: fmt::Debug + Eq + Hash,
1234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1235 f.debug_list().entries(self.clone()).finish()
1239 #[stable(feature = "fused", since = "1.26.0")]
1240 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 impl<'a, T, S> Clone for Difference<'a, T, S> {
1248 fn clone(&self) -> Difference<'a, T, S> {
1249 Difference { iter: self.iter.clone(), ..*self }
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl<'a, T, S> Iterator for Difference<'a, T, S>
1260 fn next(&mut self) -> Option<&'a T> {
1262 let elt = self.iter.next()?;
1263 if !self.other.contains(elt) {
1269 fn size_hint(&self) -> (usize, Option<usize>) {
1270 let (_, upper) = self.iter.size_hint();
1275 #[stable(feature = "fused", since = "1.26.0")]
1276 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1282 #[stable(feature = "std_debug", since = "1.16.0")]
1283 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1284 where T: fmt::Debug + Eq + Hash,
1287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1288 f.debug_list().entries(self.clone()).finish()
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1294 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1295 SymmetricDifference { iter: self.iter.clone() }
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1306 fn next(&mut self) -> Option<&'a T> {
1309 fn size_hint(&self) -> (usize, Option<usize>) {
1310 self.iter.size_hint()
1314 #[stable(feature = "fused", since = "1.26.0")]
1315 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1321 #[stable(feature = "std_debug", since = "1.16.0")]
1322 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1323 where T: fmt::Debug + Eq + Hash,
1326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1327 f.debug_list().entries(self.clone()).finish()
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<'a, T, S> Clone for Union<'a, T, S> {
1333 fn clone(&self) -> Union<'a, T, S> {
1334 Union { iter: self.iter.clone() }
1338 #[stable(feature = "fused", since = "1.26.0")]
1339 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1345 #[stable(feature = "std_debug", since = "1.16.0")]
1346 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1347 where T: fmt::Debug + Eq + Hash,
1350 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1351 f.debug_list().entries(self.clone()).finish()
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<'a, T, S> Iterator for Union<'a, T, S>
1362 fn next(&mut self) -> Option<&'a T> {
1365 fn size_hint(&self) -> (usize, Option<usize>) {
1366 self.iter.size_hint()
1371 fn assert_covariance() {
1372 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1375 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1378 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1381 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1382 -> Difference<'a, &'new str, RandomState> {
1385 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1386 -> SymmetricDifference<'a, &'new str, RandomState> {
1389 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1390 -> Intersection<'a, &'new str, RandomState> {
1393 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1394 -> Union<'a, &'new str, RandomState> {
1397 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1405 use super::super::map::RandomState;
1408 fn test_zero_capacities() {
1409 type HS = HashSet<i32>;
1412 assert_eq!(s.capacity(), 0);
1414 let s = HS::default();
1415 assert_eq!(s.capacity(), 0);
1417 let s = HS::with_hasher(RandomState::new());
1418 assert_eq!(s.capacity(), 0);
1420 let s = HS::with_capacity(0);
1421 assert_eq!(s.capacity(), 0);
1423 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1424 assert_eq!(s.capacity(), 0);
1426 let mut s = HS::new();
1432 assert_eq!(s.capacity(), 0);
1434 let mut s = HS::new();
1436 assert_eq!(s.capacity(), 0);
1440 fn test_disjoint() {
1441 let mut xs = HashSet::new();
1442 let mut ys = HashSet::new();
1443 assert!(xs.is_disjoint(&ys));
1444 assert!(ys.is_disjoint(&xs));
1445 assert!(xs.insert(5));
1446 assert!(ys.insert(11));
1447 assert!(xs.is_disjoint(&ys));
1448 assert!(ys.is_disjoint(&xs));
1449 assert!(xs.insert(7));
1450 assert!(xs.insert(19));
1451 assert!(xs.insert(4));
1452 assert!(ys.insert(2));
1453 assert!(ys.insert(-11));
1454 assert!(xs.is_disjoint(&ys));
1455 assert!(ys.is_disjoint(&xs));
1456 assert!(ys.insert(7));
1457 assert!(!xs.is_disjoint(&ys));
1458 assert!(!ys.is_disjoint(&xs));
1462 fn test_subset_and_superset() {
1463 let mut a = HashSet::new();
1464 assert!(a.insert(0));
1465 assert!(a.insert(5));
1466 assert!(a.insert(11));
1467 assert!(a.insert(7));
1469 let mut b = HashSet::new();
1470 assert!(b.insert(0));
1471 assert!(b.insert(7));
1472 assert!(b.insert(19));
1473 assert!(b.insert(250));
1474 assert!(b.insert(11));
1475 assert!(b.insert(200));
1477 assert!(!a.is_subset(&b));
1478 assert!(!a.is_superset(&b));
1479 assert!(!b.is_subset(&a));
1480 assert!(!b.is_superset(&a));
1482 assert!(b.insert(5));
1484 assert!(a.is_subset(&b));
1485 assert!(!a.is_superset(&b));
1486 assert!(!b.is_subset(&a));
1487 assert!(b.is_superset(&a));
1492 let mut a = HashSet::new();
1494 assert!(a.insert(i));
1496 let mut observed: u32 = 0;
1498 observed |= 1 << *k;
1500 assert_eq!(observed, 0xFFFF_FFFF);
1504 fn test_intersection() {
1505 let mut a = HashSet::new();
1506 let mut b = HashSet::new();
1508 assert!(a.insert(11));
1509 assert!(a.insert(1));
1510 assert!(a.insert(3));
1511 assert!(a.insert(77));
1512 assert!(a.insert(103));
1513 assert!(a.insert(5));
1514 assert!(a.insert(-5));
1516 assert!(b.insert(2));
1517 assert!(b.insert(11));
1518 assert!(b.insert(77));
1519 assert!(b.insert(-9));
1520 assert!(b.insert(-42));
1521 assert!(b.insert(5));
1522 assert!(b.insert(3));
1525 let expected = [3, 5, 11, 77];
1526 for x in a.intersection(&b) {
1527 assert!(expected.contains(x));
1530 assert_eq!(i, expected.len());
1534 fn test_difference() {
1535 let mut a = HashSet::new();
1536 let mut b = HashSet::new();
1538 assert!(a.insert(1));
1539 assert!(a.insert(3));
1540 assert!(a.insert(5));
1541 assert!(a.insert(9));
1542 assert!(a.insert(11));
1544 assert!(b.insert(3));
1545 assert!(b.insert(9));
1548 let expected = [1, 5, 11];
1549 for x in a.difference(&b) {
1550 assert!(expected.contains(x));
1553 assert_eq!(i, expected.len());
1557 fn test_symmetric_difference() {
1558 let mut a = HashSet::new();
1559 let mut b = HashSet::new();
1561 assert!(a.insert(1));
1562 assert!(a.insert(3));
1563 assert!(a.insert(5));
1564 assert!(a.insert(9));
1565 assert!(a.insert(11));
1567 assert!(b.insert(-2));
1568 assert!(b.insert(3));
1569 assert!(b.insert(9));
1570 assert!(b.insert(14));
1571 assert!(b.insert(22));
1574 let expected = [-2, 1, 5, 11, 14, 22];
1575 for x in a.symmetric_difference(&b) {
1576 assert!(expected.contains(x));
1579 assert_eq!(i, expected.len());
1584 let mut a = HashSet::new();
1585 let mut b = HashSet::new();
1587 assert!(a.insert(1));
1588 assert!(a.insert(3));
1589 assert!(a.insert(5));
1590 assert!(a.insert(9));
1591 assert!(a.insert(11));
1592 assert!(a.insert(16));
1593 assert!(a.insert(19));
1594 assert!(a.insert(24));
1596 assert!(b.insert(-2));
1597 assert!(b.insert(1));
1598 assert!(b.insert(5));
1599 assert!(b.insert(9));
1600 assert!(b.insert(13));
1601 assert!(b.insert(19));
1604 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1605 for x in a.union(&b) {
1606 assert!(expected.contains(x));
1609 assert_eq!(i, expected.len());
1613 fn test_from_iter() {
1614 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1616 let set: HashSet<_> = xs.iter().cloned().collect();
1619 assert!(set.contains(x));
1624 fn test_move_iter() {
1626 let mut hs = HashSet::new();
1634 let v = hs.into_iter().collect::<Vec<char>>();
1635 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1640 // These constants once happened to expose a bug in insert().
1641 // I'm keeping them around to prevent a regression.
1642 let mut s1 = HashSet::new();
1648 let mut s2 = HashSet::new();
1662 let mut set = HashSet::new();
1663 let empty = HashSet::<i32>::new();
1668 let set_str = format!("{:?}", set);
1670 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1671 assert_eq!(format!("{:?}", empty), "{}");
1675 fn test_trivial_drain() {
1676 let mut s = HashSet::<i32>::new();
1677 for _ in s.drain() {}
1678 assert!(s.is_empty());
1681 let mut s = HashSet::<i32>::new();
1683 assert!(s.is_empty());
1688 let mut s: HashSet<_> = (1..100).collect();
1690 // try this a bunch of times to make sure we don't screw up internal state.
1692 assert_eq!(s.len(), 99);
1696 let mut d = s.drain();
1697 for (i, x) in d.by_ref().take(50).enumerate() {
1701 assert_eq!(last_i, 49);
1705 panic!("s should be empty!");
1708 // reset to try again.
1718 struct Foo(&'static str, i32);
1720 impl PartialEq for Foo {
1721 fn eq(&self, other: &Self) -> bool {
1728 impl hash::Hash for Foo {
1729 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1734 let mut s = HashSet::new();
1735 assert_eq!(s.replace(Foo("a", 1)), None);
1736 assert_eq!(s.len(), 1);
1737 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1738 assert_eq!(s.len(), 1);
1740 let mut it = s.iter();
1741 assert_eq!(it.next(), Some(&Foo("a", 2)));
1742 assert_eq!(it.next(), None);
1746 fn test_extend_ref() {
1747 let mut a = HashSet::new();
1750 a.extend(&[2, 3, 4]);
1752 assert_eq!(a.len(), 4);
1753 assert!(a.contains(&1));
1754 assert!(a.contains(&2));
1755 assert!(a.contains(&3));
1756 assert!(a.contains(&4));
1758 let mut b = HashSet::new();
1764 assert_eq!(a.len(), 6);
1765 assert!(a.contains(&1));
1766 assert!(a.contains(&2));
1767 assert!(a.contains(&3));
1768 assert!(a.contains(&4));
1769 assert!(a.contains(&5));
1770 assert!(a.contains(&6));
1775 let xs = [1, 2, 3, 4, 5, 6];
1776 let mut set: HashSet<i32> = xs.iter().cloned().collect();
1777 set.retain(|&k| k % 2 == 0);
1778 assert_eq!(set.len(), 3);
1779 assert!(set.contains(&2));
1780 assert!(set.contains(&4));
1781 assert!(set.contains(&6));