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