]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/set.rs
Rollup merge of #39393 - ollie27:stab_impls, r=alexcrichton
[rust.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     ///
296     /// # Examples
297     ///
298     /// ```
299     /// use std::collections::HashSet;
300     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
301     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
302     ///
303     /// // Can be seen as `a - b`.
304     /// for x in a.difference(&b) {
305     ///     println!("{}", x); // Print 1
306     /// }
307     ///
308     /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
309     /// assert_eq!(diff, [1].iter().cloned().collect());
310     ///
311     /// // Note that difference is not symmetric,
312     /// // and `b - a` means something else:
313     /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
314     /// assert_eq!(diff, [4].iter().cloned().collect());
315     /// ```
316     #[stable(feature = "rust1", since = "1.0.0")]
317     pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
318         Difference {
319             iter: self.iter(),
320             other: other,
321         }
322     }
323
324     /// Visit the values representing the symmetric difference.
325     ///
326     /// # Examples
327     ///
328     /// ```
329     /// use std::collections::HashSet;
330     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
331     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
332     ///
333     /// // Print 1, 4 in arbitrary order.
334     /// for x in a.symmetric_difference(&b) {
335     ///     println!("{}", x);
336     /// }
337     ///
338     /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
339     /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
340     ///
341     /// assert_eq!(diff1, diff2);
342     /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
343     /// ```
344     #[stable(feature = "rust1", since = "1.0.0")]
345     pub fn symmetric_difference<'a>(&'a self,
346                                     other: &'a HashSet<T, S>)
347                                     -> SymmetricDifference<'a, T, S> {
348         SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
349     }
350
351     /// Visit the values representing the intersection.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// use std::collections::HashSet;
357     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
358     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
359     ///
360     /// // Print 2, 3 in arbitrary order.
361     /// for x in a.intersection(&b) {
362     ///     println!("{}", x);
363     /// }
364     ///
365     /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
366     /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
367     /// ```
368     #[stable(feature = "rust1", since = "1.0.0")]
369     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
370         Intersection {
371             iter: self.iter(),
372             other: other,
373         }
374     }
375
376     /// Visit the values representing the union.
377     ///
378     /// # Examples
379     ///
380     /// ```
381     /// use std::collections::HashSet;
382     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
383     /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
384     ///
385     /// // Print 1, 2, 3, 4 in arbitrary order.
386     /// for x in a.union(&b) {
387     ///     println!("{}", x);
388     /// }
389     ///
390     /// let union: HashSet<_> = a.union(&b).cloned().collect();
391     /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
392     /// ```
393     #[stable(feature = "rust1", since = "1.0.0")]
394     pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
395         Union { iter: self.iter().chain(other.difference(self)) }
396     }
397
398     /// Returns the number of elements in the set.
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// use std::collections::HashSet;
404     ///
405     /// let mut v = HashSet::new();
406     /// assert_eq!(v.len(), 0);
407     /// v.insert(1);
408     /// assert_eq!(v.len(), 1);
409     /// ```
410     #[stable(feature = "rust1", since = "1.0.0")]
411     pub fn len(&self) -> usize {
412         self.map.len()
413     }
414
415     /// Returns true if the set contains no elements.
416     ///
417     /// # Examples
418     ///
419     /// ```
420     /// use std::collections::HashSet;
421     ///
422     /// let mut v = HashSet::new();
423     /// assert!(v.is_empty());
424     /// v.insert(1);
425     /// assert!(!v.is_empty());
426     /// ```
427     #[stable(feature = "rust1", since = "1.0.0")]
428     pub fn is_empty(&self) -> bool {
429         self.map.is_empty()
430     }
431
432     /// Clears the set, returning all elements in an iterator.
433     #[inline]
434     #[stable(feature = "drain", since = "1.6.0")]
435     pub fn drain(&mut self) -> Drain<T> {
436         Drain { iter: self.map.drain() }
437     }
438
439     /// Clears the set, removing all values.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// use std::collections::HashSet;
445     ///
446     /// let mut v = HashSet::new();
447     /// v.insert(1);
448     /// v.clear();
449     /// assert!(v.is_empty());
450     /// ```
451     #[stable(feature = "rust1", since = "1.0.0")]
452     pub fn clear(&mut self) {
453         self.map.clear()
454     }
455
456     /// Returns `true` if the set contains a value.
457     ///
458     /// The value may be any borrowed form of the set's value type, but
459     /// `Hash` and `Eq` on the borrowed form *must* match those for
460     /// the value type.
461     ///
462     /// # Examples
463     ///
464     /// ```
465     /// use std::collections::HashSet;
466     ///
467     /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
468     /// assert_eq!(set.contains(&1), true);
469     /// assert_eq!(set.contains(&4), false);
470     /// ```
471     #[stable(feature = "rust1", since = "1.0.0")]
472     pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
473         where T: Borrow<Q>,
474               Q: Hash + Eq
475     {
476         self.map.contains_key(value)
477     }
478
479     /// Returns a reference to the value in the set, if any, that is equal to the given value.
480     ///
481     /// The value may be any borrowed form of the set's value type, but
482     /// `Hash` and `Eq` on the borrowed form *must* match those for
483     /// the value type.
484     #[stable(feature = "set_recovery", since = "1.9.0")]
485     pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
486         where T: Borrow<Q>,
487               Q: Hash + Eq
488     {
489         Recover::get(&self.map, value)
490     }
491
492     /// Returns `true` if the set has no elements in common with `other`.
493     /// This is equivalent to checking for an empty intersection.
494     ///
495     /// # Examples
496     ///
497     /// ```
498     /// use std::collections::HashSet;
499     ///
500     /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
501     /// let mut b = HashSet::new();
502     ///
503     /// assert_eq!(a.is_disjoint(&b), true);
504     /// b.insert(4);
505     /// assert_eq!(a.is_disjoint(&b), true);
506     /// b.insert(1);
507     /// assert_eq!(a.is_disjoint(&b), false);
508     /// ```
509     #[stable(feature = "rust1", since = "1.0.0")]
510     pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
511         self.iter().all(|v| !other.contains(v))
512     }
513
514     /// Returns `true` if the set is a subset of another.
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// use std::collections::HashSet;
520     ///
521     /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
522     /// let mut set = HashSet::new();
523     ///
524     /// assert_eq!(set.is_subset(&sup), true);
525     /// set.insert(2);
526     /// assert_eq!(set.is_subset(&sup), true);
527     /// set.insert(4);
528     /// assert_eq!(set.is_subset(&sup), false);
529     /// ```
530     #[stable(feature = "rust1", since = "1.0.0")]
531     pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
532         self.iter().all(|v| other.contains(v))
533     }
534
535     /// Returns `true` if the set is a superset of another.
536     ///
537     /// # Examples
538     ///
539     /// ```
540     /// use std::collections::HashSet;
541     ///
542     /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
543     /// let mut set = HashSet::new();
544     ///
545     /// assert_eq!(set.is_superset(&sub), false);
546     ///
547     /// set.insert(0);
548     /// set.insert(1);
549     /// assert_eq!(set.is_superset(&sub), false);
550     ///
551     /// set.insert(2);
552     /// assert_eq!(set.is_superset(&sub), true);
553     /// ```
554     #[inline]
555     #[stable(feature = "rust1", since = "1.0.0")]
556     pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
557         other.is_subset(self)
558     }
559
560     /// Adds a value to the set.
561     ///
562     /// If the set did not have this value present, `true` is returned.
563     ///
564     /// If the set did have this value present, `false` is returned.
565     ///
566     /// # Examples
567     ///
568     /// ```
569     /// use std::collections::HashSet;
570     ///
571     /// let mut set = HashSet::new();
572     ///
573     /// assert_eq!(set.insert(2), true);
574     /// assert_eq!(set.insert(2), false);
575     /// assert_eq!(set.len(), 1);
576     /// ```
577     #[stable(feature = "rust1", since = "1.0.0")]
578     pub fn insert(&mut self, value: T) -> bool {
579         self.map.insert(value, ()).is_none()
580     }
581
582     /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
583     /// one. Returns the replaced value.
584     #[stable(feature = "set_recovery", since = "1.9.0")]
585     pub fn replace(&mut self, value: T) -> Option<T> {
586         Recover::replace(&mut self.map, value)
587     }
588
589     /// Removes a value from the set. Returns `true` if the value was
590     /// present in the set.
591     ///
592     /// The value may be any borrowed form of the set's value type, but
593     /// `Hash` and `Eq` on the borrowed form *must* match those for
594     /// the value type.
595     ///
596     /// # Examples
597     ///
598     /// ```
599     /// use std::collections::HashSet;
600     ///
601     /// let mut set = HashSet::new();
602     ///
603     /// set.insert(2);
604     /// assert_eq!(set.remove(&2), true);
605     /// assert_eq!(set.remove(&2), false);
606     /// ```
607     #[stable(feature = "rust1", since = "1.0.0")]
608     pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
609         where T: Borrow<Q>,
610               Q: Hash + Eq
611     {
612         self.map.remove(value).is_some()
613     }
614
615     /// Removes and returns the value in the set, if any, that is equal to the given one.
616     ///
617     /// The value may be any borrowed form of the set's value type, but
618     /// `Hash` and `Eq` on the borrowed form *must* match those for
619     /// the value type.
620     #[stable(feature = "set_recovery", since = "1.9.0")]
621     pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
622         where T: Borrow<Q>,
623               Q: Hash + Eq
624     {
625         Recover::take(&mut self.map, value)
626     }
627 }
628
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<T, S> PartialEq for HashSet<T, S>
631     where T: Eq + Hash,
632           S: BuildHasher
633 {
634     fn eq(&self, other: &HashSet<T, S>) -> bool {
635         if self.len() != other.len() {
636             return false;
637         }
638
639         self.iter().all(|key| other.contains(key))
640     }
641 }
642
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T, S> Eq for HashSet<T, S>
645     where T: Eq + Hash,
646           S: BuildHasher
647 {
648 }
649
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl<T, S> fmt::Debug for HashSet<T, S>
652     where T: Eq + Hash + fmt::Debug,
653           S: BuildHasher
654 {
655     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
656         f.debug_set().entries(self.iter()).finish()
657     }
658 }
659
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<T, S> FromIterator<T> for HashSet<T, S>
662     where T: Eq + Hash,
663           S: BuildHasher + Default
664 {
665     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
666         let mut set = HashSet::with_hasher(Default::default());
667         set.extend(iter);
668         set
669     }
670 }
671
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<T, S> Extend<T> for HashSet<T, S>
674     where T: Eq + Hash,
675           S: BuildHasher
676 {
677     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
678         self.map.extend(iter.into_iter().map(|k| (k, ())));
679     }
680 }
681
682 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
683 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
684     where T: 'a + Eq + Hash + Copy,
685           S: BuildHasher
686 {
687     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
688         self.extend(iter.into_iter().cloned());
689     }
690 }
691
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<T, S> Default for HashSet<T, S>
694     where T: Eq + Hash,
695           S: BuildHasher + Default
696 {
697     /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
698     fn default() -> HashSet<T, S> {
699         HashSet { map: HashMap::default() }
700     }
701 }
702
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
705     where T: Eq + Hash + Clone,
706           S: BuildHasher + Default
707 {
708     type Output = HashSet<T, S>;
709
710     /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
711     ///
712     /// # Examples
713     ///
714     /// ```
715     /// use std::collections::HashSet;
716     ///
717     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
718     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
719     ///
720     /// let set = &a | &b;
721     ///
722     /// let mut i = 0;
723     /// let expected = [1, 2, 3, 4, 5];
724     /// for x in &set {
725     ///     assert!(expected.contains(x));
726     ///     i += 1;
727     /// }
728     /// assert_eq!(i, expected.len());
729     /// ```
730     fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
731         self.union(rhs).cloned().collect()
732     }
733 }
734
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
737     where T: Eq + Hash + Clone,
738           S: BuildHasher + Default
739 {
740     type Output = HashSet<T, S>;
741
742     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// use std::collections::HashSet;
748     ///
749     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
750     /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
751     ///
752     /// let set = &a & &b;
753     ///
754     /// let mut i = 0;
755     /// let expected = [2, 3];
756     /// for x in &set {
757     ///     assert!(expected.contains(x));
758     ///     i += 1;
759     /// }
760     /// assert_eq!(i, expected.len());
761     /// ```
762     fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
763         self.intersection(rhs).cloned().collect()
764     }
765 }
766
767 #[stable(feature = "rust1", since = "1.0.0")]
768 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
769     where T: Eq + Hash + Clone,
770           S: BuildHasher + Default
771 {
772     type Output = HashSet<T, S>;
773
774     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
775     ///
776     /// # Examples
777     ///
778     /// ```
779     /// use std::collections::HashSet;
780     ///
781     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
782     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
783     ///
784     /// let set = &a ^ &b;
785     ///
786     /// let mut i = 0;
787     /// let expected = [1, 2, 4, 5];
788     /// for x in &set {
789     ///     assert!(expected.contains(x));
790     ///     i += 1;
791     /// }
792     /// assert_eq!(i, expected.len());
793     /// ```
794     fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
795         self.symmetric_difference(rhs).cloned().collect()
796     }
797 }
798
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
801     where T: Eq + Hash + Clone,
802           S: BuildHasher + Default
803 {
804     type Output = HashSet<T, S>;
805
806     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
807     ///
808     /// # Examples
809     ///
810     /// ```
811     /// use std::collections::HashSet;
812     ///
813     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
814     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
815     ///
816     /// let set = &a - &b;
817     ///
818     /// let mut i = 0;
819     /// let expected = [1, 2];
820     /// for x in &set {
821     ///     assert!(expected.contains(x));
822     ///     i += 1;
823     /// }
824     /// assert_eq!(i, expected.len());
825     /// ```
826     fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
827         self.difference(rhs).cloned().collect()
828     }
829 }
830
831 /// HashSet iterator
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub struct Iter<'a, K: 'a> {
834     iter: Keys<'a, K, ()>,
835 }
836
837 /// HashSet move iterator
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub struct IntoIter<K> {
840     iter: map::IntoIter<K, ()>,
841 }
842
843 /// HashSet drain iterator
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub struct Drain<'a, K: 'a> {
846     iter: map::Drain<'a, K, ()>,
847 }
848
849 /// Intersection iterator
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub struct Intersection<'a, T: 'a, S: 'a> {
852     // iterator of the first set
853     iter: Iter<'a, T>,
854     // the second set
855     other: &'a HashSet<T, S>,
856 }
857
858 /// Difference iterator
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub struct Difference<'a, T: 'a, S: 'a> {
861     // iterator of the first set
862     iter: Iter<'a, T>,
863     // the second set
864     other: &'a HashSet<T, S>,
865 }
866
867 /// Symmetric difference iterator.
868 #[stable(feature = "rust1", since = "1.0.0")]
869 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
870     iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
871 }
872
873 /// Set union iterator.
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub struct Union<'a, T: 'a, S: 'a> {
876     iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
877 }
878
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
881     where T: Eq + Hash,
882           S: BuildHasher
883 {
884     type Item = &'a T;
885     type IntoIter = Iter<'a, T>;
886
887     fn into_iter(self) -> Iter<'a, T> {
888         self.iter()
889     }
890 }
891
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<T, S> IntoIterator for HashSet<T, S>
894     where T: Eq + Hash,
895           S: BuildHasher
896 {
897     type Item = T;
898     type IntoIter = IntoIter<T>;
899
900     /// Creates a consuming iterator, that is, one that moves each value out
901     /// of the set in arbitrary order. The set cannot be used after calling
902     /// this.
903     ///
904     /// # Examples
905     ///
906     /// ```
907     /// use std::collections::HashSet;
908     /// let mut set = HashSet::new();
909     /// set.insert("a".to_string());
910     /// set.insert("b".to_string());
911     ///
912     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
913     /// let v: Vec<String> = set.into_iter().collect();
914     ///
915     /// // Will print in an arbitrary order.
916     /// for x in &v {
917     ///     println!("{}", x);
918     /// }
919     /// ```
920     fn into_iter(self) -> IntoIter<T> {
921         IntoIter { iter: self.map.into_iter() }
922     }
923 }
924
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<'a, K> Clone for Iter<'a, K> {
927     fn clone(&self) -> Iter<'a, K> {
928         Iter { iter: self.iter.clone() }
929     }
930 }
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<'a, K> Iterator for Iter<'a, K> {
933     type Item = &'a K;
934
935     fn next(&mut self) -> Option<&'a K> {
936         self.iter.next()
937     }
938     fn size_hint(&self) -> (usize, Option<usize>) {
939         self.iter.size_hint()
940     }
941 }
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
944     fn len(&self) -> usize {
945         self.iter.len()
946     }
947 }
948 #[unstable(feature = "fused", issue = "35602")]
949 impl<'a, K> FusedIterator for Iter<'a, K> {}
950
951 #[stable(feature = "std_debug", since = "1.16.0")]
952 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
953     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
954         f.debug_list()
955             .entries(self.clone())
956             .finish()
957     }
958 }
959
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<K> Iterator for IntoIter<K> {
962     type Item = K;
963
964     fn next(&mut self) -> Option<K> {
965         self.iter.next().map(|(k, _)| k)
966     }
967     fn size_hint(&self) -> (usize, Option<usize>) {
968         self.iter.size_hint()
969     }
970 }
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<K> ExactSizeIterator for IntoIter<K> {
973     fn len(&self) -> usize {
974         self.iter.len()
975     }
976 }
977 #[unstable(feature = "fused", issue = "35602")]
978 impl<K> FusedIterator for IntoIter<K> {}
979
980 #[stable(feature = "std_debug", since = "1.16.0")]
981 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
982     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
983         let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
984         f.debug_list()
985             .entries(entries_iter)
986             .finish()
987     }
988 }
989
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<'a, K> Iterator for Drain<'a, K> {
992     type Item = K;
993
994     fn next(&mut self) -> Option<K> {
995         self.iter.next().map(|(k, _)| k)
996     }
997     fn size_hint(&self) -> (usize, Option<usize>) {
998         self.iter.size_hint()
999     }
1000 }
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1003     fn len(&self) -> usize {
1004         self.iter.len()
1005     }
1006 }
1007 #[unstable(feature = "fused", issue = "35602")]
1008 impl<'a, K> FusedIterator for Drain<'a, K> {}
1009
1010 #[stable(feature = "std_debug", since = "1.16.0")]
1011 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1012     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1013         let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
1014         f.debug_list()
1015             .entries(entries_iter)
1016             .finish()
1017     }
1018 }
1019
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1022     fn clone(&self) -> Intersection<'a, T, S> {
1023         Intersection { iter: self.iter.clone(), ..*self }
1024     }
1025 }
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1029     where T: Eq + Hash,
1030           S: BuildHasher
1031 {
1032     type Item = &'a T;
1033
1034     fn next(&mut self) -> Option<&'a T> {
1035         loop {
1036             match self.iter.next() {
1037                 None => return None,
1038                 Some(elt) => {
1039                     if self.other.contains(elt) {
1040                         return Some(elt);
1041                     }
1042                 }
1043             }
1044         }
1045     }
1046
1047     fn size_hint(&self) -> (usize, Option<usize>) {
1048         let (_, upper) = self.iter.size_hint();
1049         (0, upper)
1050     }
1051 }
1052
1053 #[stable(feature = "std_debug", since = "1.16.0")]
1054 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1055     where T: fmt::Debug + Eq + Hash,
1056           S: BuildHasher,
1057 {
1058     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1059         f.debug_list()
1060             .entries(self.clone())
1061             .finish()
1062     }
1063 }
1064
1065 #[unstable(feature = "fused", issue = "35602")]
1066 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1067     where T: Eq + Hash,
1068           S: BuildHasher
1069 {
1070 }
1071
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<'a, T, S> Clone for Difference<'a, T, S> {
1074     fn clone(&self) -> Difference<'a, T, S> {
1075         Difference { iter: self.iter.clone(), ..*self }
1076     }
1077 }
1078
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<'a, T, S> Iterator for Difference<'a, T, S>
1081     where T: Eq + Hash,
1082           S: BuildHasher
1083 {
1084     type Item = &'a T;
1085
1086     fn next(&mut self) -> Option<&'a T> {
1087         loop {
1088             match self.iter.next() {
1089                 None => return None,
1090                 Some(elt) => {
1091                     if !self.other.contains(elt) {
1092                         return Some(elt);
1093                     }
1094                 }
1095             }
1096         }
1097     }
1098
1099     fn size_hint(&self) -> (usize, Option<usize>) {
1100         let (_, upper) = self.iter.size_hint();
1101         (0, upper)
1102     }
1103 }
1104
1105 #[unstable(feature = "fused", issue = "35602")]
1106 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1107     where T: Eq + Hash,
1108           S: BuildHasher
1109 {
1110 }
1111
1112 #[stable(feature = "std_debug", since = "1.16.0")]
1113 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1114     where T: fmt::Debug + Eq + Hash,
1115           S: BuildHasher,
1116 {
1117     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1118         f.debug_list()
1119             .entries(self.clone())
1120             .finish()
1121     }
1122 }
1123
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1126     fn clone(&self) -> SymmetricDifference<'a, T, S> {
1127         SymmetricDifference { iter: self.iter.clone() }
1128     }
1129 }
1130
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1133     where T: Eq + Hash,
1134           S: BuildHasher
1135 {
1136     type Item = &'a T;
1137
1138     fn next(&mut self) -> Option<&'a T> {
1139         self.iter.next()
1140     }
1141     fn size_hint(&self) -> (usize, Option<usize>) {
1142         self.iter.size_hint()
1143     }
1144 }
1145
1146 #[unstable(feature = "fused", issue = "35602")]
1147 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1148     where T: Eq + Hash,
1149           S: BuildHasher
1150 {
1151 }
1152
1153 #[stable(feature = "std_debug", since = "1.16.0")]
1154 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1155     where T: fmt::Debug + Eq + Hash,
1156           S: BuildHasher,
1157 {
1158     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1159         f.debug_list()
1160             .entries(self.clone())
1161             .finish()
1162     }
1163 }
1164
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<'a, T, S> Clone for Union<'a, T, S> {
1167     fn clone(&self) -> Union<'a, T, S> {
1168         Union { iter: self.iter.clone() }
1169     }
1170 }
1171
1172 #[unstable(feature = "fused", issue = "35602")]
1173 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1174     where T: Eq + Hash,
1175           S: BuildHasher
1176 {
1177 }
1178
1179 #[stable(feature = "std_debug", since = "1.16.0")]
1180 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1181     where T: fmt::Debug + Eq + Hash,
1182           S: BuildHasher,
1183 {
1184     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1185         f.debug_list()
1186             .entries(self.clone())
1187             .finish()
1188     }
1189 }
1190
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<'a, T, S> Iterator for Union<'a, T, S>
1193     where T: Eq + Hash,
1194           S: BuildHasher
1195 {
1196     type Item = &'a T;
1197
1198     fn next(&mut self) -> Option<&'a T> {
1199         self.iter.next()
1200     }
1201     fn size_hint(&self) -> (usize, Option<usize>) {
1202         self.iter.size_hint()
1203     }
1204 }
1205
1206 #[allow(dead_code)]
1207 fn assert_covariance() {
1208     fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1209         v
1210     }
1211     fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1212         v
1213     }
1214     fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1215         v
1216     }
1217     fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1218                             -> Difference<'a, &'new str, RandomState> {
1219         v
1220     }
1221     fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1222                                       -> SymmetricDifference<'a, &'new str, RandomState> {
1223         v
1224     }
1225     fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1226                               -> Intersection<'a, &'new str, RandomState> {
1227         v
1228     }
1229     fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1230                        -> Union<'a, &'new str, RandomState> {
1231         v
1232     }
1233     fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1234         d
1235     }
1236 }
1237
1238 #[cfg(test)]
1239 mod test_set {
1240     use super::HashSet;
1241     use super::super::map::RandomState;
1242
1243     #[test]
1244     fn test_zero_capacities() {
1245         type HS = HashSet<i32>;
1246
1247         let s = HS::new();
1248         assert_eq!(s.capacity(), 0);
1249
1250         let s = HS::default();
1251         assert_eq!(s.capacity(), 0);
1252
1253         let s = HS::with_hasher(RandomState::new());
1254         assert_eq!(s.capacity(), 0);
1255
1256         let s = HS::with_capacity(0);
1257         assert_eq!(s.capacity(), 0);
1258
1259         let s = HS::with_capacity_and_hasher(0, RandomState::new());
1260         assert_eq!(s.capacity(), 0);
1261
1262         let mut s = HS::new();
1263         s.insert(1);
1264         s.insert(2);
1265         s.remove(&1);
1266         s.remove(&2);
1267         s.shrink_to_fit();
1268         assert_eq!(s.capacity(), 0);
1269
1270         let mut s = HS::new();
1271         s.reserve(0);
1272         assert_eq!(s.capacity(), 0);
1273     }
1274
1275     #[test]
1276     fn test_disjoint() {
1277         let mut xs = HashSet::new();
1278         let mut ys = HashSet::new();
1279         assert!(xs.is_disjoint(&ys));
1280         assert!(ys.is_disjoint(&xs));
1281         assert!(xs.insert(5));
1282         assert!(ys.insert(11));
1283         assert!(xs.is_disjoint(&ys));
1284         assert!(ys.is_disjoint(&xs));
1285         assert!(xs.insert(7));
1286         assert!(xs.insert(19));
1287         assert!(xs.insert(4));
1288         assert!(ys.insert(2));
1289         assert!(ys.insert(-11));
1290         assert!(xs.is_disjoint(&ys));
1291         assert!(ys.is_disjoint(&xs));
1292         assert!(ys.insert(7));
1293         assert!(!xs.is_disjoint(&ys));
1294         assert!(!ys.is_disjoint(&xs));
1295     }
1296
1297     #[test]
1298     fn test_subset_and_superset() {
1299         let mut a = HashSet::new();
1300         assert!(a.insert(0));
1301         assert!(a.insert(5));
1302         assert!(a.insert(11));
1303         assert!(a.insert(7));
1304
1305         let mut b = HashSet::new();
1306         assert!(b.insert(0));
1307         assert!(b.insert(7));
1308         assert!(b.insert(19));
1309         assert!(b.insert(250));
1310         assert!(b.insert(11));
1311         assert!(b.insert(200));
1312
1313         assert!(!a.is_subset(&b));
1314         assert!(!a.is_superset(&b));
1315         assert!(!b.is_subset(&a));
1316         assert!(!b.is_superset(&a));
1317
1318         assert!(b.insert(5));
1319
1320         assert!(a.is_subset(&b));
1321         assert!(!a.is_superset(&b));
1322         assert!(!b.is_subset(&a));
1323         assert!(b.is_superset(&a));
1324     }
1325
1326     #[test]
1327     fn test_iterate() {
1328         let mut a = HashSet::new();
1329         for i in 0..32 {
1330             assert!(a.insert(i));
1331         }
1332         let mut observed: u32 = 0;
1333         for k in &a {
1334             observed |= 1 << *k;
1335         }
1336         assert_eq!(observed, 0xFFFF_FFFF);
1337     }
1338
1339     #[test]
1340     fn test_intersection() {
1341         let mut a = HashSet::new();
1342         let mut b = HashSet::new();
1343
1344         assert!(a.insert(11));
1345         assert!(a.insert(1));
1346         assert!(a.insert(3));
1347         assert!(a.insert(77));
1348         assert!(a.insert(103));
1349         assert!(a.insert(5));
1350         assert!(a.insert(-5));
1351
1352         assert!(b.insert(2));
1353         assert!(b.insert(11));
1354         assert!(b.insert(77));
1355         assert!(b.insert(-9));
1356         assert!(b.insert(-42));
1357         assert!(b.insert(5));
1358         assert!(b.insert(3));
1359
1360         let mut i = 0;
1361         let expected = [3, 5, 11, 77];
1362         for x in a.intersection(&b) {
1363             assert!(expected.contains(x));
1364             i += 1
1365         }
1366         assert_eq!(i, expected.len());
1367     }
1368
1369     #[test]
1370     fn test_difference() {
1371         let mut a = HashSet::new();
1372         let mut b = HashSet::new();
1373
1374         assert!(a.insert(1));
1375         assert!(a.insert(3));
1376         assert!(a.insert(5));
1377         assert!(a.insert(9));
1378         assert!(a.insert(11));
1379
1380         assert!(b.insert(3));
1381         assert!(b.insert(9));
1382
1383         let mut i = 0;
1384         let expected = [1, 5, 11];
1385         for x in a.difference(&b) {
1386             assert!(expected.contains(x));
1387             i += 1
1388         }
1389         assert_eq!(i, expected.len());
1390     }
1391
1392     #[test]
1393     fn test_symmetric_difference() {
1394         let mut a = HashSet::new();
1395         let mut b = HashSet::new();
1396
1397         assert!(a.insert(1));
1398         assert!(a.insert(3));
1399         assert!(a.insert(5));
1400         assert!(a.insert(9));
1401         assert!(a.insert(11));
1402
1403         assert!(b.insert(-2));
1404         assert!(b.insert(3));
1405         assert!(b.insert(9));
1406         assert!(b.insert(14));
1407         assert!(b.insert(22));
1408
1409         let mut i = 0;
1410         let expected = [-2, 1, 5, 11, 14, 22];
1411         for x in a.symmetric_difference(&b) {
1412             assert!(expected.contains(x));
1413             i += 1
1414         }
1415         assert_eq!(i, expected.len());
1416     }
1417
1418     #[test]
1419     fn test_union() {
1420         let mut a = HashSet::new();
1421         let mut b = HashSet::new();
1422
1423         assert!(a.insert(1));
1424         assert!(a.insert(3));
1425         assert!(a.insert(5));
1426         assert!(a.insert(9));
1427         assert!(a.insert(11));
1428         assert!(a.insert(16));
1429         assert!(a.insert(19));
1430         assert!(a.insert(24));
1431
1432         assert!(b.insert(-2));
1433         assert!(b.insert(1));
1434         assert!(b.insert(5));
1435         assert!(b.insert(9));
1436         assert!(b.insert(13));
1437         assert!(b.insert(19));
1438
1439         let mut i = 0;
1440         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1441         for x in a.union(&b) {
1442             assert!(expected.contains(x));
1443             i += 1
1444         }
1445         assert_eq!(i, expected.len());
1446     }
1447
1448     #[test]
1449     fn test_from_iter() {
1450         let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1451
1452         let set: HashSet<_> = xs.iter().cloned().collect();
1453
1454         for x in &xs {
1455             assert!(set.contains(x));
1456         }
1457     }
1458
1459     #[test]
1460     fn test_move_iter() {
1461         let hs = {
1462             let mut hs = HashSet::new();
1463
1464             hs.insert('a');
1465             hs.insert('b');
1466
1467             hs
1468         };
1469
1470         let v = hs.into_iter().collect::<Vec<char>>();
1471         assert!(v == ['a', 'b'] || v == ['b', 'a']);
1472     }
1473
1474     #[test]
1475     fn test_eq() {
1476         // These constants once happened to expose a bug in insert().
1477         // I'm keeping them around to prevent a regression.
1478         let mut s1 = HashSet::new();
1479
1480         s1.insert(1);
1481         s1.insert(2);
1482         s1.insert(3);
1483
1484         let mut s2 = HashSet::new();
1485
1486         s2.insert(1);
1487         s2.insert(2);
1488
1489         assert!(s1 != s2);
1490
1491         s2.insert(3);
1492
1493         assert_eq!(s1, s2);
1494     }
1495
1496     #[test]
1497     fn test_show() {
1498         let mut set = HashSet::new();
1499         let empty = HashSet::<i32>::new();
1500
1501         set.insert(1);
1502         set.insert(2);
1503
1504         let set_str = format!("{:?}", set);
1505
1506         assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1507         assert_eq!(format!("{:?}", empty), "{}");
1508     }
1509
1510     #[test]
1511     fn test_trivial_drain() {
1512         let mut s = HashSet::<i32>::new();
1513         for _ in s.drain() {}
1514         assert!(s.is_empty());
1515         drop(s);
1516
1517         let mut s = HashSet::<i32>::new();
1518         drop(s.drain());
1519         assert!(s.is_empty());
1520     }
1521
1522     #[test]
1523     fn test_drain() {
1524         let mut s: HashSet<_> = (1..100).collect();
1525
1526         // try this a bunch of times to make sure we don't screw up internal state.
1527         for _ in 0..20 {
1528             assert_eq!(s.len(), 99);
1529
1530             {
1531                 let mut last_i = 0;
1532                 let mut d = s.drain();
1533                 for (i, x) in d.by_ref().take(50).enumerate() {
1534                     last_i = i;
1535                     assert!(x != 0);
1536                 }
1537                 assert_eq!(last_i, 49);
1538             }
1539
1540             for _ in &s {
1541                 panic!("s should be empty!");
1542             }
1543
1544             // reset to try again.
1545             s.extend(1..100);
1546         }
1547     }
1548
1549     #[test]
1550     fn test_replace() {
1551         use hash;
1552
1553         #[derive(Debug)]
1554         struct Foo(&'static str, i32);
1555
1556         impl PartialEq for Foo {
1557             fn eq(&self, other: &Self) -> bool {
1558                 self.0 == other.0
1559             }
1560         }
1561
1562         impl Eq for Foo {}
1563
1564         impl hash::Hash for Foo {
1565             fn hash<H: hash::Hasher>(&self, h: &mut H) {
1566                 self.0.hash(h);
1567             }
1568         }
1569
1570         let mut s = HashSet::new();
1571         assert_eq!(s.replace(Foo("a", 1)), None);
1572         assert_eq!(s.len(), 1);
1573         assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1574         assert_eq!(s.len(), 1);
1575
1576         let mut it = s.iter();
1577         assert_eq!(it.next(), Some(&Foo("a", 2)));
1578         assert_eq!(it.next(), None);
1579     }
1580
1581     #[test]
1582     fn test_extend_ref() {
1583         let mut a = HashSet::new();
1584         a.insert(1);
1585
1586         a.extend(&[2, 3, 4]);
1587
1588         assert_eq!(a.len(), 4);
1589         assert!(a.contains(&1));
1590         assert!(a.contains(&2));
1591         assert!(a.contains(&3));
1592         assert!(a.contains(&4));
1593
1594         let mut b = HashSet::new();
1595         b.insert(5);
1596         b.insert(6);
1597
1598         a.extend(&b);
1599
1600         assert_eq!(a.len(), 6);
1601         assert!(a.contains(&1));
1602         assert!(a.contains(&2));
1603         assert!(a.contains(&3));
1604         assert!(a.contains(&4));
1605         assert!(a.contains(&5));
1606         assert!(a.contains(&6));
1607     }
1608 }