]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/set.rs
rollup merge of #19577: aidancully/master
[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 // ignore-lexer-test FIXME #15883
12
13 use borrow::BorrowFrom;
14 use cmp::{Eq, Equiv, PartialEq};
15 use core::kinds::Sized;
16 use default::Default;
17 use fmt::Show;
18 use fmt;
19 use hash::{Hash, Hasher, RandomSipHasher};
20 use iter::{Iterator, IteratorExt, FromIterator, FilterMap, Chain, Repeat, Zip, Extend, repeat};
21 use iter;
22 use option::Option::{Some, None};
23 use result::Result::{Ok, Err};
24
25 use super::map::{HashMap, Entries, MoveEntries, INITIAL_CAPACITY};
26
27 // FIXME(conventions): implement BitOr, BitAnd, BitXor, and Sub
28
29
30 // Future Optimization (FIXME!)
31 // =============================
32 //
33 // Iteration over zero sized values is a noop. There is no need
34 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
35 // to get rid of it properly.
36
37 /// An implementation of a hash set using the underlying representation of a
38 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
39 /// requires that the elements implement the `Eq` and `Hash` traits.
40 ///
41 /// # Example
42 ///
43 /// ```
44 /// use std::collections::HashSet;
45 /// // Type inference lets us omit an explicit type signature (which
46 /// // would be `HashSet<&str>` in this example).
47 /// let mut books = HashSet::new();
48 ///
49 /// // Add some books.
50 /// books.insert("A Dance With Dragons");
51 /// books.insert("To Kill a Mockingbird");
52 /// books.insert("The Odyssey");
53 /// books.insert("The Great Gatsby");
54 ///
55 /// // Check for a specific one.
56 /// if !books.contains(&("The Winds of Winter")) {
57 ///     println!("We have {} books, but The Winds of Winter ain't one.",
58 ///              books.len());
59 /// }
60 ///
61 /// // Remove a book.
62 /// books.remove(&"The Odyssey");
63 ///
64 /// // Iterate over everything.
65 /// for book in books.iter() {
66 ///     println!("{}", *book);
67 /// }
68 /// ```
69 ///
70 /// The easiest way to use `HashSet` with a custom type is to derive
71 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
72 /// future be implied by `Eq`.
73 ///
74 /// ```
75 /// use std::collections::HashSet;
76 /// #[deriving(Hash, Eq, PartialEq, Show)]
77 /// struct Viking<'a> {
78 ///     name: &'a str,
79 ///     power: uint,
80 /// }
81 ///
82 /// let mut vikings = HashSet::new();
83 ///
84 /// vikings.insert(Viking { name: "Einar", power: 9u });
85 /// vikings.insert(Viking { name: "Einar", power: 9u });
86 /// vikings.insert(Viking { name: "Olaf", power: 4u });
87 /// vikings.insert(Viking { name: "Harald", power: 8u });
88 ///
89 /// // Use derived implementation to print the vikings.
90 /// for x in vikings.iter() {
91 ///     println!("{}", x);
92 /// }
93 /// ```
94 #[deriving(Clone)]
95 pub struct HashSet<T, H = RandomSipHasher> {
96     map: HashMap<T, (), H>
97 }
98
99 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
100     /// Create an empty HashSet.
101     ///
102     /// # Example
103     ///
104     /// ```
105     /// use std::collections::HashSet;
106     /// let mut set: HashSet<int> = HashSet::new();
107     /// ```
108     #[inline]
109     #[unstable = "matches collection reform specification, waiting for dust to settle"]
110     pub fn new() -> HashSet<T, RandomSipHasher> {
111         HashSet::with_capacity(INITIAL_CAPACITY)
112     }
113
114     /// Create an empty HashSet with space for at least `n` elements in
115     /// the hash table.
116     ///
117     /// # Example
118     ///
119     /// ```
120     /// use std::collections::HashSet;
121     /// let mut set: HashSet<int> = HashSet::with_capacity(10);
122     /// ```
123     #[inline]
124     #[unstable = "matches collection reform specification, waiting for dust to settle"]
125     pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
126         HashSet { map: HashMap::with_capacity(capacity) }
127     }
128 }
129
130 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
131     /// Creates a new empty hash set which will use the given hasher to hash
132     /// keys.
133     ///
134     /// The hash set is also created with the default initial capacity.
135     ///
136     /// # Example
137     ///
138     /// ```
139     /// use std::collections::HashSet;
140     /// use std::hash::sip::SipHasher;
141     ///
142     /// let h = SipHasher::new();
143     /// let mut set = HashSet::with_hasher(h);
144     /// set.insert(2u);
145     /// ```
146     #[inline]
147     pub fn with_hasher(hasher: H) -> HashSet<T, H> {
148         HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
149     }
150
151     /// Create an empty HashSet with space for at least `capacity`
152     /// elements in the hash table, using `hasher` to hash the keys.
153     ///
154     /// Warning: `hasher` is normally randomly generated, and
155     /// is designed to allow `HashSet`s to be resistant to attacks that
156     /// cause many collisions and very poor performance. Setting it
157     /// manually using this function can expose a DoS attack vector.
158     ///
159     /// # Example
160     ///
161     /// ```
162     /// use std::collections::HashSet;
163     /// use std::hash::sip::SipHasher;
164     ///
165     /// let h = SipHasher::new();
166     /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
167     /// set.insert(1i);
168     /// ```
169     #[inline]
170     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
171         HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
172     }
173
174     /// Returns the number of elements the set can hold without reallocating.
175     ///
176     /// # Example
177     ///
178     /// ```
179     /// use std::collections::HashSet;
180     /// let set: HashSet<int> = HashSet::with_capacity(100);
181     /// assert!(set.capacity() >= 100);
182     /// ```
183     #[inline]
184     #[unstable = "matches collection reform specification, waiting for dust to settle"]
185     pub fn capacity(&self) -> uint {
186         self.map.capacity()
187     }
188
189     /// Reserves capacity for at least `additional` more elements to be inserted
190     /// in the `HashSet`. The collection may reserve more space to avoid
191     /// frequent reallocations.
192     ///
193     /// # Panics
194     ///
195     /// Panics if the new allocation size overflows `uint`.
196     ///
197     /// # Example
198     ///
199     /// ```
200     /// use std::collections::HashSet;
201     /// let mut set: HashSet<int> = HashSet::new();
202     /// set.reserve(10);
203     /// ```
204     #[unstable = "matches collection reform specification, waiting for dust to settle"]
205     pub fn reserve(&mut self, additional: uint) {
206         self.map.reserve(additional)
207     }
208
209     /// Shrinks the capacity of the set as much as possible. It will drop
210     /// down as much as possible while maintaining the internal rules
211     /// and possibly leaving some space in accordance with the resize policy.
212     ///
213     /// # Example
214     ///
215     /// ```
216     /// use std::collections::HashSet;
217     ///
218     /// let mut set: HashSet<int> = HashSet::with_capacity(100);
219     /// set.insert(1);
220     /// set.insert(2);
221     /// assert!(set.capacity() >= 100);
222     /// set.shrink_to_fit();
223     /// assert!(set.capacity() >= 2);
224     /// ```
225     #[unstable = "matches collection reform specification, waiting for dust to settle"]
226     pub fn shrink_to_fit(&mut self) {
227         self.map.shrink_to_fit()
228     }
229
230     /// Deprecated: use `contains` and `BorrowFrom`.
231     #[deprecated = "use contains and BorrowFrom"]
232     #[allow(deprecated)]
233     pub fn contains_equiv<Sized? Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
234       self.map.contains_key_equiv(value)
235     }
236
237     /// An iterator visiting all elements in arbitrary order.
238     /// Iterator element type is &'a T.
239     ///
240     /// # Example
241     ///
242     /// ```
243     /// use std::collections::HashSet;
244     /// let mut set = HashSet::new();
245     /// set.insert("a");
246     /// set.insert("b");
247     ///
248     /// // Will print in an arbitrary order.
249     /// for x in set.iter() {
250     ///     println!("{}", x);
251     /// }
252     /// ```
253     #[unstable = "matches collection reform specification, waiting for dust to settle"]
254     pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
255         self.map.keys()
256     }
257
258     /// Creates a consuming iterator, that is, one that moves each value out
259     /// of the set in arbitrary order. The set cannot be used after calling
260     /// this.
261     ///
262     /// # Example
263     ///
264     /// ```
265     /// use std::collections::HashSet;
266     /// let mut set = HashSet::new();
267     /// set.insert("a".to_string());
268     /// set.insert("b".to_string());
269     ///
270     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
271     /// let v: Vec<String> = set.into_iter().collect();
272     ///
273     /// // Will print in an arbitrary order.
274     /// for x in v.iter() {
275     ///     println!("{}", x);
276     /// }
277     /// ```
278     #[unstable = "matches collection reform specification, waiting for dust to settle"]
279     pub fn into_iter(self) -> SetMoveItems<T> {
280         self.map.into_iter().map(|(k, _)| k)
281     }
282
283     /// Visit the values representing the difference.
284     ///
285     /// # Example
286     ///
287     /// ```
288     /// use std::collections::HashSet;
289     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
290     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
291     ///
292     /// // Can be seen as `a - b`.
293     /// for x in a.difference(&b) {
294     ///     println!("{}", x); // Print 1
295     /// }
296     ///
297     /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
298     /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
299     ///
300     /// // Note that difference is not symmetric,
301     /// // and `b - a` means something else:
302     /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
303     /// assert_eq!(diff, [4i].iter().map(|&x| x).collect());
304     /// ```
305     #[unstable = "matches collection reform specification, waiting for dust to settle"]
306     pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> SetAlgebraItems<'a, T, H> {
307         repeat(other).zip(self.iter())
308             .filter_map(|(other, elt)| {
309                 if !other.contains(elt) { Some(elt) } else { None }
310             })
311     }
312
313     /// Visit the values representing the symmetric difference.
314     ///
315     /// # Example
316     ///
317     /// ```
318     /// use std::collections::HashSet;
319     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
320     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
321     ///
322     /// // Print 1, 4 in arbitrary order.
323     /// for x in a.symmetric_difference(&b) {
324     ///     println!("{}", x);
325     /// }
326     ///
327     /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
328     /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
329     ///
330     /// assert_eq!(diff1, diff2);
331     /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
332     /// ```
333     #[unstable = "matches collection reform specification, waiting for dust to settle"]
334     pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
335         -> Chain<SetAlgebraItems<'a, T, H>, SetAlgebraItems<'a, T, H>> {
336         self.difference(other).chain(other.difference(self))
337     }
338
339     /// Visit the values representing the intersection.
340     ///
341     /// # Example
342     ///
343     /// ```
344     /// use std::collections::HashSet;
345     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
346     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
347     ///
348     /// // Print 2, 3 in arbitrary order.
349     /// for x in a.intersection(&b) {
350     ///     println!("{}", x);
351     /// }
352     ///
353     /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
354     /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
355     /// ```
356     #[unstable = "matches collection reform specification, waiting for dust to settle"]
357     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>)
358         -> SetAlgebraItems<'a, T, H> {
359         repeat(other).zip(self.iter())
360             .filter_map(|(other, elt)| {
361                 if other.contains(elt) { Some(elt) } else { None }
362             })
363     }
364
365     /// Visit the values representing the union.
366     ///
367     /// # Example
368     ///
369     /// ```
370     /// use std::collections::HashSet;
371     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
372     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
373     ///
374     /// // Print 1, 2, 3, 4 in arbitrary order.
375     /// for x in a.union(&b) {
376     ///     println!("{}", x);
377     /// }
378     ///
379     /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
380     /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect());
381     /// ```
382     #[unstable = "matches collection reform specification, waiting for dust to settle"]
383     pub fn union<'a>(&'a self, other: &'a HashSet<T, H>)
384         -> Chain<SetItems<'a, T>, SetAlgebraItems<'a, T, H>> {
385         self.iter().chain(other.difference(self))
386     }
387
388     /// Return the number of elements in the set
389     ///
390     /// # Example
391     ///
392     /// ```
393     /// use std::collections::HashSet;
394     ///
395     /// let mut v = HashSet::new();
396     /// assert_eq!(v.len(), 0);
397     /// v.insert(1u);
398     /// assert_eq!(v.len(), 1);
399     /// ```
400     #[unstable = "matches collection reform specification, waiting for dust to settle"]
401     pub fn len(&self) -> uint { self.map.len() }
402
403     /// Returns true if the set contains no elements
404     ///
405     /// # Example
406     ///
407     /// ```
408     /// use std::collections::HashSet;
409     ///
410     /// let mut v = HashSet::new();
411     /// assert!(v.is_empty());
412     /// v.insert(1u);
413     /// assert!(!v.is_empty());
414     /// ```
415     #[unstable = "matches collection reform specification, waiting for dust to settle"]
416     pub fn is_empty(&self) -> bool { self.map.len() == 0 }
417
418     /// Clears the set, removing all values.
419     ///
420     /// # Example
421     ///
422     /// ```
423     /// use std::collections::HashSet;
424     ///
425     /// let mut v = HashSet::new();
426     /// v.insert(1u);
427     /// v.clear();
428     /// assert!(v.is_empty());
429     /// ```
430     #[unstable = "matches collection reform specification, waiting for dust to settle"]
431     pub fn clear(&mut self) { self.map.clear() }
432
433     /// Returns `true` if the set contains a value.
434     ///
435     /// The value may be any borrowed form of the set's value type, but
436     /// `Hash` and `Eq` on the borrowed form *must* match those for
437     /// the value type.
438     ///
439     /// # Example
440     ///
441     /// ```
442     /// use std::collections::HashSet;
443     ///
444     /// let set: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
445     /// assert_eq!(set.contains(&1), true);
446     /// assert_eq!(set.contains(&4), false);
447     /// ```
448     #[unstable = "matches collection reform specification, waiting for dust to settle"]
449     pub fn contains<Sized? Q>(&self, value: &Q) -> bool
450         where Q: BorrowFrom<T> + Hash<S> + Eq
451     {
452         self.map.contains_key(value)
453     }
454
455     /// Returns `true` if the set has no elements in common with `other`.
456     /// This is equivalent to checking for an empty intersection.
457     ///
458     /// # Example
459     ///
460     /// ```
461     /// use std::collections::HashSet;
462     ///
463     /// let a: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
464     /// let mut b: HashSet<uint> = HashSet::new();
465     ///
466     /// assert_eq!(a.is_disjoint(&b), true);
467     /// b.insert(4);
468     /// assert_eq!(a.is_disjoint(&b), true);
469     /// b.insert(1);
470     /// assert_eq!(a.is_disjoint(&b), false);
471     /// ```
472     #[unstable = "matches collection reform specification, waiting for dust to settle"]
473     pub fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
474         self.iter().all(|v| !other.contains(v))
475     }
476
477     /// Returns `true` if the set is a subset of another.
478     ///
479     /// # Example
480     ///
481     /// ```
482     /// use std::collections::HashSet;
483     ///
484     /// let sup: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
485     /// let mut set: HashSet<uint> = HashSet::new();
486     ///
487     /// assert_eq!(set.is_subset(&sup), true);
488     /// set.insert(2);
489     /// assert_eq!(set.is_subset(&sup), true);
490     /// set.insert(4);
491     /// assert_eq!(set.is_subset(&sup), false);
492     /// ```
493     #[unstable = "matches collection reform specification, waiting for dust to settle"]
494     pub fn is_subset(&self, other: &HashSet<T, H>) -> bool {
495         self.iter().all(|v| other.contains(v))
496     }
497
498     /// Returns `true` if the set is a superset of another.
499     ///
500     /// # Example
501     ///
502     /// ```
503     /// use std::collections::HashSet;
504     ///
505     /// let sub: HashSet<uint> = [1, 2].iter().map(|&x| x).collect();
506     /// let mut set: HashSet<uint> = HashSet::new();
507     ///
508     /// assert_eq!(set.is_superset(&sub), false);
509     ///
510     /// set.insert(0);
511     /// set.insert(1);
512     /// assert_eq!(set.is_superset(&sub), false);
513     ///
514     /// set.insert(2);
515     /// assert_eq!(set.is_superset(&sub), true);
516     /// ```
517     #[inline]
518     #[unstable = "matches collection reform specification, waiting for dust to settle"]
519     pub fn is_superset(&self, other: &HashSet<T, H>) -> bool {
520         other.is_subset(self)
521     }
522
523     /// Adds a value to the set. Returns `true` if the value was not already
524     /// present in the set.
525     ///
526     /// # Example
527     ///
528     /// ```
529     /// use std::collections::HashSet;
530     ///
531     /// let mut set = HashSet::new();
532     ///
533     /// assert_eq!(set.insert(2u), true);
534     /// assert_eq!(set.insert(2), false);
535     /// assert_eq!(set.len(), 1);
536     /// ```
537     #[unstable = "matches collection reform specification, waiting for dust to settle"]
538     pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
539
540     /// Removes a value from the set. Returns `true` if the value was
541     /// present in the set.
542     ///
543     /// The value may be any borrowed form of the set's value type, but
544     /// `Hash` and `Eq` on the borrowed form *must* match those for
545     /// the value type.
546     ///
547     /// # Example
548     ///
549     /// ```
550     /// use std::collections::HashSet;
551     ///
552     /// let mut set = HashSet::new();
553     ///
554     /// set.insert(2u);
555     /// assert_eq!(set.remove(&2), true);
556     /// assert_eq!(set.remove(&2), false);
557     /// ```
558     #[unstable = "matches collection reform specification, waiting for dust to settle"]
559     pub fn remove<Sized? Q>(&mut self, value: &Q) -> bool
560         where Q: BorrowFrom<T> + Hash<S> + Eq
561     {
562         self.map.remove(value).is_some()
563     }
564 }
565
566 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
567     fn eq(&self, other: &HashSet<T, H>) -> bool {
568         if self.len() != other.len() { return false; }
569
570         self.iter().all(|key| other.contains(key))
571     }
572 }
573
574 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
575
576 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
577     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
578         try!(write!(f, "{{"));
579
580         for (i, x) in self.iter().enumerate() {
581             if i != 0 { try!(write!(f, ", ")); }
582             try!(write!(f, "{}", *x));
583         }
584
585         write!(f, "}}")
586     }
587 }
588
589 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
590     fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
591         let (lower, _) = iter.size_hint();
592         let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
593         set.extend(iter);
594         set
595     }
596 }
597
598 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extend<T> for HashSet<T, H> {
599     fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
600         for k in iter {
601             self.insert(k);
602         }
603     }
604 }
605
606 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
607     fn default() -> HashSet<T, H> {
608         HashSet::with_hasher(Default::default())
609     }
610 }
611
612 /// HashSet iterator
613 pub type SetItems<'a, K> =
614     iter::Map<'static, (&'a K, &'a ()), &'a K, Entries<'a, K, ()>>;
615
616 /// HashSet move iterator
617 pub type SetMoveItems<K> =
618     iter::Map<'static, (K, ()), K, MoveEntries<K, ()>>;
619
620 // `Repeat` is used to feed the filter closure an explicit capture
621 // of a reference to the other set
622 /// Set operations iterator
623 pub type SetAlgebraItems<'a, T, H> =
624     FilterMap<'static, (&'a HashSet<T, H>, &'a T), &'a T,
625               Zip<Repeat<&'a HashSet<T, H>>, SetItems<'a, T>>>;
626
627 #[cfg(test)]
628 mod test_set {
629     use prelude::*;
630
631     use super::HashSet;
632     use slice::PartialEqSlicePrelude;
633
634     #[test]
635     fn test_disjoint() {
636         let mut xs = HashSet::new();
637         let mut ys = HashSet::new();
638         assert!(xs.is_disjoint(&ys));
639         assert!(ys.is_disjoint(&xs));
640         assert!(xs.insert(5i));
641         assert!(ys.insert(11i));
642         assert!(xs.is_disjoint(&ys));
643         assert!(ys.is_disjoint(&xs));
644         assert!(xs.insert(7));
645         assert!(xs.insert(19));
646         assert!(xs.insert(4));
647         assert!(ys.insert(2));
648         assert!(ys.insert(-11));
649         assert!(xs.is_disjoint(&ys));
650         assert!(ys.is_disjoint(&xs));
651         assert!(ys.insert(7));
652         assert!(!xs.is_disjoint(&ys));
653         assert!(!ys.is_disjoint(&xs));
654     }
655
656     #[test]
657     fn test_subset_and_superset() {
658         let mut a = HashSet::new();
659         assert!(a.insert(0i));
660         assert!(a.insert(5));
661         assert!(a.insert(11));
662         assert!(a.insert(7));
663
664         let mut b = HashSet::new();
665         assert!(b.insert(0i));
666         assert!(b.insert(7));
667         assert!(b.insert(19));
668         assert!(b.insert(250));
669         assert!(b.insert(11));
670         assert!(b.insert(200));
671
672         assert!(!a.is_subset(&b));
673         assert!(!a.is_superset(&b));
674         assert!(!b.is_subset(&a));
675         assert!(!b.is_superset(&a));
676
677         assert!(b.insert(5));
678
679         assert!(a.is_subset(&b));
680         assert!(!a.is_superset(&b));
681         assert!(!b.is_subset(&a));
682         assert!(b.is_superset(&a));
683     }
684
685     #[test]
686     fn test_iterate() {
687         let mut a = HashSet::new();
688         for i in range(0u, 32) {
689             assert!(a.insert(i));
690         }
691         let mut observed: u32 = 0;
692         for k in a.iter() {
693             observed |= 1 << *k;
694         }
695         assert_eq!(observed, 0xFFFF_FFFF);
696     }
697
698     #[test]
699     fn test_intersection() {
700         let mut a = HashSet::new();
701         let mut b = HashSet::new();
702
703         assert!(a.insert(11i));
704         assert!(a.insert(1));
705         assert!(a.insert(3));
706         assert!(a.insert(77));
707         assert!(a.insert(103));
708         assert!(a.insert(5));
709         assert!(a.insert(-5));
710
711         assert!(b.insert(2i));
712         assert!(b.insert(11));
713         assert!(b.insert(77));
714         assert!(b.insert(-9));
715         assert!(b.insert(-42));
716         assert!(b.insert(5));
717         assert!(b.insert(3));
718
719         let mut i = 0;
720         let expected = [3, 5, 11, 77];
721         for x in a.intersection(&b) {
722             assert!(expected.contains(x));
723             i += 1
724         }
725         assert_eq!(i, expected.len());
726     }
727
728     #[test]
729     fn test_difference() {
730         let mut a = HashSet::new();
731         let mut b = HashSet::new();
732
733         assert!(a.insert(1i));
734         assert!(a.insert(3));
735         assert!(a.insert(5));
736         assert!(a.insert(9));
737         assert!(a.insert(11));
738
739         assert!(b.insert(3i));
740         assert!(b.insert(9));
741
742         let mut i = 0;
743         let expected = [1, 5, 11];
744         for x in a.difference(&b) {
745             assert!(expected.contains(x));
746             i += 1
747         }
748         assert_eq!(i, expected.len());
749     }
750
751     #[test]
752     fn test_symmetric_difference() {
753         let mut a = HashSet::new();
754         let mut b = HashSet::new();
755
756         assert!(a.insert(1i));
757         assert!(a.insert(3));
758         assert!(a.insert(5));
759         assert!(a.insert(9));
760         assert!(a.insert(11));
761
762         assert!(b.insert(-2i));
763         assert!(b.insert(3));
764         assert!(b.insert(9));
765         assert!(b.insert(14));
766         assert!(b.insert(22));
767
768         let mut i = 0;
769         let expected = [-2, 1, 5, 11, 14, 22];
770         for x in a.symmetric_difference(&b) {
771             assert!(expected.contains(x));
772             i += 1
773         }
774         assert_eq!(i, expected.len());
775     }
776
777     #[test]
778     fn test_union() {
779         let mut a = HashSet::new();
780         let mut b = HashSet::new();
781
782         assert!(a.insert(1i));
783         assert!(a.insert(3));
784         assert!(a.insert(5));
785         assert!(a.insert(9));
786         assert!(a.insert(11));
787         assert!(a.insert(16));
788         assert!(a.insert(19));
789         assert!(a.insert(24));
790
791         assert!(b.insert(-2i));
792         assert!(b.insert(1));
793         assert!(b.insert(5));
794         assert!(b.insert(9));
795         assert!(b.insert(13));
796         assert!(b.insert(19));
797
798         let mut i = 0;
799         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
800         for x in a.union(&b) {
801             assert!(expected.contains(x));
802             i += 1
803         }
804         assert_eq!(i, expected.len());
805     }
806
807     #[test]
808     fn test_from_iter() {
809         let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
810
811         let set: HashSet<int> = xs.iter().map(|&x| x).collect();
812
813         for x in xs.iter() {
814             assert!(set.contains(x));
815         }
816     }
817
818     #[test]
819     fn test_move_iter() {
820         let hs = {
821             let mut hs = HashSet::new();
822
823             hs.insert('a');
824             hs.insert('b');
825
826             hs
827         };
828
829         let v = hs.into_iter().collect::<Vec<char>>();
830         assert!(['a', 'b'] == v || ['b', 'a'] == v);
831     }
832
833     #[test]
834     fn test_eq() {
835         // These constants once happened to expose a bug in insert().
836         // I'm keeping them around to prevent a regression.
837         let mut s1 = HashSet::new();
838
839         s1.insert(1i);
840         s1.insert(2);
841         s1.insert(3);
842
843         let mut s2 = HashSet::new();
844
845         s2.insert(1i);
846         s2.insert(2);
847
848         assert!(s1 != s2);
849
850         s2.insert(3);
851
852         assert_eq!(s1, s2);
853     }
854
855     #[test]
856     fn test_show() {
857         let mut set: HashSet<int> = HashSet::new();
858         let empty: HashSet<int> = HashSet::new();
859
860         set.insert(1i);
861         set.insert(2);
862
863         let set_str = format!("{}", set);
864
865         assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
866         assert_eq!(format!("{}", empty), "{}");
867     }
868 }