Debian Codegraph @

debian/missing-sources/hashbrown-0.13.2/src/set.rs

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