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