1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // ignore-lexer-test FIXME #15883
14 use cmp::{Eq, Equiv, PartialEq};
15 use collections::{Collection, Mutable, Set, MutableSet, Map, MutableMap};
19 use hash::{Hash, Hasher, RandomSipHasher};
20 use iter::{Iterator, FromIterator, FilterMap, Chain, Repeat, Zip, Extendable};
22 use option::{Some, None};
23 use result::{Ok, Err};
25 use super::{HashMap, Entries, MoveEntries, INITIAL_CAPACITY};
28 // Future Optimization (FIXME!)
29 // =============================
31 // Iteration over zero sized values is a noop. There is no need
32 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
33 // to get rid of it properly.
35 /// An implementation of a hash set using the underlying representation of a
36 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
37 /// requires that the elements implement the `Eq` and `Hash` traits.
42 /// use std::collections::HashSet;
43 /// // Type inference lets us omit an explicit type signature (which
44 /// // would be `HashSet<&str>` in this example).
45 /// let mut books = HashSet::new();
47 /// // Add some books.
48 /// books.insert("A Dance With Dragons");
49 /// books.insert("To Kill a Mockingbird");
50 /// books.insert("The Odyssey");
51 /// books.insert("The Great Gatsby");
53 /// // Check for a specific one.
54 /// if !books.contains(&("The Winds of Winter")) {
55 /// println!("We have {} books, but The Winds of Winter ain't one.",
60 /// books.remove(&"The Odyssey");
62 /// // Iterate over everything.
63 /// for book in books.iter() {
64 /// println!("{}", *book);
68 /// The easiest way to use `HashSet` with a custom type is to derive
69 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
70 /// future be implied by `Eq`.
73 /// use std::collections::HashSet;
74 /// #[deriving(Hash, Eq, PartialEq, Show)]
75 /// struct Viking<'a> {
80 /// let mut vikings = HashSet::new();
82 /// vikings.insert(Viking { name: "Einar", power: 9u });
83 /// vikings.insert(Viking { name: "Einar", power: 9u });
84 /// vikings.insert(Viking { name: "Olaf", power: 4u });
85 /// vikings.insert(Viking { name: "Harald", power: 8u });
87 /// // Use derived implementation to print the vikings.
88 /// for x in vikings.iter() {
89 /// println!("{}", x);
93 pub struct HashSet<T, H = RandomSipHasher> {
94 map: HashMap<T, (), H>
97 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
98 /// Create an empty HashSet.
103 /// use std::collections::HashSet;
104 /// let mut set: HashSet<int> = HashSet::new();
107 pub fn new() -> HashSet<T, RandomSipHasher> {
108 HashSet::with_capacity(INITIAL_CAPACITY)
111 /// Create an empty HashSet with space for at least `n` elements in
117 /// use std::collections::HashSet;
118 /// let mut set: HashSet<int> = HashSet::with_capacity(10);
121 pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
122 HashSet { map: HashMap::with_capacity(capacity) }
126 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
127 /// Creates a new empty hash set which will use the given hasher to hash
130 /// The hash set is also created with the default initial capacity.
135 /// use std::collections::HashSet;
136 /// use std::hash::sip::SipHasher;
138 /// let h = SipHasher::new();
139 /// let mut set = HashSet::with_hasher(h);
143 pub fn with_hasher(hasher: H) -> HashSet<T, H> {
144 HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
147 /// Create an empty HashSet with space for at least `capacity`
148 /// elements in the hash table, using `hasher` to hash the keys.
150 /// Warning: `hasher` is normally randomly generated, and
151 /// is designed to allow `HashSet`s to be resistant to attacks that
152 /// cause many collisions and very poor performance. Setting it
153 /// manually using this function can expose a DoS attack vector.
158 /// use std::collections::HashSet;
159 /// use std::hash::sip::SipHasher;
161 /// let h = SipHasher::new();
162 /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
166 pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
167 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
170 /// Reserve space for at least `n` elements in the hash table.
175 /// use std::collections::HashSet;
176 /// let mut set: HashSet<int> = HashSet::new();
179 pub fn reserve(&mut self, n: uint) {
183 /// Returns true if the hash set contains a value equivalent to the
184 /// given query value.
188 /// This is a slightly silly example where we define the number's
189 /// parity as the equivilance class. It is important that the
190 /// values hash the same, which is why we implement `Hash`.
193 /// use std::collections::HashSet;
194 /// use std::hash::Hash;
195 /// use std::hash::sip::SipState;
197 /// #[deriving(Eq, PartialEq)]
198 /// struct EvenOrOdd {
202 /// impl Hash for EvenOrOdd {
203 /// fn hash(&self, state: &mut SipState) {
204 /// let parity = self.num % 2;
205 /// parity.hash(state);
209 /// impl Equiv<EvenOrOdd> for EvenOrOdd {
210 /// fn equiv(&self, other: &EvenOrOdd) -> bool {
211 /// self.num % 2 == other.num % 2
215 /// let mut set = HashSet::new();
216 /// set.insert(EvenOrOdd { num: 3u });
218 /// assert!(set.contains_equiv(&EvenOrOdd { num: 3u }));
219 /// assert!(set.contains_equiv(&EvenOrOdd { num: 5u }));
220 /// assert!(!set.contains_equiv(&EvenOrOdd { num: 4u }));
221 /// assert!(!set.contains_equiv(&EvenOrOdd { num: 2u }));
224 pub fn contains_equiv<Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
225 self.map.contains_key_equiv(value)
228 /// An iterator visiting all elements in arbitrary order.
229 /// Iterator element type is &'a T.
234 /// use std::collections::HashSet;
235 /// let mut set = HashSet::new();
239 /// // Will print in an arbitrary order.
240 /// for x in set.iter() {
241 /// println!("{}", x);
244 pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
248 /// Deprecated: use `into_iter`.
249 #[deprecated = "use into_iter"]
250 pub fn move_iter(self) -> SetMoveItems<T> {
254 /// Creates a consuming iterator, that is, one that moves each value out
255 /// of the set in arbitrary order. The set cannot be used after calling
261 /// use std::collections::HashSet;
262 /// let mut set = HashSet::new();
263 /// set.insert("a".to_string());
264 /// set.insert("b".to_string());
266 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
267 /// let v: Vec<String> = set.into_iter().collect();
269 /// // Will print in an arbitrary order.
270 /// for x in v.iter() {
271 /// println!("{}", x);
274 pub fn into_iter(self) -> SetMoveItems<T> {
275 self.map.into_iter().map(|(k, _)| k)
278 /// Visit the values representing the difference.
283 /// use std::collections::HashSet;
284 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
285 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
287 /// // Can be seen as `a - b`.
288 /// for x in a.difference(&b) {
289 /// println!("{}", x); // Print 1
292 /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
293 /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
295 /// // Note that difference is not symmetric,
296 /// // and `b - a` means something else:
297 /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
298 /// assert_eq!(diff, [4i].iter().map(|&x| x).collect());
300 pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> SetAlgebraItems<'a, T, H> {
301 Repeat::new(other).zip(self.iter())
302 .filter_map(|(other, elt)| {
303 if !other.contains(elt) { Some(elt) } else { None }
307 /// Visit the values representing the symmetric difference.
312 /// use std::collections::HashSet;
313 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
314 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
316 /// // Print 1, 4 in arbitrary order.
317 /// for x in a.symmetric_difference(&b) {
318 /// println!("{}", x);
321 /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
322 /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
324 /// assert_eq!(diff1, diff2);
325 /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
327 pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
328 -> Chain<SetAlgebraItems<'a, T, H>, SetAlgebraItems<'a, T, H>> {
329 self.difference(other).chain(other.difference(self))
332 /// Visit the values representing the intersection.
337 /// use std::collections::HashSet;
338 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
339 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
341 /// // Print 2, 3 in arbitrary order.
342 /// for x in a.intersection(&b) {
343 /// println!("{}", x);
346 /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
347 /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
349 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>)
350 -> SetAlgebraItems<'a, T, H> {
351 Repeat::new(other).zip(self.iter())
352 .filter_map(|(other, elt)| {
353 if other.contains(elt) { Some(elt) } else { None }
357 /// Visit the values representing the union.
362 /// use std::collections::HashSet;
363 /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
364 /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
366 /// // Print 1, 2, 3, 4 in arbitrary order.
367 /// for x in a.union(&b) {
368 /// println!("{}", x);
371 /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
372 /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect());
374 pub fn union<'a>(&'a self, other: &'a HashSet<T, H>)
375 -> Chain<SetItems<'a, T>, SetAlgebraItems<'a, T, H>> {
376 self.iter().chain(other.difference(self))
380 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
381 fn eq(&self, other: &HashSet<T, H>) -> bool {
382 if self.len() != other.len() { return false; }
384 self.iter().all(|key| other.contains(key))
388 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
390 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Collection for HashSet<T, H> {
391 fn len(&self) -> uint { self.map.len() }
394 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Mutable for HashSet<T, H> {
395 fn clear(&mut self) { self.map.clear() }
398 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Set<T> for HashSet<T, H> {
399 fn contains(&self, value: &T) -> bool { self.map.contains_key(value) }
401 fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
402 self.iter().all(|v| !other.contains(v))
405 fn is_subset(&self, other: &HashSet<T, H>) -> bool {
406 self.iter().all(|v| other.contains(v))
410 impl<T: Eq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> {
411 fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) }
413 fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
416 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418 try!(write!(f, "{{"));
420 for (i, x) in self.iter().enumerate() {
421 if i != 0 { try!(write!(f, ", ")); }
422 try!(write!(f, "{}", *x));
429 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
430 fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
431 let (lower, _) = iter.size_hint();
432 let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
438 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H> {
439 fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
446 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
447 fn default() -> HashSet<T, H> {
448 HashSet::with_hasher(Default::default())
453 pub type SetItems<'a, K> =
454 iter::Map<'static, (&'a K, &'a ()), &'a K, Entries<'a, K, ()>>;
456 /// HashSet move iterator
457 pub type SetMoveItems<K> =
458 iter::Map<'static, (K, ()), K, MoveEntries<K, ()>>;
460 // `Repeat` is used to feed the filter closure an explicit capture
461 // of a reference to the other set
462 /// Set operations iterator
463 pub type SetAlgebraItems<'a, T, H> =
464 FilterMap<'static, (&'a HashSet<T, H>, &'a T), &'a T,
465 Zip<Repeat<&'a HashSet<T, H>>, SetItems<'a, T>>>;
472 use slice::ImmutablePartialEqSlice;
473 use collections::Collection;
477 let mut xs = HashSet::new();
478 let mut ys = HashSet::new();
479 assert!(xs.is_disjoint(&ys));
480 assert!(ys.is_disjoint(&xs));
481 assert!(xs.insert(5i));
482 assert!(ys.insert(11i));
483 assert!(xs.is_disjoint(&ys));
484 assert!(ys.is_disjoint(&xs));
485 assert!(xs.insert(7));
486 assert!(xs.insert(19));
487 assert!(xs.insert(4));
488 assert!(ys.insert(2));
489 assert!(ys.insert(-11));
490 assert!(xs.is_disjoint(&ys));
491 assert!(ys.is_disjoint(&xs));
492 assert!(ys.insert(7));
493 assert!(!xs.is_disjoint(&ys));
494 assert!(!ys.is_disjoint(&xs));
498 fn test_subset_and_superset() {
499 let mut a = HashSet::new();
500 assert!(a.insert(0i));
501 assert!(a.insert(5));
502 assert!(a.insert(11));
503 assert!(a.insert(7));
505 let mut b = HashSet::new();
506 assert!(b.insert(0i));
507 assert!(b.insert(7));
508 assert!(b.insert(19));
509 assert!(b.insert(250));
510 assert!(b.insert(11));
511 assert!(b.insert(200));
513 assert!(!a.is_subset(&b));
514 assert!(!a.is_superset(&b));
515 assert!(!b.is_subset(&a));
516 assert!(!b.is_superset(&a));
518 assert!(b.insert(5));
520 assert!(a.is_subset(&b));
521 assert!(!a.is_superset(&b));
522 assert!(!b.is_subset(&a));
523 assert!(b.is_superset(&a));
528 let mut a = HashSet::new();
529 for i in range(0u, 32) {
530 assert!(a.insert(i));
532 let mut observed: u32 = 0;
536 assert_eq!(observed, 0xFFFF_FFFF);
540 fn test_intersection() {
541 let mut a = HashSet::new();
542 let mut b = HashSet::new();
544 assert!(a.insert(11i));
545 assert!(a.insert(1));
546 assert!(a.insert(3));
547 assert!(a.insert(77));
548 assert!(a.insert(103));
549 assert!(a.insert(5));
550 assert!(a.insert(-5));
552 assert!(b.insert(2i));
553 assert!(b.insert(11));
554 assert!(b.insert(77));
555 assert!(b.insert(-9));
556 assert!(b.insert(-42));
557 assert!(b.insert(5));
558 assert!(b.insert(3));
561 let expected = [3, 5, 11, 77];
562 for x in a.intersection(&b) {
563 assert!(expected.contains(x));
566 assert_eq!(i, expected.len());
570 fn test_difference() {
571 let mut a = HashSet::new();
572 let mut b = HashSet::new();
574 assert!(a.insert(1i));
575 assert!(a.insert(3));
576 assert!(a.insert(5));
577 assert!(a.insert(9));
578 assert!(a.insert(11));
580 assert!(b.insert(3i));
581 assert!(b.insert(9));
584 let expected = [1, 5, 11];
585 for x in a.difference(&b) {
586 assert!(expected.contains(x));
589 assert_eq!(i, expected.len());
593 fn test_symmetric_difference() {
594 let mut a = HashSet::new();
595 let mut b = HashSet::new();
597 assert!(a.insert(1i));
598 assert!(a.insert(3));
599 assert!(a.insert(5));
600 assert!(a.insert(9));
601 assert!(a.insert(11));
603 assert!(b.insert(-2i));
604 assert!(b.insert(3));
605 assert!(b.insert(9));
606 assert!(b.insert(14));
607 assert!(b.insert(22));
610 let expected = [-2, 1, 5, 11, 14, 22];
611 for x in a.symmetric_difference(&b) {
612 assert!(expected.contains(x));
615 assert_eq!(i, expected.len());
620 let mut a = HashSet::new();
621 let mut b = HashSet::new();
623 assert!(a.insert(1i));
624 assert!(a.insert(3));
625 assert!(a.insert(5));
626 assert!(a.insert(9));
627 assert!(a.insert(11));
628 assert!(a.insert(16));
629 assert!(a.insert(19));
630 assert!(a.insert(24));
632 assert!(b.insert(-2i));
633 assert!(b.insert(1));
634 assert!(b.insert(5));
635 assert!(b.insert(9));
636 assert!(b.insert(13));
637 assert!(b.insert(19));
640 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
641 for x in a.union(&b) {
642 assert!(expected.contains(x));
645 assert_eq!(i, expected.len());
649 fn test_from_iter() {
650 let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
652 let set: HashSet<int> = xs.iter().map(|&x| x).collect();
655 assert!(set.contains(x));
660 fn test_move_iter() {
662 let mut hs = HashSet::new();
670 let v = hs.into_iter().collect::<Vec<char>>();
671 assert!(['a', 'b'] == v.as_slice() || ['b', 'a'] == v.as_slice());
676 // These constants once happened to expose a bug in insert().
677 // I'm keeping them around to prevent a regression.
678 let mut s1 = HashSet::new();
684 let mut s2 = HashSet::new();
698 let mut set: HashSet<int> = HashSet::new();
699 let empty: HashSet<int> = HashSet::new();
704 let set_str = format!("{}", set);
706 assert!(set_str == "{1, 2}".to_string() || set_str == "{2, 1}".to_string());
707 assert_eq!(format!("{}", empty), "{}".to_string());