]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hashmap/set.rs
rollup merge of #17355 : gamazeps/issue17210
[rust.git] / src / libstd / collections / hashmap / 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 clone::Clone;
14 use cmp::{Eq, Equiv, PartialEq};
15 use collections::{Collection, Mutable, Set, MutableSet, Map, MutableMap};
16 use default::Default;
17 use fmt::Show;
18 use fmt;
19 use hash::{Hash, Hasher, RandomSipHasher};
20 use iter::{Iterator, FromIterator, FilterMap, Chain, Repeat, Zip, Extendable};
21 use iter;
22 use option::{Some, None};
23 use result::{Ok, Err};
24
25 use super::{HashMap, Entries, MoveEntries, INITIAL_CAPACITY};
26
27
28 // Future Optimization (FIXME!)
29 // =============================
30 //
31 // Iteration over zero sized values is a noop. There is no need
32 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
33 // to get rid of it properly.
34
35 /// An implementation of a hash set using the underlying representation of a
36 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
37 /// requires that the elements implement the `Eq` and `Hash` traits.
38 ///
39 /// # Example
40 ///
41 /// ```
42 /// use std::collections::HashSet;
43 /// // Type inference lets us omit an explicit type signature (which
44 /// // would be `HashSet<&str>` in this example).
45 /// let mut books = HashSet::new();
46 ///
47 /// // Add some books.
48 /// books.insert("A Dance With Dragons");
49 /// books.insert("To Kill a Mockingbird");
50 /// books.insert("The Odyssey");
51 /// books.insert("The Great Gatsby");
52 ///
53 /// // Check for a specific one.
54 /// if !books.contains(&("The Winds of Winter")) {
55 ///     println!("We have {} books, but The Winds of Winter ain't one.",
56 ///              books.len());
57 /// }
58 ///
59 /// // Remove a book.
60 /// books.remove(&"The Odyssey");
61 ///
62 /// // Iterate over everything.
63 /// for book in books.iter() {
64 ///     println!("{}", *book);
65 /// }
66 /// ```
67 ///
68 /// The easiest way to use `HashSet` with a custom type is to derive
69 /// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
70 /// future be implied by `Eq`.
71 ///
72 /// ```
73 /// use std::collections::HashSet;
74 /// #[deriving(Hash, Eq, PartialEq, Show)]
75 /// struct Viking<'a> {
76 ///     name: &'a str,
77 ///     power: uint,
78 /// }
79 ///
80 /// let mut vikings = HashSet::new();
81 ///
82 /// vikings.insert(Viking { name: "Einar", power: 9u });
83 /// vikings.insert(Viking { name: "Einar", power: 9u });
84 /// vikings.insert(Viking { name: "Olaf", power: 4u });
85 /// vikings.insert(Viking { name: "Harald", power: 8u });
86 ///
87 /// // Use derived implementation to print the vikings.
88 /// for x in vikings.iter() {
89 ///     println!("{}", x);
90 /// }
91 /// ```
92 #[deriving(Clone)]
93 pub struct HashSet<T, H = RandomSipHasher> {
94     map: HashMap<T, (), H>
95 }
96
97 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
98     /// Create an empty HashSet.
99     ///
100     /// # Example
101     ///
102     /// ```
103     /// use std::collections::HashSet;
104     /// let mut set: HashSet<int> = HashSet::new();
105     /// ```
106     #[inline]
107     pub fn new() -> HashSet<T, RandomSipHasher> {
108         HashSet::with_capacity(INITIAL_CAPACITY)
109     }
110
111     /// Create an empty HashSet with space for at least `n` elements in
112     /// the hash table.
113     ///
114     /// # Example
115     ///
116     /// ```
117     /// use std::collections::HashSet;
118     /// let mut set: HashSet<int> = HashSet::with_capacity(10);
119     /// ```
120     #[inline]
121     pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
122         HashSet { map: HashMap::with_capacity(capacity) }
123     }
124 }
125
126 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
127     /// Creates a new empty hash set which will use the given hasher to hash
128     /// keys.
129     ///
130     /// The hash set is also created with the default initial capacity.
131     ///
132     /// # Example
133     ///
134     /// ```
135     /// use std::collections::HashSet;
136     /// use std::hash::sip::SipHasher;
137     ///
138     /// let h = SipHasher::new();
139     /// let mut set = HashSet::with_hasher(h);
140     /// set.insert(2u);
141     /// ```
142     #[inline]
143     pub fn with_hasher(hasher: H) -> HashSet<T, H> {
144         HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
145     }
146
147     /// Create an empty HashSet with space for at least `capacity`
148     /// elements in the hash table, using `hasher` to hash the keys.
149     ///
150     /// Warning: `hasher` is normally randomly generated, and
151     /// is designed to allow `HashSet`s to be resistant to attacks that
152     /// cause many collisions and very poor performance. Setting it
153     /// manually using this function can expose a DoS attack vector.
154     ///
155     /// # Example
156     ///
157     /// ```
158     /// use std::collections::HashSet;
159     /// use std::hash::sip::SipHasher;
160     ///
161     /// let h = SipHasher::new();
162     /// let mut set = HashSet::with_capacity_and_hasher(10u, h);
163     /// set.insert(1i);
164     /// ```
165     #[inline]
166     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
167         HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
168     }
169
170     /// Reserve space for at least `n` elements in the hash table.
171     ///
172     /// # Example
173     ///
174     /// ```
175     /// use std::collections::HashSet;
176     /// let mut set: HashSet<int> = HashSet::new();
177     /// set.reserve(10);
178     /// ```
179     pub fn reserve(&mut self, n: uint) {
180         self.map.reserve(n)
181     }
182
183     /// Returns true if the hash set contains a value equivalent to the
184     /// given query value.
185     ///
186     /// # Example
187     ///
188     /// This is a slightly silly example where we define the number's
189     /// parity as the equivilance class. It is important that the
190     /// values hash the same, which is why we implement `Hash`.
191     ///
192     /// ```
193     /// use std::collections::HashSet;
194     /// use std::hash::Hash;
195     /// use std::hash::sip::SipState;
196     ///
197     /// #[deriving(Eq, PartialEq)]
198     /// struct EvenOrOdd {
199     ///     num: uint
200     /// };
201     ///
202     /// impl Hash for EvenOrOdd {
203     ///     fn hash(&self, state: &mut SipState) {
204     ///         let parity = self.num % 2;
205     ///         parity.hash(state);
206     ///     }
207     /// }
208     ///
209     /// impl Equiv<EvenOrOdd> for EvenOrOdd {
210     ///     fn equiv(&self, other: &EvenOrOdd) -> bool {
211     ///         self.num % 2 == other.num % 2
212     ///     }
213     /// }
214     ///
215     /// let mut set = HashSet::new();
216     /// set.insert(EvenOrOdd { num: 3u });
217     ///
218     /// assert!(set.contains_equiv(&EvenOrOdd { num: 3u }));
219     /// assert!(set.contains_equiv(&EvenOrOdd { num: 5u }));
220     /// assert!(!set.contains_equiv(&EvenOrOdd { num: 4u }));
221     /// assert!(!set.contains_equiv(&EvenOrOdd { num: 2u }));
222     ///
223     /// ```
224     pub fn contains_equiv<Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
225       self.map.contains_key_equiv(value)
226     }
227
228     /// An iterator visiting all elements in arbitrary order.
229     /// Iterator element type is &'a T.
230     ///
231     /// # Example
232     ///
233     /// ```
234     /// use std::collections::HashSet;
235     /// let mut set = HashSet::new();
236     /// set.insert("a");
237     /// set.insert("b");
238     ///
239     /// // Will print in an arbitrary order.
240     /// for x in set.iter() {
241     ///     println!("{}", x);
242     /// }
243     /// ```
244     pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
245         self.map.keys()
246     }
247
248     /// Deprecated: use `into_iter`.
249     #[deprecated = "use into_iter"]
250     pub fn move_iter(self) -> SetMoveItems<T> {
251         self.into_iter()
252     }
253
254     /// Creates a consuming iterator, that is, one that moves each value out
255     /// of the set in arbitrary order. The set cannot be used after calling
256     /// this.
257     ///
258     /// # Example
259     ///
260     /// ```
261     /// use std::collections::HashSet;
262     /// let mut set = HashSet::new();
263     /// set.insert("a".to_string());
264     /// set.insert("b".to_string());
265     ///
266     /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
267     /// let v: Vec<String> = set.into_iter().collect();
268     ///
269     /// // Will print in an arbitrary order.
270     /// for x in v.iter() {
271     ///     println!("{}", x);
272     /// }
273     /// ```
274     pub fn into_iter(self) -> SetMoveItems<T> {
275         self.map.into_iter().map(|(k, _)| k)
276     }
277
278     /// Visit the values representing the difference.
279     ///
280     /// # Example
281     ///
282     /// ```
283     /// use std::collections::HashSet;
284     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
285     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
286     ///
287     /// // Can be seen as `a - b`.
288     /// for x in a.difference(&b) {
289     ///     println!("{}", x); // Print 1
290     /// }
291     ///
292     /// let diff: HashSet<int> = a.difference(&b).map(|&x| x).collect();
293     /// assert_eq!(diff, [1i].iter().map(|&x| x).collect());
294     ///
295     /// // Note that difference is not symmetric,
296     /// // and `b - a` means something else:
297     /// let diff: HashSet<int> = b.difference(&a).map(|&x| x).collect();
298     /// assert_eq!(diff, [4i].iter().map(|&x| x).collect());
299     /// ```
300     pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> SetAlgebraItems<'a, T, H> {
301         Repeat::new(other).zip(self.iter())
302             .filter_map(|(other, elt)| {
303                 if !other.contains(elt) { Some(elt) } else { None }
304             })
305     }
306
307     /// Visit the values representing the symmetric difference.
308     ///
309     /// # Example
310     ///
311     /// ```
312     /// use std::collections::HashSet;
313     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
314     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
315     ///
316     /// // Print 1, 4 in arbitrary order.
317     /// for x in a.symmetric_difference(&b) {
318     ///     println!("{}", x);
319     /// }
320     ///
321     /// let diff1: HashSet<int> = a.symmetric_difference(&b).map(|&x| x).collect();
322     /// let diff2: HashSet<int> = b.symmetric_difference(&a).map(|&x| x).collect();
323     ///
324     /// assert_eq!(diff1, diff2);
325     /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect());
326     /// ```
327     pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
328         -> Chain<SetAlgebraItems<'a, T, H>, SetAlgebraItems<'a, T, H>> {
329         self.difference(other).chain(other.difference(self))
330     }
331
332     /// Visit the values representing the intersection.
333     ///
334     /// # Example
335     ///
336     /// ```
337     /// use std::collections::HashSet;
338     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
339     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
340     ///
341     /// // Print 2, 3 in arbitrary order.
342     /// for x in a.intersection(&b) {
343     ///     println!("{}", x);
344     /// }
345     ///
346     /// let diff: HashSet<int> = a.intersection(&b).map(|&x| x).collect();
347     /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect());
348     /// ```
349     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>)
350         -> SetAlgebraItems<'a, T, H> {
351         Repeat::new(other).zip(self.iter())
352             .filter_map(|(other, elt)| {
353                 if other.contains(elt) { Some(elt) } else { None }
354             })
355     }
356
357     /// Visit the values representing the union.
358     ///
359     /// # Example
360     ///
361     /// ```
362     /// use std::collections::HashSet;
363     /// let a: HashSet<int> = [1i, 2, 3].iter().map(|&x| x).collect();
364     /// let b: HashSet<int> = [4i, 2, 3, 4].iter().map(|&x| x).collect();
365     ///
366     /// // Print 1, 2, 3, 4 in arbitrary order.
367     /// for x in a.union(&b) {
368     ///     println!("{}", x);
369     /// }
370     ///
371     /// let diff: HashSet<int> = a.union(&b).map(|&x| x).collect();
372     /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect());
373     /// ```
374     pub fn union<'a>(&'a self, other: &'a HashSet<T, H>)
375         -> Chain<SetItems<'a, T>, SetAlgebraItems<'a, T, H>> {
376         self.iter().chain(other.difference(self))
377     }
378 }
379
380 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
381     fn eq(&self, other: &HashSet<T, H>) -> bool {
382         if self.len() != other.len() { return false; }
383
384         self.iter().all(|key| other.contains(key))
385     }
386 }
387
388 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
389
390 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Collection for HashSet<T, H> {
391     fn len(&self) -> uint { self.map.len() }
392 }
393
394 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Mutable for HashSet<T, H> {
395     fn clear(&mut self) { self.map.clear() }
396 }
397
398 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Set<T> for HashSet<T, H> {
399     fn contains(&self, value: &T) -> bool { self.map.contains_key(value) }
400
401     fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
402         self.iter().all(|v| !other.contains(v))
403     }
404
405     fn is_subset(&self, other: &HashSet<T, H>) -> bool {
406         self.iter().all(|v| other.contains(v))
407     }
408 }
409
410 impl<T: Eq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> {
411     fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) }
412
413     fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
414 }
415
416 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
417     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418         try!(write!(f, "{{"));
419
420         for (i, x) in self.iter().enumerate() {
421             if i != 0 { try!(write!(f, ", ")); }
422             try!(write!(f, "{}", *x));
423         }
424
425         write!(f, "}}")
426     }
427 }
428
429 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
430     fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
431         let (lower, _) = iter.size_hint();
432         let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
433         set.extend(iter);
434         set
435     }
436 }
437
438 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H> {
439     fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
440         for k in iter {
441             self.insert(k);
442         }
443     }
444 }
445
446 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
447     fn default() -> HashSet<T, H> {
448         HashSet::with_hasher(Default::default())
449     }
450 }
451
452 /// HashSet iterator
453 pub type SetItems<'a, K> =
454     iter::Map<'static, (&'a K, &'a ()), &'a K, Entries<'a, K, ()>>;
455
456 /// HashSet move iterator
457 pub type SetMoveItems<K> =
458     iter::Map<'static, (K, ()), K, MoveEntries<K, ()>>;
459
460 // `Repeat` is used to feed the filter closure an explicit capture
461 // of a reference to the other set
462 /// Set operations iterator
463 pub type SetAlgebraItems<'a, T, H> =
464     FilterMap<'static, (&'a HashSet<T, H>, &'a T), &'a T,
465               Zip<Repeat<&'a HashSet<T, H>>, SetItems<'a, T>>>;
466
467 #[cfg(test)]
468 mod test_set {
469     use prelude::*;
470
471     use super::HashSet;
472     use slice::ImmutablePartialEqSlice;
473     use collections::Collection;
474
475     #[test]
476     fn test_disjoint() {
477         let mut xs = HashSet::new();
478         let mut ys = HashSet::new();
479         assert!(xs.is_disjoint(&ys));
480         assert!(ys.is_disjoint(&xs));
481         assert!(xs.insert(5i));
482         assert!(ys.insert(11i));
483         assert!(xs.is_disjoint(&ys));
484         assert!(ys.is_disjoint(&xs));
485         assert!(xs.insert(7));
486         assert!(xs.insert(19));
487         assert!(xs.insert(4));
488         assert!(ys.insert(2));
489         assert!(ys.insert(-11));
490         assert!(xs.is_disjoint(&ys));
491         assert!(ys.is_disjoint(&xs));
492         assert!(ys.insert(7));
493         assert!(!xs.is_disjoint(&ys));
494         assert!(!ys.is_disjoint(&xs));
495     }
496
497     #[test]
498     fn test_subset_and_superset() {
499         let mut a = HashSet::new();
500         assert!(a.insert(0i));
501         assert!(a.insert(5));
502         assert!(a.insert(11));
503         assert!(a.insert(7));
504
505         let mut b = HashSet::new();
506         assert!(b.insert(0i));
507         assert!(b.insert(7));
508         assert!(b.insert(19));
509         assert!(b.insert(250));
510         assert!(b.insert(11));
511         assert!(b.insert(200));
512
513         assert!(!a.is_subset(&b));
514         assert!(!a.is_superset(&b));
515         assert!(!b.is_subset(&a));
516         assert!(!b.is_superset(&a));
517
518         assert!(b.insert(5));
519
520         assert!(a.is_subset(&b));
521         assert!(!a.is_superset(&b));
522         assert!(!b.is_subset(&a));
523         assert!(b.is_superset(&a));
524     }
525
526     #[test]
527     fn test_iterate() {
528         let mut a = HashSet::new();
529         for i in range(0u, 32) {
530             assert!(a.insert(i));
531         }
532         let mut observed: u32 = 0;
533         for k in a.iter() {
534             observed |= 1 << *k;
535         }
536         assert_eq!(observed, 0xFFFF_FFFF);
537     }
538
539     #[test]
540     fn test_intersection() {
541         let mut a = HashSet::new();
542         let mut b = HashSet::new();
543
544         assert!(a.insert(11i));
545         assert!(a.insert(1));
546         assert!(a.insert(3));
547         assert!(a.insert(77));
548         assert!(a.insert(103));
549         assert!(a.insert(5));
550         assert!(a.insert(-5));
551
552         assert!(b.insert(2i));
553         assert!(b.insert(11));
554         assert!(b.insert(77));
555         assert!(b.insert(-9));
556         assert!(b.insert(-42));
557         assert!(b.insert(5));
558         assert!(b.insert(3));
559
560         let mut i = 0;
561         let expected = [3, 5, 11, 77];
562         for x in a.intersection(&b) {
563             assert!(expected.contains(x));
564             i += 1
565         }
566         assert_eq!(i, expected.len());
567     }
568
569     #[test]
570     fn test_difference() {
571         let mut a = HashSet::new();
572         let mut b = HashSet::new();
573
574         assert!(a.insert(1i));
575         assert!(a.insert(3));
576         assert!(a.insert(5));
577         assert!(a.insert(9));
578         assert!(a.insert(11));
579
580         assert!(b.insert(3i));
581         assert!(b.insert(9));
582
583         let mut i = 0;
584         let expected = [1, 5, 11];
585         for x in a.difference(&b) {
586             assert!(expected.contains(x));
587             i += 1
588         }
589         assert_eq!(i, expected.len());
590     }
591
592     #[test]
593     fn test_symmetric_difference() {
594         let mut a = HashSet::new();
595         let mut b = HashSet::new();
596
597         assert!(a.insert(1i));
598         assert!(a.insert(3));
599         assert!(a.insert(5));
600         assert!(a.insert(9));
601         assert!(a.insert(11));
602
603         assert!(b.insert(-2i));
604         assert!(b.insert(3));
605         assert!(b.insert(9));
606         assert!(b.insert(14));
607         assert!(b.insert(22));
608
609         let mut i = 0;
610         let expected = [-2, 1, 5, 11, 14, 22];
611         for x in a.symmetric_difference(&b) {
612             assert!(expected.contains(x));
613             i += 1
614         }
615         assert_eq!(i, expected.len());
616     }
617
618     #[test]
619     fn test_union() {
620         let mut a = HashSet::new();
621         let mut b = HashSet::new();
622
623         assert!(a.insert(1i));
624         assert!(a.insert(3));
625         assert!(a.insert(5));
626         assert!(a.insert(9));
627         assert!(a.insert(11));
628         assert!(a.insert(16));
629         assert!(a.insert(19));
630         assert!(a.insert(24));
631
632         assert!(b.insert(-2i));
633         assert!(b.insert(1));
634         assert!(b.insert(5));
635         assert!(b.insert(9));
636         assert!(b.insert(13));
637         assert!(b.insert(19));
638
639         let mut i = 0;
640         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
641         for x in a.union(&b) {
642             assert!(expected.contains(x));
643             i += 1
644         }
645         assert_eq!(i, expected.len());
646     }
647
648     #[test]
649     fn test_from_iter() {
650         let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
651
652         let set: HashSet<int> = xs.iter().map(|&x| x).collect();
653
654         for x in xs.iter() {
655             assert!(set.contains(x));
656         }
657     }
658
659     #[test]
660     fn test_move_iter() {
661         let hs = {
662             let mut hs = HashSet::new();
663
664             hs.insert('a');
665             hs.insert('b');
666
667             hs
668         };
669
670         let v = hs.into_iter().collect::<Vec<char>>();
671         assert!(['a', 'b'] == v.as_slice() || ['b', 'a'] == v.as_slice());
672     }
673
674     #[test]
675     fn test_eq() {
676         // These constants once happened to expose a bug in insert().
677         // I'm keeping them around to prevent a regression.
678         let mut s1 = HashSet::new();
679
680         s1.insert(1i);
681         s1.insert(2);
682         s1.insert(3);
683
684         let mut s2 = HashSet::new();
685
686         s2.insert(1i);
687         s2.insert(2);
688
689         assert!(s1 != s2);
690
691         s2.insert(3);
692
693         assert_eq!(s1, s2);
694     }
695
696     #[test]
697     fn test_show() {
698         let mut set: HashSet<int> = HashSet::new();
699         let empty: HashSet<int> = HashSet::new();
700
701         set.insert(1i);
702         set.insert(2);
703
704         let set_str = format!("{}", set);
705
706         assert!(set_str == "{1, 2}".to_string() || set_str == "{2, 1}".to_string());
707         assert_eq!(format!("{}", empty), "{}".to_string());
708     }
709 }