]> git.proxmox.com Git - rustc.git/blob - src/libstd/collections/hash/set.rs
New upstream version 1.21.0+dfsg1
[rustc.git] / src / libstd / collections / hash / set.rs
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.
4 //
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.
10
11 use borrow::Borrow;
12 use fmt;
13 use hash::{Hash, BuildHasher};
14 use iter::{Chain, FromIterator, FusedIterator};
15 use ops::{BitOr, BitAnd, BitXor, Sub};
16
17 use super::Recover;
18 use super::map::{self, HashMap, Keys, RandomState};
19
20 // Future Optimization (FIXME!)
21 // =============================
22 //
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.
26
27 /// A hash set implemented as a `HashMap` where the value is `()`.
28 ///
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:
33 ///
34 /// ```text
35 /// k1 == k2 -> hash(k1) == hash(k2)
36 /// ```
37 ///
38 /// In other words, if two keys are equal, their hashes must be equal.
39 ///
40 ///
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
45 /// unsafe code.
46 ///
47 /// # Examples
48 ///
49 /// ```
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();
54 ///
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");
60 ///
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.",
64 /// books.len());
65 /// }
66 ///
67 /// // Remove a book.
68 /// books.remove("The Odyssey");
69 ///
70 /// // Iterate over everything.
71 /// for book in &books {
72 /// println!("{}", book);
73 /// }
74 /// ```
75 ///
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`].
79 ///
80 /// ```
81 /// use std::collections::HashSet;
82 /// #[derive(Hash, Eq, PartialEq, Debug)]
83 /// struct Viking<'a> {
84 /// name: &'a str,
85 /// power: usize,
86 /// }
87 ///
88 /// let mut vikings = HashSet::new();
89 ///
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 });
94 ///
95 /// // Use derived implementation to print the vikings.
96 /// for x in &vikings {
97 /// println!("{:?}", x);
98 /// }
99 /// ```
100 ///
101 /// A `HashSet` with fixed list of elements can be initialized from an array:
102 ///
103 /// ```
104 /// use std::collections::HashSet;
105 ///
106 /// fn main() {
107 /// let viking_names: HashSet<&str> =
108 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
109 /// // use the values stored in the set
110 /// }
111 /// ```
112 ///
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
119 #[derive(Clone)]
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct HashSet<T, S = RandomState> {
122 map: HashMap<T, (), S>,
123 }
124
125 impl<T: Hash + Eq> HashSet<T, RandomState> {
126 /// Creates an empty `HashSet`.
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// use std::collections::HashSet;
132 /// let set: HashSet<i32> = HashSet::new();
133 /// ```
134 #[inline]
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub fn new() -> HashSet<T, RandomState> {
137 HashSet { map: HashMap::new() }
138 }
139
140 /// Creates an empty `HashSet` with the specified capacity.
141 ///
142 /// The hash set will be able to hold at least `capacity` elements without
143 /// reallocating. If `capacity` is 0, the hash set will not allocate.
144 ///
145 /// # Examples
146 ///
147 /// ```
148 /// use std::collections::HashSet;
149 /// let set: HashSet<i32> = HashSet::with_capacity(10);
150 /// assert!(set.capacity() >= 10);
151 /// ```
152 #[inline]
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
155 HashSet { map: HashMap::with_capacity(capacity) }
156 }
157 }
158
159 impl<T, S> HashSet<T, S>
160 where T: Eq + Hash,
161 S: BuildHasher
162 {
163 /// Creates a new empty hash set which will use the given hasher to hash
164 /// keys.
165 ///
166 /// The hash set is also created with the default initial capacity.
167 ///
168 /// Warning: `hasher` is normally randomly generated, and
169 /// is designed to allow `HashSet`s to be resistant to attacks that
170 /// cause many collisions and very poor performance. Setting it
171 /// manually using this function can expose a DoS attack vector.
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use std::collections::HashSet;
177 /// use std::collections::hash_map::RandomState;
178 ///
179 /// let s = RandomState::new();
180 /// let mut set = HashSet::with_hasher(s);
181 /// set.insert(2);
182 /// ```
183 #[inline]
184 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
185 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
186 HashSet { map: HashMap::with_hasher(hasher) }
187 }
188
189 /// Creates an empty `HashSet` with with the specified capacity, using
190 /// `hasher` to hash the keys.
191 ///
192 /// The hash set will be able to hold at least `capacity` elements without
193 /// reallocating. If `capacity` is 0, the hash set will not allocate.
194 ///
195 /// Warning: `hasher` is normally randomly generated, and
196 /// is designed to allow `HashSet`s to be resistant to attacks that
197 /// cause many collisions and very poor performance. Setting it
198 /// manually using this function can expose a DoS attack vector.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// use std::collections::HashSet;
204 /// use std::collections::hash_map::RandomState;
205 ///
206 /// let s = RandomState::new();
207 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
208 /// set.insert(1);
209 /// ```
210 #[inline]
211 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
212 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
213 HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
214 }
215
216 /// Returns a reference to the set's [`BuildHasher`].
217 ///
218 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
219 ///
220 /// # Examples
221 ///
222 /// ```
223 /// use std::collections::HashSet;
224 /// use std::collections::hash_map::RandomState;
225 ///
226 /// let hasher = RandomState::new();
227 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
228 /// let hasher: &RandomState = set.hasher();
229 /// ```
230 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
231 pub fn hasher(&self) -> &S {
232 self.map.hasher()
233 }
234
235 /// Returns the number of elements the set can hold without reallocating.
236 ///
237 /// # Examples
238 ///
239 /// ```
240 /// use std::collections::HashSet;
241 /// let set: HashSet<i32> = HashSet::with_capacity(100);
242 /// assert!(set.capacity() >= 100);
243 /// ```
244 #[inline]
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn capacity(&self) -> usize {
247 self.map.capacity()
248 }
249
250 /// Reserves capacity for at least `additional` more elements to be inserted
251 /// in the `HashSet`. The collection may reserve more space to avoid
252 /// frequent reallocations.
253 ///
254 /// # Panics
255 ///
256 /// Panics if the new allocation size overflows `usize`.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use std::collections::HashSet;
262 /// let mut set: HashSet<i32> = HashSet::new();
263 /// set.reserve(10);
264 /// assert!(set.capacity() >= 10);
265 /// ```
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn reserve(&mut self, additional: usize) {
268 self.map.reserve(additional)
269 }
270
271 /// Shrinks the capacity of the set as much as possible. It will drop
272 /// down as much as possible while maintaining the internal rules
273 /// and possibly leaving some space in accordance with the resize policy.
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// use std::collections::HashSet;
279 ///
280 /// let mut set = HashSet::with_capacity(100);
281 /// set.insert(1);
282 /// set.insert(2);
283 /// assert!(set.capacity() >= 100);
284 /// set.shrink_to_fit();
285 /// assert!(set.capacity() >= 2);
286 /// ```
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn shrink_to_fit(&mut self) {
289 self.map.shrink_to_fit()
290 }
291
292 /// An iterator visiting all elements in arbitrary order.
293 /// The iterator element type is `&'a T`.
294 ///
295 /// # Examples
296 ///
297 /// ```
298 /// use std::collections::HashSet;
299 /// let mut set = HashSet::new();
300 /// set.insert("a");
301 /// set.insert("b");
302 ///
303 /// // Will print in an arbitrary order.
304 /// for x in set.iter() {
305 /// println!("{}", x);
306 /// }
307 /// ```
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn iter(&self) -> Iter<T> {
310 Iter { iter: self.map.keys() }
311 }
312
313 /// Visits the values representing the difference,
314 /// i.e. the values that are in `self` but not in `other`.
315 ///
316 /// # Examples
317 ///
318 /// ```
319 /// use std::collections::HashSet;
320 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
321 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
322 ///
323 /// // Can be seen as `a - b`.
324 /// for x in a.difference(&b) {
325 /// println!("{}", x); // Print 1
326 /// }
327 ///
328 /// let diff: HashSet<_> = a.difference(&b).collect();
329 /// assert_eq!(diff, [1].iter().collect());
330 ///
331 /// // Note that difference is not symmetric,
332 /// // and `b - a` means something else:
333 /// let diff: HashSet<_> = b.difference(&a).collect();
334 /// assert_eq!(diff, [4].iter().collect());
335 /// ```
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
338 Difference {
339 iter: self.iter(),
340 other,
341 }
342 }
343
344 /// Visits the values representing the symmetric difference,
345 /// i.e. the values that are in `self` or in `other` but not in both.
346 ///
347 /// # Examples
348 ///
349 /// ```
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();
353 ///
354 /// // Print 1, 4 in arbitrary order.
355 /// for x in a.symmetric_difference(&b) {
356 /// println!("{}", x);
357 /// }
358 ///
359 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
360 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
361 ///
362 /// assert_eq!(diff1, diff2);
363 /// assert_eq!(diff1, [1, 4].iter().collect());
364 /// ```
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn symmetric_difference<'a>(&'a self,
367 other: &'a HashSet<T, S>)
368 -> SymmetricDifference<'a, T, S> {
369 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
370 }
371
372 /// Visits the values representing the intersection,
373 /// i.e. the values that are both in `self` and `other`.
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// use std::collections::HashSet;
379 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
380 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
381 ///
382 /// // Print 2, 3 in arbitrary order.
383 /// for x in a.intersection(&b) {
384 /// println!("{}", x);
385 /// }
386 ///
387 /// let intersection: HashSet<_> = a.intersection(&b).collect();
388 /// assert_eq!(intersection, [2, 3].iter().collect());
389 /// ```
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
392 Intersection {
393 iter: self.iter(),
394 other,
395 }
396 }
397
398 /// Visits the values representing the union,
399 /// i.e. all the values in `self` or `other`, without duplicates.
400 ///
401 /// # Examples
402 ///
403 /// ```
404 /// use std::collections::HashSet;
405 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
406 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
407 ///
408 /// // Print 1, 2, 3, 4 in arbitrary order.
409 /// for x in a.union(&b) {
410 /// println!("{}", x);
411 /// }
412 ///
413 /// let union: HashSet<_> = a.union(&b).collect();
414 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
415 /// ```
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
418 Union { iter: self.iter().chain(other.difference(self)) }
419 }
420
421 /// Returns the number of elements in the set.
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// use std::collections::HashSet;
427 ///
428 /// let mut v = HashSet::new();
429 /// assert_eq!(v.len(), 0);
430 /// v.insert(1);
431 /// assert_eq!(v.len(), 1);
432 /// ```
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn len(&self) -> usize {
435 self.map.len()
436 }
437
438 /// Returns true if the set contains no elements.
439 ///
440 /// # Examples
441 ///
442 /// ```
443 /// use std::collections::HashSet;
444 ///
445 /// let mut v = HashSet::new();
446 /// assert!(v.is_empty());
447 /// v.insert(1);
448 /// assert!(!v.is_empty());
449 /// ```
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn is_empty(&self) -> bool {
452 self.map.is_empty()
453 }
454
455 /// Clears the set, returning all elements in an iterator.
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// use std::collections::HashSet;
461 ///
462 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
463 /// assert!(!set.is_empty());
464 ///
465 /// // print 1, 2, 3 in an arbitrary order
466 /// for i in set.drain() {
467 /// println!("{}", i);
468 /// }
469 ///
470 /// assert!(set.is_empty());
471 /// ```
472 #[inline]
473 #[stable(feature = "drain", since = "1.6.0")]
474 pub fn drain(&mut self) -> Drain<T> {
475 Drain { iter: self.map.drain() }
476 }
477
478 /// Clears the set, removing all values.
479 ///
480 /// # Examples
481 ///
482 /// ```
483 /// use std::collections::HashSet;
484 ///
485 /// let mut v = HashSet::new();
486 /// v.insert(1);
487 /// v.clear();
488 /// assert!(v.is_empty());
489 /// ```
490 #[stable(feature = "rust1", since = "1.0.0")]
491 pub fn clear(&mut self) {
492 self.map.clear()
493 }
494
495 /// Returns `true` if the set contains a value.
496 ///
497 /// The value may be any borrowed form of the set's value type, but
498 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
499 /// the value type.
500 ///
501 /// # Examples
502 ///
503 /// ```
504 /// use std::collections::HashSet;
505 ///
506 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
507 /// assert_eq!(set.contains(&1), true);
508 /// assert_eq!(set.contains(&4), false);
509 /// ```
510 ///
511 /// [`Eq`]: ../../std/cmp/trait.Eq.html
512 /// [`Hash`]: ../../std/hash/trait.Hash.html
513 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
515 where T: Borrow<Q>,
516 Q: Hash + Eq
517 {
518 self.map.contains_key(value)
519 }
520
521 /// Returns a reference to the value in the set, if any, that is equal to the given value.
522 ///
523 /// The value may be any borrowed form of the set's value type, but
524 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
525 /// the value type.
526 ///
527 /// [`Eq`]: ../../std/cmp/trait.Eq.html
528 /// [`Hash`]: ../../std/hash/trait.Hash.html
529 #[stable(feature = "set_recovery", since = "1.9.0")]
530 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
531 where T: Borrow<Q>,
532 Q: Hash + Eq
533 {
534 Recover::get(&self.map, value)
535 }
536
537 /// Returns `true` if `self` has no elements in common with `other`.
538 /// This is equivalent to checking for an empty intersection.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// use std::collections::HashSet;
544 ///
545 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
546 /// let mut b = HashSet::new();
547 ///
548 /// assert_eq!(a.is_disjoint(&b), true);
549 /// b.insert(4);
550 /// assert_eq!(a.is_disjoint(&b), true);
551 /// b.insert(1);
552 /// assert_eq!(a.is_disjoint(&b), false);
553 /// ```
554 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
556 self.iter().all(|v| !other.contains(v))
557 }
558
559 /// Returns `true` if the set is a subset of another,
560 /// i.e. `other` contains at least all the values in `self`.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// use std::collections::HashSet;
566 ///
567 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
568 /// let mut set = HashSet::new();
569 ///
570 /// assert_eq!(set.is_subset(&sup), true);
571 /// set.insert(2);
572 /// assert_eq!(set.is_subset(&sup), true);
573 /// set.insert(4);
574 /// assert_eq!(set.is_subset(&sup), false);
575 /// ```
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
578 self.iter().all(|v| other.contains(v))
579 }
580
581 /// Returns `true` if the set is a superset of another,
582 /// i.e. `self` contains at least all the values in `other`.
583 ///
584 /// # Examples
585 ///
586 /// ```
587 /// use std::collections::HashSet;
588 ///
589 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
590 /// let mut set = HashSet::new();
591 ///
592 /// assert_eq!(set.is_superset(&sub), false);
593 ///
594 /// set.insert(0);
595 /// set.insert(1);
596 /// assert_eq!(set.is_superset(&sub), false);
597 ///
598 /// set.insert(2);
599 /// assert_eq!(set.is_superset(&sub), true);
600 /// ```
601 #[inline]
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
604 other.is_subset(self)
605 }
606
607 /// Adds a value to the set.
608 ///
609 /// If the set did not have this value present, `true` is returned.
610 ///
611 /// If the set did have this value present, `false` is returned.
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// use std::collections::HashSet;
617 ///
618 /// let mut set = HashSet::new();
619 ///
620 /// assert_eq!(set.insert(2), true);
621 /// assert_eq!(set.insert(2), false);
622 /// assert_eq!(set.len(), 1);
623 /// ```
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn insert(&mut self, value: T) -> bool {
626 self.map.insert(value, ()).is_none()
627 }
628
629 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
630 /// one. Returns the replaced value.
631 #[stable(feature = "set_recovery", since = "1.9.0")]
632 pub fn replace(&mut self, value: T) -> Option<T> {
633 Recover::replace(&mut self.map, value)
634 }
635
636 /// Removes a value from the set. Returns `true` if the value was
637 /// present in the set.
638 ///
639 /// The value may be any borrowed form of the set's value type, but
640 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
641 /// the value type.
642 ///
643 /// # Examples
644 ///
645 /// ```
646 /// use std::collections::HashSet;
647 ///
648 /// let mut set = HashSet::new();
649 ///
650 /// set.insert(2);
651 /// assert_eq!(set.remove(&2), true);
652 /// assert_eq!(set.remove(&2), false);
653 /// ```
654 ///
655 /// [`Eq`]: ../../std/cmp/trait.Eq.html
656 /// [`Hash`]: ../../std/hash/trait.Hash.html
657 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
659 where T: Borrow<Q>,
660 Q: Hash + Eq
661 {
662 self.map.remove(value).is_some()
663 }
664
665 /// Removes and returns the value in the set, if any, that is equal to the given one.
666 ///
667 /// The value may be any borrowed form of the set's value type, but
668 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
669 /// the value type.
670 ///
671 /// [`Eq`]: ../../std/cmp/trait.Eq.html
672 /// [`Hash`]: ../../std/hash/trait.Hash.html
673 #[stable(feature = "set_recovery", since = "1.9.0")]
674 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
675 where T: Borrow<Q>,
676 Q: Hash + Eq
677 {
678 Recover::take(&mut self.map, value)
679 }
680
681 /// Retains only the elements specified by the predicate.
682 ///
683 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
684 ///
685 /// # Examples
686 ///
687 /// ```
688 /// use std::collections::HashSet;
689 ///
690 /// let xs = [1,2,3,4,5,6];
691 /// let mut set: HashSet<isize> = xs.iter().cloned().collect();
692 /// set.retain(|&k| k % 2 == 0);
693 /// assert_eq!(set.len(), 3);
694 /// ```
695 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
696 pub fn retain<F>(&mut self, mut f: F)
697 where F: FnMut(&T) -> bool
698 {
699 self.map.retain(|k, _| f(k));
700 }
701 }
702
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T, S> PartialEq for HashSet<T, S>
705 where T: Eq + Hash,
706 S: BuildHasher
707 {
708 fn eq(&self, other: &HashSet<T, S>) -> bool {
709 if self.len() != other.len() {
710 return false;
711 }
712
713 self.iter().all(|key| other.contains(key))
714 }
715 }
716
717 #[stable(feature = "rust1", since = "1.0.0")]
718 impl<T, S> Eq for HashSet<T, S>
719 where T: Eq + Hash,
720 S: BuildHasher
721 {
722 }
723
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl<T, S> fmt::Debug for HashSet<T, S>
726 where T: Eq + Hash + fmt::Debug,
727 S: BuildHasher
728 {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730 f.debug_set().entries(self.iter()).finish()
731 }
732 }
733
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T, S> FromIterator<T> for HashSet<T, S>
736 where T: Eq + Hash,
737 S: BuildHasher + Default
738 {
739 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
740 let mut set = HashSet::with_hasher(Default::default());
741 set.extend(iter);
742 set
743 }
744 }
745
746 #[stable(feature = "rust1", since = "1.0.0")]
747 impl<T, S> Extend<T> for HashSet<T, S>
748 where T: Eq + Hash,
749 S: BuildHasher
750 {
751 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
752 self.map.extend(iter.into_iter().map(|k| (k, ())));
753 }
754 }
755
756 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
757 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
758 where T: 'a + Eq + Hash + Copy,
759 S: BuildHasher
760 {
761 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
762 self.extend(iter.into_iter().cloned());
763 }
764 }
765
766 #[stable(feature = "rust1", since = "1.0.0")]
767 impl<T, S> Default for HashSet<T, S>
768 where T: Eq + Hash,
769 S: BuildHasher + Default
770 {
771 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
772 fn default() -> HashSet<T, S> {
773 HashSet { map: HashMap::default() }
774 }
775 }
776
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
779 where T: Eq + Hash + Clone,
780 S: BuildHasher + Default
781 {
782 type Output = HashSet<T, S>;
783
784 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
785 ///
786 /// # Examples
787 ///
788 /// ```
789 /// use std::collections::HashSet;
790 ///
791 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
792 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
793 ///
794 /// let set = &a | &b;
795 ///
796 /// let mut i = 0;
797 /// let expected = [1, 2, 3, 4, 5];
798 /// for x in &set {
799 /// assert!(expected.contains(x));
800 /// i += 1;
801 /// }
802 /// assert_eq!(i, expected.len());
803 /// ```
804 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
805 self.union(rhs).cloned().collect()
806 }
807 }
808
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
811 where T: Eq + Hash + Clone,
812 S: BuildHasher + Default
813 {
814 type Output = HashSet<T, S>;
815
816 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
817 ///
818 /// # Examples
819 ///
820 /// ```
821 /// use std::collections::HashSet;
822 ///
823 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
824 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
825 ///
826 /// let set = &a & &b;
827 ///
828 /// let mut i = 0;
829 /// let expected = [2, 3];
830 /// for x in &set {
831 /// assert!(expected.contains(x));
832 /// i += 1;
833 /// }
834 /// assert_eq!(i, expected.len());
835 /// ```
836 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
837 self.intersection(rhs).cloned().collect()
838 }
839 }
840
841 #[stable(feature = "rust1", since = "1.0.0")]
842 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
843 where T: Eq + Hash + Clone,
844 S: BuildHasher + Default
845 {
846 type Output = HashSet<T, S>;
847
848 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
849 ///
850 /// # Examples
851 ///
852 /// ```
853 /// use std::collections::HashSet;
854 ///
855 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
856 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
857 ///
858 /// let set = &a ^ &b;
859 ///
860 /// let mut i = 0;
861 /// let expected = [1, 2, 4, 5];
862 /// for x in &set {
863 /// assert!(expected.contains(x));
864 /// i += 1;
865 /// }
866 /// assert_eq!(i, expected.len());
867 /// ```
868 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
869 self.symmetric_difference(rhs).cloned().collect()
870 }
871 }
872
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
875 where T: Eq + Hash + Clone,
876 S: BuildHasher + Default
877 {
878 type Output = HashSet<T, S>;
879
880 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
881 ///
882 /// # Examples
883 ///
884 /// ```
885 /// use std::collections::HashSet;
886 ///
887 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
888 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
889 ///
890 /// let set = &a - &b;
891 ///
892 /// let mut i = 0;
893 /// let expected = [1, 2];
894 /// for x in &set {
895 /// assert!(expected.contains(x));
896 /// i += 1;
897 /// }
898 /// assert_eq!(i, expected.len());
899 /// ```
900 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
901 self.difference(rhs).cloned().collect()
902 }
903 }
904
905 /// An iterator over the items of a `HashSet`.
906 ///
907 /// This `struct` is created by the [`iter`] method on [`HashSet`].
908 /// See its documentation for more.
909 ///
910 /// [`HashSet`]: struct.HashSet.html
911 /// [`iter`]: struct.HashSet.html#method.iter
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub struct Iter<'a, K: 'a> {
914 iter: Keys<'a, K, ()>,
915 }
916
917 /// An owning iterator over the items of a `HashSet`.
918 ///
919 /// This `struct` is created by the [`into_iter`] method on [`HashSet`][`HashSet`]
920 /// (provided by the `IntoIterator` trait). See its documentation for more.
921 ///
922 /// [`HashSet`]: struct.HashSet.html
923 /// [`into_iter`]: struct.HashSet.html#method.into_iter
924 #[stable(feature = "rust1", since = "1.0.0")]
925 pub struct IntoIter<K> {
926 iter: map::IntoIter<K, ()>,
927 }
928
929 /// A draining iterator over the items of a `HashSet`.
930 ///
931 /// This `struct` is created by the [`drain`] method on [`HashSet`].
932 /// See its documentation for more.
933 ///
934 /// [`HashSet`]: struct.HashSet.html
935 /// [`drain`]: struct.HashSet.html#method.drain
936 #[stable(feature = "rust1", since = "1.0.0")]
937 pub struct Drain<'a, K: 'a> {
938 iter: map::Drain<'a, K, ()>,
939 }
940
941 /// A lazy iterator producing elements in the intersection of `HashSet`s.
942 ///
943 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
944 /// See its documentation for more.
945 ///
946 /// [`HashSet`]: struct.HashSet.html
947 /// [`intersection`]: struct.HashSet.html#method.intersection
948 #[stable(feature = "rust1", since = "1.0.0")]
949 pub struct Intersection<'a, T: 'a, S: 'a> {
950 // iterator of the first set
951 iter: Iter<'a, T>,
952 // the second set
953 other: &'a HashSet<T, S>,
954 }
955
956 /// A lazy iterator producing elements in the difference of `HashSet`s.
957 ///
958 /// This `struct` is created by the [`difference`] method on [`HashSet`].
959 /// See its documentation for more.
960 ///
961 /// [`HashSet`]: struct.HashSet.html
962 /// [`difference`]: struct.HashSet.html#method.difference
963 #[stable(feature = "rust1", since = "1.0.0")]
964 pub struct Difference<'a, T: 'a, S: 'a> {
965 // iterator of the first set
966 iter: Iter<'a, T>,
967 // the second set
968 other: &'a HashSet<T, S>,
969 }
970
971 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
972 ///
973 /// This `struct` is created by the [`symmetric_difference`] method on
974 /// [`HashSet`]. See its documentation for more.
975 ///
976 /// [`HashSet`]: struct.HashSet.html
977 /// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
980 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
981 }
982
983 /// A lazy iterator producing elements in the union of `HashSet`s.
984 ///
985 /// This `struct` is created by the [`union`] method on [`HashSet`].
986 /// See its documentation for more.
987 ///
988 /// [`HashSet`]: struct.HashSet.html
989 /// [`union`]: struct.HashSet.html#method.union
990 #[stable(feature = "rust1", since = "1.0.0")]
991 pub struct Union<'a, T: 'a, S: 'a> {
992 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
993 }
994
995 #[stable(feature = "rust1", since = "1.0.0")]
996 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
997 where T: Eq + Hash,
998 S: BuildHasher
999 {
1000 type Item = &'a T;
1001 type IntoIter = Iter<'a, T>;
1002
1003 fn into_iter(self) -> Iter<'a, T> {
1004 self.iter()
1005 }
1006 }
1007
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T, S> IntoIterator for HashSet<T, S>
1010 where T: Eq + Hash,
1011 S: BuildHasher
1012 {
1013 type Item = T;
1014 type IntoIter = IntoIter<T>;
1015
1016 /// Creates a consuming iterator, that is, one that moves each value out
1017 /// of the set in arbitrary order. The set cannot be used after calling
1018 /// this.
1019 ///
1020 /// # Examples
1021 ///
1022 /// ```
1023 /// use std::collections::HashSet;
1024 /// let mut set = HashSet::new();
1025 /// set.insert("a".to_string());
1026 /// set.insert("b".to_string());
1027 ///
1028 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1029 /// let v: Vec<String> = set.into_iter().collect();
1030 ///
1031 /// // Will print in an arbitrary order.
1032 /// for x in &v {
1033 /// println!("{}", x);
1034 /// }
1035 /// ```
1036 fn into_iter(self) -> IntoIter<T> {
1037 IntoIter { iter: self.map.into_iter() }
1038 }
1039 }
1040
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<'a, K> Clone for Iter<'a, K> {
1043 fn clone(&self) -> Iter<'a, K> {
1044 Iter { iter: self.iter.clone() }
1045 }
1046 }
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 impl<'a, K> Iterator for Iter<'a, K> {
1049 type Item = &'a K;
1050
1051 fn next(&mut self) -> Option<&'a K> {
1052 self.iter.next()
1053 }
1054 fn size_hint(&self) -> (usize, Option<usize>) {
1055 self.iter.size_hint()
1056 }
1057 }
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
1060 fn len(&self) -> usize {
1061 self.iter.len()
1062 }
1063 }
1064 #[unstable(feature = "fused", issue = "35602")]
1065 impl<'a, K> FusedIterator for Iter<'a, K> {}
1066
1067 #[stable(feature = "std_debug", since = "1.16.0")]
1068 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
1069 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1070 f.debug_list().entries(self.clone()).finish()
1071 }
1072 }
1073
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 impl<K> Iterator for IntoIter<K> {
1076 type Item = K;
1077
1078 fn next(&mut self) -> Option<K> {
1079 self.iter.next().map(|(k, _)| k)
1080 }
1081 fn size_hint(&self) -> (usize, Option<usize>) {
1082 self.iter.size_hint()
1083 }
1084 }
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<K> ExactSizeIterator for IntoIter<K> {
1087 fn len(&self) -> usize {
1088 self.iter.len()
1089 }
1090 }
1091 #[unstable(feature = "fused", issue = "35602")]
1092 impl<K> FusedIterator for IntoIter<K> {}
1093
1094 #[stable(feature = "std_debug", since = "1.16.0")]
1095 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1097 let entries_iter = self.iter
1098 .inner
1099 .iter()
1100 .map(|(k, _)| k);
1101 f.debug_list().entries(entries_iter).finish()
1102 }
1103 }
1104
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a, K> Iterator for Drain<'a, K> {
1107 type Item = K;
1108
1109 fn next(&mut self) -> Option<K> {
1110 self.iter.next().map(|(k, _)| k)
1111 }
1112 fn size_hint(&self) -> (usize, Option<usize>) {
1113 self.iter.size_hint()
1114 }
1115 }
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1118 fn len(&self) -> usize {
1119 self.iter.len()
1120 }
1121 }
1122 #[unstable(feature = "fused", issue = "35602")]
1123 impl<'a, K> FusedIterator for Drain<'a, K> {}
1124
1125 #[stable(feature = "std_debug", since = "1.16.0")]
1126 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1128 let entries_iter = self.iter
1129 .inner
1130 .iter()
1131 .map(|(k, _)| k);
1132 f.debug_list().entries(entries_iter).finish()
1133 }
1134 }
1135
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1138 fn clone(&self) -> Intersection<'a, T, S> {
1139 Intersection { iter: self.iter.clone(), ..*self }
1140 }
1141 }
1142
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1145 where T: Eq + Hash,
1146 S: BuildHasher
1147 {
1148 type Item = &'a T;
1149
1150 fn next(&mut self) -> Option<&'a T> {
1151 loop {
1152 match self.iter.next() {
1153 None => return None,
1154 Some(elt) => {
1155 if self.other.contains(elt) {
1156 return Some(elt);
1157 }
1158 }
1159 }
1160 }
1161 }
1162
1163 fn size_hint(&self) -> (usize, Option<usize>) {
1164 let (_, upper) = self.iter.size_hint();
1165 (0, upper)
1166 }
1167 }
1168
1169 #[stable(feature = "std_debug", since = "1.16.0")]
1170 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1171 where T: fmt::Debug + Eq + Hash,
1172 S: BuildHasher
1173 {
1174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1175 f.debug_list().entries(self.clone()).finish()
1176 }
1177 }
1178
1179 #[unstable(feature = "fused", issue = "35602")]
1180 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1181 where T: Eq + Hash,
1182 S: BuildHasher
1183 {
1184 }
1185
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 impl<'a, T, S> Clone for Difference<'a, T, S> {
1188 fn clone(&self) -> Difference<'a, T, S> {
1189 Difference { iter: self.iter.clone(), ..*self }
1190 }
1191 }
1192
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<'a, T, S> Iterator for Difference<'a, T, S>
1195 where T: Eq + Hash,
1196 S: BuildHasher
1197 {
1198 type Item = &'a T;
1199
1200 fn next(&mut self) -> Option<&'a T> {
1201 loop {
1202 match self.iter.next() {
1203 None => return None,
1204 Some(elt) => {
1205 if !self.other.contains(elt) {
1206 return Some(elt);
1207 }
1208 }
1209 }
1210 }
1211 }
1212
1213 fn size_hint(&self) -> (usize, Option<usize>) {
1214 let (_, upper) = self.iter.size_hint();
1215 (0, upper)
1216 }
1217 }
1218
1219 #[unstable(feature = "fused", issue = "35602")]
1220 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1221 where T: Eq + Hash,
1222 S: BuildHasher
1223 {
1224 }
1225
1226 #[stable(feature = "std_debug", since = "1.16.0")]
1227 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1228 where T: fmt::Debug + Eq + Hash,
1229 S: BuildHasher
1230 {
1231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232 f.debug_list().entries(self.clone()).finish()
1233 }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1238 fn clone(&self) -> SymmetricDifference<'a, T, S> {
1239 SymmetricDifference { iter: self.iter.clone() }
1240 }
1241 }
1242
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1245 where T: Eq + Hash,
1246 S: BuildHasher
1247 {
1248 type Item = &'a T;
1249
1250 fn next(&mut self) -> Option<&'a T> {
1251 self.iter.next()
1252 }
1253 fn size_hint(&self) -> (usize, Option<usize>) {
1254 self.iter.size_hint()
1255 }
1256 }
1257
1258 #[unstable(feature = "fused", issue = "35602")]
1259 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1260 where T: Eq + Hash,
1261 S: BuildHasher
1262 {
1263 }
1264
1265 #[stable(feature = "std_debug", since = "1.16.0")]
1266 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1267 where T: fmt::Debug + Eq + Hash,
1268 S: BuildHasher
1269 {
1270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1271 f.debug_list().entries(self.clone()).finish()
1272 }
1273 }
1274
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<'a, T, S> Clone for Union<'a, T, S> {
1277 fn clone(&self) -> Union<'a, T, S> {
1278 Union { iter: self.iter.clone() }
1279 }
1280 }
1281
1282 #[unstable(feature = "fused", issue = "35602")]
1283 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1284 where T: Eq + Hash,
1285 S: BuildHasher
1286 {
1287 }
1288
1289 #[stable(feature = "std_debug", since = "1.16.0")]
1290 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1291 where T: fmt::Debug + Eq + Hash,
1292 S: BuildHasher
1293 {
1294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1295 f.debug_list().entries(self.clone()).finish()
1296 }
1297 }
1298
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl<'a, T, S> Iterator for Union<'a, T, S>
1301 where T: Eq + Hash,
1302 S: BuildHasher
1303 {
1304 type Item = &'a T;
1305
1306 fn next(&mut self) -> Option<&'a T> {
1307 self.iter.next()
1308 }
1309 fn size_hint(&self) -> (usize, Option<usize>) {
1310 self.iter.size_hint()
1311 }
1312 }
1313
1314 #[allow(dead_code)]
1315 fn assert_covariance() {
1316 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1317 v
1318 }
1319 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1320 v
1321 }
1322 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1323 v
1324 }
1325 fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1326 -> Difference<'a, &'new str, RandomState> {
1327 v
1328 }
1329 fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1330 -> SymmetricDifference<'a, &'new str, RandomState> {
1331 v
1332 }
1333 fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1334 -> Intersection<'a, &'new str, RandomState> {
1335 v
1336 }
1337 fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1338 -> Union<'a, &'new str, RandomState> {
1339 v
1340 }
1341 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1342 d
1343 }
1344 }
1345
1346 #[cfg(test)]
1347 mod test_set {
1348 use super::HashSet;
1349 use super::super::map::RandomState;
1350
1351 #[test]
1352 fn test_zero_capacities() {
1353 type HS = HashSet<i32>;
1354
1355 let s = HS::new();
1356 assert_eq!(s.capacity(), 0);
1357
1358 let s = HS::default();
1359 assert_eq!(s.capacity(), 0);
1360
1361 let s = HS::with_hasher(RandomState::new());
1362 assert_eq!(s.capacity(), 0);
1363
1364 let s = HS::with_capacity(0);
1365 assert_eq!(s.capacity(), 0);
1366
1367 let s = HS::with_capacity_and_hasher(0, RandomState::new());
1368 assert_eq!(s.capacity(), 0);
1369
1370 let mut s = HS::new();
1371 s.insert(1);
1372 s.insert(2);
1373 s.remove(&1);
1374 s.remove(&2);
1375 s.shrink_to_fit();
1376 assert_eq!(s.capacity(), 0);
1377
1378 let mut s = HS::new();
1379 s.reserve(0);
1380 assert_eq!(s.capacity(), 0);
1381 }
1382
1383 #[test]
1384 fn test_disjoint() {
1385 let mut xs = HashSet::new();
1386 let mut ys = HashSet::new();
1387 assert!(xs.is_disjoint(&ys));
1388 assert!(ys.is_disjoint(&xs));
1389 assert!(xs.insert(5));
1390 assert!(ys.insert(11));
1391 assert!(xs.is_disjoint(&ys));
1392 assert!(ys.is_disjoint(&xs));
1393 assert!(xs.insert(7));
1394 assert!(xs.insert(19));
1395 assert!(xs.insert(4));
1396 assert!(ys.insert(2));
1397 assert!(ys.insert(-11));
1398 assert!(xs.is_disjoint(&ys));
1399 assert!(ys.is_disjoint(&xs));
1400 assert!(ys.insert(7));
1401 assert!(!xs.is_disjoint(&ys));
1402 assert!(!ys.is_disjoint(&xs));
1403 }
1404
1405 #[test]
1406 fn test_subset_and_superset() {
1407 let mut a = HashSet::new();
1408 assert!(a.insert(0));
1409 assert!(a.insert(5));
1410 assert!(a.insert(11));
1411 assert!(a.insert(7));
1412
1413 let mut b = HashSet::new();
1414 assert!(b.insert(0));
1415 assert!(b.insert(7));
1416 assert!(b.insert(19));
1417 assert!(b.insert(250));
1418 assert!(b.insert(11));
1419 assert!(b.insert(200));
1420
1421 assert!(!a.is_subset(&b));
1422 assert!(!a.is_superset(&b));
1423 assert!(!b.is_subset(&a));
1424 assert!(!b.is_superset(&a));
1425
1426 assert!(b.insert(5));
1427
1428 assert!(a.is_subset(&b));
1429 assert!(!a.is_superset(&b));
1430 assert!(!b.is_subset(&a));
1431 assert!(b.is_superset(&a));
1432 }
1433
1434 #[test]
1435 fn test_iterate() {
1436 let mut a = HashSet::new();
1437 for i in 0..32 {
1438 assert!(a.insert(i));
1439 }
1440 let mut observed: u32 = 0;
1441 for k in &a {
1442 observed |= 1 << *k;
1443 }
1444 assert_eq!(observed, 0xFFFF_FFFF);
1445 }
1446
1447 #[test]
1448 fn test_intersection() {
1449 let mut a = HashSet::new();
1450 let mut b = HashSet::new();
1451
1452 assert!(a.insert(11));
1453 assert!(a.insert(1));
1454 assert!(a.insert(3));
1455 assert!(a.insert(77));
1456 assert!(a.insert(103));
1457 assert!(a.insert(5));
1458 assert!(a.insert(-5));
1459
1460 assert!(b.insert(2));
1461 assert!(b.insert(11));
1462 assert!(b.insert(77));
1463 assert!(b.insert(-9));
1464 assert!(b.insert(-42));
1465 assert!(b.insert(5));
1466 assert!(b.insert(3));
1467
1468 let mut i = 0;
1469 let expected = [3, 5, 11, 77];
1470 for x in a.intersection(&b) {
1471 assert!(expected.contains(x));
1472 i += 1
1473 }
1474 assert_eq!(i, expected.len());
1475 }
1476
1477 #[test]
1478 fn test_difference() {
1479 let mut a = HashSet::new();
1480 let mut b = HashSet::new();
1481
1482 assert!(a.insert(1));
1483 assert!(a.insert(3));
1484 assert!(a.insert(5));
1485 assert!(a.insert(9));
1486 assert!(a.insert(11));
1487
1488 assert!(b.insert(3));
1489 assert!(b.insert(9));
1490
1491 let mut i = 0;
1492 let expected = [1, 5, 11];
1493 for x in a.difference(&b) {
1494 assert!(expected.contains(x));
1495 i += 1
1496 }
1497 assert_eq!(i, expected.len());
1498 }
1499
1500 #[test]
1501 fn test_symmetric_difference() {
1502 let mut a = HashSet::new();
1503 let mut b = HashSet::new();
1504
1505 assert!(a.insert(1));
1506 assert!(a.insert(3));
1507 assert!(a.insert(5));
1508 assert!(a.insert(9));
1509 assert!(a.insert(11));
1510
1511 assert!(b.insert(-2));
1512 assert!(b.insert(3));
1513 assert!(b.insert(9));
1514 assert!(b.insert(14));
1515 assert!(b.insert(22));
1516
1517 let mut i = 0;
1518 let expected = [-2, 1, 5, 11, 14, 22];
1519 for x in a.symmetric_difference(&b) {
1520 assert!(expected.contains(x));
1521 i += 1
1522 }
1523 assert_eq!(i, expected.len());
1524 }
1525
1526 #[test]
1527 fn test_union() {
1528 let mut a = HashSet::new();
1529 let mut b = HashSet::new();
1530
1531 assert!(a.insert(1));
1532 assert!(a.insert(3));
1533 assert!(a.insert(5));
1534 assert!(a.insert(9));
1535 assert!(a.insert(11));
1536 assert!(a.insert(16));
1537 assert!(a.insert(19));
1538 assert!(a.insert(24));
1539
1540 assert!(b.insert(-2));
1541 assert!(b.insert(1));
1542 assert!(b.insert(5));
1543 assert!(b.insert(9));
1544 assert!(b.insert(13));
1545 assert!(b.insert(19));
1546
1547 let mut i = 0;
1548 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1549 for x in a.union(&b) {
1550 assert!(expected.contains(x));
1551 i += 1
1552 }
1553 assert_eq!(i, expected.len());
1554 }
1555
1556 #[test]
1557 fn test_from_iter() {
1558 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1559
1560 let set: HashSet<_> = xs.iter().cloned().collect();
1561
1562 for x in &xs {
1563 assert!(set.contains(x));
1564 }
1565 }
1566
1567 #[test]
1568 fn test_move_iter() {
1569 let hs = {
1570 let mut hs = HashSet::new();
1571
1572 hs.insert('a');
1573 hs.insert('b');
1574
1575 hs
1576 };
1577
1578 let v = hs.into_iter().collect::<Vec<char>>();
1579 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1580 }
1581
1582 #[test]
1583 fn test_eq() {
1584 // These constants once happened to expose a bug in insert().
1585 // I'm keeping them around to prevent a regression.
1586 let mut s1 = HashSet::new();
1587
1588 s1.insert(1);
1589 s1.insert(2);
1590 s1.insert(3);
1591
1592 let mut s2 = HashSet::new();
1593
1594 s2.insert(1);
1595 s2.insert(2);
1596
1597 assert!(s1 != s2);
1598
1599 s2.insert(3);
1600
1601 assert_eq!(s1, s2);
1602 }
1603
1604 #[test]
1605 fn test_show() {
1606 let mut set = HashSet::new();
1607 let empty = HashSet::<i32>::new();
1608
1609 set.insert(1);
1610 set.insert(2);
1611
1612 let set_str = format!("{:?}", set);
1613
1614 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1615 assert_eq!(format!("{:?}", empty), "{}");
1616 }
1617
1618 #[test]
1619 fn test_trivial_drain() {
1620 let mut s = HashSet::<i32>::new();
1621 for _ in s.drain() {}
1622 assert!(s.is_empty());
1623 drop(s);
1624
1625 let mut s = HashSet::<i32>::new();
1626 drop(s.drain());
1627 assert!(s.is_empty());
1628 }
1629
1630 #[test]
1631 fn test_drain() {
1632 let mut s: HashSet<_> = (1..100).collect();
1633
1634 // try this a bunch of times to make sure we don't screw up internal state.
1635 for _ in 0..20 {
1636 assert_eq!(s.len(), 99);
1637
1638 {
1639 let mut last_i = 0;
1640 let mut d = s.drain();
1641 for (i, x) in d.by_ref().take(50).enumerate() {
1642 last_i = i;
1643 assert!(x != 0);
1644 }
1645 assert_eq!(last_i, 49);
1646 }
1647
1648 for _ in &s {
1649 panic!("s should be empty!");
1650 }
1651
1652 // reset to try again.
1653 s.extend(1..100);
1654 }
1655 }
1656
1657 #[test]
1658 fn test_replace() {
1659 use hash;
1660
1661 #[derive(Debug)]
1662 struct Foo(&'static str, i32);
1663
1664 impl PartialEq for Foo {
1665 fn eq(&self, other: &Self) -> bool {
1666 self.0 == other.0
1667 }
1668 }
1669
1670 impl Eq for Foo {}
1671
1672 impl hash::Hash for Foo {
1673 fn hash<H: hash::Hasher>(&self, h: &mut H) {
1674 self.0.hash(h);
1675 }
1676 }
1677
1678 let mut s = HashSet::new();
1679 assert_eq!(s.replace(Foo("a", 1)), None);
1680 assert_eq!(s.len(), 1);
1681 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1682 assert_eq!(s.len(), 1);
1683
1684 let mut it = s.iter();
1685 assert_eq!(it.next(), Some(&Foo("a", 2)));
1686 assert_eq!(it.next(), None);
1687 }
1688
1689 #[test]
1690 fn test_extend_ref() {
1691 let mut a = HashSet::new();
1692 a.insert(1);
1693
1694 a.extend(&[2, 3, 4]);
1695
1696 assert_eq!(a.len(), 4);
1697 assert!(a.contains(&1));
1698 assert!(a.contains(&2));
1699 assert!(a.contains(&3));
1700 assert!(a.contains(&4));
1701
1702 let mut b = HashSet::new();
1703 b.insert(5);
1704 b.insert(6);
1705
1706 a.extend(&b);
1707
1708 assert_eq!(a.len(), 6);
1709 assert!(a.contains(&1));
1710 assert!(a.contains(&2));
1711 assert!(a.contains(&3));
1712 assert!(a.contains(&4));
1713 assert!(a.contains(&5));
1714 assert!(a.contains(&6));
1715 }
1716
1717 #[test]
1718 fn test_retain() {
1719 let xs = [1, 2, 3, 4, 5, 6];
1720 let mut set: HashSet<isize> = xs.iter().cloned().collect();
1721 set.retain(|&k| k % 2 == 0);
1722 assert_eq!(set.len(), 3);
1723 assert!(set.contains(&2));
1724 assert!(set.contains(&4));
1725 assert!(set.contains(&6));
1726 }
1727 }