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