]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/set.rs
Update set operations documentation
[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     /// 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
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl<T, S> PartialEq for HashSet<T, S>
637     where T: Eq + Hash,
638           S: BuildHasher
639 {
640     fn eq(&self, other: &HashSet<T, S>) -> bool {
641         if self.len() != other.len() {
642             return false;
643         }
644
645         self.iter().all(|key| other.contains(key))
646     }
647 }
648
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl<T, S> Eq for HashSet<T, S>
651     where T: Eq + Hash,
652           S: BuildHasher
653 {
654 }
655
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl<T, S> fmt::Debug for HashSet<T, S>
658     where T: Eq + Hash + fmt::Debug,
659           S: BuildHasher
660 {
661     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662         f.debug_set().entries(self.iter()).finish()
663     }
664 }
665
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<T, S> FromIterator<T> for HashSet<T, S>
668     where T: Eq + Hash,
669           S: BuildHasher + Default
670 {
671     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
672         let mut set = HashSet::with_hasher(Default::default());
673         set.extend(iter);
674         set
675     }
676 }
677
678 #[stable(feature = "rust1", since = "1.0.0")]
679 impl<T, S> Extend<T> for HashSet<T, S>
680     where T: Eq + Hash,
681           S: BuildHasher
682 {
683     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
684         self.map.extend(iter.into_iter().map(|k| (k, ())));
685     }
686 }
687
688 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
689 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
690     where T: 'a + Eq + Hash + Copy,
691           S: BuildHasher
692 {
693     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
694         self.extend(iter.into_iter().cloned());
695     }
696 }
697
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<T, S> Default for HashSet<T, S>
700     where T: Eq + Hash,
701           S: BuildHasher + Default
702 {
703     /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
704     fn default() -> HashSet<T, S> {
705         HashSet { map: HashMap::default() }
706     }
707 }
708
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
711     where T: Eq + Hash + Clone,
712           S: BuildHasher + Default
713 {
714     type Output = HashSet<T, S>;
715
716     /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
717     ///
718     /// # Examples
719     ///
720     /// ```
721     /// use std::collections::HashSet;
722     ///
723     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
724     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
725     ///
726     /// let set = &a | &b;
727     ///
728     /// let mut i = 0;
729     /// let expected = [1, 2, 3, 4, 5];
730     /// for x in &set {
731     ///     assert!(expected.contains(x));
732     ///     i += 1;
733     /// }
734     /// assert_eq!(i, expected.len());
735     /// ```
736     fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
737         self.union(rhs).cloned().collect()
738     }
739 }
740
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
743     where T: Eq + Hash + Clone,
744           S: BuildHasher + Default
745 {
746     type Output = HashSet<T, S>;
747
748     /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
749     ///
750     /// # Examples
751     ///
752     /// ```
753     /// use std::collections::HashSet;
754     ///
755     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
756     /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
757     ///
758     /// let set = &a & &b;
759     ///
760     /// let mut i = 0;
761     /// let expected = [2, 3];
762     /// for x in &set {
763     ///     assert!(expected.contains(x));
764     ///     i += 1;
765     /// }
766     /// assert_eq!(i, expected.len());
767     /// ```
768     fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
769         self.intersection(rhs).cloned().collect()
770     }
771 }
772
773 #[stable(feature = "rust1", since = "1.0.0")]
774 impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
775     where T: Eq + Hash + Clone,
776           S: BuildHasher + Default
777 {
778     type Output = HashSet<T, S>;
779
780     /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
781     ///
782     /// # Examples
783     ///
784     /// ```
785     /// use std::collections::HashSet;
786     ///
787     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
788     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
789     ///
790     /// let set = &a ^ &b;
791     ///
792     /// let mut i = 0;
793     /// let expected = [1, 2, 4, 5];
794     /// for x in &set {
795     ///     assert!(expected.contains(x));
796     ///     i += 1;
797     /// }
798     /// assert_eq!(i, expected.len());
799     /// ```
800     fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
801         self.symmetric_difference(rhs).cloned().collect()
802     }
803 }
804
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
807     where T: Eq + Hash + Clone,
808           S: BuildHasher + Default
809 {
810     type Output = HashSet<T, S>;
811
812     /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
813     ///
814     /// # Examples
815     ///
816     /// ```
817     /// use std::collections::HashSet;
818     ///
819     /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
820     /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
821     ///
822     /// let set = &a - &b;
823     ///
824     /// let mut i = 0;
825     /// let expected = [1, 2];
826     /// for x in &set {
827     ///     assert!(expected.contains(x));
828     ///     i += 1;
829     /// }
830     /// assert_eq!(i, expected.len());
831     /// ```
832     fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
833         self.difference(rhs).cloned().collect()
834     }
835 }
836
837 /// HashSet iterator
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub struct Iter<'a, K: 'a> {
840     iter: Keys<'a, K, ()>,
841 }
842
843 /// HashSet move iterator
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub struct IntoIter<K> {
846     iter: map::IntoIter<K, ()>,
847 }
848
849 /// HashSet drain iterator
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub struct Drain<'a, K: 'a> {
852     iter: map::Drain<'a, K, ()>,
853 }
854
855 /// Intersection iterator
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub struct Intersection<'a, T: 'a, S: 'a> {
858     // iterator of the first set
859     iter: Iter<'a, T>,
860     // the second set
861     other: &'a HashSet<T, S>,
862 }
863
864 /// Difference iterator
865 #[stable(feature = "rust1", since = "1.0.0")]
866 pub struct Difference<'a, T: 'a, S: 'a> {
867     // iterator of the first set
868     iter: Iter<'a, T>,
869     // the second set
870     other: &'a HashSet<T, S>,
871 }
872
873 /// Symmetric difference iterator.
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
876     iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
877 }
878
879 /// Set union iterator.
880 #[stable(feature = "rust1", since = "1.0.0")]
881 pub struct Union<'a, T: 'a, S: 'a> {
882     iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
883 }
884
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
887     where T: Eq + Hash,
888           S: BuildHasher
889 {
890     type Item = &'a T;
891     type IntoIter = Iter<'a, T>;
892
893     fn into_iter(self) -> Iter<'a, T> {
894         self.iter()
895     }
896 }
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<T, S> IntoIterator for HashSet<T, S>
900     where T: Eq + Hash,
901           S: BuildHasher
902 {
903     type Item = T;
904     type IntoIter = IntoIter<T>;
905
906     /// Creates a consuming iterator, that is, one that moves each value out
907     /// of the set in arbitrary order. The set cannot be used after calling
908     /// this.
909     ///
910     /// # Examples
911     ///
912     /// ```
913     /// use std::collections::HashSet;
914     /// let mut set = HashSet::new();
915     /// set.insert("a".to_string());
916     /// set.insert("b".to_string());
917     ///
918     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
919     /// let v: Vec<String> = set.into_iter().collect();
920     ///
921     /// // Will print in an arbitrary order.
922     /// for x in &v {
923     ///     println!("{}", x);
924     /// }
925     /// ```
926     fn into_iter(self) -> IntoIter<T> {
927         IntoIter { iter: self.map.into_iter() }
928     }
929 }
930
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<'a, K> Clone for Iter<'a, K> {
933     fn clone(&self) -> Iter<'a, K> {
934         Iter { iter: self.iter.clone() }
935     }
936 }
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, K> Iterator for Iter<'a, K> {
939     type Item = &'a K;
940
941     fn next(&mut self) -> Option<&'a K> {
942         self.iter.next()
943     }
944     fn size_hint(&self) -> (usize, Option<usize>) {
945         self.iter.size_hint()
946     }
947 }
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<'a, K> ExactSizeIterator for Iter<'a, K> {
950     fn len(&self) -> usize {
951         self.iter.len()
952     }
953 }
954 #[unstable(feature = "fused", issue = "35602")]
955 impl<'a, K> FusedIterator for Iter<'a, K> {}
956
957 #[stable(feature = "std_debug", since = "1.16.0")]
958 impl<'a, K: fmt::Debug> fmt::Debug for Iter<'a, K> {
959     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
960         f.debug_list()
961             .entries(self.clone())
962             .finish()
963     }
964 }
965
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<K> Iterator for IntoIter<K> {
968     type Item = K;
969
970     fn next(&mut self) -> Option<K> {
971         self.iter.next().map(|(k, _)| k)
972     }
973     fn size_hint(&self) -> (usize, Option<usize>) {
974         self.iter.size_hint()
975     }
976 }
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<K> ExactSizeIterator for IntoIter<K> {
979     fn len(&self) -> usize {
980         self.iter.len()
981     }
982 }
983 #[unstable(feature = "fused", issue = "35602")]
984 impl<K> FusedIterator for IntoIter<K> {}
985
986 #[stable(feature = "std_debug", since = "1.16.0")]
987 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
988     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
989         let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
990         f.debug_list()
991             .entries(entries_iter)
992             .finish()
993     }
994 }
995
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl<'a, K> Iterator for Drain<'a, K> {
998     type Item = K;
999
1000     fn next(&mut self) -> Option<K> {
1001         self.iter.next().map(|(k, _)| k)
1002     }
1003     fn size_hint(&self) -> (usize, Option<usize>) {
1004         self.iter.size_hint()
1005     }
1006 }
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<'a, K> ExactSizeIterator for Drain<'a, K> {
1009     fn len(&self) -> usize {
1010         self.iter.len()
1011     }
1012 }
1013 #[unstable(feature = "fused", issue = "35602")]
1014 impl<'a, K> FusedIterator for Drain<'a, K> {}
1015
1016 #[stable(feature = "std_debug", since = "1.16.0")]
1017 impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
1018     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1019         let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
1020         f.debug_list()
1021             .entries(entries_iter)
1022             .finish()
1023     }
1024 }
1025
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<'a, T, S> Clone for Intersection<'a, T, S> {
1028     fn clone(&self) -> Intersection<'a, T, S> {
1029         Intersection { iter: self.iter.clone(), ..*self }
1030     }
1031 }
1032
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1035     where T: Eq + Hash,
1036           S: BuildHasher
1037 {
1038     type Item = &'a T;
1039
1040     fn next(&mut self) -> Option<&'a T> {
1041         loop {
1042             match self.iter.next() {
1043                 None => return None,
1044                 Some(elt) => {
1045                     if self.other.contains(elt) {
1046                         return Some(elt);
1047                     }
1048                 }
1049             }
1050         }
1051     }
1052
1053     fn size_hint(&self) -> (usize, Option<usize>) {
1054         let (_, upper) = self.iter.size_hint();
1055         (0, upper)
1056     }
1057 }
1058
1059 #[stable(feature = "std_debug", since = "1.16.0")]
1060 impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
1061     where T: fmt::Debug + Eq + Hash,
1062           S: BuildHasher,
1063 {
1064     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1065         f.debug_list()
1066             .entries(self.clone())
1067             .finish()
1068     }
1069 }
1070
1071 #[unstable(feature = "fused", issue = "35602")]
1072 impl<'a, T, S> FusedIterator for Intersection<'a, T, S>
1073     where T: Eq + Hash,
1074           S: BuildHasher
1075 {
1076 }
1077
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<'a, T, S> Clone for Difference<'a, T, S> {
1080     fn clone(&self) -> Difference<'a, T, S> {
1081         Difference { iter: self.iter.clone(), ..*self }
1082     }
1083 }
1084
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<'a, T, S> Iterator for Difference<'a, T, S>
1087     where T: Eq + Hash,
1088           S: BuildHasher
1089 {
1090     type Item = &'a T;
1091
1092     fn next(&mut self) -> Option<&'a T> {
1093         loop {
1094             match self.iter.next() {
1095                 None => return None,
1096                 Some(elt) => {
1097                     if !self.other.contains(elt) {
1098                         return Some(elt);
1099                     }
1100                 }
1101             }
1102         }
1103     }
1104
1105     fn size_hint(&self) -> (usize, Option<usize>) {
1106         let (_, upper) = self.iter.size_hint();
1107         (0, upper)
1108     }
1109 }
1110
1111 #[unstable(feature = "fused", issue = "35602")]
1112 impl<'a, T, S> FusedIterator for Difference<'a, T, S>
1113     where T: Eq + Hash,
1114           S: BuildHasher
1115 {
1116 }
1117
1118 #[stable(feature = "std_debug", since = "1.16.0")]
1119 impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
1120     where T: fmt::Debug + Eq + Hash,
1121           S: BuildHasher,
1122 {
1123     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1124         f.debug_list()
1125             .entries(self.clone())
1126             .finish()
1127     }
1128 }
1129
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
1132     fn clone(&self) -> SymmetricDifference<'a, T, S> {
1133         SymmetricDifference { iter: self.iter.clone() }
1134     }
1135 }
1136
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1139     where T: Eq + Hash,
1140           S: BuildHasher
1141 {
1142     type Item = &'a T;
1143
1144     fn next(&mut self) -> Option<&'a T> {
1145         self.iter.next()
1146     }
1147     fn size_hint(&self) -> (usize, Option<usize>) {
1148         self.iter.size_hint()
1149     }
1150 }
1151
1152 #[unstable(feature = "fused", issue = "35602")]
1153 impl<'a, T, S> FusedIterator for SymmetricDifference<'a, T, S>
1154     where T: Eq + Hash,
1155           S: BuildHasher
1156 {
1157 }
1158
1159 #[stable(feature = "std_debug", since = "1.16.0")]
1160 impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
1161     where T: fmt::Debug + Eq + Hash,
1162           S: BuildHasher,
1163 {
1164     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1165         f.debug_list()
1166             .entries(self.clone())
1167             .finish()
1168     }
1169 }
1170
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<'a, T, S> Clone for Union<'a, T, S> {
1173     fn clone(&self) -> Union<'a, T, S> {
1174         Union { iter: self.iter.clone() }
1175     }
1176 }
1177
1178 #[unstable(feature = "fused", issue = "35602")]
1179 impl<'a, T, S> FusedIterator for Union<'a, T, S>
1180     where T: Eq + Hash,
1181           S: BuildHasher
1182 {
1183 }
1184
1185 #[stable(feature = "std_debug", since = "1.16.0")]
1186 impl<'a, T, S> fmt::Debug for Union<'a, T, S>
1187     where T: fmt::Debug + Eq + Hash,
1188           S: BuildHasher,
1189 {
1190     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1191         f.debug_list()
1192             .entries(self.clone())
1193             .finish()
1194     }
1195 }
1196
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<'a, T, S> Iterator for Union<'a, T, S>
1199     where T: Eq + Hash,
1200           S: BuildHasher
1201 {
1202     type Item = &'a T;
1203
1204     fn next(&mut self) -> Option<&'a T> {
1205         self.iter.next()
1206     }
1207     fn size_hint(&self) -> (usize, Option<usize>) {
1208         self.iter.size_hint()
1209     }
1210 }
1211
1212 #[allow(dead_code)]
1213 fn assert_covariance() {
1214     fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1215         v
1216     }
1217     fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1218         v
1219     }
1220     fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1221         v
1222     }
1223     fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>)
1224                             -> Difference<'a, &'new str, RandomState> {
1225         v
1226     }
1227     fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>)
1228                                       -> SymmetricDifference<'a, &'new str, RandomState> {
1229         v
1230     }
1231     fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>)
1232                               -> Intersection<'a, &'new str, RandomState> {
1233         v
1234     }
1235     fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>)
1236                        -> Union<'a, &'new str, RandomState> {
1237         v
1238     }
1239     fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1240         d
1241     }
1242 }
1243
1244 #[cfg(test)]
1245 mod test_set {
1246     use super::HashSet;
1247     use super::super::map::RandomState;
1248
1249     #[test]
1250     fn test_zero_capacities() {
1251         type HS = HashSet<i32>;
1252
1253         let s = HS::new();
1254         assert_eq!(s.capacity(), 0);
1255
1256         let s = HS::default();
1257         assert_eq!(s.capacity(), 0);
1258
1259         let s = HS::with_hasher(RandomState::new());
1260         assert_eq!(s.capacity(), 0);
1261
1262         let s = HS::with_capacity(0);
1263         assert_eq!(s.capacity(), 0);
1264
1265         let s = HS::with_capacity_and_hasher(0, RandomState::new());
1266         assert_eq!(s.capacity(), 0);
1267
1268         let mut s = HS::new();
1269         s.insert(1);
1270         s.insert(2);
1271         s.remove(&1);
1272         s.remove(&2);
1273         s.shrink_to_fit();
1274         assert_eq!(s.capacity(), 0);
1275
1276         let mut s = HS::new();
1277         s.reserve(0);
1278         assert_eq!(s.capacity(), 0);
1279     }
1280
1281     #[test]
1282     fn test_disjoint() {
1283         let mut xs = HashSet::new();
1284         let mut ys = HashSet::new();
1285         assert!(xs.is_disjoint(&ys));
1286         assert!(ys.is_disjoint(&xs));
1287         assert!(xs.insert(5));
1288         assert!(ys.insert(11));
1289         assert!(xs.is_disjoint(&ys));
1290         assert!(ys.is_disjoint(&xs));
1291         assert!(xs.insert(7));
1292         assert!(xs.insert(19));
1293         assert!(xs.insert(4));
1294         assert!(ys.insert(2));
1295         assert!(ys.insert(-11));
1296         assert!(xs.is_disjoint(&ys));
1297         assert!(ys.is_disjoint(&xs));
1298         assert!(ys.insert(7));
1299         assert!(!xs.is_disjoint(&ys));
1300         assert!(!ys.is_disjoint(&xs));
1301     }
1302
1303     #[test]
1304     fn test_subset_and_superset() {
1305         let mut a = HashSet::new();
1306         assert!(a.insert(0));
1307         assert!(a.insert(5));
1308         assert!(a.insert(11));
1309         assert!(a.insert(7));
1310
1311         let mut b = HashSet::new();
1312         assert!(b.insert(0));
1313         assert!(b.insert(7));
1314         assert!(b.insert(19));
1315         assert!(b.insert(250));
1316         assert!(b.insert(11));
1317         assert!(b.insert(200));
1318
1319         assert!(!a.is_subset(&b));
1320         assert!(!a.is_superset(&b));
1321         assert!(!b.is_subset(&a));
1322         assert!(!b.is_superset(&a));
1323
1324         assert!(b.insert(5));
1325
1326         assert!(a.is_subset(&b));
1327         assert!(!a.is_superset(&b));
1328         assert!(!b.is_subset(&a));
1329         assert!(b.is_superset(&a));
1330     }
1331
1332     #[test]
1333     fn test_iterate() {
1334         let mut a = HashSet::new();
1335         for i in 0..32 {
1336             assert!(a.insert(i));
1337         }
1338         let mut observed: u32 = 0;
1339         for k in &a {
1340             observed |= 1 << *k;
1341         }
1342         assert_eq!(observed, 0xFFFF_FFFF);
1343     }
1344
1345     #[test]
1346     fn test_intersection() {
1347         let mut a = HashSet::new();
1348         let mut b = HashSet::new();
1349
1350         assert!(a.insert(11));
1351         assert!(a.insert(1));
1352         assert!(a.insert(3));
1353         assert!(a.insert(77));
1354         assert!(a.insert(103));
1355         assert!(a.insert(5));
1356         assert!(a.insert(-5));
1357
1358         assert!(b.insert(2));
1359         assert!(b.insert(11));
1360         assert!(b.insert(77));
1361         assert!(b.insert(-9));
1362         assert!(b.insert(-42));
1363         assert!(b.insert(5));
1364         assert!(b.insert(3));
1365
1366         let mut i = 0;
1367         let expected = [3, 5, 11, 77];
1368         for x in a.intersection(&b) {
1369             assert!(expected.contains(x));
1370             i += 1
1371         }
1372         assert_eq!(i, expected.len());
1373     }
1374
1375     #[test]
1376     fn test_difference() {
1377         let mut a = HashSet::new();
1378         let mut b = HashSet::new();
1379
1380         assert!(a.insert(1));
1381         assert!(a.insert(3));
1382         assert!(a.insert(5));
1383         assert!(a.insert(9));
1384         assert!(a.insert(11));
1385
1386         assert!(b.insert(3));
1387         assert!(b.insert(9));
1388
1389         let mut i = 0;
1390         let expected = [1, 5, 11];
1391         for x in a.difference(&b) {
1392             assert!(expected.contains(x));
1393             i += 1
1394         }
1395         assert_eq!(i, expected.len());
1396     }
1397
1398     #[test]
1399     fn test_symmetric_difference() {
1400         let mut a = HashSet::new();
1401         let mut b = HashSet::new();
1402
1403         assert!(a.insert(1));
1404         assert!(a.insert(3));
1405         assert!(a.insert(5));
1406         assert!(a.insert(9));
1407         assert!(a.insert(11));
1408
1409         assert!(b.insert(-2));
1410         assert!(b.insert(3));
1411         assert!(b.insert(9));
1412         assert!(b.insert(14));
1413         assert!(b.insert(22));
1414
1415         let mut i = 0;
1416         let expected = [-2, 1, 5, 11, 14, 22];
1417         for x in a.symmetric_difference(&b) {
1418             assert!(expected.contains(x));
1419             i += 1
1420         }
1421         assert_eq!(i, expected.len());
1422     }
1423
1424     #[test]
1425     fn test_union() {
1426         let mut a = HashSet::new();
1427         let mut b = HashSet::new();
1428
1429         assert!(a.insert(1));
1430         assert!(a.insert(3));
1431         assert!(a.insert(5));
1432         assert!(a.insert(9));
1433         assert!(a.insert(11));
1434         assert!(a.insert(16));
1435         assert!(a.insert(19));
1436         assert!(a.insert(24));
1437
1438         assert!(b.insert(-2));
1439         assert!(b.insert(1));
1440         assert!(b.insert(5));
1441         assert!(b.insert(9));
1442         assert!(b.insert(13));
1443         assert!(b.insert(19));
1444
1445         let mut i = 0;
1446         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1447         for x in a.union(&b) {
1448             assert!(expected.contains(x));
1449             i += 1
1450         }
1451         assert_eq!(i, expected.len());
1452     }
1453
1454     #[test]
1455     fn test_from_iter() {
1456         let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1457
1458         let set: HashSet<_> = xs.iter().cloned().collect();
1459
1460         for x in &xs {
1461             assert!(set.contains(x));
1462         }
1463     }
1464
1465     #[test]
1466     fn test_move_iter() {
1467         let hs = {
1468             let mut hs = HashSet::new();
1469
1470             hs.insert('a');
1471             hs.insert('b');
1472
1473             hs
1474         };
1475
1476         let v = hs.into_iter().collect::<Vec<char>>();
1477         assert!(v == ['a', 'b'] || v == ['b', 'a']);
1478     }
1479
1480     #[test]
1481     fn test_eq() {
1482         // These constants once happened to expose a bug in insert().
1483         // I'm keeping them around to prevent a regression.
1484         let mut s1 = HashSet::new();
1485
1486         s1.insert(1);
1487         s1.insert(2);
1488         s1.insert(3);
1489
1490         let mut s2 = HashSet::new();
1491
1492         s2.insert(1);
1493         s2.insert(2);
1494
1495         assert!(s1 != s2);
1496
1497         s2.insert(3);
1498
1499         assert_eq!(s1, s2);
1500     }
1501
1502     #[test]
1503     fn test_show() {
1504         let mut set = HashSet::new();
1505         let empty = HashSet::<i32>::new();
1506
1507         set.insert(1);
1508         set.insert(2);
1509
1510         let set_str = format!("{:?}", set);
1511
1512         assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1513         assert_eq!(format!("{:?}", empty), "{}");
1514     }
1515
1516     #[test]
1517     fn test_trivial_drain() {
1518         let mut s = HashSet::<i32>::new();
1519         for _ in s.drain() {}
1520         assert!(s.is_empty());
1521         drop(s);
1522
1523         let mut s = HashSet::<i32>::new();
1524         drop(s.drain());
1525         assert!(s.is_empty());
1526     }
1527
1528     #[test]
1529     fn test_drain() {
1530         let mut s: HashSet<_> = (1..100).collect();
1531
1532         // try this a bunch of times to make sure we don't screw up internal state.
1533         for _ in 0..20 {
1534             assert_eq!(s.len(), 99);
1535
1536             {
1537                 let mut last_i = 0;
1538                 let mut d = s.drain();
1539                 for (i, x) in d.by_ref().take(50).enumerate() {
1540                     last_i = i;
1541                     assert!(x != 0);
1542                 }
1543                 assert_eq!(last_i, 49);
1544             }
1545
1546             for _ in &s {
1547                 panic!("s should be empty!");
1548             }
1549
1550             // reset to try again.
1551             s.extend(1..100);
1552         }
1553     }
1554
1555     #[test]
1556     fn test_replace() {
1557         use hash;
1558
1559         #[derive(Debug)]
1560         struct Foo(&'static str, i32);
1561
1562         impl PartialEq for Foo {
1563             fn eq(&self, other: &Self) -> bool {
1564                 self.0 == other.0
1565             }
1566         }
1567
1568         impl Eq for Foo {}
1569
1570         impl hash::Hash for Foo {
1571             fn hash<H: hash::Hasher>(&self, h: &mut H) {
1572                 self.0.hash(h);
1573             }
1574         }
1575
1576         let mut s = HashSet::new();
1577         assert_eq!(s.replace(Foo("a", 1)), None);
1578         assert_eq!(s.len(), 1);
1579         assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
1580         assert_eq!(s.len(), 1);
1581
1582         let mut it = s.iter();
1583         assert_eq!(it.next(), Some(&Foo("a", 2)));
1584         assert_eq!(it.next(), None);
1585     }
1586
1587     #[test]
1588     fn test_extend_ref() {
1589         let mut a = HashSet::new();
1590         a.insert(1);
1591
1592         a.extend(&[2, 3, 4]);
1593
1594         assert_eq!(a.len(), 4);
1595         assert!(a.contains(&1));
1596         assert!(a.contains(&2));
1597         assert!(a.contains(&3));
1598         assert!(a.contains(&4));
1599
1600         let mut b = HashSet::new();
1601         b.insert(5);
1602         b.insert(6);
1603
1604         a.extend(&b);
1605
1606         assert_eq!(a.len(), 6);
1607         assert!(a.contains(&1));
1608         assert!(a.contains(&2));
1609         assert!(a.contains(&3));
1610         assert!(a.contains(&4));
1611         assert!(a.contains(&5));
1612         assert!(a.contains(&6));
1613     }
1614 }