]> git.proxmox.com Git - rustc.git/blame - src/libstd/collections/hash/set.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / libstd / collections / hash / set.rs
CommitLineData
1a4d82fc
JJ
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.
1a4d82fc 10
85aaf69f 11use borrow::Borrow;
1a4d82fc
JJ
12use clone::Clone;
13use cmp::{Eq, PartialEq};
14use core::marker::Sized;
15use default::Default;
85aaf69f 16use fmt::Debug;
1a4d82fc 17use fmt;
85aaf69f 18use hash::Hash;
c34b1796 19use iter::{Iterator, IntoIterator, ExactSizeIterator, FromIterator, Map, Chain, Extend};
1a4d82fc
JJ
20use ops::{BitOr, BitAnd, BitXor, Sub};
21use option::Option::{Some, None, self};
22
62682a34 23use super::map::{self, HashMap, Keys, RandomState};
1a4d82fc
JJ
24use super::state::HashState;
25
62682a34
SL
26const INITIAL_CAPACITY: usize = 32;
27
1a4d82fc
JJ
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
d9579d0f
AL
36/// HashMap where the value is ().
37///
38/// As with the `HashMap` type, a `HashSet` requires that the elements
39/// implement the `Eq` and `Hash` traits. This can frequently be achieved by
40/// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
41/// it is important that the following property holds:
c34b1796
AL
42///
43/// ```text
44/// k1 == k2 -> hash(k1) == hash(k2)
45/// ```
46///
47/// In other words, if two keys are equal, their hashes must be equal.
1a4d82fc 48///
c34b1796
AL
49///
50/// It is a logic error for an item to be modified in such a way that the
51/// item's hash, as determined by the `Hash` trait, or its equality, as
52/// determined by the `Eq` trait, changes while it is in the set. This is
53/// normally only possible through `Cell`, `RefCell`, global state, I/O, or
54/// unsafe code.
55///
56/// # Examples
1a4d82fc
JJ
57///
58/// ```
59/// use std::collections::HashSet;
60/// // Type inference lets us omit an explicit type signature (which
61/// // would be `HashSet<&str>` in this example).
62/// let mut books = HashSet::new();
63///
64/// // Add some books.
65/// books.insert("A Dance With Dragons");
66/// books.insert("To Kill a Mockingbird");
67/// books.insert("The Odyssey");
68/// books.insert("The Great Gatsby");
69///
70/// // Check for a specific one.
d9579d0f 71/// if !books.contains("The Winds of Winter") {
1a4d82fc
JJ
72/// println!("We have {} books, but The Winds of Winter ain't one.",
73/// books.len());
74/// }
75///
76/// // Remove a book.
d9579d0f 77/// books.remove("The Odyssey");
1a4d82fc
JJ
78///
79/// // Iterate over everything.
d9579d0f
AL
80/// for book in &books {
81/// println!("{}", book);
1a4d82fc
JJ
82/// }
83/// ```
84///
85/// The easiest way to use `HashSet` with a custom type is to derive
86/// `Eq` and `Hash`. We must also derive `PartialEq`, this will in the
87/// future be implied by `Eq`.
88///
89/// ```
90/// use std::collections::HashSet;
85aaf69f 91/// #[derive(Hash, Eq, PartialEq, Debug)]
1a4d82fc
JJ
92/// struct Viking<'a> {
93/// name: &'a str,
85aaf69f 94/// power: usize,
1a4d82fc
JJ
95/// }
96///
97/// let mut vikings = HashSet::new();
98///
85aaf69f
SL
99/// vikings.insert(Viking { name: "Einar", power: 9 });
100/// vikings.insert(Viking { name: "Einar", power: 9 });
101/// vikings.insert(Viking { name: "Olaf", power: 4 });
102/// vikings.insert(Viking { name: "Harald", power: 8 });
1a4d82fc
JJ
103///
104/// // Use derived implementation to print the vikings.
d9579d0f 105/// for x in &vikings {
1a4d82fc
JJ
106/// println!("{:?}", x);
107/// }
108/// ```
109#[derive(Clone)]
85aaf69f 110#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
111pub struct HashSet<T, S = RandomState> {
112 map: HashMap<T, (), S>
113}
114
85aaf69f 115impl<T: Hash + Eq> HashSet<T, RandomState> {
9346a6ac 116 /// Creates an empty HashSet.
1a4d82fc 117 ///
c34b1796 118 /// # Examples
1a4d82fc
JJ
119 ///
120 /// ```
121 /// use std::collections::HashSet;
85aaf69f 122 /// let mut set: HashSet<i32> = HashSet::new();
1a4d82fc
JJ
123 /// ```
124 #[inline]
85aaf69f 125 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
126 pub fn new() -> HashSet<T, RandomState> {
127 HashSet::with_capacity(INITIAL_CAPACITY)
128 }
129
9346a6ac 130 /// Creates an empty HashSet with space for at least `n` elements in
1a4d82fc
JJ
131 /// the hash table.
132 ///
c34b1796 133 /// # Examples
1a4d82fc
JJ
134 ///
135 /// ```
136 /// use std::collections::HashSet;
85aaf69f 137 /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
1a4d82fc
JJ
138 /// ```
139 #[inline]
85aaf69f
SL
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
1a4d82fc
JJ
142 HashSet { map: HashMap::with_capacity(capacity) }
143 }
144}
145
85aaf69f
SL
146impl<T, S> HashSet<T, S>
147 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
148{
149 /// Creates a new empty hash set which will use the given hasher to hash
150 /// keys.
151 ///
152 /// The hash set is also created with the default initial capacity.
153 ///
c34b1796 154 /// # Examples
1a4d82fc
JJ
155 ///
156 /// ```
c1a9b12d
SL
157 /// #![feature(hashmap_hasher)]
158 ///
1a4d82fc
JJ
159 /// use std::collections::HashSet;
160 /// use std::collections::hash_map::RandomState;
161 ///
162 /// let s = RandomState::new();
163 /// let mut set = HashSet::with_hash_state(s);
85aaf69f 164 /// set.insert(2);
1a4d82fc
JJ
165 /// ```
166 #[inline]
62682a34 167 #[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear")]
1a4d82fc
JJ
168 pub fn with_hash_state(hash_state: S) -> HashSet<T, S> {
169 HashSet::with_capacity_and_hash_state(INITIAL_CAPACITY, hash_state)
170 }
171
9346a6ac 172 /// Creates an empty HashSet with space for at least `capacity`
1a4d82fc
JJ
173 /// elements in the hash table, using `hasher` to hash the keys.
174 ///
175 /// Warning: `hasher` is normally randomly generated, and
176 /// is designed to allow `HashSet`s to be resistant to attacks that
177 /// cause many collisions and very poor performance. Setting it
178 /// manually using this function can expose a DoS attack vector.
179 ///
c34b1796 180 /// # Examples
1a4d82fc
JJ
181 ///
182 /// ```
c1a9b12d
SL
183 /// #![feature(hashmap_hasher)]
184 ///
1a4d82fc
JJ
185 /// use std::collections::HashSet;
186 /// use std::collections::hash_map::RandomState;
187 ///
188 /// let s = RandomState::new();
85aaf69f
SL
189 /// let mut set = HashSet::with_capacity_and_hash_state(10, s);
190 /// set.insert(1);
1a4d82fc
JJ
191 /// ```
192 #[inline]
62682a34 193 #[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear")]
85aaf69f 194 pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
1a4d82fc
JJ
195 -> HashSet<T, S> {
196 HashSet {
197 map: HashMap::with_capacity_and_hash_state(capacity, hash_state),
198 }
199 }
200
201 /// Returns the number of elements the set can hold without reallocating.
202 ///
c34b1796 203 /// # Examples
1a4d82fc
JJ
204 ///
205 /// ```
206 /// use std::collections::HashSet;
85aaf69f 207 /// let set: HashSet<i32> = HashSet::with_capacity(100);
1a4d82fc
JJ
208 /// assert!(set.capacity() >= 100);
209 /// ```
210 #[inline]
85aaf69f
SL
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub fn capacity(&self) -> usize {
1a4d82fc
JJ
213 self.map.capacity()
214 }
215
216 /// Reserves capacity for at least `additional` more elements to be inserted
217 /// in the `HashSet`. The collection may reserve more space to avoid
218 /// frequent reallocations.
219 ///
220 /// # Panics
221 ///
85aaf69f 222 /// Panics if the new allocation size overflows `usize`.
1a4d82fc 223 ///
c34b1796 224 /// # Examples
1a4d82fc
JJ
225 ///
226 /// ```
227 /// use std::collections::HashSet;
85aaf69f 228 /// let mut set: HashSet<i32> = HashSet::new();
1a4d82fc
JJ
229 /// set.reserve(10);
230 /// ```
85aaf69f
SL
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn reserve(&mut self, additional: usize) {
1a4d82fc
JJ
233 self.map.reserve(additional)
234 }
235
236 /// Shrinks the capacity of the set as much as possible. It will drop
237 /// down as much as possible while maintaining the internal rules
238 /// and possibly leaving some space in accordance with the resize policy.
239 ///
c34b1796 240 /// # Examples
1a4d82fc
JJ
241 ///
242 /// ```
243 /// use std::collections::HashSet;
244 ///
85aaf69f 245 /// let mut set = HashSet::with_capacity(100);
1a4d82fc
JJ
246 /// set.insert(1);
247 /// set.insert(2);
248 /// assert!(set.capacity() >= 100);
249 /// set.shrink_to_fit();
250 /// assert!(set.capacity() >= 2);
251 /// ```
85aaf69f 252 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
253 pub fn shrink_to_fit(&mut self) {
254 self.map.shrink_to_fit()
255 }
256
257 /// An iterator visiting all elements in arbitrary order.
258 /// Iterator element type is &'a T.
259 ///
c34b1796 260 /// # Examples
1a4d82fc
JJ
261 ///
262 /// ```
263 /// use std::collections::HashSet;
264 /// let mut set = HashSet::new();
265 /// set.insert("a");
266 /// set.insert("b");
267 ///
268 /// // Will print in an arbitrary order.
269 /// for x in set.iter() {
270 /// println!("{}", x);
271 /// }
272 /// ```
85aaf69f 273 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
274 pub fn iter(&self) -> Iter<T> {
275 Iter { iter: self.map.keys() }
276 }
277
1a4d82fc
JJ
278 /// Visit the values representing the difference.
279 ///
c34b1796 280 /// # Examples
1a4d82fc
JJ
281 ///
282 /// ```
283 /// use std::collections::HashSet;
85aaf69f
SL
284 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
285 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1a4d82fc
JJ
286 ///
287 /// // Can be seen as `a - b`.
288 /// for x in a.difference(&b) {
289 /// println!("{}", x); // Print 1
290 /// }
291 ///
85aaf69f
SL
292 /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
293 /// assert_eq!(diff, [1].iter().cloned().collect());
1a4d82fc
JJ
294 ///
295 /// // Note that difference is not symmetric,
296 /// // and `b - a` means something else:
85aaf69f
SL
297 /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
298 /// assert_eq!(diff, [4].iter().cloned().collect());
1a4d82fc 299 /// ```
85aaf69f 300 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
301 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
302 Difference {
303 iter: self.iter(),
304 other: other,
305 }
306 }
307
308 /// Visit the values representing the symmetric difference.
309 ///
c34b1796 310 /// # Examples
1a4d82fc
JJ
311 ///
312 /// ```
313 /// use std::collections::HashSet;
85aaf69f
SL
314 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
315 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1a4d82fc
JJ
316 ///
317 /// // Print 1, 4 in arbitrary order.
318 /// for x in a.symmetric_difference(&b) {
319 /// println!("{}", x);
320 /// }
321 ///
85aaf69f
SL
322 /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
323 /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
1a4d82fc
JJ
324 ///
325 /// assert_eq!(diff1, diff2);
85aaf69f 326 /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
1a4d82fc 327 /// ```
85aaf69f 328 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
329 pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>)
330 -> SymmetricDifference<'a, T, S> {
331 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
332 }
333
334 /// Visit the values representing the intersection.
335 ///
c34b1796 336 /// # Examples
1a4d82fc
JJ
337 ///
338 /// ```
339 /// use std::collections::HashSet;
85aaf69f
SL
340 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
341 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1a4d82fc
JJ
342 ///
343 /// // Print 2, 3 in arbitrary order.
344 /// for x in a.intersection(&b) {
345 /// println!("{}", x);
346 /// }
347 ///
85aaf69f
SL
348 /// let diff: HashSet<_> = a.intersection(&b).cloned().collect();
349 /// assert_eq!(diff, [2, 3].iter().cloned().collect());
1a4d82fc 350 /// ```
85aaf69f 351 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
352 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
353 Intersection {
354 iter: self.iter(),
355 other: other,
356 }
357 }
358
359 /// Visit the values representing the union.
360 ///
c34b1796 361 /// # Examples
1a4d82fc
JJ
362 ///
363 /// ```
364 /// use std::collections::HashSet;
85aaf69f
SL
365 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
366 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1a4d82fc
JJ
367 ///
368 /// // Print 1, 2, 3, 4 in arbitrary order.
369 /// for x in a.union(&b) {
370 /// println!("{}", x);
371 /// }
372 ///
85aaf69f
SL
373 /// let diff: HashSet<_> = a.union(&b).cloned().collect();
374 /// assert_eq!(diff, [1, 2, 3, 4].iter().cloned().collect());
1a4d82fc 375 /// ```
85aaf69f 376 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
377 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
378 Union { iter: self.iter().chain(other.difference(self)) }
379 }
380
9346a6ac 381 /// Returns the number of elements in the set.
1a4d82fc 382 ///
c34b1796 383 /// # Examples
1a4d82fc
JJ
384 ///
385 /// ```
386 /// use std::collections::HashSet;
387 ///
388 /// let mut v = HashSet::new();
389 /// assert_eq!(v.len(), 0);
85aaf69f 390 /// v.insert(1);
1a4d82fc
JJ
391 /// assert_eq!(v.len(), 1);
392 /// ```
85aaf69f
SL
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn len(&self) -> usize { self.map.len() }
1a4d82fc 395
9346a6ac 396 /// Returns true if the set contains no elements.
1a4d82fc 397 ///
c34b1796 398 /// # Examples
1a4d82fc
JJ
399 ///
400 /// ```
401 /// use std::collections::HashSet;
402 ///
403 /// let mut v = HashSet::new();
404 /// assert!(v.is_empty());
85aaf69f 405 /// v.insert(1);
1a4d82fc
JJ
406 /// assert!(!v.is_empty());
407 /// ```
85aaf69f 408 #[stable(feature = "rust1", since = "1.0.0")]
9346a6ac 409 pub fn is_empty(&self) -> bool { self.map.is_empty() }
1a4d82fc
JJ
410
411 /// Clears the set, returning all elements in an iterator.
412 #[inline]
62682a34 413 #[unstable(feature = "drain",
85aaf69f 414 reason = "matches collection reform specification, waiting for dust to settle")]
1a4d82fc
JJ
415 pub fn drain(&mut self) -> Drain<T> {
416 fn first<A, B>((a, _): (A, B)) -> A { a }
417 let first: fn((T, ())) -> T = first; // coerce to fn pointer
418
419 Drain { iter: self.map.drain().map(first) }
420 }
421
422 /// Clears the set, removing all values.
423 ///
c34b1796 424 /// # Examples
1a4d82fc
JJ
425 ///
426 /// ```
427 /// use std::collections::HashSet;
428 ///
429 /// let mut v = HashSet::new();
85aaf69f 430 /// v.insert(1);
1a4d82fc
JJ
431 /// v.clear();
432 /// assert!(v.is_empty());
433 /// ```
85aaf69f 434 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
435 pub fn clear(&mut self) { self.map.clear() }
436
437 /// Returns `true` if the set contains a value.
438 ///
439 /// The value may be any borrowed form of the set's value type, but
440 /// `Hash` and `Eq` on the borrowed form *must* match those for
441 /// the value type.
442 ///
c34b1796 443 /// # Examples
1a4d82fc
JJ
444 ///
445 /// ```
446 /// use std::collections::HashSet;
447 ///
85aaf69f 448 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
1a4d82fc
JJ
449 /// assert_eq!(set.contains(&1), true);
450 /// assert_eq!(set.contains(&4), false);
451 /// ```
85aaf69f 452 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 453 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
85aaf69f 454 where T: Borrow<Q>, Q: Hash + Eq
1a4d82fc
JJ
455 {
456 self.map.contains_key(value)
457 }
458
459 /// Returns `true` if the set has no elements in common with `other`.
460 /// This is equivalent to checking for an empty intersection.
461 ///
c34b1796 462 /// # Examples
1a4d82fc
JJ
463 ///
464 /// ```
465 /// use std::collections::HashSet;
466 ///
85aaf69f
SL
467 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
468 /// let mut b = HashSet::new();
1a4d82fc
JJ
469 ///
470 /// assert_eq!(a.is_disjoint(&b), true);
471 /// b.insert(4);
472 /// assert_eq!(a.is_disjoint(&b), true);
473 /// b.insert(1);
474 /// assert_eq!(a.is_disjoint(&b), false);
475 /// ```
85aaf69f 476 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
477 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
478 self.iter().all(|v| !other.contains(v))
479 }
480
481 /// Returns `true` if the set is a subset of another.
482 ///
c34b1796 483 /// # Examples
1a4d82fc
JJ
484 ///
485 /// ```
486 /// use std::collections::HashSet;
487 ///
85aaf69f
SL
488 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
489 /// let mut set = HashSet::new();
1a4d82fc
JJ
490 ///
491 /// assert_eq!(set.is_subset(&sup), true);
492 /// set.insert(2);
493 /// assert_eq!(set.is_subset(&sup), true);
494 /// set.insert(4);
495 /// assert_eq!(set.is_subset(&sup), false);
496 /// ```
85aaf69f 497 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
498 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
499 self.iter().all(|v| other.contains(v))
500 }
501
502 /// Returns `true` if the set is a superset of another.
503 ///
c34b1796 504 /// # Examples
1a4d82fc
JJ
505 ///
506 /// ```
507 /// use std::collections::HashSet;
508 ///
85aaf69f
SL
509 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
510 /// let mut set = HashSet::new();
1a4d82fc
JJ
511 ///
512 /// assert_eq!(set.is_superset(&sub), false);
513 ///
514 /// set.insert(0);
515 /// set.insert(1);
516 /// assert_eq!(set.is_superset(&sub), false);
517 ///
518 /// set.insert(2);
519 /// assert_eq!(set.is_superset(&sub), true);
520 /// ```
521 #[inline]
85aaf69f 522 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
523 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
524 other.is_subset(self)
525 }
526
527 /// Adds a value to the set. Returns `true` if the value was not already
528 /// present in the set.
529 ///
c34b1796 530 /// # Examples
1a4d82fc
JJ
531 ///
532 /// ```
533 /// use std::collections::HashSet;
534 ///
535 /// let mut set = HashSet::new();
536 ///
85aaf69f 537 /// assert_eq!(set.insert(2), true);
1a4d82fc
JJ
538 /// assert_eq!(set.insert(2), false);
539 /// assert_eq!(set.len(), 1);
540 /// ```
85aaf69f 541 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
542 pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none() }
543
544 /// Removes a value from the set. Returns `true` if the value was
545 /// present in the set.
546 ///
547 /// The value may be any borrowed form of the set's value type, but
548 /// `Hash` and `Eq` on the borrowed form *must* match those for
549 /// the value type.
550 ///
c34b1796 551 /// # Examples
1a4d82fc
JJ
552 ///
553 /// ```
554 /// use std::collections::HashSet;
555 ///
556 /// let mut set = HashSet::new();
557 ///
85aaf69f 558 /// set.insert(2);
1a4d82fc
JJ
559 /// assert_eq!(set.remove(&2), true);
560 /// assert_eq!(set.remove(&2), false);
561 /// ```
85aaf69f 562 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 563 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
85aaf69f 564 where T: Borrow<Q>, Q: Hash + Eq
1a4d82fc
JJ
565 {
566 self.map.remove(value).is_some()
567 }
568}
569
85aaf69f
SL
570#[stable(feature = "rust1", since = "1.0.0")]
571impl<T, S> PartialEq for HashSet<T, S>
572 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
573{
574 fn eq(&self, other: &HashSet<T, S>) -> bool {
575 if self.len() != other.len() { return false; }
576
577 self.iter().all(|key| other.contains(key))
578 }
579}
580
85aaf69f
SL
581#[stable(feature = "rust1", since = "1.0.0")]
582impl<T, S> Eq for HashSet<T, S>
583 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
584{}
585
85aaf69f
SL
586#[stable(feature = "rust1", since = "1.0.0")]
587impl<T, S> fmt::Debug for HashSet<T, S>
588 where T: Eq + Hash + fmt::Debug,
589 S: HashState
1a4d82fc
JJ
590{
591 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62682a34 592 f.debug_set().entries(self.iter()).finish()
1a4d82fc
JJ
593 }
594}
595
85aaf69f
SL
596#[stable(feature = "rust1", since = "1.0.0")]
597impl<T, S> FromIterator<T> for HashSet<T, S>
598 where T: Eq + Hash,
599 S: HashState + Default,
1a4d82fc 600{
85aaf69f
SL
601 fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> HashSet<T, S> {
602 let iter = iterable.into_iter();
1a4d82fc
JJ
603 let lower = iter.size_hint().0;
604 let mut set = HashSet::with_capacity_and_hash_state(lower, Default::default());
605 set.extend(iter);
606 set
607 }
608}
609
85aaf69f
SL
610#[stable(feature = "rust1", since = "1.0.0")]
611impl<T, S> Extend<T> for HashSet<T, S>
612 where T: Eq + Hash,
613 S: HashState,
1a4d82fc 614{
85aaf69f 615 fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
1a4d82fc
JJ
616 for k in iter {
617 self.insert(k);
618 }
619 }
620}
621
85aaf69f
SL
622#[stable(feature = "rust1", since = "1.0.0")]
623impl<T, S> Default for HashSet<T, S>
624 where T: Eq + Hash,
625 S: HashState + Default,
1a4d82fc 626{
85aaf69f 627 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
628 fn default() -> HashSet<T, S> {
629 HashSet::with_hash_state(Default::default())
630 }
631}
632
85aaf69f
SL
633#[stable(feature = "rust1", since = "1.0.0")]
634impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
635 where T: Eq + Hash + Clone,
636 S: HashState + Default,
1a4d82fc
JJ
637{
638 type Output = HashSet<T, S>;
639
640 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
641 ///
642 /// # Examples
643 ///
644 /// ```
645 /// use std::collections::HashSet;
646 ///
85aaf69f
SL
647 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
648 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1a4d82fc 649 ///
85aaf69f 650 /// let set = &a | &b;
1a4d82fc
JJ
651 ///
652 /// let mut i = 0;
653 /// let expected = [1, 2, 3, 4, 5];
62682a34 654 /// for x in &set {
1a4d82fc
JJ
655 /// assert!(expected.contains(x));
656 /// i += 1;
657 /// }
658 /// assert_eq!(i, expected.len());
659 /// ```
660 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
661 self.union(rhs).cloned().collect()
662 }
663}
664
85aaf69f
SL
665#[stable(feature = "rust1", since = "1.0.0")]
666impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
667 where T: Eq + Hash + Clone,
668 S: HashState + Default,
1a4d82fc
JJ
669{
670 type Output = HashSet<T, S>;
671
672 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
673 ///
674 /// # Examples
675 ///
676 /// ```
677 /// use std::collections::HashSet;
678 ///
85aaf69f
SL
679 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
680 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1a4d82fc 681 ///
85aaf69f 682 /// let set = &a & &b;
1a4d82fc
JJ
683 ///
684 /// let mut i = 0;
685 /// let expected = [2, 3];
62682a34 686 /// for x in &set {
1a4d82fc
JJ
687 /// assert!(expected.contains(x));
688 /// i += 1;
689 /// }
690 /// assert_eq!(i, expected.len());
691 /// ```
692 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
693 self.intersection(rhs).cloned().collect()
694 }
695}
696
85aaf69f
SL
697#[stable(feature = "rust1", since = "1.0.0")]
698impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
699 where T: Eq + Hash + Clone,
700 S: HashState + Default,
1a4d82fc
JJ
701{
702 type Output = HashSet<T, S>;
703
704 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
705 ///
706 /// # Examples
707 ///
708 /// ```
709 /// use std::collections::HashSet;
710 ///
85aaf69f
SL
711 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
712 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1a4d82fc 713 ///
85aaf69f 714 /// let set = &a ^ &b;
1a4d82fc
JJ
715 ///
716 /// let mut i = 0;
717 /// let expected = [1, 2, 4, 5];
62682a34 718 /// for x in &set {
1a4d82fc
JJ
719 /// assert!(expected.contains(x));
720 /// i += 1;
721 /// }
722 /// assert_eq!(i, expected.len());
723 /// ```
724 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
725 self.symmetric_difference(rhs).cloned().collect()
726 }
727}
728
85aaf69f
SL
729#[stable(feature = "rust1", since = "1.0.0")]
730impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
731 where T: Eq + Hash + Clone,
732 S: HashState + Default,
1a4d82fc
JJ
733{
734 type Output = HashSet<T, S>;
735
736 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
737 ///
738 /// # Examples
739 ///
740 /// ```
741 /// use std::collections::HashSet;
742 ///
85aaf69f
SL
743 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
744 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1a4d82fc 745 ///
85aaf69f 746 /// let set = &a - &b;
1a4d82fc
JJ
747 ///
748 /// let mut i = 0;
749 /// let expected = [1, 2];
62682a34 750 /// for x in &set {
1a4d82fc
JJ
751 /// assert!(expected.contains(x));
752 /// i += 1;
753 /// }
754 /// assert_eq!(i, expected.len());
755 /// ```
756 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
757 self.difference(rhs).cloned().collect()
758 }
759}
760
761/// HashSet iterator
85aaf69f 762#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
763pub struct Iter<'a, K: 'a> {
764 iter: Keys<'a, K, ()>
765}
766
767/// HashSet move iterator
85aaf69f 768#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 769pub struct IntoIter<K> {
85aaf69f 770 iter: Map<map::IntoIter<K, ()>, fn((K, ())) -> K>
1a4d82fc
JJ
771}
772
773/// HashSet drain iterator
85aaf69f 774#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 775pub struct Drain<'a, K: 'a> {
85aaf69f 776 iter: Map<map::Drain<'a, K, ()>, fn((K, ())) -> K>,
1a4d82fc
JJ
777}
778
779/// Intersection iterator
85aaf69f 780#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
781pub struct Intersection<'a, T: 'a, S: 'a> {
782 // iterator of the first set
783 iter: Iter<'a, T>,
784 // the second set
785 other: &'a HashSet<T, S>,
786}
787
788/// Difference iterator
85aaf69f 789#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
790pub struct Difference<'a, T: 'a, S: 'a> {
791 // iterator of the first set
792 iter: Iter<'a, T>,
793 // the second set
794 other: &'a HashSet<T, S>,
795}
796
797/// Symmetric difference iterator.
85aaf69f 798#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
799pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
800 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>
801}
802
803/// Set union iterator.
85aaf69f 804#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
805pub struct Union<'a, T: 'a, S: 'a> {
806 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>
807}
808
85aaf69f
SL
809#[stable(feature = "rust1", since = "1.0.0")]
810impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
811 where T: Eq + Hash, S: HashState
812{
813 type Item = &'a T;
814 type IntoIter = Iter<'a, T>;
815
816 fn into_iter(self) -> Iter<'a, T> {
817 self.iter()
818 }
819}
820
821#[stable(feature = "rust1", since = "1.0.0")]
822impl<T, S> IntoIterator for HashSet<T, S>
823 where T: Eq + Hash,
824 S: HashState
825{
826 type Item = T;
827 type IntoIter = IntoIter<T>;
828
9346a6ac
AL
829 /// Creates a consuming iterator, that is, one that moves each value out
830 /// of the set in arbitrary order. The set cannot be used after calling
831 /// this.
832 ///
833 /// # Examples
834 ///
835 /// ```
836 /// use std::collections::HashSet;
837 /// let mut set = HashSet::new();
838 /// set.insert("a".to_string());
839 /// set.insert("b".to_string());
840 ///
841 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
842 /// let v: Vec<String> = set.into_iter().collect();
843 ///
844 /// // Will print in an arbitrary order.
62682a34 845 /// for x in &v {
9346a6ac
AL
846 /// println!("{}", x);
847 /// }
848 /// ```
85aaf69f 849 fn into_iter(self) -> IntoIter<T> {
9346a6ac
AL
850 fn first<A, B>((a, _): (A, B)) -> A { a }
851 let first: fn((T, ())) -> T = first;
852
853 IntoIter { iter: self.map.into_iter().map(first) }
85aaf69f
SL
854 }
855}
856
c34b1796
AL
857impl<'a, K> Clone for Iter<'a, K> {
858 fn clone(&self) -> Iter<'a, K> { Iter { iter: self.iter.clone() } }
859}
85aaf69f 860#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
861impl<'a, K> Iterator for Iter<'a, K> {
862 type Item = &'a K;
863
864 fn next(&mut self) -> Option<&'a K> { self.iter.next() }
85aaf69f
SL
865 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
866}
867#[stable(feature = "rust1", since = "1.0.0")]
868impl<'a, K> ExactSizeIterator for Iter<'a, K> {
869 fn len(&self) -> usize { self.iter.len() }
1a4d82fc
JJ
870}
871
85aaf69f 872#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
873impl<K> Iterator for IntoIter<K> {
874 type Item = K;
875
876 fn next(&mut self) -> Option<K> { self.iter.next() }
85aaf69f
SL
877 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
878}
879#[stable(feature = "rust1", since = "1.0.0")]
880impl<K> ExactSizeIterator for IntoIter<K> {
881 fn len(&self) -> usize { self.iter.len() }
1a4d82fc
JJ
882}
883
85aaf69f
SL
884#[stable(feature = "rust1", since = "1.0.0")]
885impl<'a, K> Iterator for Drain<'a, K> {
1a4d82fc
JJ
886 type Item = K;
887
888 fn next(&mut self) -> Option<K> { self.iter.next() }
85aaf69f
SL
889 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
890}
891#[stable(feature = "rust1", since = "1.0.0")]
892impl<'a, K> ExactSizeIterator for Drain<'a, K> {
893 fn len(&self) -> usize { self.iter.len() }
1a4d82fc
JJ
894}
895
c34b1796
AL
896impl<'a, T, S> Clone for Intersection<'a, T, S> {
897 fn clone(&self) -> Intersection<'a, T, S> {
898 Intersection { iter: self.iter.clone(), ..*self }
899 }
900}
901
85aaf69f
SL
902#[stable(feature = "rust1", since = "1.0.0")]
903impl<'a, T, S> Iterator for Intersection<'a, T, S>
904 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
905{
906 type Item = &'a T;
907
908 fn next(&mut self) -> Option<&'a T> {
909 loop {
910 match self.iter.next() {
911 None => return None,
912 Some(elt) => if self.other.contains(elt) {
913 return Some(elt)
914 },
915 }
916 }
917 }
918
85aaf69f 919 fn size_hint(&self) -> (usize, Option<usize>) {
1a4d82fc
JJ
920 let (_, upper) = self.iter.size_hint();
921 (0, upper)
922 }
923}
924
c34b1796
AL
925impl<'a, T, S> Clone for Difference<'a, T, S> {
926 fn clone(&self) -> Difference<'a, T, S> {
927 Difference { iter: self.iter.clone(), ..*self }
928 }
929}
930
85aaf69f
SL
931#[stable(feature = "rust1", since = "1.0.0")]
932impl<'a, T, S> Iterator for Difference<'a, T, S>
933 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
934{
935 type Item = &'a T;
936
937 fn next(&mut self) -> Option<&'a T> {
938 loop {
939 match self.iter.next() {
940 None => return None,
941 Some(elt) => if !self.other.contains(elt) {
942 return Some(elt)
943 },
944 }
945 }
946 }
947
85aaf69f 948 fn size_hint(&self) -> (usize, Option<usize>) {
1a4d82fc
JJ
949 let (_, upper) = self.iter.size_hint();
950 (0, upper)
951 }
952}
953
c34b1796
AL
954impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
955 fn clone(&self) -> SymmetricDifference<'a, T, S> {
956 SymmetricDifference { iter: self.iter.clone() }
957 }
958}
959
85aaf69f
SL
960#[stable(feature = "rust1", since = "1.0.0")]
961impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
962 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
963{
964 type Item = &'a T;
965
966 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
85aaf69f 967 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1a4d82fc
JJ
968}
969
c34b1796
AL
970impl<'a, T, S> Clone for Union<'a, T, S> {
971 fn clone(&self) -> Union<'a, T, S> { Union { iter: self.iter.clone() } }
972}
973
85aaf69f
SL
974#[stable(feature = "rust1", since = "1.0.0")]
975impl<'a, T, S> Iterator for Union<'a, T, S>
976 where T: Eq + Hash, S: HashState
1a4d82fc
JJ
977{
978 type Item = &'a T;
979
980 fn next(&mut self) -> Option<&'a T> { self.iter.next() }
85aaf69f 981 fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
1a4d82fc
JJ
982}
983
984#[cfg(test)]
985mod test_set {
986 use prelude::v1::*;
987
988 use super::HashSet;
989
990 #[test]
991 fn test_disjoint() {
992 let mut xs = HashSet::new();
993 let mut ys = HashSet::new();
994 assert!(xs.is_disjoint(&ys));
995 assert!(ys.is_disjoint(&xs));
85aaf69f
SL
996 assert!(xs.insert(5));
997 assert!(ys.insert(11));
1a4d82fc
JJ
998 assert!(xs.is_disjoint(&ys));
999 assert!(ys.is_disjoint(&xs));
1000 assert!(xs.insert(7));
1001 assert!(xs.insert(19));
1002 assert!(xs.insert(4));
1003 assert!(ys.insert(2));
1004 assert!(ys.insert(-11));
1005 assert!(xs.is_disjoint(&ys));
1006 assert!(ys.is_disjoint(&xs));
1007 assert!(ys.insert(7));
1008 assert!(!xs.is_disjoint(&ys));
1009 assert!(!ys.is_disjoint(&xs));
1010 }
1011
1012 #[test]
1013 fn test_subset_and_superset() {
1014 let mut a = HashSet::new();
85aaf69f 1015 assert!(a.insert(0));
1a4d82fc
JJ
1016 assert!(a.insert(5));
1017 assert!(a.insert(11));
1018 assert!(a.insert(7));
1019
1020 let mut b = HashSet::new();
85aaf69f 1021 assert!(b.insert(0));
1a4d82fc
JJ
1022 assert!(b.insert(7));
1023 assert!(b.insert(19));
1024 assert!(b.insert(250));
1025 assert!(b.insert(11));
1026 assert!(b.insert(200));
1027
1028 assert!(!a.is_subset(&b));
1029 assert!(!a.is_superset(&b));
1030 assert!(!b.is_subset(&a));
1031 assert!(!b.is_superset(&a));
1032
1033 assert!(b.insert(5));
1034
1035 assert!(a.is_subset(&b));
1036 assert!(!a.is_superset(&b));
1037 assert!(!b.is_subset(&a));
1038 assert!(b.is_superset(&a));
1039 }
1040
1041 #[test]
1042 fn test_iterate() {
1043 let mut a = HashSet::new();
85aaf69f 1044 for i in 0..32 {
1a4d82fc
JJ
1045 assert!(a.insert(i));
1046 }
1047 let mut observed: u32 = 0;
85aaf69f 1048 for k in &a {
1a4d82fc
JJ
1049 observed |= 1 << *k;
1050 }
1051 assert_eq!(observed, 0xFFFF_FFFF);
1052 }
1053
1054 #[test]
1055 fn test_intersection() {
1056 let mut a = HashSet::new();
1057 let mut b = HashSet::new();
1058
85aaf69f 1059 assert!(a.insert(11));
1a4d82fc
JJ
1060 assert!(a.insert(1));
1061 assert!(a.insert(3));
1062 assert!(a.insert(77));
1063 assert!(a.insert(103));
1064 assert!(a.insert(5));
1065 assert!(a.insert(-5));
1066
85aaf69f 1067 assert!(b.insert(2));
1a4d82fc
JJ
1068 assert!(b.insert(11));
1069 assert!(b.insert(77));
1070 assert!(b.insert(-9));
1071 assert!(b.insert(-42));
1072 assert!(b.insert(5));
1073 assert!(b.insert(3));
1074
1075 let mut i = 0;
1076 let expected = [3, 5, 11, 77];
1077 for x in a.intersection(&b) {
1078 assert!(expected.contains(x));
1079 i += 1
1080 }
1081 assert_eq!(i, expected.len());
1082 }
1083
1084 #[test]
1085 fn test_difference() {
1086 let mut a = HashSet::new();
1087 let mut b = HashSet::new();
1088
85aaf69f 1089 assert!(a.insert(1));
1a4d82fc
JJ
1090 assert!(a.insert(3));
1091 assert!(a.insert(5));
1092 assert!(a.insert(9));
1093 assert!(a.insert(11));
1094
85aaf69f 1095 assert!(b.insert(3));
1a4d82fc
JJ
1096 assert!(b.insert(9));
1097
1098 let mut i = 0;
1099 let expected = [1, 5, 11];
1100 for x in a.difference(&b) {
1101 assert!(expected.contains(x));
1102 i += 1
1103 }
1104 assert_eq!(i, expected.len());
1105 }
1106
1107 #[test]
1108 fn test_symmetric_difference() {
1109 let mut a = HashSet::new();
1110 let mut b = HashSet::new();
1111
85aaf69f 1112 assert!(a.insert(1));
1a4d82fc
JJ
1113 assert!(a.insert(3));
1114 assert!(a.insert(5));
1115 assert!(a.insert(9));
1116 assert!(a.insert(11));
1117
85aaf69f 1118 assert!(b.insert(-2));
1a4d82fc
JJ
1119 assert!(b.insert(3));
1120 assert!(b.insert(9));
1121 assert!(b.insert(14));
1122 assert!(b.insert(22));
1123
1124 let mut i = 0;
1125 let expected = [-2, 1, 5, 11, 14, 22];
1126 for x in a.symmetric_difference(&b) {
1127 assert!(expected.contains(x));
1128 i += 1
1129 }
1130 assert_eq!(i, expected.len());
1131 }
1132
1133 #[test]
1134 fn test_union() {
1135 let mut a = HashSet::new();
1136 let mut b = HashSet::new();
1137
85aaf69f 1138 assert!(a.insert(1));
1a4d82fc
JJ
1139 assert!(a.insert(3));
1140 assert!(a.insert(5));
1141 assert!(a.insert(9));
1142 assert!(a.insert(11));
1143 assert!(a.insert(16));
1144 assert!(a.insert(19));
1145 assert!(a.insert(24));
1146
85aaf69f 1147 assert!(b.insert(-2));
1a4d82fc
JJ
1148 assert!(b.insert(1));
1149 assert!(b.insert(5));
1150 assert!(b.insert(9));
1151 assert!(b.insert(13));
1152 assert!(b.insert(19));
1153
1154 let mut i = 0;
1155 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
1156 for x in a.union(&b) {
1157 assert!(expected.contains(x));
1158 i += 1
1159 }
1160 assert_eq!(i, expected.len());
1161 }
1162
1163 #[test]
1164 fn test_from_iter() {
85aaf69f 1165 let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
1a4d82fc 1166
85aaf69f 1167 let set: HashSet<_> = xs.iter().cloned().collect();
1a4d82fc 1168
85aaf69f 1169 for x in &xs {
1a4d82fc
JJ
1170 assert!(set.contains(x));
1171 }
1172 }
1173
1174 #[test]
1175 fn test_move_iter() {
1176 let hs = {
1177 let mut hs = HashSet::new();
1178
1179 hs.insert('a');
1180 hs.insert('b');
1181
1182 hs
1183 };
1184
1185 let v = hs.into_iter().collect::<Vec<char>>();
c34b1796 1186 assert!(v == ['a', 'b'] || v == ['b', 'a']);
1a4d82fc
JJ
1187 }
1188
1189 #[test]
1190 fn test_eq() {
1191 // These constants once happened to expose a bug in insert().
1192 // I'm keeping them around to prevent a regression.
1193 let mut s1 = HashSet::new();
1194
85aaf69f 1195 s1.insert(1);
1a4d82fc
JJ
1196 s1.insert(2);
1197 s1.insert(3);
1198
1199 let mut s2 = HashSet::new();
1200
85aaf69f 1201 s2.insert(1);
1a4d82fc
JJ
1202 s2.insert(2);
1203
1204 assert!(s1 != s2);
1205
1206 s2.insert(3);
1207
1208 assert_eq!(s1, s2);
1209 }
1210
1211 #[test]
1212 fn test_show() {
85aaf69f
SL
1213 let mut set = HashSet::new();
1214 let empty = HashSet::<i32>::new();
1a4d82fc 1215
85aaf69f 1216 set.insert(1);
1a4d82fc
JJ
1217 set.insert(2);
1218
1219 let set_str = format!("{:?}", set);
1220
c34b1796
AL
1221 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
1222 assert_eq!(format!("{:?}", empty), "{}");
1a4d82fc
JJ
1223 }
1224
1225 #[test]
1226 fn test_trivial_drain() {
85aaf69f 1227 let mut s = HashSet::<i32>::new();
1a4d82fc
JJ
1228 for _ in s.drain() {}
1229 assert!(s.is_empty());
1230 drop(s);
1231
85aaf69f 1232 let mut s = HashSet::<i32>::new();
1a4d82fc
JJ
1233 drop(s.drain());
1234 assert!(s.is_empty());
1235 }
1236
1237 #[test]
1238 fn test_drain() {
85aaf69f 1239 let mut s: HashSet<_> = (1..100).collect();
1a4d82fc
JJ
1240
1241 // try this a bunch of times to make sure we don't screw up internal state.
85aaf69f 1242 for _ in 0..20 {
1a4d82fc
JJ
1243 assert_eq!(s.len(), 99);
1244
1245 {
1246 let mut last_i = 0;
1247 let mut d = s.drain();
1248 for (i, x) in d.by_ref().take(50).enumerate() {
1249 last_i = i;
1250 assert!(x != 0);
1251 }
1252 assert_eq!(last_i, 49);
1253 }
1254
85aaf69f 1255 for _ in &s { panic!("s should be empty!"); }
1a4d82fc
JJ
1256
1257 // reset to try again.
85aaf69f 1258 s.extend(1..100);
1a4d82fc
JJ
1259 }
1260 }
1261}