hashbrown/set.rs
1use crate::{Equivalent, TryReserveError};
2use core::hash::{BuildHasher, Hash};
3use core::iter::{Chain, FusedIterator};
4use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Sub, SubAssign};
5use core::{fmt, mem};
6use map::make_hash;
7
8use super::map::{self, HashMap, Keys};
9use crate::raw::{Allocator, Global, RawExtractIf};
10use crate::DefaultHashBuilder;
11
12// Future Optimization (FIXME!)
13// =============================
14//
15// Iteration over zero sized values is a noop. There is no need
16// for `bucket.val` in the case of HashSet. I suppose we would need HKT
17// to get rid of it properly.
18
19/// A hash set implemented as a `HashMap` where the value is `()`.
20///
21/// As with the [`HashMap`] type, a `HashSet` requires that the elements
22/// implement the [`Eq`] and [`Hash`] traits. This can frequently be achieved by
23/// using `#[derive(PartialEq, Eq, Hash)]`. If you implement these yourself,
24/// it is important that the following property holds:
25///
26/// ```text
27/// k1 == k2 -> hash(k1) == hash(k2)
28/// ```
29///
30/// In other words, if two keys are equal, their hashes must be equal.
31///
32///
33/// It is a logic error for an item to be modified in such a way that the
34/// item's hash, as determined by the [`Hash`] trait, or its equality, as
35/// determined by the [`Eq`] trait, changes while it is in the set. This is
36/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or
37/// unsafe code.
38///
39/// It is also a logic error for the [`Hash`] implementation of a key to panic.
40/// This is generally only possible if the trait is implemented manually. If a
41/// panic does occur then the contents of the `HashSet` may become corrupted and
42/// some items may be dropped from the table.
43///
44/// # Examples
45///
46/// ```
47/// use hashbrown::HashSet;
48/// // Type inference lets us omit an explicit type signature (which
49/// // would be `HashSet<String>` in this example).
50/// let mut books = HashSet::new();
51///
52/// // Add some books.
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());
57///
58/// // Check for a specific one.
59/// if !books.contains("The Winds of Winter") {
60/// println!("We have {} books, but The Winds of Winter ain't one.",
61/// books.len());
62/// }
63///
64/// // Remove a book.
65/// books.remove("The Odyssey");
66///
67/// // Iterate over everything.
68/// for book in &books {
69/// println!("{}", book);
70/// }
71/// ```
72///
73/// The easiest way to use `HashSet` with a custom type is to derive
74/// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`]. This will in the
75/// future be implied by [`Eq`].
76///
77/// ```
78/// use hashbrown::HashSet;
79/// #[derive(Hash, Eq, PartialEq, Debug)]
80/// struct Viking {
81/// name: String,
82/// power: usize,
83/// }
84///
85/// let mut vikings = HashSet::new();
86///
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 });
91///
92/// // Use derived implementation to print the vikings.
93/// for x in &vikings {
94/// println!("{:?}", x);
95/// }
96/// ```
97///
98/// A `HashSet` with fixed list of elements can be initialized from an array:
99///
100/// ```
101/// use hashbrown::HashSet;
102///
103/// let viking_names: HashSet<&'static str> =
104/// [ "Einar", "Olaf", "Harald" ].into_iter().collect();
105/// // use the values stored in the set
106/// ```
107///
108/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
109/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
110/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
111/// [`HashMap`]: struct.HashMap.html
112/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
113/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
114pub struct HashSet<T, S = DefaultHashBuilder, A: Allocator = Global> {
115 pub(crate) map: HashMap<T, (), S, A>,
116}
117
118impl<T: Clone, S: Clone, A: Allocator + Clone> Clone for HashSet<T, S, A> {
119 fn clone(&self) -> Self {
120 HashSet {
121 map: self.map.clone(),
122 }
123 }
124
125 fn clone_from(&mut self, source: &Self) {
126 self.map.clone_from(&source.map);
127 }
128}
129
130#[cfg(feature = "default-hasher")]
131impl<T> HashSet<T, DefaultHashBuilder> {
132 /// Creates an empty `HashSet`.
133 ///
134 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
135 /// is first inserted into.
136 ///
137 /// # HashDoS resistance
138 ///
139 /// The `hash_builder` normally use a fixed key by default and that does
140 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
141 /// Users who require HashDoS resistance should explicitly use
142 /// [`std::collections::hash_map::RandomState`]
143 /// as the hasher when creating a [`HashSet`], for example with
144 /// [`with_hasher`](HashSet::with_hasher) method.
145 ///
146 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
147 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use hashbrown::HashSet;
153 /// let set: HashSet<i32> = HashSet::new();
154 /// ```
155 #[cfg_attr(feature = "inline-more", inline)]
156 pub fn new() -> Self {
157 Self {
158 map: HashMap::new(),
159 }
160 }
161
162 /// Creates an empty `HashSet` with the specified capacity.
163 ///
164 /// The hash set will be able to hold at least `capacity` elements without
165 /// reallocating. If `capacity` is 0, the hash set will not allocate.
166 ///
167 /// # HashDoS resistance
168 ///
169 /// The `hash_builder` normally use a fixed key by default and that does
170 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
171 /// Users who require HashDoS resistance should explicitly use
172 /// [`std::collections::hash_map::RandomState`]
173 /// as the hasher when creating a [`HashSet`], for example with
174 /// [`with_capacity_and_hasher`](HashSet::with_capacity_and_hasher) method.
175 ///
176 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
177 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
178 ///
179 /// # Examples
180 ///
181 /// ```
182 /// use hashbrown::HashSet;
183 /// let set: HashSet<i32> = HashSet::with_capacity(10);
184 /// assert!(set.capacity() >= 10);
185 /// ```
186 #[cfg_attr(feature = "inline-more", inline)]
187 pub fn with_capacity(capacity: usize) -> Self {
188 Self {
189 map: HashMap::with_capacity(capacity),
190 }
191 }
192}
193
194#[cfg(feature = "default-hasher")]
195impl<T: Hash + Eq, A: Allocator> HashSet<T, DefaultHashBuilder, A> {
196 /// Creates an empty `HashSet`.
197 ///
198 /// The hash set is initially created with a capacity of 0, so it will not allocate until it
199 /// is first inserted into.
200 ///
201 /// # HashDoS resistance
202 ///
203 /// The `hash_builder` normally use a fixed key by default and that does
204 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
205 /// Users who require HashDoS resistance should explicitly use
206 /// [`std::collections::hash_map::RandomState`]
207 /// as the hasher when creating a [`HashSet`], for example with
208 /// [`with_hasher_in`](HashSet::with_hasher_in) method.
209 ///
210 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
211 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// use hashbrown::HashSet;
217 /// let set: HashSet<i32> = HashSet::new();
218 /// ```
219 #[cfg_attr(feature = "inline-more", inline)]
220 pub fn new_in(alloc: A) -> Self {
221 Self {
222 map: HashMap::new_in(alloc),
223 }
224 }
225
226 /// Creates an empty `HashSet` with the specified capacity.
227 ///
228 /// The hash set will be able to hold at least `capacity` elements without
229 /// reallocating. If `capacity` is 0, the hash set will not allocate.
230 ///
231 /// # HashDoS resistance
232 ///
233 /// The `hash_builder` normally use a fixed key by default and that does
234 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
235 /// Users who require HashDoS resistance should explicitly use
236 /// [`std::collections::hash_map::RandomState`]
237 /// as the hasher when creating a [`HashSet`], for example with
238 /// [`with_capacity_and_hasher_in`](HashSet::with_capacity_and_hasher_in) method.
239 ///
240 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
241 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
242 ///
243 /// # Examples
244 ///
245 /// ```
246 /// use hashbrown::HashSet;
247 /// let set: HashSet<i32> = HashSet::with_capacity(10);
248 /// assert!(set.capacity() >= 10);
249 /// ```
250 #[cfg_attr(feature = "inline-more", inline)]
251 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
252 Self {
253 map: HashMap::with_capacity_in(capacity, alloc),
254 }
255 }
256}
257
258impl<T, S, A: Allocator> HashSet<T, S, A> {
259 /// Returns the number of elements the set can hold without reallocating.
260 ///
261 /// # Examples
262 ///
263 /// ```
264 /// use hashbrown::HashSet;
265 /// let set: HashSet<i32> = HashSet::with_capacity(100);
266 /// assert!(set.capacity() >= 100);
267 /// ```
268 #[cfg_attr(feature = "inline-more", inline)]
269 pub fn capacity(&self) -> usize {
270 self.map.capacity()
271 }
272
273 /// An iterator visiting all elements in arbitrary order.
274 /// The iterator element type is `&'a T`.
275 ///
276 /// # Examples
277 ///
278 /// ```
279 /// use hashbrown::HashSet;
280 /// let mut set = HashSet::new();
281 /// set.insert("a");
282 /// set.insert("b");
283 ///
284 /// // Will print in an arbitrary order.
285 /// for x in set.iter() {
286 /// println!("{}", x);
287 /// }
288 /// ```
289 #[cfg_attr(feature = "inline-more", inline)]
290 pub fn iter(&self) -> Iter<'_, T> {
291 Iter {
292 iter: self.map.keys(),
293 }
294 }
295
296 /// Returns the number of elements in the set.
297 ///
298 /// # Examples
299 ///
300 /// ```
301 /// use hashbrown::HashSet;
302 ///
303 /// let mut v = HashSet::new();
304 /// assert_eq!(v.len(), 0);
305 /// v.insert(1);
306 /// assert_eq!(v.len(), 1);
307 /// ```
308 #[cfg_attr(feature = "inline-more", inline)]
309 pub fn len(&self) -> usize {
310 self.map.len()
311 }
312
313 /// Returns `true` if the set contains no elements.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// use hashbrown::HashSet;
319 ///
320 /// let mut v = HashSet::new();
321 /// assert!(v.is_empty());
322 /// v.insert(1);
323 /// assert!(!v.is_empty());
324 /// ```
325 #[cfg_attr(feature = "inline-more", inline)]
326 pub fn is_empty(&self) -> bool {
327 self.map.is_empty()
328 }
329
330 /// Clears the set, returning all elements in an iterator.
331 ///
332 /// # Examples
333 ///
334 /// ```
335 /// use hashbrown::HashSet;
336 ///
337 /// let mut set: HashSet<_> = [1, 2, 3].into_iter().collect();
338 /// assert!(!set.is_empty());
339 ///
340 /// // print 1, 2, 3 in an arbitrary order
341 /// for i in set.drain() {
342 /// println!("{}", i);
343 /// }
344 ///
345 /// assert!(set.is_empty());
346 /// ```
347 #[cfg_attr(feature = "inline-more", inline)]
348 pub fn drain(&mut self) -> Drain<'_, T, A> {
349 Drain {
350 iter: self.map.drain(),
351 }
352 }
353
354 /// Retains only the elements specified by the predicate.
355 ///
356 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// use hashbrown::HashSet;
362 ///
363 /// let xs = [1,2,3,4,5,6];
364 /// let mut set: HashSet<i32> = xs.into_iter().collect();
365 /// set.retain(|&k| k % 2 == 0);
366 /// assert_eq!(set.len(), 3);
367 /// ```
368 pub fn retain<F>(&mut self, mut f: F)
369 where
370 F: FnMut(&T) -> bool,
371 {
372 self.map.retain(|k, _| f(k));
373 }
374
375 /// Drains elements which are true under the given predicate,
376 /// and returns an iterator over the removed items.
377 ///
378 /// In other words, move all elements `e` such that `f(&e)` returns `true` out
379 /// into another iterator.
380 ///
381 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
382 /// or the iteration short-circuits, then the remaining elements will be retained.
383 /// Use [`retain()`] with a negated predicate if you do not need the returned iterator.
384 ///
385 /// [`retain()`]: HashSet::retain
386 ///
387 /// # Examples
388 ///
389 /// ```
390 /// use hashbrown::HashSet;
391 ///
392 /// let mut set: HashSet<i32> = (0..8).collect();
393 /// let drained: HashSet<i32> = set.extract_if(|v| v % 2 == 0).collect();
394 ///
395 /// let mut evens = drained.into_iter().collect::<Vec<_>>();
396 /// let mut odds = set.into_iter().collect::<Vec<_>>();
397 /// evens.sort();
398 /// odds.sort();
399 ///
400 /// assert_eq!(evens, vec![0, 2, 4, 6]);
401 /// assert_eq!(odds, vec![1, 3, 5, 7]);
402 /// ```
403 #[cfg_attr(feature = "inline-more", inline)]
404 pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, T, F, A>
405 where
406 F: FnMut(&T) -> bool,
407 {
408 ExtractIf {
409 f,
410 inner: RawExtractIf {
411 iter: unsafe { self.map.table.iter() },
412 table: &mut self.map.table,
413 },
414 }
415 }
416
417 /// Clears the set, removing all values.
418 ///
419 /// # Examples
420 ///
421 /// ```
422 /// use hashbrown::HashSet;
423 ///
424 /// let mut v = HashSet::new();
425 /// v.insert(1);
426 /// v.clear();
427 /// assert!(v.is_empty());
428 /// ```
429 #[cfg_attr(feature = "inline-more", inline)]
430 pub fn clear(&mut self) {
431 self.map.clear();
432 }
433}
434
435impl<T, S> HashSet<T, S, Global> {
436 /// Creates a new empty hash set which will use the given hasher to hash
437 /// keys.
438 ///
439 /// The hash set is initially created with a capacity of 0, so it will not
440 /// allocate until it is first inserted into.
441 ///
442 /// # HashDoS resistance
443 ///
444 /// The `hash_builder` normally use a fixed key by default and that does
445 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
446 /// Users who require HashDoS resistance should explicitly use
447 /// [`std::collections::hash_map::RandomState`]
448 /// as the hasher when creating a [`HashSet`].
449 ///
450 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
451 /// the `HashSet` to be useful, see its documentation for details.
452 ///
453 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
454 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
455 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// use hashbrown::HashSet;
461 /// use hashbrown::DefaultHashBuilder;
462 ///
463 /// let s = DefaultHashBuilder::default();
464 /// let mut set = HashSet::with_hasher(s);
465 /// set.insert(2);
466 /// ```
467 #[cfg_attr(feature = "inline-more", inline)]
468 pub const fn with_hasher(hasher: S) -> Self {
469 Self {
470 map: HashMap::with_hasher(hasher),
471 }
472 }
473
474 /// Creates an empty `HashSet` with the specified capacity, using
475 /// `hasher` to hash the keys.
476 ///
477 /// The hash set will be able to hold at least `capacity` elements without
478 /// reallocating. If `capacity` is 0, the hash set will not allocate.
479 ///
480 /// # HashDoS resistance
481 ///
482 /// The `hash_builder` normally use a fixed key by default and that does
483 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
484 /// Users who require HashDoS resistance should explicitly use
485 /// [`std::collections::hash_map::RandomState`]
486 /// as the hasher when creating a [`HashSet`].
487 ///
488 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
489 /// the `HashSet` to be useful, see its documentation for details.
490 ///
491 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
492 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
493 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
494 ///
495 /// # Examples
496 ///
497 /// ```
498 /// use hashbrown::HashSet;
499 /// use hashbrown::DefaultHashBuilder;
500 ///
501 /// let s = DefaultHashBuilder::default();
502 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
503 /// set.insert(1);
504 /// ```
505 #[cfg_attr(feature = "inline-more", inline)]
506 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> Self {
507 Self {
508 map: HashMap::with_capacity_and_hasher(capacity, hasher),
509 }
510 }
511}
512
513impl<T, S, A> HashSet<T, S, A>
514where
515 A: Allocator,
516{
517 /// Returns a reference to the underlying allocator.
518 #[inline]
519 pub fn allocator(&self) -> &A {
520 self.map.allocator()
521 }
522
523 /// Creates a new empty hash set which will use the given hasher to hash
524 /// keys.
525 ///
526 /// The hash set is initially created with a capacity of 0, so it will not
527 /// allocate until it is first inserted into.
528 ///
529 /// # HashDoS resistance
530 ///
531 /// The `hash_builder` normally use a fixed key by default and that does
532 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
533 /// Users who require HashDoS resistance should explicitly use
534 /// [`std::collections::hash_map::RandomState`]
535 /// as the hasher when creating a [`HashSet`].
536 ///
537 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
538 /// the `HashSet` to be useful, see its documentation for details.
539 ///
540 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
541 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
542 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
543 ///
544 /// # Examples
545 ///
546 /// ```
547 /// use hashbrown::HashSet;
548 /// use hashbrown::DefaultHashBuilder;
549 ///
550 /// let s = DefaultHashBuilder::default();
551 /// let mut set = HashSet::with_hasher(s);
552 /// set.insert(2);
553 /// ```
554 #[cfg_attr(feature = "inline-more", inline)]
555 pub const fn with_hasher_in(hasher: S, alloc: A) -> Self {
556 Self {
557 map: HashMap::with_hasher_in(hasher, alloc),
558 }
559 }
560
561 /// Creates an empty `HashSet` with the specified capacity, using
562 /// `hasher` to hash the keys.
563 ///
564 /// The hash set will be able to hold at least `capacity` elements without
565 /// reallocating. If `capacity` is 0, the hash set will not allocate.
566 ///
567 /// # HashDoS resistance
568 ///
569 /// The `hash_builder` normally use a fixed key by default and that does
570 /// not allow the `HashSet` to be protected against attacks such as [`HashDoS`].
571 /// Users who require HashDoS resistance should explicitly use
572 /// [`std::collections::hash_map::RandomState`]
573 /// as the hasher when creating a [`HashSet`].
574 ///
575 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
576 /// the `HashSet` to be useful, see its documentation for details.
577 ///
578 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
579 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
580 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// use hashbrown::HashSet;
586 /// use hashbrown::DefaultHashBuilder;
587 ///
588 /// let s = DefaultHashBuilder::default();
589 /// let mut set = HashSet::with_capacity_and_hasher(10, s);
590 /// set.insert(1);
591 /// ```
592 #[cfg_attr(feature = "inline-more", inline)]
593 pub fn with_capacity_and_hasher_in(capacity: usize, hasher: S, alloc: A) -> Self {
594 Self {
595 map: HashMap::with_capacity_and_hasher_in(capacity, hasher, alloc),
596 }
597 }
598
599 /// Returns a reference to the set's [`BuildHasher`].
600 ///
601 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// use hashbrown::HashSet;
607 /// use hashbrown::DefaultHashBuilder;
608 ///
609 /// let hasher = DefaultHashBuilder::default();
610 /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
611 /// let hasher: &DefaultHashBuilder = set.hasher();
612 /// ```
613 #[cfg_attr(feature = "inline-more", inline)]
614 pub fn hasher(&self) -> &S {
615 self.map.hasher()
616 }
617}
618
619impl<T, S, A> HashSet<T, S, A>
620where
621 T: Eq + Hash,
622 S: BuildHasher,
623 A: Allocator,
624{
625 /// Reserves capacity for at least `additional` more elements to be inserted
626 /// in the `HashSet`. The collection may reserve more space to avoid
627 /// frequent reallocations.
628 ///
629 /// # Panics
630 ///
631 /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
632 /// in case of allocation error. Use [`try_reserve`](HashSet::try_reserve) instead
633 /// if you want to handle memory allocation failure.
634 ///
635 /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html
636 /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use hashbrown::HashSet;
642 /// let mut set: HashSet<i32> = HashSet::new();
643 /// set.reserve(10);
644 /// assert!(set.capacity() >= 10);
645 /// ```
646 #[cfg_attr(feature = "inline-more", inline)]
647 pub fn reserve(&mut self, additional: usize) {
648 self.map.reserve(additional);
649 }
650
651 /// Tries to reserve capacity for at least `additional` more elements to be inserted
652 /// in the given `HashSet<K,V>`. The collection may reserve more space to avoid
653 /// frequent reallocations.
654 ///
655 /// # Errors
656 ///
657 /// If the capacity overflows, or the allocator reports a failure, then an error
658 /// is returned.
659 ///
660 /// # Examples
661 ///
662 /// ```
663 /// use hashbrown::HashSet;
664 /// let mut set: HashSet<i32> = HashSet::new();
665 /// set.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
666 /// ```
667 #[cfg_attr(feature = "inline-more", inline)]
668 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
669 self.map.try_reserve(additional)
670 }
671
672 /// Shrinks the capacity of the set as much as possible. It will drop
673 /// down as much as possible while maintaining the internal rules
674 /// and possibly leaving some space in accordance with the resize policy.
675 ///
676 /// # Examples
677 ///
678 /// ```
679 /// use hashbrown::HashSet;
680 ///
681 /// let mut set = HashSet::with_capacity(100);
682 /// set.insert(1);
683 /// set.insert(2);
684 /// assert!(set.capacity() >= 100);
685 /// set.shrink_to_fit();
686 /// assert!(set.capacity() >= 2);
687 /// ```
688 #[cfg_attr(feature = "inline-more", inline)]
689 pub fn shrink_to_fit(&mut self) {
690 self.map.shrink_to_fit();
691 }
692
693 /// Shrinks the capacity of the set with a lower limit. It will drop
694 /// down no lower than the supplied limit while maintaining the internal rules
695 /// and possibly leaving some space in accordance with the resize policy.
696 ///
697 /// Panics if the current capacity is smaller than the supplied
698 /// minimum capacity.
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// use hashbrown::HashSet;
704 ///
705 /// let mut set = HashSet::with_capacity(100);
706 /// set.insert(1);
707 /// set.insert(2);
708 /// assert!(set.capacity() >= 100);
709 /// set.shrink_to(10);
710 /// assert!(set.capacity() >= 10);
711 /// set.shrink_to(0);
712 /// assert!(set.capacity() >= 2);
713 /// ```
714 #[cfg_attr(feature = "inline-more", inline)]
715 pub fn shrink_to(&mut self, min_capacity: usize) {
716 self.map.shrink_to(min_capacity);
717 }
718
719 /// Visits the values representing the difference,
720 /// i.e., the values that are in `self` but not in `other`.
721 ///
722 /// # Examples
723 ///
724 /// ```
725 /// use hashbrown::HashSet;
726 /// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
727 /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect();
728 ///
729 /// // Can be seen as `a - b`.
730 /// for x in a.difference(&b) {
731 /// println!("{}", x); // Print 1
732 /// }
733 ///
734 /// let diff: HashSet<_> = a.difference(&b).collect();
735 /// assert_eq!(diff, [1].iter().collect());
736 ///
737 /// // Note that difference is not symmetric,
738 /// // and `b - a` means something else:
739 /// let diff: HashSet<_> = b.difference(&a).collect();
740 /// assert_eq!(diff, [4].iter().collect());
741 /// ```
742 #[cfg_attr(feature = "inline-more", inline)]
743 pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T, S, A> {
744 Difference {
745 iter: self.iter(),
746 other,
747 }
748 }
749
750 /// Visits the values representing the symmetric difference,
751 /// i.e., the values that are in `self` or in `other` but not in both.
752 ///
753 /// # Examples
754 ///
755 /// ```
756 /// use hashbrown::HashSet;
757 /// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
758 /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect();
759 ///
760 /// // Print 1, 4 in arbitrary order.
761 /// for x in a.symmetric_difference(&b) {
762 /// println!("{}", x);
763 /// }
764 ///
765 /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
766 /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
767 ///
768 /// assert_eq!(diff1, diff2);
769 /// assert_eq!(diff1, [1, 4].iter().collect());
770 /// ```
771 #[cfg_attr(feature = "inline-more", inline)]
772 pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, T, S, A> {
773 SymmetricDifference {
774 iter: self.difference(other).chain(other.difference(self)),
775 }
776 }
777
778 /// Visits the values representing the intersection,
779 /// i.e., the values that are both in `self` and `other`.
780 ///
781 /// # Examples
782 ///
783 /// ```
784 /// use hashbrown::HashSet;
785 /// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
786 /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect();
787 ///
788 /// // Print 2, 3 in arbitrary order.
789 /// for x in a.intersection(&b) {
790 /// println!("{}", x);
791 /// }
792 ///
793 /// let intersection: HashSet<_> = a.intersection(&b).collect();
794 /// assert_eq!(intersection, [2, 3].iter().collect());
795 /// ```
796 #[cfg_attr(feature = "inline-more", inline)]
797 pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T, S, A> {
798 let (smaller, larger) = if self.len() <= other.len() {
799 (self, other)
800 } else {
801 (other, self)
802 };
803 Intersection {
804 iter: smaller.iter(),
805 other: larger,
806 }
807 }
808
809 /// Visits the values representing the union,
810 /// i.e., all the values in `self` or `other`, without duplicates.
811 ///
812 /// # Examples
813 ///
814 /// ```
815 /// use hashbrown::HashSet;
816 /// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
817 /// let b: HashSet<_> = [4, 2, 3, 4].into_iter().collect();
818 ///
819 /// // Print 1, 2, 3, 4 in arbitrary order.
820 /// for x in a.union(&b) {
821 /// println!("{}", x);
822 /// }
823 ///
824 /// let union: HashSet<_> = a.union(&b).collect();
825 /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
826 /// ```
827 #[cfg_attr(feature = "inline-more", inline)]
828 pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T, S, A> {
829 // We'll iterate one set in full, and only the remaining difference from the other.
830 // Use the smaller set for the difference in order to reduce hash lookups.
831 let (smaller, larger) = if self.len() <= other.len() {
832 (self, other)
833 } else {
834 (other, self)
835 };
836 Union {
837 iter: larger.iter().chain(smaller.difference(larger)),
838 }
839 }
840
841 /// Returns `true` if the set contains a value.
842 ///
843 /// The value may be any borrowed form of the set's value type, but
844 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
845 /// the value type.
846 ///
847 /// # Examples
848 ///
849 /// ```
850 /// use hashbrown::HashSet;
851 ///
852 /// let set: HashSet<_> = [1, 2, 3].into_iter().collect();
853 /// assert_eq!(set.contains(&1), true);
854 /// assert_eq!(set.contains(&4), false);
855 /// ```
856 ///
857 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
858 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
859 #[cfg_attr(feature = "inline-more", inline)]
860 pub fn contains<Q>(&self, value: &Q) -> bool
861 where
862 Q: Hash + Equivalent<T> + ?Sized,
863 {
864 self.map.contains_key(value)
865 }
866
867 /// Returns a reference to the value in the set, if any, that is equal to the given value.
868 ///
869 /// The value may be any borrowed form of the set's value type, but
870 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
871 /// the value type.
872 ///
873 /// # Examples
874 ///
875 /// ```
876 /// use hashbrown::HashSet;
877 ///
878 /// let set: HashSet<_> = [1, 2, 3].into_iter().collect();
879 /// assert_eq!(set.get(&2), Some(&2));
880 /// assert_eq!(set.get(&4), None);
881 /// ```
882 ///
883 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
884 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
885 #[cfg_attr(feature = "inline-more", inline)]
886 pub fn get<Q>(&self, value: &Q) -> Option<&T>
887 where
888 Q: Hash + Equivalent<T> + ?Sized,
889 {
890 // Avoid `Option::map` because it bloats LLVM IR.
891 match self.map.get_key_value(value) {
892 Some((k, _)) => Some(k),
893 None => None,
894 }
895 }
896
897 /// Inserts the given `value` into the set if it is not present, then
898 /// returns a reference to the value in the set.
899 ///
900 /// # Examples
901 ///
902 /// ```
903 /// use hashbrown::HashSet;
904 ///
905 /// let mut set: HashSet<_> = [1, 2, 3].into_iter().collect();
906 /// assert_eq!(set.len(), 3);
907 /// assert_eq!(set.get_or_insert(2), &2);
908 /// assert_eq!(set.get_or_insert(100), &100);
909 /// assert_eq!(set.len(), 4); // 100 was inserted
910 /// ```
911 #[cfg_attr(feature = "inline-more", inline)]
912 pub fn get_or_insert(&mut self, value: T) -> &T {
913 let hash = make_hash(&self.map.hash_builder, &value);
914 let bucket = match self.map.find_or_find_insert_slot(hash, &value) {
915 Ok(bucket) => bucket,
916 Err(slot) => unsafe { self.map.table.insert_in_slot(hash, slot, (value, ())) },
917 };
918 unsafe { &bucket.as_ref().0 }
919 }
920
921 /// Inserts a value computed from `f` into the set if the given `value` is
922 /// not present, then returns a reference to the value in the set.
923 ///
924 /// # Examples
925 ///
926 /// ```
927 /// use hashbrown::HashSet;
928 ///
929 /// let mut set: HashSet<String> = ["cat", "dog", "horse"]
930 /// .iter().map(|&pet| pet.to_owned()).collect();
931 ///
932 /// assert_eq!(set.len(), 3);
933 /// for &pet in &["cat", "dog", "fish"] {
934 /// let value = set.get_or_insert_with(pet, str::to_owned);
935 /// assert_eq!(value, pet);
936 /// }
937 /// assert_eq!(set.len(), 4); // a new "fish" was inserted
938 /// ```
939 ///
940 /// The following example will panic because the new value doesn't match.
941 ///
942 /// ```should_panic
943 /// let mut set = hashbrown::HashSet::new();
944 /// set.get_or_insert_with("rust", |_| String::new());
945 /// ```
946 #[cfg_attr(feature = "inline-more", inline)]
947 pub fn get_or_insert_with<Q, F>(&mut self, value: &Q, f: F) -> &T
948 where
949 Q: Hash + Equivalent<T> + ?Sized,
950 F: FnOnce(&Q) -> T,
951 {
952 let hash = make_hash(&self.map.hash_builder, value);
953 let bucket = match self.map.find_or_find_insert_slot(hash, value) {
954 Ok(bucket) => bucket,
955 Err(slot) => {
956 let new = f(value);
957 assert!(value.equivalent(&new), "new value is not equivalent");
958 unsafe { self.map.table.insert_in_slot(hash, slot, (new, ())) }
959 }
960 };
961 unsafe { &bucket.as_ref().0 }
962 }
963
964 /// Gets the given value's corresponding entry in the set for in-place manipulation.
965 ///
966 /// # Examples
967 ///
968 /// ```
969 /// use hashbrown::HashSet;
970 /// use hashbrown::hash_set::Entry::*;
971 ///
972 /// let mut singles = HashSet::new();
973 /// let mut dupes = HashSet::new();
974 ///
975 /// for ch in "a short treatise on fungi".chars() {
976 /// if let Vacant(dupe_entry) = dupes.entry(ch) {
977 /// // We haven't already seen a duplicate, so
978 /// // check if we've at least seen it once.
979 /// match singles.entry(ch) {
980 /// Vacant(single_entry) => {
981 /// // We found a new character for the first time.
982 /// single_entry.insert();
983 /// }
984 /// Occupied(single_entry) => {
985 /// // We've already seen this once, "move" it to dupes.
986 /// single_entry.remove();
987 /// dupe_entry.insert();
988 /// }
989 /// }
990 /// }
991 /// }
992 ///
993 /// assert!(!singles.contains(&'t') && dupes.contains(&'t'));
994 /// assert!(singles.contains(&'u') && !dupes.contains(&'u'));
995 /// assert!(!singles.contains(&'v') && !dupes.contains(&'v'));
996 /// ```
997 #[cfg_attr(feature = "inline-more", inline)]
998 pub fn entry(&mut self, value: T) -> Entry<'_, T, S, A> {
999 match self.map.entry(value) {
1000 map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { inner: entry }),
1001 map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { inner: entry }),
1002 }
1003 }
1004
1005 /// Returns `true` if `self` has no elements in common with `other`.
1006 /// This is equivalent to checking for an empty intersection.
1007 ///
1008 /// # Examples
1009 ///
1010 /// ```
1011 /// use hashbrown::HashSet;
1012 ///
1013 /// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
1014 /// let mut b = HashSet::new();
1015 ///
1016 /// assert_eq!(a.is_disjoint(&b), true);
1017 /// b.insert(4);
1018 /// assert_eq!(a.is_disjoint(&b), true);
1019 /// b.insert(1);
1020 /// assert_eq!(a.is_disjoint(&b), false);
1021 /// ```
1022 pub fn is_disjoint(&self, other: &Self) -> bool {
1023 self.intersection(other).next().is_none()
1024 }
1025
1026 /// Returns `true` if the set is a subset of another,
1027 /// i.e., `other` contains at least all the values in `self`.
1028 ///
1029 /// # Examples
1030 ///
1031 /// ```
1032 /// use hashbrown::HashSet;
1033 ///
1034 /// let sup: HashSet<_> = [1, 2, 3].into_iter().collect();
1035 /// let mut set = HashSet::new();
1036 ///
1037 /// assert_eq!(set.is_subset(&sup), true);
1038 /// set.insert(2);
1039 /// assert_eq!(set.is_subset(&sup), true);
1040 /// set.insert(4);
1041 /// assert_eq!(set.is_subset(&sup), false);
1042 /// ```
1043 pub fn is_subset(&self, other: &Self) -> bool {
1044 self.len() <= other.len() && self.iter().all(|v| other.contains(v))
1045 }
1046
1047 /// Returns `true` if the set is a superset of another,
1048 /// i.e., `self` contains at least all the values in `other`.
1049 ///
1050 /// # Examples
1051 ///
1052 /// ```
1053 /// use hashbrown::HashSet;
1054 ///
1055 /// let sub: HashSet<_> = [1, 2].into_iter().collect();
1056 /// let mut set = HashSet::new();
1057 ///
1058 /// assert_eq!(set.is_superset(&sub), false);
1059 ///
1060 /// set.insert(0);
1061 /// set.insert(1);
1062 /// assert_eq!(set.is_superset(&sub), false);
1063 ///
1064 /// set.insert(2);
1065 /// assert_eq!(set.is_superset(&sub), true);
1066 /// ```
1067 #[cfg_attr(feature = "inline-more", inline)]
1068 pub fn is_superset(&self, other: &Self) -> bool {
1069 other.is_subset(self)
1070 }
1071
1072 /// Adds a value to the set.
1073 ///
1074 /// If the set did not have this value present, `true` is returned.
1075 ///
1076 /// If the set did have this value present, `false` is returned.
1077 ///
1078 /// # Examples
1079 ///
1080 /// ```
1081 /// use hashbrown::HashSet;
1082 ///
1083 /// let mut set = HashSet::new();
1084 ///
1085 /// assert_eq!(set.insert(2), true);
1086 /// assert_eq!(set.insert(2), false);
1087 /// assert_eq!(set.len(), 1);
1088 /// ```
1089 #[cfg_attr(feature = "inline-more", inline)]
1090 pub fn insert(&mut self, value: T) -> bool {
1091 self.map.insert(value, ()).is_none()
1092 }
1093
1094 /// Insert a value the set without checking if the value already exists in the set.
1095 ///
1096 /// This operation is faster than regular insert, because it does not perform
1097 /// lookup before insertion.
1098 ///
1099 /// This operation is useful during initial population of the set.
1100 /// For example, when constructing a set from another set, we know
1101 /// that values are unique.
1102 ///
1103 /// # Safety
1104 ///
1105 /// This operation is safe if a value does not exist in the set.
1106 ///
1107 /// However, if a value exists in the set already, the behavior is unspecified:
1108 /// this operation may panic, loop forever, or any following operation with the set
1109 /// may panic, loop forever or return arbitrary result.
1110 ///
1111 /// That said, this operation (and following operations) are guaranteed to
1112 /// not violate memory safety.
1113 ///
1114 /// However this operation is still unsafe because the resulting `HashSet`
1115 /// may be passed to unsafe code which does expect the set to behave
1116 /// correctly, and would cause unsoundness as a result.
1117 #[cfg_attr(feature = "inline-more", inline)]
1118 pub unsafe fn insert_unique_unchecked(&mut self, value: T) -> &T {
1119 self.map.insert_unique_unchecked(value, ()).0
1120 }
1121
1122 /// Adds a value to the set, replacing the existing value, if any, that is equal to the given
1123 /// one. Returns the replaced value.
1124 ///
1125 /// # Examples
1126 ///
1127 /// ```
1128 /// use hashbrown::HashSet;
1129 ///
1130 /// let mut set = HashSet::new();
1131 /// set.insert(Vec::<i32>::new());
1132 ///
1133 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 0);
1134 /// set.replace(Vec::with_capacity(10));
1135 /// assert_eq!(set.get(&[][..]).unwrap().capacity(), 10);
1136 /// ```
1137 #[cfg_attr(feature = "inline-more", inline)]
1138 pub fn replace(&mut self, value: T) -> Option<T> {
1139 let hash = make_hash(&self.map.hash_builder, &value);
1140 match self.map.find_or_find_insert_slot(hash, &value) {
1141 Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().0 }, value)),
1142 Err(slot) => {
1143 unsafe {
1144 self.map.table.insert_in_slot(hash, slot, (value, ()));
1145 }
1146 None
1147 }
1148 }
1149 }
1150
1151 /// Removes a value from the set. Returns whether the value was
1152 /// present in the set.
1153 ///
1154 /// The value may be any borrowed form of the set's value type, but
1155 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1156 /// the value type.
1157 ///
1158 /// # Examples
1159 ///
1160 /// ```
1161 /// use hashbrown::HashSet;
1162 ///
1163 /// let mut set = HashSet::new();
1164 ///
1165 /// set.insert(2);
1166 /// assert_eq!(set.remove(&2), true);
1167 /// assert_eq!(set.remove(&2), false);
1168 /// ```
1169 ///
1170 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1171 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1172 #[cfg_attr(feature = "inline-more", inline)]
1173 pub fn remove<Q>(&mut self, value: &Q) -> bool
1174 where
1175 Q: Hash + Equivalent<T> + ?Sized,
1176 {
1177 self.map.remove(value).is_some()
1178 }
1179
1180 /// Removes and returns the value in the set, if any, that is equal to the given one.
1181 ///
1182 /// The value may be any borrowed form of the set's value type, but
1183 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1184 /// the value type.
1185 ///
1186 /// # Examples
1187 ///
1188 /// ```
1189 /// use hashbrown::HashSet;
1190 ///
1191 /// let mut set: HashSet<_> = [1, 2, 3].into_iter().collect();
1192 /// assert_eq!(set.take(&2), Some(2));
1193 /// assert_eq!(set.take(&2), None);
1194 /// ```
1195 ///
1196 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1197 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1198 #[cfg_attr(feature = "inline-more", inline)]
1199 pub fn take<Q>(&mut self, value: &Q) -> Option<T>
1200 where
1201 Q: Hash + Equivalent<T> + ?Sized,
1202 {
1203 // Avoid `Option::map` because it bloats LLVM IR.
1204 match self.map.remove_entry(value) {
1205 Some((k, _)) => Some(k),
1206 None => None,
1207 }
1208 }
1209
1210 /// Returns the total amount of memory allocated internally by the hash
1211 /// set, in bytes.
1212 ///
1213 /// The returned number is informational only. It is intended to be
1214 /// primarily used for memory profiling.
1215 #[inline]
1216 pub fn allocation_size(&self) -> usize {
1217 self.map.allocation_size()
1218 }
1219}
1220
1221impl<T, S, A> PartialEq for HashSet<T, S, A>
1222where
1223 T: Eq + Hash,
1224 S: BuildHasher,
1225 A: Allocator,
1226{
1227 fn eq(&self, other: &Self) -> bool {
1228 if self.len() != other.len() {
1229 return false;
1230 }
1231
1232 self.iter().all(|key| other.contains(key))
1233 }
1234}
1235
1236impl<T, S, A> Eq for HashSet<T, S, A>
1237where
1238 T: Eq + Hash,
1239 S: BuildHasher,
1240 A: Allocator,
1241{
1242}
1243
1244impl<T, S, A> fmt::Debug for HashSet<T, S, A>
1245where
1246 T: fmt::Debug,
1247 A: Allocator,
1248{
1249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250 f.debug_set().entries(self.iter()).finish()
1251 }
1252}
1253
1254impl<T, S, A> From<HashMap<T, (), S, A>> for HashSet<T, S, A>
1255where
1256 A: Allocator,
1257{
1258 fn from(map: HashMap<T, (), S, A>) -> Self {
1259 Self { map }
1260 }
1261}
1262
1263impl<T, S, A> FromIterator<T> for HashSet<T, S, A>
1264where
1265 T: Eq + Hash,
1266 S: BuildHasher + Default,
1267 A: Default + Allocator,
1268{
1269 #[cfg_attr(feature = "inline-more", inline)]
1270 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1271 let mut set = Self::with_hasher_in(Default::default(), Default::default());
1272 set.extend(iter);
1273 set
1274 }
1275}
1276
1277// The default hasher is used to match the std implementation signature
1278#[cfg(feature = "default-hasher")]
1279impl<T, A, const N: usize> From<[T; N]> for HashSet<T, DefaultHashBuilder, A>
1280where
1281 T: Eq + Hash,
1282 A: Default + Allocator,
1283{
1284 /// # Examples
1285 ///
1286 /// ```
1287 /// use hashbrown::HashSet;
1288 ///
1289 /// let set1 = HashSet::from([1, 2, 3, 4]);
1290 /// let set2: HashSet<_> = [1, 2, 3, 4].into();
1291 /// assert_eq!(set1, set2);
1292 /// ```
1293 fn from(arr: [T; N]) -> Self {
1294 arr.into_iter().collect()
1295 }
1296}
1297
1298impl<T, S, A> Extend<T> for HashSet<T, S, A>
1299where
1300 T: Eq + Hash,
1301 S: BuildHasher,
1302 A: Allocator,
1303{
1304 #[cfg_attr(feature = "inline-more", inline)]
1305 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1306 self.map.extend(iter.into_iter().map(|k| (k, ())));
1307 }
1308
1309 #[inline]
1310 #[cfg(feature = "nightly")]
1311 fn extend_one(&mut self, k: T) {
1312 self.map.insert(k, ());
1313 }
1314
1315 #[inline]
1316 #[cfg(feature = "nightly")]
1317 fn extend_reserve(&mut self, additional: usize) {
1318 Extend::<(T, ())>::extend_reserve(&mut self.map, additional);
1319 }
1320}
1321
1322impl<'a, T, S, A> Extend<&'a T> for HashSet<T, S, A>
1323where
1324 T: 'a + Eq + Hash + Copy,
1325 S: BuildHasher,
1326 A: Allocator,
1327{
1328 #[cfg_attr(feature = "inline-more", inline)]
1329 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1330 self.extend(iter.into_iter().copied());
1331 }
1332
1333 #[inline]
1334 #[cfg(feature = "nightly")]
1335 fn extend_one(&mut self, k: &'a T) {
1336 self.map.insert(*k, ());
1337 }
1338
1339 #[inline]
1340 #[cfg(feature = "nightly")]
1341 fn extend_reserve(&mut self, additional: usize) {
1342 Extend::<(T, ())>::extend_reserve(&mut self.map, additional);
1343 }
1344}
1345
1346impl<T, S, A> Default for HashSet<T, S, A>
1347where
1348 S: Default,
1349 A: Default + Allocator,
1350{
1351 /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
1352 #[cfg_attr(feature = "inline-more", inline)]
1353 fn default() -> Self {
1354 Self {
1355 map: HashMap::default(),
1356 }
1357 }
1358}
1359
1360impl<T, S, A> BitOr<&HashSet<T, S, A>> for &HashSet<T, S, A>
1361where
1362 T: Eq + Hash + Clone,
1363 S: BuildHasher + Default,
1364 A: Allocator + Default,
1365{
1366 type Output = HashSet<T, S, A>;
1367
1368 /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`.
1369 ///
1370 /// # Examples
1371 ///
1372 /// ```
1373 /// use hashbrown::HashSet;
1374 ///
1375 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1376 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1377 ///
1378 /// let set = &a | &b;
1379 ///
1380 /// let mut i = 0;
1381 /// let expected = [1, 2, 3, 4, 5];
1382 /// for x in &set {
1383 /// assert!(expected.contains(x));
1384 /// i += 1;
1385 /// }
1386 /// assert_eq!(i, expected.len());
1387 /// ```
1388 fn bitor(self, rhs: &HashSet<T, S, A>) -> HashSet<T, S, A> {
1389 self.union(rhs).cloned().collect()
1390 }
1391}
1392
1393impl<T, S, A> BitAnd<&HashSet<T, S, A>> for &HashSet<T, S, A>
1394where
1395 T: Eq + Hash + Clone,
1396 S: BuildHasher + Default,
1397 A: Allocator + Default,
1398{
1399 type Output = HashSet<T, S, A>;
1400
1401 /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`.
1402 ///
1403 /// # Examples
1404 ///
1405 /// ```
1406 /// use hashbrown::HashSet;
1407 ///
1408 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1409 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1410 ///
1411 /// let set = &a & &b;
1412 ///
1413 /// let mut i = 0;
1414 /// let expected = [2, 3];
1415 /// for x in &set {
1416 /// assert!(expected.contains(x));
1417 /// i += 1;
1418 /// }
1419 /// assert_eq!(i, expected.len());
1420 /// ```
1421 fn bitand(self, rhs: &HashSet<T, S, A>) -> HashSet<T, S, A> {
1422 self.intersection(rhs).cloned().collect()
1423 }
1424}
1425
1426impl<T, S, A> BitXor<&HashSet<T, S, A>> for &HashSet<T, S, A>
1427where
1428 T: Eq + Hash + Clone,
1429 S: BuildHasher + Default,
1430 A: Allocator + Default,
1431{
1432 type Output = HashSet<T, S, A>;
1433
1434 /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`.
1435 ///
1436 /// # Examples
1437 ///
1438 /// ```
1439 /// use hashbrown::HashSet;
1440 ///
1441 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1442 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1443 ///
1444 /// let set = &a ^ &b;
1445 ///
1446 /// let mut i = 0;
1447 /// let expected = [1, 2, 4, 5];
1448 /// for x in &set {
1449 /// assert!(expected.contains(x));
1450 /// i += 1;
1451 /// }
1452 /// assert_eq!(i, expected.len());
1453 /// ```
1454 fn bitxor(self, rhs: &HashSet<T, S, A>) -> HashSet<T, S, A> {
1455 self.symmetric_difference(rhs).cloned().collect()
1456 }
1457}
1458
1459impl<T, S, A> Sub<&HashSet<T, S, A>> for &HashSet<T, S, A>
1460where
1461 T: Eq + Hash + Clone,
1462 S: BuildHasher + Default,
1463 A: Allocator + Default,
1464{
1465 type Output = HashSet<T, S, A>;
1466
1467 /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`.
1468 ///
1469 /// # Examples
1470 ///
1471 /// ```
1472 /// use hashbrown::HashSet;
1473 ///
1474 /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1475 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1476 ///
1477 /// let set = &a - &b;
1478 ///
1479 /// let mut i = 0;
1480 /// let expected = [1, 2];
1481 /// for x in &set {
1482 /// assert!(expected.contains(x));
1483 /// i += 1;
1484 /// }
1485 /// assert_eq!(i, expected.len());
1486 /// ```
1487 fn sub(self, rhs: &HashSet<T, S, A>) -> HashSet<T, S, A> {
1488 self.difference(rhs).cloned().collect()
1489 }
1490}
1491
1492impl<T, S, A> BitOrAssign<&HashSet<T, S, A>> for HashSet<T, S, A>
1493where
1494 T: Eq + Hash + Clone,
1495 S: BuildHasher,
1496 A: Allocator,
1497{
1498 /// Modifies this set to contain the union of `self` and `rhs`.
1499 ///
1500 /// # Examples
1501 ///
1502 /// ```
1503 /// use hashbrown::HashSet;
1504 ///
1505 /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1506 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1507 ///
1508 /// a |= &b;
1509 ///
1510 /// let mut i = 0;
1511 /// let expected = [1, 2, 3, 4, 5];
1512 /// for x in &a {
1513 /// assert!(expected.contains(x));
1514 /// i += 1;
1515 /// }
1516 /// assert_eq!(i, expected.len());
1517 /// ```
1518 fn bitor_assign(&mut self, rhs: &HashSet<T, S, A>) {
1519 for item in rhs {
1520 if !self.contains(item) {
1521 self.insert(item.clone());
1522 }
1523 }
1524 }
1525}
1526
1527impl<T, S, A> BitAndAssign<&HashSet<T, S, A>> for HashSet<T, S, A>
1528where
1529 T: Eq + Hash + Clone,
1530 S: BuildHasher,
1531 A: Allocator,
1532{
1533 /// Modifies this set to contain the intersection of `self` and `rhs`.
1534 ///
1535 /// # Examples
1536 ///
1537 /// ```
1538 /// use hashbrown::HashSet;
1539 ///
1540 /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1541 /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
1542 ///
1543 /// a &= &b;
1544 ///
1545 /// let mut i = 0;
1546 /// let expected = [2, 3];
1547 /// for x in &a {
1548 /// assert!(expected.contains(x));
1549 /// i += 1;
1550 /// }
1551 /// assert_eq!(i, expected.len());
1552 /// ```
1553 fn bitand_assign(&mut self, rhs: &HashSet<T, S, A>) {
1554 self.retain(|item| rhs.contains(item));
1555 }
1556}
1557
1558impl<T, S, A> BitXorAssign<&HashSet<T, S, A>> for HashSet<T, S, A>
1559where
1560 T: Eq + Hash + Clone,
1561 S: BuildHasher,
1562 A: Allocator,
1563{
1564 /// Modifies this set to contain the symmetric difference of `self` and `rhs`.
1565 ///
1566 /// # Examples
1567 ///
1568 /// ```
1569 /// use hashbrown::HashSet;
1570 ///
1571 /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1572 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1573 ///
1574 /// a ^= &b;
1575 ///
1576 /// let mut i = 0;
1577 /// let expected = [1, 2, 4, 5];
1578 /// for x in &a {
1579 /// assert!(expected.contains(x));
1580 /// i += 1;
1581 /// }
1582 /// assert_eq!(i, expected.len());
1583 /// ```
1584 fn bitxor_assign(&mut self, rhs: &HashSet<T, S, A>) {
1585 for item in rhs {
1586 let hash = make_hash(&self.map.hash_builder, item);
1587 match self.map.find_or_find_insert_slot(hash, item) {
1588 Ok(bucket) => unsafe {
1589 self.map.table.remove(bucket);
1590 },
1591 Err(slot) => unsafe {
1592 self.map
1593 .table
1594 .insert_in_slot(hash, slot, (item.clone(), ()));
1595 },
1596 }
1597 }
1598 }
1599}
1600
1601impl<T, S, A> SubAssign<&HashSet<T, S, A>> for HashSet<T, S, A>
1602where
1603 T: Eq + Hash + Clone,
1604 S: BuildHasher,
1605 A: Allocator,
1606{
1607 /// Modifies this set to contain the difference of `self` and `rhs`.
1608 ///
1609 /// # Examples
1610 ///
1611 /// ```
1612 /// use hashbrown::HashSet;
1613 ///
1614 /// let mut a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
1615 /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
1616 ///
1617 /// a -= &b;
1618 ///
1619 /// let mut i = 0;
1620 /// let expected = [1, 2];
1621 /// for x in &a {
1622 /// assert!(expected.contains(x));
1623 /// i += 1;
1624 /// }
1625 /// assert_eq!(i, expected.len());
1626 /// ```
1627 fn sub_assign(&mut self, rhs: &HashSet<T, S, A>) {
1628 if rhs.len() < self.len() {
1629 for item in rhs {
1630 self.remove(item);
1631 }
1632 } else {
1633 self.retain(|item| !rhs.contains(item));
1634 }
1635 }
1636}
1637
1638/// An iterator over the items of a `HashSet`.
1639///
1640/// This `struct` is created by the [`iter`] method on [`HashSet`].
1641/// See its documentation for more.
1642///
1643/// [`HashSet`]: struct.HashSet.html
1644/// [`iter`]: struct.HashSet.html#method.iter
1645pub struct Iter<'a, K> {
1646 iter: Keys<'a, K, ()>,
1647}
1648
1649/// An owning iterator over the items of a `HashSet`.
1650///
1651/// This `struct` is created by the [`into_iter`] method on [`HashSet`]
1652/// (provided by the `IntoIterator` trait). See its documentation for more.
1653///
1654/// [`HashSet`]: struct.HashSet.html
1655/// [`into_iter`]: struct.HashSet.html#method.into_iter
1656pub struct IntoIter<K, A: Allocator = Global> {
1657 iter: map::IntoIter<K, (), A>,
1658}
1659
1660/// A draining iterator over the items of a `HashSet`.
1661///
1662/// This `struct` is created by the [`drain`] method on [`HashSet`].
1663/// See its documentation for more.
1664///
1665/// [`HashSet`]: struct.HashSet.html
1666/// [`drain`]: struct.HashSet.html#method.drain
1667pub struct Drain<'a, K, A: Allocator = Global> {
1668 iter: map::Drain<'a, K, (), A>,
1669}
1670
1671/// A draining iterator over entries of a `HashSet` which don't satisfy the predicate `f`.
1672///
1673/// This `struct` is created by the [`extract_if`] method on [`HashSet`]. See its
1674/// documentation for more.
1675///
1676/// [`extract_if`]: struct.HashSet.html#method.extract_if
1677/// [`HashSet`]: struct.HashSet.html
1678#[must_use = "Iterators are lazy unless consumed"]
1679pub struct ExtractIf<'a, K, F, A: Allocator = Global>
1680where
1681 F: FnMut(&K) -> bool,
1682{
1683 f: F,
1684 inner: RawExtractIf<'a, (K, ()), A>,
1685}
1686
1687/// A lazy iterator producing elements in the intersection of `HashSet`s.
1688///
1689/// This `struct` is created by the [`intersection`] method on [`HashSet`].
1690/// See its documentation for more.
1691///
1692/// [`HashSet`]: struct.HashSet.html
1693/// [`intersection`]: struct.HashSet.html#method.intersection
1694pub struct Intersection<'a, T, S, A: Allocator = Global> {
1695 // iterator of the first set
1696 iter: Iter<'a, T>,
1697 // the second set
1698 other: &'a HashSet<T, S, A>,
1699}
1700
1701/// A lazy iterator producing elements in the difference of `HashSet`s.
1702///
1703/// This `struct` is created by the [`difference`] method on [`HashSet`].
1704/// See its documentation for more.
1705///
1706/// [`HashSet`]: struct.HashSet.html
1707/// [`difference`]: struct.HashSet.html#method.difference
1708pub struct Difference<'a, T, S, A: Allocator = Global> {
1709 // iterator of the first set
1710 iter: Iter<'a, T>,
1711 // the second set
1712 other: &'a HashSet<T, S, A>,
1713}
1714
1715/// A lazy iterator producing elements in the symmetric difference of `HashSet`s.
1716///
1717/// This `struct` is created by the [`symmetric_difference`] method on
1718/// [`HashSet`]. See its documentation for more.
1719///
1720/// [`HashSet`]: struct.HashSet.html
1721/// [`symmetric_difference`]: struct.HashSet.html#method.symmetric_difference
1722pub struct SymmetricDifference<'a, T, S, A: Allocator = Global> {
1723 iter: Chain<Difference<'a, T, S, A>, Difference<'a, T, S, A>>,
1724}
1725
1726/// A lazy iterator producing elements in the union of `HashSet`s.
1727///
1728/// This `struct` is created by the [`union`] method on [`HashSet`].
1729/// See its documentation for more.
1730///
1731/// [`HashSet`]: struct.HashSet.html
1732/// [`union`]: struct.HashSet.html#method.union
1733pub struct Union<'a, T, S, A: Allocator = Global> {
1734 iter: Chain<Iter<'a, T>, Difference<'a, T, S, A>>,
1735}
1736
1737impl<'a, T, S, A: Allocator> IntoIterator for &'a HashSet<T, S, A> {
1738 type Item = &'a T;
1739 type IntoIter = Iter<'a, T>;
1740
1741 #[cfg_attr(feature = "inline-more", inline)]
1742 fn into_iter(self) -> Iter<'a, T> {
1743 self.iter()
1744 }
1745}
1746
1747impl<T, S, A: Allocator> IntoIterator for HashSet<T, S, A> {
1748 type Item = T;
1749 type IntoIter = IntoIter<T, A>;
1750
1751 /// Creates a consuming iterator, that is, one that moves each value out
1752 /// of the set in arbitrary order. The set cannot be used after calling
1753 /// this.
1754 ///
1755 /// # Examples
1756 ///
1757 /// ```
1758 /// use hashbrown::HashSet;
1759 /// let mut set = HashSet::new();
1760 /// set.insert("a".to_string());
1761 /// set.insert("b".to_string());
1762 ///
1763 /// // Not possible to collect to a Vec<String> with a regular `.iter()`.
1764 /// let v: Vec<String> = set.into_iter().collect();
1765 ///
1766 /// // Will print in an arbitrary order.
1767 /// for x in &v {
1768 /// println!("{}", x);
1769 /// }
1770 /// ```
1771 #[cfg_attr(feature = "inline-more", inline)]
1772 fn into_iter(self) -> IntoIter<T, A> {
1773 IntoIter {
1774 iter: self.map.into_iter(),
1775 }
1776 }
1777}
1778
1779impl<K> Clone for Iter<'_, K> {
1780 #[cfg_attr(feature = "inline-more", inline)]
1781 fn clone(&self) -> Self {
1782 Iter {
1783 iter: self.iter.clone(),
1784 }
1785 }
1786}
1787impl<K> Default for Iter<'_, K> {
1788 #[cfg_attr(feature = "inline-more", inline)]
1789 fn default() -> Self {
1790 Iter {
1791 iter: Default::default(),
1792 }
1793 }
1794}
1795impl<'a, K> Iterator for Iter<'a, K> {
1796 type Item = &'a K;
1797
1798 #[cfg_attr(feature = "inline-more", inline)]
1799 fn next(&mut self) -> Option<&'a K> {
1800 self.iter.next()
1801 }
1802 #[cfg_attr(feature = "inline-more", inline)]
1803 fn size_hint(&self) -> (usize, Option<usize>) {
1804 self.iter.size_hint()
1805 }
1806 #[cfg_attr(feature = "inline-more", inline)]
1807 fn fold<B, F>(self, init: B, f: F) -> B
1808 where
1809 Self: Sized,
1810 F: FnMut(B, Self::Item) -> B,
1811 {
1812 self.iter.fold(init, f)
1813 }
1814}
1815impl<K> ExactSizeIterator for Iter<'_, K> {
1816 #[cfg_attr(feature = "inline-more", inline)]
1817 fn len(&self) -> usize {
1818 self.iter.len()
1819 }
1820}
1821impl<K> FusedIterator for Iter<'_, K> {}
1822
1823impl<K: fmt::Debug> fmt::Debug for Iter<'_, K> {
1824 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1825 f.debug_list().entries(self.clone()).finish()
1826 }
1827}
1828
1829impl<K, A: Allocator> Default for IntoIter<K, A> {
1830 #[cfg_attr(feature = "inline-more", inline)]
1831 fn default() -> Self {
1832 IntoIter {
1833 iter: Default::default(),
1834 }
1835 }
1836}
1837impl<K, A: Allocator> Iterator for IntoIter<K, A> {
1838 type Item = K;
1839
1840 #[cfg_attr(feature = "inline-more", inline)]
1841 fn next(&mut self) -> Option<K> {
1842 // Avoid `Option::map` because it bloats LLVM IR.
1843 match self.iter.next() {
1844 Some((k, _)) => Some(k),
1845 None => None,
1846 }
1847 }
1848 #[cfg_attr(feature = "inline-more", inline)]
1849 fn size_hint(&self) -> (usize, Option<usize>) {
1850 self.iter.size_hint()
1851 }
1852 #[cfg_attr(feature = "inline-more", inline)]
1853 fn fold<B, F>(self, init: B, mut f: F) -> B
1854 where
1855 Self: Sized,
1856 F: FnMut(B, Self::Item) -> B,
1857 {
1858 self.iter.fold(init, |acc, (k, ())| f(acc, k))
1859 }
1860}
1861impl<K, A: Allocator> ExactSizeIterator for IntoIter<K, A> {
1862 #[cfg_attr(feature = "inline-more", inline)]
1863 fn len(&self) -> usize {
1864 self.iter.len()
1865 }
1866}
1867impl<K, A: Allocator> FusedIterator for IntoIter<K, A> {}
1868
1869impl<K: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<K, A> {
1870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1871 let entries_iter = self.iter.iter().map(|(k, _)| k);
1872 f.debug_list().entries(entries_iter).finish()
1873 }
1874}
1875
1876impl<K, A: Allocator> Iterator for Drain<'_, K, A> {
1877 type Item = K;
1878
1879 #[cfg_attr(feature = "inline-more", inline)]
1880 fn next(&mut self) -> Option<K> {
1881 // Avoid `Option::map` because it bloats LLVM IR.
1882 match self.iter.next() {
1883 Some((k, _)) => Some(k),
1884 None => None,
1885 }
1886 }
1887 #[cfg_attr(feature = "inline-more", inline)]
1888 fn size_hint(&self) -> (usize, Option<usize>) {
1889 self.iter.size_hint()
1890 }
1891 #[cfg_attr(feature = "inline-more", inline)]
1892 fn fold<B, F>(self, init: B, mut f: F) -> B
1893 where
1894 Self: Sized,
1895 F: FnMut(B, Self::Item) -> B,
1896 {
1897 self.iter.fold(init, |acc, (k, ())| f(acc, k))
1898 }
1899}
1900impl<K, A: Allocator> ExactSizeIterator for Drain<'_, K, A> {
1901 #[cfg_attr(feature = "inline-more", inline)]
1902 fn len(&self) -> usize {
1903 self.iter.len()
1904 }
1905}
1906impl<K, A: Allocator> FusedIterator for Drain<'_, K, A> {}
1907
1908impl<K: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, K, A> {
1909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1910 let entries_iter = self.iter.iter().map(|(k, _)| k);
1911 f.debug_list().entries(entries_iter).finish()
1912 }
1913}
1914
1915impl<K, F, A: Allocator> Iterator for ExtractIf<'_, K, F, A>
1916where
1917 F: FnMut(&K) -> bool,
1918{
1919 type Item = K;
1920
1921 #[cfg_attr(feature = "inline-more", inline)]
1922 fn next(&mut self) -> Option<Self::Item> {
1923 self.inner
1924 .next(|&mut (ref k, ())| (self.f)(k))
1925 .map(|(k, ())| k)
1926 }
1927
1928 #[inline]
1929 fn size_hint(&self) -> (usize, Option<usize>) {
1930 (0, self.inner.iter.size_hint().1)
1931 }
1932}
1933
1934impl<K, F, A: Allocator> FusedIterator for ExtractIf<'_, K, F, A> where F: FnMut(&K) -> bool {}
1935
1936impl<T, S, A: Allocator> Clone for Intersection<'_, T, S, A> {
1937 #[cfg_attr(feature = "inline-more", inline)]
1938 fn clone(&self) -> Self {
1939 Intersection {
1940 iter: self.iter.clone(),
1941 ..*self
1942 }
1943 }
1944}
1945
1946impl<'a, T, S, A> Iterator for Intersection<'a, T, S, A>
1947where
1948 T: Eq + Hash,
1949 S: BuildHasher,
1950 A: Allocator,
1951{
1952 type Item = &'a T;
1953
1954 #[cfg_attr(feature = "inline-more", inline)]
1955 fn next(&mut self) -> Option<&'a T> {
1956 loop {
1957 let elt = self.iter.next()?;
1958 if self.other.contains(elt) {
1959 return Some(elt);
1960 }
1961 }
1962 }
1963
1964 #[cfg_attr(feature = "inline-more", inline)]
1965 fn size_hint(&self) -> (usize, Option<usize>) {
1966 let (_, upper) = self.iter.size_hint();
1967 (0, upper)
1968 }
1969
1970 #[cfg_attr(feature = "inline-more", inline)]
1971 fn fold<B, F>(self, init: B, mut f: F) -> B
1972 where
1973 Self: Sized,
1974 F: FnMut(B, Self::Item) -> B,
1975 {
1976 self.iter.fold(init, |acc, elt| {
1977 if self.other.contains(elt) {
1978 f(acc, elt)
1979 } else {
1980 acc
1981 }
1982 })
1983 }
1984}
1985
1986impl<T, S, A> fmt::Debug for Intersection<'_, T, S, A>
1987where
1988 T: fmt::Debug + Eq + Hash,
1989 S: BuildHasher,
1990 A: Allocator,
1991{
1992 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1993 f.debug_list().entries(self.clone()).finish()
1994 }
1995}
1996
1997impl<T, S, A> FusedIterator for Intersection<'_, T, S, A>
1998where
1999 T: Eq + Hash,
2000 S: BuildHasher,
2001 A: Allocator,
2002{
2003}
2004
2005impl<T, S, A: Allocator> Clone for Difference<'_, T, S, A> {
2006 #[cfg_attr(feature = "inline-more", inline)]
2007 fn clone(&self) -> Self {
2008 Difference {
2009 iter: self.iter.clone(),
2010 ..*self
2011 }
2012 }
2013}
2014
2015impl<'a, T, S, A> Iterator for Difference<'a, T, S, A>
2016where
2017 T: Eq + Hash,
2018 S: BuildHasher,
2019 A: Allocator,
2020{
2021 type Item = &'a T;
2022
2023 #[cfg_attr(feature = "inline-more", inline)]
2024 fn next(&mut self) -> Option<&'a T> {
2025 loop {
2026 let elt = self.iter.next()?;
2027 if !self.other.contains(elt) {
2028 return Some(elt);
2029 }
2030 }
2031 }
2032
2033 #[cfg_attr(feature = "inline-more", inline)]
2034 fn size_hint(&self) -> (usize, Option<usize>) {
2035 let (lower, upper) = self.iter.size_hint();
2036 (lower.saturating_sub(self.other.len()), upper)
2037 }
2038
2039 #[cfg_attr(feature = "inline-more", inline)]
2040 fn fold<B, F>(self, init: B, mut f: F) -> B
2041 where
2042 Self: Sized,
2043 F: FnMut(B, Self::Item) -> B,
2044 {
2045 self.iter.fold(init, |acc, elt| {
2046 if self.other.contains(elt) {
2047 acc
2048 } else {
2049 f(acc, elt)
2050 }
2051 })
2052 }
2053}
2054
2055impl<T, S, A> FusedIterator for Difference<'_, T, S, A>
2056where
2057 T: Eq + Hash,
2058 S: BuildHasher,
2059 A: Allocator,
2060{
2061}
2062
2063impl<T, S, A> fmt::Debug for Difference<'_, T, S, A>
2064where
2065 T: fmt::Debug + Eq + Hash,
2066 S: BuildHasher,
2067 A: Allocator,
2068{
2069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2070 f.debug_list().entries(self.clone()).finish()
2071 }
2072}
2073
2074impl<T, S, A: Allocator> Clone for SymmetricDifference<'_, T, S, A> {
2075 #[cfg_attr(feature = "inline-more", inline)]
2076 fn clone(&self) -> Self {
2077 SymmetricDifference {
2078 iter: self.iter.clone(),
2079 }
2080 }
2081}
2082
2083impl<'a, T, S, A> Iterator for SymmetricDifference<'a, T, S, A>
2084where
2085 T: Eq + Hash,
2086 S: BuildHasher,
2087 A: Allocator,
2088{
2089 type Item = &'a T;
2090
2091 #[cfg_attr(feature = "inline-more", inline)]
2092 fn next(&mut self) -> Option<&'a T> {
2093 self.iter.next()
2094 }
2095
2096 #[cfg_attr(feature = "inline-more", inline)]
2097 fn size_hint(&self) -> (usize, Option<usize>) {
2098 self.iter.size_hint()
2099 }
2100
2101 #[cfg_attr(feature = "inline-more", inline)]
2102 fn fold<B, F>(self, init: B, f: F) -> B
2103 where
2104 Self: Sized,
2105 F: FnMut(B, Self::Item) -> B,
2106 {
2107 self.iter.fold(init, f)
2108 }
2109}
2110
2111impl<T, S, A> FusedIterator for SymmetricDifference<'_, T, S, A>
2112where
2113 T: Eq + Hash,
2114 S: BuildHasher,
2115 A: Allocator,
2116{
2117}
2118
2119impl<T, S, A> fmt::Debug for SymmetricDifference<'_, T, S, A>
2120where
2121 T: fmt::Debug + Eq + Hash,
2122 S: BuildHasher,
2123 A: Allocator,
2124{
2125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2126 f.debug_list().entries(self.clone()).finish()
2127 }
2128}
2129
2130impl<T, S, A: Allocator> Clone for Union<'_, T, S, A> {
2131 #[cfg_attr(feature = "inline-more", inline)]
2132 fn clone(&self) -> Self {
2133 Union {
2134 iter: self.iter.clone(),
2135 }
2136 }
2137}
2138
2139impl<T, S, A> FusedIterator for Union<'_, T, S, A>
2140where
2141 T: Eq + Hash,
2142 S: BuildHasher,
2143 A: Allocator,
2144{
2145}
2146
2147impl<T, S, A> fmt::Debug for Union<'_, T, S, A>
2148where
2149 T: fmt::Debug + Eq + Hash,
2150 S: BuildHasher,
2151 A: Allocator,
2152{
2153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2154 f.debug_list().entries(self.clone()).finish()
2155 }
2156}
2157
2158impl<'a, T, S, A> Iterator for Union<'a, T, S, A>
2159where
2160 T: Eq + Hash,
2161 S: BuildHasher,
2162 A: Allocator,
2163{
2164 type Item = &'a T;
2165
2166 #[cfg_attr(feature = "inline-more", inline)]
2167 fn next(&mut self) -> Option<&'a T> {
2168 self.iter.next()
2169 }
2170
2171 #[cfg_attr(feature = "inline-more", inline)]
2172 fn size_hint(&self) -> (usize, Option<usize>) {
2173 self.iter.size_hint()
2174 }
2175
2176 #[cfg_attr(feature = "inline-more", inline)]
2177 fn fold<B, F>(self, init: B, f: F) -> B
2178 where
2179 Self: Sized,
2180 F: FnMut(B, Self::Item) -> B,
2181 {
2182 self.iter.fold(init, f)
2183 }
2184}
2185
2186/// A view into a single entry in a set, which may either be vacant or occupied.
2187///
2188/// This `enum` is constructed from the [`entry`] method on [`HashSet`].
2189///
2190/// [`HashSet`]: struct.HashSet.html
2191/// [`entry`]: struct.HashSet.html#method.entry
2192///
2193/// # Examples
2194///
2195/// ```
2196/// use hashbrown::hash_set::{Entry, HashSet, OccupiedEntry};
2197///
2198/// let mut set = HashSet::new();
2199/// set.extend(["a", "b", "c"]);
2200/// assert_eq!(set.len(), 3);
2201///
2202/// // Existing value (insert)
2203/// let entry: Entry<_, _> = set.entry("a");
2204/// let _raw_o: OccupiedEntry<_, _> = entry.insert();
2205/// assert_eq!(set.len(), 3);
2206/// // Nonexistent value (insert)
2207/// set.entry("d").insert();
2208///
2209/// // Existing value (or_insert)
2210/// set.entry("b").or_insert();
2211/// // Nonexistent value (or_insert)
2212/// set.entry("e").or_insert();
2213///
2214/// println!("Our HashSet: {:?}", set);
2215///
2216/// let mut vec: Vec<_> = set.iter().copied().collect();
2217/// // The `Iter` iterator produces items in arbitrary order, so the
2218/// // items must be sorted to test them against a sorted array.
2219/// vec.sort_unstable();
2220/// assert_eq!(vec, ["a", "b", "c", "d", "e"]);
2221/// ```
2222pub enum Entry<'a, T, S, A = Global>
2223where
2224 A: Allocator,
2225{
2226 /// An occupied entry.
2227 ///
2228 /// # Examples
2229 ///
2230 /// ```
2231 /// use hashbrown::hash_set::{Entry, HashSet};
2232 /// let mut set: HashSet<_> = ["a", "b"].into();
2233 ///
2234 /// match set.entry("a") {
2235 /// Entry::Vacant(_) => unreachable!(),
2236 /// Entry::Occupied(_) => { }
2237 /// }
2238 /// ```
2239 Occupied(OccupiedEntry<'a, T, S, A>),
2240
2241 /// A vacant entry.
2242 ///
2243 /// # Examples
2244 ///
2245 /// ```
2246 /// use hashbrown::hash_set::{Entry, HashSet};
2247 /// let mut set: HashSet<&str> = HashSet::new();
2248 ///
2249 /// match set.entry("a") {
2250 /// Entry::Occupied(_) => unreachable!(),
2251 /// Entry::Vacant(_) => { }
2252 /// }
2253 /// ```
2254 Vacant(VacantEntry<'a, T, S, A>),
2255}
2256
2257impl<T: fmt::Debug, S, A: Allocator> fmt::Debug for Entry<'_, T, S, A> {
2258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2259 match *self {
2260 Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2261 Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2262 }
2263 }
2264}
2265
2266/// A view into an occupied entry in a `HashSet`.
2267/// It is part of the [`Entry`] enum.
2268///
2269/// [`Entry`]: enum.Entry.html
2270///
2271/// # Examples
2272///
2273/// ```
2274/// use hashbrown::hash_set::{Entry, HashSet, OccupiedEntry};
2275///
2276/// let mut set = HashSet::new();
2277/// set.extend(["a", "b", "c"]);
2278///
2279/// let _entry_o: OccupiedEntry<_, _> = set.entry("a").insert();
2280/// assert_eq!(set.len(), 3);
2281///
2282/// // Existing key
2283/// match set.entry("a") {
2284/// Entry::Vacant(_) => unreachable!(),
2285/// Entry::Occupied(view) => {
2286/// assert_eq!(view.get(), &"a");
2287/// }
2288/// }
2289///
2290/// assert_eq!(set.len(), 3);
2291///
2292/// // Existing key (take)
2293/// match set.entry("c") {
2294/// Entry::Vacant(_) => unreachable!(),
2295/// Entry::Occupied(view) => {
2296/// assert_eq!(view.remove(), "c");
2297/// }
2298/// }
2299/// assert_eq!(set.get(&"c"), None);
2300/// assert_eq!(set.len(), 2);
2301/// ```
2302pub struct OccupiedEntry<'a, T, S, A: Allocator = Global> {
2303 inner: map::OccupiedEntry<'a, T, (), S, A>,
2304}
2305
2306impl<T: fmt::Debug, S, A: Allocator> fmt::Debug for OccupiedEntry<'_, T, S, A> {
2307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2308 f.debug_struct("OccupiedEntry")
2309 .field("value", self.get())
2310 .finish()
2311 }
2312}
2313
2314/// A view into a vacant entry in a `HashSet`.
2315/// It is part of the [`Entry`] enum.
2316///
2317/// [`Entry`]: enum.Entry.html
2318///
2319/// # Examples
2320///
2321/// ```
2322/// use hashbrown::hash_set::{Entry, HashSet, VacantEntry};
2323///
2324/// let mut set = HashSet::<&str>::new();
2325///
2326/// let entry_v: VacantEntry<_, _> = match set.entry("a") {
2327/// Entry::Vacant(view) => view,
2328/// Entry::Occupied(_) => unreachable!(),
2329/// };
2330/// entry_v.insert();
2331/// assert!(set.contains("a") && set.len() == 1);
2332///
2333/// // Nonexistent key (insert)
2334/// match set.entry("b") {
2335/// Entry::Vacant(view) => { view.insert(); },
2336/// Entry::Occupied(_) => unreachable!(),
2337/// }
2338/// assert!(set.contains("b") && set.len() == 2);
2339/// ```
2340pub struct VacantEntry<'a, T, S, A: Allocator = Global> {
2341 inner: map::VacantEntry<'a, T, (), S, A>,
2342}
2343
2344impl<T: fmt::Debug, S, A: Allocator> fmt::Debug for VacantEntry<'_, T, S, A> {
2345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2346 f.debug_tuple("VacantEntry").field(self.get()).finish()
2347 }
2348}
2349
2350impl<'a, T, S, A: Allocator> Entry<'a, T, S, A> {
2351 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2352 ///
2353 /// # Examples
2354 ///
2355 /// ```
2356 /// use hashbrown::HashSet;
2357 ///
2358 /// let mut set: HashSet<&str> = HashSet::new();
2359 /// let entry = set.entry("horseyland").insert();
2360 ///
2361 /// assert_eq!(entry.get(), &"horseyland");
2362 /// ```
2363 #[cfg_attr(feature = "inline-more", inline)]
2364 pub fn insert(self) -> OccupiedEntry<'a, T, S, A>
2365 where
2366 T: Hash,
2367 S: BuildHasher,
2368 {
2369 match self {
2370 Entry::Occupied(entry) => entry,
2371 Entry::Vacant(entry) => entry.insert(),
2372 }
2373 }
2374
2375 /// Ensures a value is in the entry by inserting if it was vacant.
2376 ///
2377 /// # Examples
2378 ///
2379 /// ```
2380 /// use hashbrown::HashSet;
2381 ///
2382 /// let mut set: HashSet<&str> = HashSet::new();
2383 ///
2384 /// // nonexistent key
2385 /// set.entry("poneyland").or_insert();
2386 /// assert!(set.contains("poneyland"));
2387 ///
2388 /// // existing key
2389 /// set.entry("poneyland").or_insert();
2390 /// assert!(set.contains("poneyland"));
2391 /// assert_eq!(set.len(), 1);
2392 /// ```
2393 #[cfg_attr(feature = "inline-more", inline)]
2394 pub fn or_insert(self)
2395 where
2396 T: Hash,
2397 S: BuildHasher,
2398 {
2399 if let Entry::Vacant(entry) = self {
2400 entry.insert();
2401 }
2402 }
2403
2404 /// Returns a reference to this entry's value.
2405 ///
2406 /// # Examples
2407 ///
2408 /// ```
2409 /// use hashbrown::HashSet;
2410 ///
2411 /// let mut set: HashSet<&str> = HashSet::new();
2412 /// set.entry("poneyland").or_insert();
2413 /// // existing key
2414 /// assert_eq!(set.entry("poneyland").get(), &"poneyland");
2415 /// // nonexistent key
2416 /// assert_eq!(set.entry("horseland").get(), &"horseland");
2417 /// ```
2418 #[cfg_attr(feature = "inline-more", inline)]
2419 pub fn get(&self) -> &T {
2420 match *self {
2421 Entry::Occupied(ref entry) => entry.get(),
2422 Entry::Vacant(ref entry) => entry.get(),
2423 }
2424 }
2425}
2426
2427impl<T, S, A: Allocator> OccupiedEntry<'_, T, S, A> {
2428 /// Gets a reference to the value in the entry.
2429 ///
2430 /// # Examples
2431 ///
2432 /// ```
2433 /// use hashbrown::hash_set::{Entry, HashSet};
2434 ///
2435 /// let mut set: HashSet<&str> = HashSet::new();
2436 /// set.entry("poneyland").or_insert();
2437 ///
2438 /// match set.entry("poneyland") {
2439 /// Entry::Vacant(_) => panic!(),
2440 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &"poneyland"),
2441 /// }
2442 /// ```
2443 #[cfg_attr(feature = "inline-more", inline)]
2444 pub fn get(&self) -> &T {
2445 self.inner.key()
2446 }
2447
2448 /// Takes the value out of the entry, and returns it.
2449 /// Keeps the allocated memory for reuse.
2450 ///
2451 /// # Examples
2452 ///
2453 /// ```
2454 /// use hashbrown::HashSet;
2455 /// use hashbrown::hash_set::Entry;
2456 ///
2457 /// let mut set: HashSet<&str> = HashSet::new();
2458 /// // The set is empty
2459 /// assert!(set.is_empty() && set.capacity() == 0);
2460 ///
2461 /// set.entry("poneyland").or_insert();
2462 /// let capacity_before_remove = set.capacity();
2463 ///
2464 /// if let Entry::Occupied(o) = set.entry("poneyland") {
2465 /// assert_eq!(o.remove(), "poneyland");
2466 /// }
2467 ///
2468 /// assert_eq!(set.contains("poneyland"), false);
2469 /// // Now set hold none elements but capacity is equal to the old one
2470 /// assert!(set.len() == 0 && set.capacity() == capacity_before_remove);
2471 /// ```
2472 #[cfg_attr(feature = "inline-more", inline)]
2473 pub fn remove(self) -> T {
2474 self.inner.remove_entry().0
2475 }
2476}
2477
2478impl<'a, T, S, A: Allocator> VacantEntry<'a, T, S, A> {
2479 /// Gets a reference to the value that would be used when inserting
2480 /// through the `VacantEntry`.
2481 ///
2482 /// # Examples
2483 ///
2484 /// ```
2485 /// use hashbrown::HashSet;
2486 ///
2487 /// let mut set: HashSet<&str> = HashSet::new();
2488 /// assert_eq!(set.entry("poneyland").get(), &"poneyland");
2489 /// ```
2490 #[cfg_attr(feature = "inline-more", inline)]
2491 pub fn get(&self) -> &T {
2492 self.inner.key()
2493 }
2494
2495 /// Take ownership of the value.
2496 ///
2497 /// # Examples
2498 ///
2499 /// ```
2500 /// use hashbrown::hash_set::{Entry, HashSet};
2501 ///
2502 /// let mut set: HashSet<&str> = HashSet::new();
2503 ///
2504 /// match set.entry("poneyland") {
2505 /// Entry::Occupied(_) => panic!(),
2506 /// Entry::Vacant(v) => assert_eq!(v.into_value(), "poneyland"),
2507 /// }
2508 /// ```
2509 #[cfg_attr(feature = "inline-more", inline)]
2510 pub fn into_value(self) -> T {
2511 self.inner.into_key()
2512 }
2513
2514 /// Sets the value of the entry with the `VacantEntry`'s value.
2515 ///
2516 /// # Examples
2517 ///
2518 /// ```
2519 /// use hashbrown::HashSet;
2520 /// use hashbrown::hash_set::Entry;
2521 ///
2522 /// let mut set: HashSet<&str> = HashSet::new();
2523 ///
2524 /// if let Entry::Vacant(o) = set.entry("poneyland") {
2525 /// o.insert();
2526 /// }
2527 /// assert!(set.contains("poneyland"));
2528 /// ```
2529 #[cfg_attr(feature = "inline-more", inline)]
2530 pub fn insert(self) -> OccupiedEntry<'a, T, S, A>
2531 where
2532 T: Hash,
2533 S: BuildHasher,
2534 {
2535 OccupiedEntry {
2536 inner: self.inner.insert_entry(()),
2537 }
2538 }
2539}
2540
2541#[allow(dead_code)]
2542fn assert_covariance() {
2543 fn set<'new>(v: HashSet<&'static str>) -> HashSet<&'new str> {
2544 v
2545 }
2546 fn iter<'a, 'new>(v: Iter<'a, &'static str>) -> Iter<'a, &'new str> {
2547 v
2548 }
2549 fn into_iter<'new, A: Allocator>(v: IntoIter<&'static str, A>) -> IntoIter<&'new str, A> {
2550 v
2551 }
2552 fn difference<'a, 'new, A: Allocator>(
2553 v: Difference<'a, &'static str, DefaultHashBuilder, A>,
2554 ) -> Difference<'a, &'new str, DefaultHashBuilder, A> {
2555 v
2556 }
2557 fn symmetric_difference<'a, 'new, A: Allocator>(
2558 v: SymmetricDifference<'a, &'static str, DefaultHashBuilder, A>,
2559 ) -> SymmetricDifference<'a, &'new str, DefaultHashBuilder, A> {
2560 v
2561 }
2562 fn intersection<'a, 'new, A: Allocator>(
2563 v: Intersection<'a, &'static str, DefaultHashBuilder, A>,
2564 ) -> Intersection<'a, &'new str, DefaultHashBuilder, A> {
2565 v
2566 }
2567 fn union<'a, 'new, A: Allocator>(
2568 v: Union<'a, &'static str, DefaultHashBuilder, A>,
2569 ) -> Union<'a, &'new str, DefaultHashBuilder, A> {
2570 v
2571 }
2572 fn drain<'new, A: Allocator>(d: Drain<'static, &'static str, A>) -> Drain<'new, &'new str, A> {
2573 d
2574 }
2575}
2576
2577#[cfg(test)]
2578mod test_set {
2579 use super::{make_hash, Equivalent, HashSet};
2580 use crate::DefaultHashBuilder;
2581 use std::vec::Vec;
2582
2583 #[test]
2584 fn test_zero_capacities() {
2585 type HS = HashSet<i32>;
2586
2587 let s = HS::new();
2588 assert_eq!(s.capacity(), 0);
2589
2590 let s = HS::default();
2591 assert_eq!(s.capacity(), 0);
2592
2593 let s = HS::with_hasher(DefaultHashBuilder::default());
2594 assert_eq!(s.capacity(), 0);
2595
2596 let s = HS::with_capacity(0);
2597 assert_eq!(s.capacity(), 0);
2598
2599 let s = HS::with_capacity_and_hasher(0, DefaultHashBuilder::default());
2600 assert_eq!(s.capacity(), 0);
2601
2602 let mut s = HS::new();
2603 s.insert(1);
2604 s.insert(2);
2605 s.remove(&1);
2606 s.remove(&2);
2607 s.shrink_to_fit();
2608 assert_eq!(s.capacity(), 0);
2609
2610 let mut s = HS::new();
2611 s.reserve(0);
2612 assert_eq!(s.capacity(), 0);
2613 }
2614
2615 #[test]
2616 fn test_disjoint() {
2617 let mut xs = HashSet::new();
2618 let mut ys = HashSet::new();
2619 assert!(xs.is_disjoint(&ys));
2620 assert!(ys.is_disjoint(&xs));
2621 assert!(xs.insert(5));
2622 assert!(ys.insert(11));
2623 assert!(xs.is_disjoint(&ys));
2624 assert!(ys.is_disjoint(&xs));
2625 assert!(xs.insert(7));
2626 assert!(xs.insert(19));
2627 assert!(xs.insert(4));
2628 assert!(ys.insert(2));
2629 assert!(ys.insert(-11));
2630 assert!(xs.is_disjoint(&ys));
2631 assert!(ys.is_disjoint(&xs));
2632 assert!(ys.insert(7));
2633 assert!(!xs.is_disjoint(&ys));
2634 assert!(!ys.is_disjoint(&xs));
2635 }
2636
2637 #[test]
2638 fn test_subset_and_superset() {
2639 let mut a = HashSet::new();
2640 assert!(a.insert(0));
2641 assert!(a.insert(5));
2642 assert!(a.insert(11));
2643 assert!(a.insert(7));
2644
2645 let mut b = HashSet::new();
2646 assert!(b.insert(0));
2647 assert!(b.insert(7));
2648 assert!(b.insert(19));
2649 assert!(b.insert(250));
2650 assert!(b.insert(11));
2651 assert!(b.insert(200));
2652
2653 assert!(!a.is_subset(&b));
2654 assert!(!a.is_superset(&b));
2655 assert!(!b.is_subset(&a));
2656 assert!(!b.is_superset(&a));
2657
2658 assert!(b.insert(5));
2659
2660 assert!(a.is_subset(&b));
2661 assert!(!a.is_superset(&b));
2662 assert!(!b.is_subset(&a));
2663 assert!(b.is_superset(&a));
2664 }
2665
2666 #[test]
2667 fn test_iterate() {
2668 let mut a = HashSet::new();
2669 for i in 0..32 {
2670 assert!(a.insert(i));
2671 }
2672 let mut observed: u32 = 0;
2673 for k in &a {
2674 observed |= 1 << *k;
2675 }
2676 assert_eq!(observed, 0xFFFF_FFFF);
2677 }
2678
2679 #[test]
2680 fn test_intersection() {
2681 let mut a = HashSet::new();
2682 let mut b = HashSet::new();
2683
2684 assert!(a.insert(11));
2685 assert!(a.insert(1));
2686 assert!(a.insert(3));
2687 assert!(a.insert(77));
2688 assert!(a.insert(103));
2689 assert!(a.insert(5));
2690 assert!(a.insert(-5));
2691
2692 assert!(b.insert(2));
2693 assert!(b.insert(11));
2694 assert!(b.insert(77));
2695 assert!(b.insert(-9));
2696 assert!(b.insert(-42));
2697 assert!(b.insert(5));
2698 assert!(b.insert(3));
2699
2700 let mut i = 0;
2701 let expected = [3, 5, 11, 77];
2702 for x in a.intersection(&b) {
2703 assert!(expected.contains(x));
2704 i += 1;
2705 }
2706 assert_eq!(i, expected.len());
2707 }
2708
2709 #[test]
2710 fn test_difference() {
2711 let mut a = HashSet::new();
2712 let mut b = HashSet::new();
2713
2714 assert!(a.insert(1));
2715 assert!(a.insert(3));
2716 assert!(a.insert(5));
2717 assert!(a.insert(9));
2718 assert!(a.insert(11));
2719
2720 assert!(b.insert(3));
2721 assert!(b.insert(9));
2722
2723 let mut i = 0;
2724 let expected = [1, 5, 11];
2725 for x in a.difference(&b) {
2726 assert!(expected.contains(x));
2727 i += 1;
2728 }
2729 assert_eq!(i, expected.len());
2730 }
2731
2732 #[test]
2733 fn test_symmetric_difference() {
2734 let mut a = HashSet::new();
2735 let mut b = HashSet::new();
2736
2737 assert!(a.insert(1));
2738 assert!(a.insert(3));
2739 assert!(a.insert(5));
2740 assert!(a.insert(9));
2741 assert!(a.insert(11));
2742
2743 assert!(b.insert(-2));
2744 assert!(b.insert(3));
2745 assert!(b.insert(9));
2746 assert!(b.insert(14));
2747 assert!(b.insert(22));
2748
2749 let mut i = 0;
2750 let expected = [-2, 1, 5, 11, 14, 22];
2751 for x in a.symmetric_difference(&b) {
2752 assert!(expected.contains(x));
2753 i += 1;
2754 }
2755 assert_eq!(i, expected.len());
2756 }
2757
2758 #[test]
2759 fn test_union() {
2760 let mut a = HashSet::new();
2761 let mut b = HashSet::new();
2762
2763 assert!(a.insert(1));
2764 assert!(a.insert(3));
2765 assert!(a.insert(5));
2766 assert!(a.insert(9));
2767 assert!(a.insert(11));
2768 assert!(a.insert(16));
2769 assert!(a.insert(19));
2770 assert!(a.insert(24));
2771
2772 assert!(b.insert(-2));
2773 assert!(b.insert(1));
2774 assert!(b.insert(5));
2775 assert!(b.insert(9));
2776 assert!(b.insert(13));
2777 assert!(b.insert(19));
2778
2779 let mut i = 0;
2780 let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
2781 for x in a.union(&b) {
2782 assert!(expected.contains(x));
2783 i += 1;
2784 }
2785 assert_eq!(i, expected.len());
2786 }
2787
2788 #[test]
2789 fn test_from_map() {
2790 let mut a = crate::HashMap::new();
2791 a.insert(1, ());
2792 a.insert(2, ());
2793 a.insert(3, ());
2794 a.insert(4, ());
2795
2796 let a: HashSet<_> = a.into();
2797
2798 assert_eq!(a.len(), 4);
2799 assert!(a.contains(&1));
2800 assert!(a.contains(&2));
2801 assert!(a.contains(&3));
2802 assert!(a.contains(&4));
2803 }
2804
2805 #[test]
2806 fn test_from_iter() {
2807 let xs = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9];
2808
2809 let set: HashSet<_> = xs.iter().copied().collect();
2810
2811 for x in &xs {
2812 assert!(set.contains(x));
2813 }
2814
2815 assert_eq!(set.iter().len(), xs.len() - 1);
2816 }
2817
2818 #[test]
2819 fn test_move_iter() {
2820 let hs = {
2821 let mut hs = HashSet::new();
2822
2823 hs.insert('a');
2824 hs.insert('b');
2825
2826 hs
2827 };
2828
2829 let v = hs.into_iter().collect::<Vec<char>>();
2830 assert!(v == ['a', 'b'] || v == ['b', 'a']);
2831 }
2832
2833 #[test]
2834 fn test_eq() {
2835 // These constants once happened to expose a bug in insert().
2836 // I'm keeping them around to prevent a regression.
2837 let mut s1 = HashSet::new();
2838
2839 s1.insert(1);
2840 s1.insert(2);
2841 s1.insert(3);
2842
2843 let mut s2 = HashSet::new();
2844
2845 s2.insert(1);
2846 s2.insert(2);
2847
2848 assert!(s1 != s2);
2849
2850 s2.insert(3);
2851
2852 assert_eq!(s1, s2);
2853 }
2854
2855 #[test]
2856 fn test_show() {
2857 let mut set = HashSet::new();
2858 let empty = HashSet::<i32>::new();
2859
2860 set.insert(1);
2861 set.insert(2);
2862
2863 let set_str = format!("{set:?}");
2864
2865 assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
2866 assert_eq!(format!("{empty:?}"), "{}");
2867 }
2868
2869 #[test]
2870 fn test_trivial_drain() {
2871 let mut s = HashSet::<i32>::new();
2872 for _ in s.drain() {}
2873 assert!(s.is_empty());
2874 drop(s);
2875
2876 let mut s = HashSet::<i32>::new();
2877 drop(s.drain());
2878 assert!(s.is_empty());
2879 }
2880
2881 #[test]
2882 fn test_drain() {
2883 let mut s: HashSet<_> = (1..100).collect();
2884
2885 // try this a bunch of times to make sure we don't screw up internal state.
2886 for _ in 0..20 {
2887 assert_eq!(s.len(), 99);
2888
2889 {
2890 let mut last_i = 0;
2891 let mut d = s.drain();
2892 for (i, x) in d.by_ref().take(50).enumerate() {
2893 last_i = i;
2894 assert!(x != 0);
2895 }
2896 assert_eq!(last_i, 49);
2897 }
2898
2899 if !s.is_empty() {
2900 panic!("s should be empty!");
2901 }
2902
2903 // reset to try again.
2904 s.extend(1..100);
2905 }
2906 }
2907
2908 #[test]
2909 fn test_replace() {
2910 use core::hash;
2911
2912 #[derive(Debug)]
2913 #[allow(dead_code)]
2914 struct Foo(&'static str, i32);
2915
2916 impl PartialEq for Foo {
2917 fn eq(&self, other: &Self) -> bool {
2918 self.0 == other.0
2919 }
2920 }
2921
2922 impl Eq for Foo {}
2923
2924 impl hash::Hash for Foo {
2925 fn hash<H: hash::Hasher>(&self, h: &mut H) {
2926 self.0.hash(h);
2927 }
2928 }
2929
2930 let mut s = HashSet::new();
2931 assert_eq!(s.replace(Foo("a", 1)), None);
2932 assert_eq!(s.len(), 1);
2933 assert_eq!(s.replace(Foo("a", 2)), Some(Foo("a", 1)));
2934 assert_eq!(s.len(), 1);
2935
2936 let mut it = s.iter();
2937 assert_eq!(it.next(), Some(&Foo("a", 2)));
2938 assert_eq!(it.next(), None);
2939 }
2940
2941 #[test]
2942 #[allow(clippy::needless_borrow)]
2943 fn test_extend_ref() {
2944 let mut a = HashSet::new();
2945 a.insert(1);
2946
2947 a.extend([2, 3, 4]);
2948
2949 assert_eq!(a.len(), 4);
2950 assert!(a.contains(&1));
2951 assert!(a.contains(&2));
2952 assert!(a.contains(&3));
2953 assert!(a.contains(&4));
2954
2955 let mut b = HashSet::new();
2956 b.insert(5);
2957 b.insert(6);
2958
2959 a.extend(&b);
2960
2961 assert_eq!(a.len(), 6);
2962 assert!(a.contains(&1));
2963 assert!(a.contains(&2));
2964 assert!(a.contains(&3));
2965 assert!(a.contains(&4));
2966 assert!(a.contains(&5));
2967 assert!(a.contains(&6));
2968 }
2969
2970 #[test]
2971 fn test_retain() {
2972 let xs = [1, 2, 3, 4, 5, 6];
2973 let mut set: HashSet<i32> = xs.iter().copied().collect();
2974 set.retain(|&k| k % 2 == 0);
2975 assert_eq!(set.len(), 3);
2976 assert!(set.contains(&2));
2977 assert!(set.contains(&4));
2978 assert!(set.contains(&6));
2979 }
2980
2981 #[test]
2982 fn test_extract_if() {
2983 {
2984 let mut set: HashSet<i32> = (0..8).collect();
2985 let drained = set.extract_if(|&k| k % 2 == 0);
2986 let mut out = drained.collect::<Vec<_>>();
2987 out.sort_unstable();
2988 assert_eq!(vec![0, 2, 4, 6], out);
2989 assert_eq!(set.len(), 4);
2990 }
2991 {
2992 let mut set: HashSet<i32> = (0..8).collect();
2993 set.extract_if(|&k| k % 2 == 0).for_each(drop);
2994 assert_eq!(set.len(), 4, "Removes non-matching items on drop");
2995 }
2996 }
2997
2998 #[test]
2999 fn test_const_with_hasher() {
3000 use core::hash::BuildHasher;
3001 use std::collections::hash_map::DefaultHasher;
3002
3003 #[derive(Clone)]
3004 struct MyHasher;
3005 impl BuildHasher for MyHasher {
3006 type Hasher = DefaultHasher;
3007
3008 fn build_hasher(&self) -> DefaultHasher {
3009 DefaultHasher::new()
3010 }
3011 }
3012
3013 const EMPTY_SET: HashSet<u32, MyHasher> = HashSet::with_hasher(MyHasher);
3014
3015 let mut set = EMPTY_SET;
3016 set.insert(19);
3017 assert!(set.contains(&19));
3018 }
3019
3020 #[test]
3021 fn rehash_in_place() {
3022 let mut set = HashSet::new();
3023
3024 for i in 0..224 {
3025 set.insert(i);
3026 }
3027
3028 assert_eq!(
3029 set.capacity(),
3030 224,
3031 "The set must be at or close to capacity to trigger a re hashing"
3032 );
3033
3034 for i in 100..1400 {
3035 set.remove(&(i - 100));
3036 set.insert(i);
3037 }
3038 }
3039
3040 #[test]
3041 fn collect() {
3042 // At the time of writing, this hits the ZST case in from_base_index
3043 // (and without the `map`, it does not).
3044 let mut _set: HashSet<_> = (0..3).map(|_| ()).collect();
3045 }
3046
3047 #[test]
3048 fn test_allocation_info() {
3049 assert_eq!(HashSet::<()>::new().allocation_size(), 0);
3050 assert_eq!(HashSet::<u32>::new().allocation_size(), 0);
3051 assert!(HashSet::<u32>::with_capacity(1).allocation_size() > core::mem::size_of::<u32>());
3052 }
3053
3054 #[test]
3055 fn duplicate_insert() {
3056 let mut set = HashSet::new();
3057 set.insert(1);
3058 set.get_or_insert_with(&1, |_| 1);
3059 set.get_or_insert_with(&1, |_| 1);
3060 assert!([1].iter().eq(set.iter()));
3061 }
3062
3063 #[test]
3064 #[should_panic]
3065 fn some_invalid_equivalent() {
3066 use core::hash::{Hash, Hasher};
3067 struct Invalid {
3068 count: u32,
3069 other: u32,
3070 }
3071
3072 struct InvalidRef {
3073 count: u32,
3074 other: u32,
3075 }
3076
3077 impl PartialEq for Invalid {
3078 fn eq(&self, other: &Self) -> bool {
3079 self.count == other.count && self.other == other.other
3080 }
3081 }
3082 impl Eq for Invalid {}
3083
3084 impl Equivalent<Invalid> for InvalidRef {
3085 fn equivalent(&self, key: &Invalid) -> bool {
3086 self.count == key.count && self.other == key.other
3087 }
3088 }
3089 impl Hash for Invalid {
3090 fn hash<H: Hasher>(&self, state: &mut H) {
3091 self.count.hash(state);
3092 }
3093 }
3094 impl Hash for InvalidRef {
3095 fn hash<H: Hasher>(&self, state: &mut H) {
3096 self.count.hash(state);
3097 }
3098 }
3099 let mut set: HashSet<Invalid> = HashSet::new();
3100 let key = InvalidRef { count: 1, other: 1 };
3101 let value = Invalid { count: 1, other: 2 };
3102 if make_hash(set.hasher(), &key) == make_hash(set.hasher(), &value) {
3103 set.get_or_insert_with(&key, |_| value);
3104 }
3105 }
3106}