]> git.proxmox.com Git - rustc.git/blob - library/std/src/collections/hash/set.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / library / std / src / collections / hash / set.rs
1 #[cfg(test)]
2 mod tests;
3
4 use hashbrown::hash_set as base;
5
6 use crate::borrow::Borrow;
7 use crate::collections::TryReserveError;
8 use crate::fmt;
9 use crate::hash::{BuildHasher, Hash};
10 use crate::iter::{Chain, FromIterator, FusedIterator};
11 use crate::ops::{BitAnd, BitOr, BitXor, Sub};
12
13 use super::map::{map_try_reserve_error, RandomState};
14
15 // Future Optimization (FIXME!)
16 // ============================
17 //
18 // Iteration over zero sized values is a noop. There is no need
19 // for `bucket.val` in the case of HashSet. I suppose we would need HKT
20 // to get rid of it properly.
21
22 /// A hash set implemented as a `HashMap` where the value is `()`.
23 ///
24 /// As with the [`HashMap`] type, a `HashSet` requires that the elements
25 /// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
26 /// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
27 /// it is important that the following property holds:
28 ///
29 /// ```text
30 /// k1 == k2 -> hash(k1) == hash(k2)
31 /// ```
32 ///
33 /// In other words, if two keys are equal, their hashes must be equal.
34 ///
35 ///
36 /// It is a logic error for an item to be modified in such a way that the
37 /// item's hash, as determined by the [`Hash`] trait, or its equality, as
38 /// determined by the [`Eq`] trait, changes while it is in the set. This is
39 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
40 /// unsafe code.
41 ///
42 /// # Examples
43 ///
44 /// ```
45 /// use std::collections::HashSet;
46 /// // Type inference lets us omit an explicit type signature (which
47 /// // would be `HashSet<String>` in this example).
48 /// let mut books = HashSet::new();
49 ///
50 /// // Add some books.
51 /// books.insert("A Dance With Dragons".to_string());
52 /// books.insert("To Kill a Mockingbird".to_string());
53 /// books.insert("The Odyssey".to_string());
54 /// books.insert("The Great Gatsby".to_string());
55 ///
56 /// // Check for a specific one.
57 /// if !books.contains("The Winds of Winter") {
58 /// println!("We have {} books, but The Winds of Winter ain't one.",
59 /// books.len());
60 /// }
61 ///
62 /// // Remove a book.
63 /// books.remove("The Odyssey");
64 ///
65 /// // Iterate over everything.
66 /// for book in &books {
67 /// println!("{}", book);
68 /// }
69 /// ```
70 ///
71 /// The easiest way to use `HashSet` with a custom type is to derive
72 /// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the
73 /// future be implied by [`Eq`].
74 ///
75 /// ```
76 /// use std::collections::HashSet;
77 /// #[derive(Hash, Eq, PartialEq, Debug)]
78 /// struct Viking {
79 /// name: String,
80 /// power: usize,
81 /// }
82 ///
83 /// let mut vikings = HashSet::new();
84 ///
85 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
86 /// vikings.insert(Viking { name: "Einar".to_string(), power: 9 });
87 /// vikings.insert(Viking { name: "Olaf".to_string(), power: 4 });
88 /// vikings.insert(Viking { name: "Harald".to_string(), power: 8 });
89 ///
90 /// // Use derived implementation to print the vikings.
91 /// for x in &vikings {
92 /// println!("{:?}", x);
93 /// }
94 /// ```
95 ///
96 /// A `HashSet` with fixed list of elements can be initialized from an array:
97 ///
98 /// ```
99 /// use std::collections::HashSet;
100 ///
101 /// let viking_names: HashSet<&'static str> =
102 /// [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
103 /// // use the values stored in the set
104 /// ```
105 ///
106 /// [`HashMap`]: crate::collections::HashMap
107 /// [`RefCell`]: crate::cell::RefCell
108 /// [`Cell`]: crate::cell::Cell
109 #[derive(Clone)]
110 #[cfg_attr(not(test), rustc_diagnostic_item = "hashset_type")]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct HashSet<T, S = RandomState> {
113 base: base::HashSet<T, S>,
114 }
115
116 impl<T> HashSet<T, RandomState> {
117 /// Creates an empty `HashSet`.
118 ///
119 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
120 /// is first inserted into.
121 ///
122 /// # Examples
123 ///
124 /// ```
125 /// use std::collections::HashSet;
126 /// let set: HashSet<i32> = HashSet::new();
127 /// ```
128 #[inline]
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub fn new() -> HashSet<T, RandomState> {
131 Default::default()
132 }
133
134 /// Creates an empty `HashSet` with the specified capacity.
135 ///
136 /// The hash set will be able to hold at least `capacity` elements without
137 /// reallocating. If `capacity` is 0, the hash set will not allocate.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// use std::collections::HashSet;
143 /// let set: HashSet<i32> = HashSet::with_capacity(10);
144 /// assert!(set.capacity() >= 10);
145 /// ```
146 #[inline]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
149 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, Default::default()) }
150 }
151 }
152
153 impl<T, S> HashSet<T, S> {
154 /// Returns the number of elements the set can hold without reallocating.
155 ///
156 /// # Examples
157 ///
158 /// ```
159 /// use std::collections::HashSet;
160 /// let set: HashSet<i32> = HashSet::with_capacity(100);
161 /// assert!(set.capacity() >= 100);
162 /// ```
163 #[inline]
164 #[stable(feature = "rust1", since = "1.0.0")]
165 pub fn capacity(&self) -> usize {
166 self.base.capacity()
167 }
168
169 /// An iterator visiting all elements in arbitrary order.
170 /// The iterator element type is `&'a T`.
171 ///
172 /// # Examples
173 ///
174 /// ```
175 /// use std::collections::HashSet;
176 /// let mut set = HashSet::new();
177 /// set.insert("a");
178 /// set.insert("b");
179 ///
180 /// // Will print in an arbitrary order.
181 /// for x in set.iter() {
182 /// println!("{}", x);
183 /// }
184 /// ```
185 #[inline]
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn iter(&self) -> Iter<'_, T> {
188 Iter { base: self.base.iter() }
189 }
190
191 /// Returns the number of elements in the set.
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// use std::collections::HashSet;
197 ///
198 /// let mut v = HashSet::new();
199 /// assert_eq!(v.len(), 0);
200 /// v.insert(1);
201 /// assert_eq!(v.len(), 1);
202 /// ```
203 #[inline]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn len(&self) -> usize {
206 self.base.len()
207 }
208
209 /// Returns `true` if the set contains no elements.
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// use std::collections::HashSet;
215 ///
216 /// let mut v = HashSet::new();
217 /// assert!(v.is_empty());
218 /// v.insert(1);
219 /// assert!(!v.is_empty());
220 /// ```
221 #[inline]
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn is_empty(&self) -> bool {
224 self.base.is_empty()
225 }
226
227 /// Clears the set, returning all elements in an iterator.
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// use std::collections::HashSet;
233 ///
234 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
235 /// assert!(!set.is_empty());
236 ///
237 /// // print 1, 2, 3 in an arbitrary order
238 /// for i in set.drain() {
239 /// println!("{}", i);
240 /// }
241 ///
242 /// assert!(set.is_empty());
243 /// ```
244 #[inline]
245 #[stable(feature = "drain", since = "1.6.0")]
246 pub fn drain(&mut self) -> Drain<'_, T> {
247 Drain { base: self.base.drain() }
248 }
249
250 /// Creates an iterator which uses a closure to determine if a value should be removed.
251 ///
252 /// If the closure returns true, then the value is removed and yielded.
253 /// If the closure returns false, the value will remain in the list and will not be yielded
254 /// by the iterator.
255 ///
256 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
257 /// values will still be subjected to the closure and removed and dropped if it returns true.
258 ///
259 /// It is unspecified how many more values will be subjected to the closure
260 /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the
261 /// `DrainFilter` itself is leaked.
262 ///
263 /// # Examples
264 ///
265 /// Splitting a set into even and odd values, reusing the original set:
266 ///
267 /// ```
268 /// #![feature(hash_drain_filter)]
269 /// use std::collections::HashSet;
270 ///
271 /// let mut set: HashSet<i32> = (0..8).collect();
272 /// let drained: HashSet<i32> = set.drain_filter(|v| v % 2 == 0).collect();
273 ///
274 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
275 /// let mut odds = set.into_iter().collect::<Vec<_>>();
276 /// evens.sort();
277 /// odds.sort();
278 ///
279 /// assert_eq!(evens, vec![0, 2, 4, 6]);
280 /// assert_eq!(odds, vec![1, 3, 5, 7]);
281 /// ```
282 #[inline]
283 #[unstable(feature = "hash_drain_filter", issue = "59618")]
284 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, T, F>
285 where
286 F: FnMut(&T) -> bool,
287 {
288 DrainFilter { base: self.base.drain_filter(pred) }
289 }
290
291 /// Clears the set, removing all values.
292 ///
293 /// # Examples
294 ///
295 /// ```
296 /// use std::collections::HashSet;
297 ///
298 /// let mut v = HashSet::new();
299 /// v.insert(1);
300 /// v.clear();
301 /// assert!(v.is_empty());
302 /// ```
303 #[inline]
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub fn clear(&mut self) {
306 self.base.clear()
307 }
308
309 /// Creates a new empty hash set which will use the given hasher to hash
310 /// keys.
311 ///
312 /// The hash set is also created with the default initial capacity.
313 ///
314 /// Warning: `hasher` is normally randomly generated, and
315 /// is designed to allow `HashSet`s to be resistant to attacks that
316 /// cause many collisions and very poor performance. Setting it
317 /// manually using this function can expose a DoS attack vector.
318 ///
319 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
320 /// the HashMap to be useful, see its documentation for details.
321 ///
322 /// # Examples
323 ///
324 /// ```
325 /// use std::collections::HashSet;
326 /// use std::collections::hash_map::RandomState;
327 ///
328 /// let s = RandomState::new();
329 /// let mut set = HashSet::with_hasher(s);
330 /// set.insert(2);
331 /// ```
332 #[inline]
333 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
334 pub fn with_hasher(hasher: S) -> HashSet<T, S> {
335 HashSet { base: base::HashSet::with_hasher(hasher) }
336 }
337
338 /// Creates an empty `HashSet` with the specified capacity, using
339 /// `hasher` to hash the keys.
340 ///
341 /// The hash set will be able to hold at least `capacity` elements without
342 /// reallocating. If `capacity` is 0, the hash set will not allocate.
343 ///
344 /// Warning: `hasher` is normally randomly generated, and
345 /// is designed to allow `HashSet`s to be resistant to attacks that
346 /// cause many collisions and very poor performance. Setting it
347 /// manually using this function can expose a DoS attack vector.
348 ///
349 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
350 /// the HashMap to be useful, see its documentation for details.
351 ///
352 /// # Examples
353 ///
354 /// ```
355 /// use std::collections::HashSet;
356 /// use std::collections::hash_map::RandomState;
357 ///
358 /// let s = RandomState::new();
359 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
360 /// set.insert(1);
361 /// ```
362 #[inline]
363 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
364 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
365 HashSet { base: base::HashSet::with_capacity_and_hasher(capacity, hasher) }
366 }
367
368 /// Returns a reference to the set's [`BuildHasher`].
369 ///
370 /// # Examples
371 ///
372 /// ```
373 /// use std::collections::HashSet;
374 /// use std::collections::hash_map::RandomState;
375 ///
376 /// let hasher = RandomState::new();
377 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
378 /// let hasher: &RandomState = set.hasher();
379 /// ```
380 #[inline]
381 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
382 pub fn hasher(&self) -> &S {
383 self.base.hasher()
384 }
385 }
386
387 impl<T, S> HashSet<T, S>
388 where
389 T: Eq + Hash,
390 S: BuildHasher,
391 {
392 /// Reserves capacity for at least `additional` more elements to be inserted
393 /// in the `HashSet`. The collection may reserve more space to avoid
394 /// frequent reallocations.
395 ///
396 /// # Panics
397 ///
398 /// Panics if the new allocation size overflows `usize`.
399 ///
400 /// # Examples
401 ///
402 /// ```
403 /// use std::collections::HashSet;
404 /// let mut set: HashSet<i32> = HashSet::new();
405 /// set.reserve(10);
406 /// assert!(set.capacity() >= 10);
407 /// ```
408 #[inline]
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn reserve(&mut self, additional: usize) {
411 self.base.reserve(additional)
412 }
413
414 /// Tries to reserve capacity for at least `additional` more elements to be inserted
415 /// in the given `HashSet<K, V>`. The collection may reserve more space to avoid
416 /// frequent reallocations.
417 ///
418 /// # Errors
419 ///
420 /// If the capacity overflows, or the allocator reports a failure, then an error
421 /// is returned.
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// #![feature(try_reserve)]
427 /// use std::collections::HashSet;
428 /// let mut set: HashSet<i32> = HashSet::new();
429 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
430 /// ```
431 #[inline]
432 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
433 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
434 self.base.try_reserve(additional).map_err(map_try_reserve_error)
435 }
436
437 /// Shrinks the capacity of the set as much as possible. It will drop
438 /// down as much as possible while maintaining the internal rules
439 /// and possibly leaving some space in accordance with the resize policy.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use std::collections::HashSet;
445 ///
446 /// let mut set = HashSet::with_capacity(100);
447 /// set.insert(1);
448 /// set.insert(2);
449 /// assert!(set.capacity() >= 100);
450 /// set.shrink_to_fit();
451 /// assert!(set.capacity() >= 2);
452 /// ```
453 #[inline]
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn shrink_to_fit(&mut self) {
456 self.base.shrink_to_fit()
457 }
458
459 /// Shrinks the capacity of the set with a lower limit. It will drop
460 /// down no lower than the supplied limit while maintaining the internal rules
461 /// and possibly leaving some space in accordance with the resize policy.
462 ///
463 /// Panics if the current capacity is smaller than the supplied
464 /// minimum capacity.
465 ///
466 /// # Examples
467 ///
468 /// ```
469 /// #![feature(shrink_to)]
470 /// use std::collections::HashSet;
471 ///
472 /// let mut set = HashSet::with_capacity(100);
473 /// set.insert(1);
474 /// set.insert(2);
475 /// assert!(set.capacity() >= 100);
476 /// set.shrink_to(10);
477 /// assert!(set.capacity() >= 10);
478 /// set.shrink_to(0);
479 /// assert!(set.capacity() >= 2);
480 /// ```
481 #[inline]
482 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
483 pub fn shrink_to(&mut self, min_capacity: usize) {
484 self.base.shrink_to(min_capacity)
485 }
486
487 /// Visits the values representing the difference,
488 /// i.e., the values that are in `self` but not in `other`.
489 ///
490 /// # Examples
491 ///
492 /// ```
493 /// use std::collections::HashSet;
494 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
495 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
496 ///
497 /// // Can be seen as `a - b`.
498 /// for x in a.difference(&b) {
499 /// println!("{}", x); // Print 1
500 /// }
501 ///
502 /// let diff: HashSet<_> = a.difference(&b).collect();
503 /// assert_eq!(diff, [1].iter().collect());
504 ///
505 /// // Note that difference is not symmetric,
506 /// // and `b - a` means something else:
507 /// let diff: HashSet<_> = b.difference(&a).collect();
508 /// assert_eq!(diff, [4].iter().collect());
509 /// ```
510 #[inline]
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
513 Difference { iter: self.iter(), other }
514 }
515
516 /// Visits the values representing the symmetric difference,
517 /// i.e., the values that are in `self` or in `other` but not in both.
518 ///
519 /// # Examples
520 ///
521 /// ```
522 /// use std::collections::HashSet;
523 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
524 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
525 ///
526 /// // Print 1, 4 in arbitrary order.
527 /// for x in a.symmetric_difference(&b) {
528 /// println!("{}", x);
529 /// }
530 ///
531 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
532 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
533 ///
534 /// assert_eq!(diff1, diff2);
535 /// assert_eq!(diff1, [1, 4].iter().collect());
536 /// ```
537 #[inline]
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn symmetric_difference<'a>(
540 &'a self,
541 other: &'a HashSet<T, S>,
542 ) -> SymmetricDifference<'a, T, S> {
543 SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) }
544 }
545
546 /// Visits the values representing the intersection,
547 /// i.e., the values that are both in `self` and `other`.
548 ///
549 /// # Examples
550 ///
551 /// ```
552 /// use std::collections::HashSet;
553 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
554 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
555 ///
556 /// // Print 2, 3 in arbitrary order.
557 /// for x in a.intersection(&b) {
558 /// println!("{}", x);
559 /// }
560 ///
561 /// let intersection: HashSet<_> = a.intersection(&b).collect();
562 /// assert_eq!(intersection, [2, 3].iter().collect());
563 /// ```
564 #[inline]
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
567 if self.len() <= other.len() {
568 Intersection { iter: self.iter(), other }
569 } else {
570 Intersection { iter: other.iter(), other: self }
571 }
572 }
573
574 /// Visits the values representing the union,
575 /// i.e., all the values in `self` or `other`, without duplicates.
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use std::collections::HashSet;
581 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
582 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
583 ///
584 /// // Print 1, 2, 3, 4 in arbitrary order.
585 /// for x in a.union(&b) {
586 /// println!("{}", x);
587 /// }
588 ///
589 /// let union: HashSet<_> = a.union(&b).collect();
590 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
591 /// ```
592 #[inline]
593 #[stable(feature = "rust1", since = "1.0.0")]
594 pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
595 if self.len() >= other.len() {
596 Union { iter: self.iter().chain(other.difference(self)) }
597 } else {
598 Union { iter: other.iter().chain(self.difference(other)) }
599 }
600 }
601
602 /// Returns `true` if the set contains a value.
603 ///
604 /// The value may be any borrowed form of the set's value type, but
605 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
606 /// the value type.
607 ///
608 /// # Examples
609 ///
610 /// ```
611 /// use std::collections::HashSet;
612 ///
613 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
614 /// assert_eq!(set.contains(&1), true);
615 /// assert_eq!(set.contains(&4), false);
616 /// ```
617 #[inline]
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
620 where
621 T: Borrow<Q>,
622 Q: Hash + Eq,
623 {
624 self.base.contains(value)
625 }
626
627 /// Returns a reference to the value in the set, if any, that is equal to the given value.
628 ///
629 /// The value may be any borrowed form of the set's value type, but
630 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
631 /// the value type.
632 ///
633 /// # Examples
634 ///
635 /// ```
636 /// use std::collections::HashSet;
637 ///
638 /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
639 /// assert_eq!(set.get(&2), Some(&2));
640 /// assert_eq!(set.get(&4), None);
641 /// ```
642 #[inline]
643 #[stable(feature = "set_recovery", since = "1.9.0")]
644 pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
645 where
646 T: Borrow<Q>,
647 Q: Hash + Eq,
648 {
649 self.base.get(value)
650 }
651
652 /// Inserts the given `value` into the set if it is not present, then
653 /// returns a reference to the value in the set.
654 ///
655 /// # Examples
656 ///
657 /// ```
658 /// #![feature(hash_set_entry)]
659 ///
660 /// use std::collections::HashSet;
661 ///
662 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
663 /// assert_eq!(set.len(), 3);
664 /// assert_eq!(set.get_or_insert(2), &2);
665 /// assert_eq!(set.get_or_insert(100), &100);
666 /// assert_eq!(set.len(), 4); // 100 was inserted
667 /// ```
668 #[inline]
669 #[unstable(feature = "hash_set_entry", issue = "60896")]
670 pub fn get_or_insert(&mut self, value: T) -> &T {
671 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
672 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
673 self.base.get_or_insert(value)
674 }
675
676 /// Inserts an owned copy of the given `value` into the set if it is not
677 /// present, then returns a reference to the value in the set.
678 ///
679 /// # Examples
680 ///
681 /// ```
682 /// #![feature(hash_set_entry)]
683 ///
684 /// use std::collections::HashSet;
685 ///
686 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
687 /// .iter().map(|&pet| pet.to_owned()).collect();
688 ///
689 /// assert_eq!(set.len(), 3);
690 /// for &pet in &["cat", "dog", "fish"] {
691 /// let value = set.get_or_insert_owned(pet);
692 /// assert_eq!(value, pet);
693 /// }
694 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
695 /// ```
696 #[inline]
697 #[unstable(feature = "hash_set_entry", issue = "60896")]
698 pub fn get_or_insert_owned<Q: ?Sized>(&mut self, value: &Q) -> &T
699 where
700 T: Borrow<Q>,
701 Q: Hash + Eq + ToOwned<Owned = T>,
702 {
703 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
704 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
705 self.base.get_or_insert_owned(value)
706 }
707
708 /// Inserts a value computed from `f` into the set if the given `value` is
709 /// not present, then returns a reference to the value in the set.
710 ///
711 /// # Examples
712 ///
713 /// ```
714 /// #![feature(hash_set_entry)]
715 ///
716 /// use std::collections::HashSet;
717 ///
718 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
719 /// .iter().map(|&pet| pet.to_owned()).collect();
720 ///
721 /// assert_eq!(set.len(), 3);
722 /// for &pet in &["cat", "dog", "fish"] {
723 /// let value = set.get_or_insert_with(pet, str::to_owned);
724 /// assert_eq!(value, pet);
725 /// }
726 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
727 /// ```
728 #[inline]
729 #[unstable(feature = "hash_set_entry", issue = "60896")]
730 pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T
731 where
732 T: Borrow<Q>,
733 Q: Hash + Eq,
734 F: FnOnce(&Q) -> T,
735 {
736 // Although the raw entry gives us `&mut T`, we only return `&T` to be consistent with
737 // `get`. Key mutation is "raw" because you're not supposed to affect `Eq` or `Hash`.
738 self.base.get_or_insert_with(value, f)
739 }
740
741 /// Returns `true` if `self` has no elements in common with `other`.
742 /// This is equivalent to checking for an empty intersection.
743 ///
744 /// # Examples
745 ///
746 /// ```
747 /// use std::collections::HashSet;
748 ///
749 /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
750 /// let mut b = HashSet::new();
751 ///
752 /// assert_eq!(a.is_disjoint(&b), true);
753 /// b.insert(4);
754 /// assert_eq!(a.is_disjoint(&b), true);
755 /// b.insert(1);
756 /// assert_eq!(a.is_disjoint(&b), false);
757 /// ```
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
760 if self.len() <= other.len() {
761 self.iter().all(|v| !other.contains(v))
762 } else {
763 other.iter().all(|v| !self.contains(v))
764 }
765 }
766
767 /// Returns `true` if the set is a subset of another,
768 /// i.e., `other` contains at least all the values in `self`.
769 ///
770 /// # Examples
771 ///
772 /// ```
773 /// use std::collections::HashSet;
774 ///
775 /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
776 /// let mut set = HashSet::new();
777 ///
778 /// assert_eq!(set.is_subset(&sup), true);
779 /// set.insert(2);
780 /// assert_eq!(set.is_subset(&sup), true);
781 /// set.insert(4);
782 /// assert_eq!(set.is_subset(&sup), false);
783 /// ```
784 #[stable(feature = "rust1", since = "1.0.0")]
785 pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
786 if self.len() <= other.len() { self.iter().all(|v| other.contains(v)) } else { false }
787 }
788
789 /// Returns `true` if the set is a superset of another,
790 /// i.e., `self` contains at least all the values in `other`.
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// use std::collections::HashSet;
796 ///
797 /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
798 /// let mut set = HashSet::new();
799 ///
800 /// assert_eq!(set.is_superset(&sub), false);
801 ///
802 /// set.insert(0);
803 /// set.insert(1);
804 /// assert_eq!(set.is_superset(&sub), false);
805 ///
806 /// set.insert(2);
807 /// assert_eq!(set.is_superset(&sub), true);
808 /// ```
809 #[inline]
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
812 other.is_subset(self)
813 }
814
815 /// Adds a value to the set.
816 ///
817 /// If the set did not have this value present, `true` is returned.
818 ///
819 /// If the set did have this value present, `false` is returned.
820 ///
821 /// # Examples
822 ///
823 /// ```
824 /// use std::collections::HashSet;
825 ///
826 /// let mut set = HashSet::new();
827 ///
828 /// assert_eq!(set.insert(2), true);
829 /// assert_eq!(set.insert(2), false);
830 /// assert_eq!(set.len(), 1);
831 /// ```
832 #[inline]
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn insert(&mut self, value: T) -> bool {
835 self.base.insert(value)
836 }
837
838 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
839 /// one. Returns the replaced value.
840 ///
841 /// # Examples
842 ///
843 /// ```
844 /// use std::collections::HashSet;
845 ///
846 /// let mut set = HashSet::new();
847 /// set.insert(Vec::<i32>::new());
848 ///
849 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
850 /// set.replace(Vec::with_capacity(10));
851 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
852 /// ```
853 #[inline]
854 #[stable(feature = "set_recovery", since = "1.9.0")]
855 pub fn replace(&mut self, value: T) -> Option<T> {
856 self.base.replace(value)
857 }
858
859 /// Removes a value from the set. Returns whether the value was
860 /// present in the set.
861 ///
862 /// The value may be any borrowed form of the set's value type, but
863 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
864 /// the value type.
865 ///
866 /// # Examples
867 ///
868 /// ```
869 /// use std::collections::HashSet;
870 ///
871 /// let mut set = HashSet::new();
872 ///
873 /// set.insert(2);
874 /// assert_eq!(set.remove(&2), true);
875 /// assert_eq!(set.remove(&2), false);
876 /// ```
877 #[inline]
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
880 where
881 T: Borrow<Q>,
882 Q: Hash + Eq,
883 {
884 self.base.remove(value)
885 }
886
887 /// Removes and returns the value in the set, if any, that is equal to the given one.
888 ///
889 /// The value may be any borrowed form of the set's value type, but
890 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
891 /// the value type.
892 ///
893 /// # Examples
894 ///
895 /// ```
896 /// use std::collections::HashSet;
897 ///
898 /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
899 /// assert_eq!(set.take(&2), Some(2));
900 /// assert_eq!(set.take(&2), None);
901 /// ```
902 #[inline]
903 #[stable(feature = "set_recovery", since = "1.9.0")]
904 pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
905 where
906 T: Borrow<Q>,
907 Q: Hash + Eq,
908 {
909 self.base.take(value)
910 }
911
912 /// Retains only the elements specified by the predicate.
913 ///
914 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
915 ///
916 /// # Examples
917 ///
918 /// ```
919 /// use std::collections::HashSet;
920 ///
921 /// let xs = [1, 2, 3, 4, 5, 6];
922 /// let mut set: HashSet<i32> = xs.iter().cloned().collect();
923 /// set.retain(|&k| k % 2 == 0);
924 /// assert_eq!(set.len(), 3);
925 /// ```
926 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
927 pub fn retain<F>(&mut self, f: F)
928 where
929 F: FnMut(&T) -> bool,
930 {
931 self.base.retain(f)
932 }
933 }
934
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<T, S> PartialEq for HashSet<T, S>
937 where
938 T: Eq + Hash,
939 S: BuildHasher,
940 {
941 fn eq(&self, other: &HashSet<T, S>) -> bool {
942 if self.len() != other.len() {
943 return false;
944 }
945
946 self.iter().all(|key| other.contains(key))
947 }
948 }
949
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl<T, S> Eq for HashSet<T, S>
952 where
953 T: Eq + Hash,
954 S: BuildHasher,
955 {
956 }
957
958 #[stable(feature = "rust1", since = "1.0.0")]
959 impl<T, S> fmt::Debug for HashSet<T, S>
960 where
961 T: fmt::Debug,
962 {
963 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
964 f.debug_set().entries(self.iter()).finish()
965 }
966 }
967
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<T, S> FromIterator<T> for HashSet<T, S>
970 where
971 T: Eq + Hash,
972 S: BuildHasher + Default,
973 {
974 #[inline]
975 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
976 let mut set = HashSet::with_hasher(Default::default());
977 set.extend(iter);
978 set
979 }
980 }
981
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T, S> Extend<T> for HashSet<T, S>
984 where
985 T: Eq + Hash,
986 S: BuildHasher,
987 {
988 #[inline]
989 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
990 self.base.extend(iter);
991 }
992
993 #[inline]
994 fn extend_one(&mut self, item: T) {
995 self.base.insert(item);
996 }
997
998 #[inline]
999 fn extend_reserve(&mut self, additional: usize) {
1000 self.base.extend_reserve(additional);
1001 }
1002 }
1003
1004 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
1005 impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
1006 where
1007 T: 'a + Eq + Hash + Copy,
1008 S: BuildHasher,
1009 {
1010 #[inline]
1011 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1012 self.extend(iter.into_iter().cloned());
1013 }
1014
1015 #[inline]
1016 fn extend_one(&mut self, &item: &'a T) {
1017 self.base.insert(item);
1018 }
1019
1020 #[inline]
1021 fn extend_reserve(&mut self, additional: usize) {
1022 Extend::<T>::extend_reserve(self, additional)
1023 }
1024 }
1025
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<T, S> Default for HashSet<T, S>
1028 where
1029 S: Default,
1030 {
1031 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1032 #[inline]
1033 fn default() -> HashSet<T, S> {
1034 HashSet { base: Default::default() }
1035 }
1036 }
1037
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
1040 where
1041 T: Eq + Hash + Clone,
1042 S: BuildHasher + Default,
1043 {
1044 type Output = HashSet<T, S>;
1045
1046 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// use std::collections::HashSet;
1052 ///
1053 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1054 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1055 ///
1056 /// let set = &a | &b;
1057 ///
1058 /// let mut i = 0;
1059 /// let expected = [1, 2, 3, 4, 5];
1060 /// for x in &set {
1061 /// assert!(expected.contains(x));
1062 /// i += 1;
1063 /// }
1064 /// assert_eq!(i, expected.len());
1065 /// ```
1066 fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1067 self.union(rhs).cloned().collect()
1068 }
1069 }
1070
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<T, S> BitAnd<&HashSet<T, S>> for &HashSet<T, S>
1073 where
1074 T: Eq + Hash + Clone,
1075 S: BuildHasher + Default,
1076 {
1077 type Output = HashSet<T, S>;
1078
1079 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```
1084 /// use std::collections::HashSet;
1085 ///
1086 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1087 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1088 ///
1089 /// let set = &a & &b;
1090 ///
1091 /// let mut i = 0;
1092 /// let expected = [2, 3];
1093 /// for x in &set {
1094 /// assert!(expected.contains(x));
1095 /// i += 1;
1096 /// }
1097 /// assert_eq!(i, expected.len());
1098 /// ```
1099 fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1100 self.intersection(rhs).cloned().collect()
1101 }
1102 }
1103
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<T, S> BitXor<&HashSet<T, S>> for &HashSet<T, S>
1106 where
1107 T: Eq + Hash + Clone,
1108 S: BuildHasher + Default,
1109 {
1110 type Output = HashSet<T, S>;
1111
1112 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1113 ///
1114 /// # Examples
1115 ///
1116 /// ```
1117 /// use std::collections::HashSet;
1118 ///
1119 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1120 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1121 ///
1122 /// let set = &a ^ &b;
1123 ///
1124 /// let mut i = 0;
1125 /// let expected = [1, 2, 4, 5];
1126 /// for x in &set {
1127 /// assert!(expected.contains(x));
1128 /// i += 1;
1129 /// }
1130 /// assert_eq!(i, expected.len());
1131 /// ```
1132 fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1133 self.symmetric_difference(rhs).cloned().collect()
1134 }
1135 }
1136
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<T, S> Sub<&HashSet<T, S>> for &HashSet<T, S>
1139 where
1140 T: Eq + Hash + Clone,
1141 S: BuildHasher + Default,
1142 {
1143 type Output = HashSet<T, S>;
1144
1145 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1146 ///
1147 /// # Examples
1148 ///
1149 /// ```
1150 /// use std::collections::HashSet;
1151 ///
1152 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1153 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1154 ///
1155 /// let set = &a - &b;
1156 ///
1157 /// let mut i = 0;
1158 /// let expected = [1, 2];
1159 /// for x in &set {
1160 /// assert!(expected.contains(x));
1161 /// i += 1;
1162 /// }
1163 /// assert_eq!(i, expected.len());
1164 /// ```
1165 fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
1166 self.difference(rhs).cloned().collect()
1167 }
1168 }
1169
1170 /// An iterator over the items of a `HashSet`.
1171 ///
1172 /// This `struct` is created by the [`iter`] method on [`HashSet`].
1173 /// See its documentation for more.
1174 ///
1175 /// [`iter`]: HashSet::iter
1176 ///
1177 /// # Examples
1178 ///
1179 /// ```
1180 /// use std::collections::HashSet;
1181 ///
1182 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1183 ///
1184 /// let mut iter = a.iter();
1185 /// ```
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 pub struct Iter<'a, K: 'a> {
1188 base: base::Iter<'a, K>,
1189 }
1190
1191 /// An owning iterator over the items of a `HashSet`.
1192 ///
1193 /// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1194 /// (provided by the `IntoIterator` trait). See its documentation for more.
1195 ///
1196 /// [`into_iter`]: IntoIterator::into_iter
1197 ///
1198 /// # Examples
1199 ///
1200 /// ```
1201 /// use std::collections::HashSet;
1202 ///
1203 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1204 ///
1205 /// let mut iter = a.into_iter();
1206 /// ```
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 pub struct IntoIter<K> {
1209 base: base::IntoIter<K>,
1210 }
1211
1212 /// A draining iterator over the items of a `HashSet`.
1213 ///
1214 /// This `struct` is created by the [`drain`] method on [`HashSet`].
1215 /// See its documentation for more.
1216 ///
1217 /// [`drain`]: HashSet::drain
1218 ///
1219 /// # Examples
1220 ///
1221 /// ```
1222 /// use std::collections::HashSet;
1223 ///
1224 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1225 ///
1226 /// let mut drain = a.drain();
1227 /// ```
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub struct Drain<'a, K: 'a> {
1230 base: base::Drain<'a, K>,
1231 }
1232
1233 /// A draining, filtering iterator over the items of a `HashSet`.
1234 ///
1235 /// This `struct` is created by the [`drain_filter`] method on [`HashSet`].
1236 ///
1237 /// [`drain_filter`]: HashSet::drain_filter
1238 ///
1239 /// # Examples
1240 ///
1241 /// ```
1242 /// #![feature(hash_drain_filter)]
1243 ///
1244 /// use std::collections::HashSet;
1245 ///
1246 /// let mut a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1247 ///
1248 /// let mut drain_filtered = a.drain_filter(|v| v % 2 == 0);
1249 /// ```
1250 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1251 pub struct DrainFilter<'a, K, F>
1252 where
1253 F: FnMut(&K) -> bool,
1254 {
1255 base: base::DrainFilter<'a, K, F>,
1256 }
1257
1258 /// A lazy iterator producing elements in the intersection of `HashSet`s.
1259 ///
1260 /// This `struct` is created by the [`intersection`] method on [`HashSet`].
1261 /// See its documentation for more.
1262 ///
1263 /// [`intersection`]: HashSet::intersection
1264 ///
1265 /// # Examples
1266 ///
1267 /// ```
1268 /// use std::collections::HashSet;
1269 ///
1270 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1271 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1272 ///
1273 /// let mut intersection = a.intersection(&b);
1274 /// ```
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub struct Intersection<'a, T: 'a, S: 'a> {
1277 // iterator of the first set
1278 iter: Iter<'a, T>,
1279 // the second set
1280 other: &'a HashSet<T, S>,
1281 }
1282
1283 /// A lazy iterator producing elements in the difference of `HashSet`s.
1284 ///
1285 /// This `struct` is created by the [`difference`] method on [`HashSet`].
1286 /// See its documentation for more.
1287 ///
1288 /// [`difference`]: HashSet::difference
1289 ///
1290 /// # Examples
1291 ///
1292 /// ```
1293 /// use std::collections::HashSet;
1294 ///
1295 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1296 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1297 ///
1298 /// let mut difference = a.difference(&b);
1299 /// ```
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 pub struct Difference<'a, T: 'a, S: 'a> {
1302 // iterator of the first set
1303 iter: Iter<'a, T>,
1304 // the second set
1305 other: &'a HashSet<T, S>,
1306 }
1307
1308 /// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1309 ///
1310 /// This `struct` is created by the [`symmetric_difference`] method on
1311 /// [`HashSet`]. See its documentation for more.
1312 ///
1313 /// [`symmetric_difference`]: HashSet::symmetric_difference
1314 ///
1315 /// # Examples
1316 ///
1317 /// ```
1318 /// use std::collections::HashSet;
1319 ///
1320 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1321 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1322 ///
1323 /// let mut intersection = a.symmetric_difference(&b);
1324 /// ```
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 pub struct SymmetricDifference<'a, T: 'a, S: 'a> {
1327 iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>>,
1328 }
1329
1330 /// A lazy iterator producing elements in the union of `HashSet`s.
1331 ///
1332 /// This `struct` is created by the [`union`] method on [`HashSet`].
1333 /// See its documentation for more.
1334 ///
1335 /// [`union`]: HashSet::union
1336 ///
1337 /// # Examples
1338 ///
1339 /// ```
1340 /// use std::collections::HashSet;
1341 ///
1342 /// let a: HashSet<u32> = vec![1, 2, 3].into_iter().collect();
1343 /// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
1344 ///
1345 /// let mut union_iter = a.union(&b);
1346 /// ```
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 pub struct Union<'a, T: 'a, S: 'a> {
1349 iter: Chain<Iter<'a, T>, Difference<'a, T, S>>,
1350 }
1351
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl<'a, T, S> IntoIterator for &'a HashSet<T, S> {
1354 type Item = &'a T;
1355 type IntoIter = Iter<'a, T>;
1356
1357 #[inline]
1358 fn into_iter(self) -> Iter<'a, T> {
1359 self.iter()
1360 }
1361 }
1362
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 impl<T, S> IntoIterator for HashSet<T, S> {
1365 type Item = T;
1366 type IntoIter = IntoIter<T>;
1367
1368 /// Creates a consuming iterator, that is, one that moves each value out
1369 /// of the set in arbitrary order. The set cannot be used after calling
1370 /// this.
1371 ///
1372 /// # Examples
1373 ///
1374 /// ```
1375 /// use std::collections::HashSet;
1376 /// let mut set = HashSet::new();
1377 /// set.insert("a".to_string());
1378 /// set.insert("b".to_string());
1379 ///
1380 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1381 /// let v: Vec<String> = set.into_iter().collect();
1382 ///
1383 /// // Will print in an arbitrary order.
1384 /// for x in &v {
1385 /// println!("{}", x);
1386 /// }
1387 /// ```
1388 #[inline]
1389 fn into_iter(self) -> IntoIter<T> {
1390 IntoIter { base: self.base.into_iter() }
1391 }
1392 }
1393
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 impl<K> Clone for Iter<'_, K> {
1396 #[inline]
1397 fn clone(&self) -> Self {
1398 Iter { base: self.base.clone() }
1399 }
1400 }
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<'a, K> Iterator for Iter<'a, K> {
1403 type Item = &'a K;
1404
1405 #[inline]
1406 fn next(&mut self) -> Option<&'a K> {
1407 self.base.next()
1408 }
1409 #[inline]
1410 fn size_hint(&self) -> (usize, Option<usize>) {
1411 self.base.size_hint()
1412 }
1413 }
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl<K> ExactSizeIterator for Iter<'_, K> {
1416 #[inline]
1417 fn len(&self) -> usize {
1418 self.base.len()
1419 }
1420 }
1421 #[stable(feature = "fused", since = "1.26.0")]
1422 impl<K> FusedIterator for Iter<'_, K> {}
1423
1424 #[stable(feature = "std_debug", since = "1.16.0")]
1425 impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427 f.debug_list().entries(self.clone()).finish()
1428 }
1429 }
1430
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<K> Iterator for IntoIter<K> {
1433 type Item = K;
1434
1435 #[inline]
1436 fn next(&mut self) -> Option<K> {
1437 self.base.next()
1438 }
1439 #[inline]
1440 fn size_hint(&self) -> (usize, Option<usize>) {
1441 self.base.size_hint()
1442 }
1443 }
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<K> ExactSizeIterator for IntoIter<K> {
1446 #[inline]
1447 fn len(&self) -> usize {
1448 self.base.len()
1449 }
1450 }
1451 #[stable(feature = "fused", since = "1.26.0")]
1452 impl<K> FusedIterator for IntoIter<K> {}
1453
1454 #[stable(feature = "std_debug", since = "1.16.0")]
1455 impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
1456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1457 fmt::Debug::fmt(&self.base, f)
1458 }
1459 }
1460
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<'a, K> Iterator for Drain<'a, K> {
1463 type Item = K;
1464
1465 #[inline]
1466 fn next(&mut self) -> Option<K> {
1467 self.base.next()
1468 }
1469 #[inline]
1470 fn size_hint(&self) -> (usize, Option<usize>) {
1471 self.base.size_hint()
1472 }
1473 }
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<K> ExactSizeIterator for Drain<'_, K> {
1476 #[inline]
1477 fn len(&self) -> usize {
1478 self.base.len()
1479 }
1480 }
1481 #[stable(feature = "fused", since = "1.26.0")]
1482 impl<K> FusedIterator for Drain<'_, K> {}
1483
1484 #[stable(feature = "std_debug", since = "1.16.0")]
1485 impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
1486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1487 fmt::Debug::fmt(&self.base, f)
1488 }
1489 }
1490
1491 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1492 impl<K, F> Iterator for DrainFilter<'_, K, F>
1493 where
1494 F: FnMut(&K) -> bool,
1495 {
1496 type Item = K;
1497
1498 #[inline]
1499 fn next(&mut self) -> Option<K> {
1500 self.base.next()
1501 }
1502 #[inline]
1503 fn size_hint(&self) -> (usize, Option<usize>) {
1504 self.base.size_hint()
1505 }
1506 }
1507
1508 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1509 impl<K, F> FusedIterator for DrainFilter<'_, K, F> where F: FnMut(&K) -> bool {}
1510
1511 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1512 impl<'a, K, F> fmt::Debug for DrainFilter<'a, K, F>
1513 where
1514 F: FnMut(&K) -> bool,
1515 {
1516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1517 f.pad("DrainFilter { .. }")
1518 }
1519 }
1520
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl<T, S> Clone for Intersection<'_, T, S> {
1523 #[inline]
1524 fn clone(&self) -> Self {
1525 Intersection { iter: self.iter.clone(), ..*self }
1526 }
1527 }
1528
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<'a, T, S> Iterator for Intersection<'a, T, S>
1531 where
1532 T: Eq + Hash,
1533 S: BuildHasher,
1534 {
1535 type Item = &'a T;
1536
1537 #[inline]
1538 fn next(&mut self) -> Option<&'a T> {
1539 loop {
1540 let elt = self.iter.next()?;
1541 if self.other.contains(elt) {
1542 return Some(elt);
1543 }
1544 }
1545 }
1546
1547 #[inline]
1548 fn size_hint(&self) -> (usize, Option<usize>) {
1549 let (_, upper) = self.iter.size_hint();
1550 (0, upper)
1551 }
1552 }
1553
1554 #[stable(feature = "std_debug", since = "1.16.0")]
1555 impl<T, S> fmt::Debug for Intersection<'_, T, S>
1556 where
1557 T: fmt::Debug + Eq + Hash,
1558 S: BuildHasher,
1559 {
1560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1561 f.debug_list().entries(self.clone()).finish()
1562 }
1563 }
1564
1565 #[stable(feature = "fused", since = "1.26.0")]
1566 impl<T, S> FusedIterator for Intersection<'_, T, S>
1567 where
1568 T: Eq + Hash,
1569 S: BuildHasher,
1570 {
1571 }
1572
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl<T, S> Clone for Difference<'_, T, S> {
1575 #[inline]
1576 fn clone(&self) -> Self {
1577 Difference { iter: self.iter.clone(), ..*self }
1578 }
1579 }
1580
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<'a, T, S> Iterator for Difference<'a, T, S>
1583 where
1584 T: Eq + Hash,
1585 S: BuildHasher,
1586 {
1587 type Item = &'a T;
1588
1589 #[inline]
1590 fn next(&mut self) -> Option<&'a T> {
1591 loop {
1592 let elt = self.iter.next()?;
1593 if !self.other.contains(elt) {
1594 return Some(elt);
1595 }
1596 }
1597 }
1598
1599 #[inline]
1600 fn size_hint(&self) -> (usize, Option<usize>) {
1601 let (_, upper) = self.iter.size_hint();
1602 (0, upper)
1603 }
1604 }
1605
1606 #[stable(feature = "fused", since = "1.26.0")]
1607 impl<T, S> FusedIterator for Difference<'_, T, S>
1608 where
1609 T: Eq + Hash,
1610 S: BuildHasher,
1611 {
1612 }
1613
1614 #[stable(feature = "std_debug", since = "1.16.0")]
1615 impl<T, S> fmt::Debug for Difference<'_, T, S>
1616 where
1617 T: fmt::Debug + Eq + Hash,
1618 S: BuildHasher,
1619 {
1620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 f.debug_list().entries(self.clone()).finish()
1622 }
1623 }
1624
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<T, S> Clone for SymmetricDifference<'_, T, S> {
1627 #[inline]
1628 fn clone(&self) -> Self {
1629 SymmetricDifference { iter: self.iter.clone() }
1630 }
1631 }
1632
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
1635 where
1636 T: Eq + Hash,
1637 S: BuildHasher,
1638 {
1639 type Item = &'a T;
1640
1641 #[inline]
1642 fn next(&mut self) -> Option<&'a T> {
1643 self.iter.next()
1644 }
1645 #[inline]
1646 fn size_hint(&self) -> (usize, Option<usize>) {
1647 self.iter.size_hint()
1648 }
1649 }
1650
1651 #[stable(feature = "fused", since = "1.26.0")]
1652 impl<T, S> FusedIterator for SymmetricDifference<'_, T, S>
1653 where
1654 T: Eq + Hash,
1655 S: BuildHasher,
1656 {
1657 }
1658
1659 #[stable(feature = "std_debug", since = "1.16.0")]
1660 impl<T, S> fmt::Debug for SymmetricDifference<'_, T, S>
1661 where
1662 T: fmt::Debug + Eq + Hash,
1663 S: BuildHasher,
1664 {
1665 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1666 f.debug_list().entries(self.clone()).finish()
1667 }
1668 }
1669
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 impl<T, S> Clone for Union<'_, T, S> {
1672 #[inline]
1673 fn clone(&self) -> Self {
1674 Union { iter: self.iter.clone() }
1675 }
1676 }
1677
1678 #[stable(feature = "fused", since = "1.26.0")]
1679 impl<T, S> FusedIterator for Union<'_, T, S>
1680 where
1681 T: Eq + Hash,
1682 S: BuildHasher,
1683 {
1684 }
1685
1686 #[stable(feature = "std_debug", since = "1.16.0")]
1687 impl<T, S> fmt::Debug for Union<'_, T, S>
1688 where
1689 T: fmt::Debug + Eq + Hash,
1690 S: BuildHasher,
1691 {
1692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1693 f.debug_list().entries(self.clone()).finish()
1694 }
1695 }
1696
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<'a, T, S> Iterator for Union<'a, T, S>
1699 where
1700 T: Eq + Hash,
1701 S: BuildHasher,
1702 {
1703 type Item = &'a T;
1704
1705 #[inline]
1706 fn next(&mut self) -> Option<&'a T> {
1707 self.iter.next()
1708 }
1709 #[inline]
1710 fn size_hint(&self) -> (usize, Option<usize>) {
1711 self.iter.size_hint()
1712 }
1713 }
1714
1715 #[allow(dead_code)]
1716 fn assert_covariance() {
1717 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
1718 v
1719 }
1720 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
1721 v
1722 }
1723 fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
1724 v
1725 }
1726 fn difference<'a, 'new>(
1727 v: Difference<'a, &'static str, RandomState>,
1728 ) -> Difference<'a, &'new str, RandomState> {
1729 v
1730 }
1731 fn symmetric_difference<'a, 'new>(
1732 v: SymmetricDifference<'a, &'static str, RandomState>,
1733 ) -> SymmetricDifference<'a, &'new str, RandomState> {
1734 v
1735 }
1736 fn intersection<'a, 'new>(
1737 v: Intersection<'a, &'static str, RandomState>,
1738 ) -> Intersection<'a, &'new str, RandomState> {
1739 v
1740 }
1741 fn union<'a, 'new>(
1742 v: Union<'a, &'static str, RandomState>,
1743 ) -> Union<'a, &'new str, RandomState> {
1744 v
1745 }
1746 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1747 d
1748 }
1749 }