hashbrown/map.rs
1use crate::alloc::{Allocator, Global};
2use crate::raw::{Bucket, RawDrain, RawExtractIf, RawIntoIter, RawIter, RawTable};
3use crate::{DefaultHashBuilder, Equivalent, TryReserveError};
4use core::borrow::Borrow;
5use core::fmt::{self, Debug};
6use core::hash::{BuildHasher, Hash};
7use core::iter::FusedIterator;
8use core::marker::PhantomData;
9use core::mem;
10use core::ops::Index;
11use stdalloc::borrow::ToOwned;
12
13#[cfg(feature = "raw-entry")]
14pub use crate::raw_entry::*;
15
16/// A hash map implemented with quadratic probing and SIMD lookup.
17///
18/// The default hashing algorithm is currently [`foldhash`], though this is
19/// subject to change at any point in the future. This hash function is very
20/// fast for all types of keys, but this algorithm will typically *not* protect
21/// against attacks such as HashDoS.
22///
23/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
24/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
25/// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
26///
27/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
28/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
29/// If you implement these yourself, it is important that the following
30/// property holds:
31///
32/// ```text
33/// k1 == k2 -> hash(k1) == hash(k2)
34/// ```
35///
36/// In other words, if two keys are equal, their hashes must be equal.
37///
38/// It is a logic error for a key to be modified in such a way that the key's
39/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
40/// the [`Eq`] trait, changes while it is in the map. This is normally only
41/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
42///
43/// It is also a logic error for the [`Hash`] implementation of a key to panic.
44/// This is generally only possible if the trait is implemented manually. If a
45/// panic does occur then the contents of the `HashMap` may become corrupted and
46/// some items may be dropped from the table.
47///
48/// # Examples
49///
50/// ```
51/// use hashbrown::HashMap;
52///
53/// // Type inference lets us omit an explicit type signature (which
54/// // would be `HashMap<String, String>` in this example).
55/// let mut book_reviews = HashMap::new();
56///
57/// // Review some books.
58/// book_reviews.insert(
59/// "Adventures of Huckleberry Finn".to_string(),
60/// "My favorite book.".to_string(),
61/// );
62/// book_reviews.insert(
63/// "Grimms' Fairy Tales".to_string(),
64/// "Masterpiece.".to_string(),
65/// );
66/// book_reviews.insert(
67/// "Pride and Prejudice".to_string(),
68/// "Very enjoyable.".to_string(),
69/// );
70/// book_reviews.insert(
71/// "The Adventures of Sherlock Holmes".to_string(),
72/// "Eye lyked it alot.".to_string(),
73/// );
74///
75/// // Check for a specific one.
76/// // When collections store owned values (String), they can still be
77/// // queried using references (&str).
78/// if !book_reviews.contains_key("Les Misérables") {
79/// println!("We've got {} reviews, but Les Misérables ain't one.",
80/// book_reviews.len());
81/// }
82///
83/// // oops, this review has a lot of spelling mistakes, let's delete it.
84/// book_reviews.remove("The Adventures of Sherlock Holmes");
85///
86/// // Look up the values associated with some keys.
87/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
88/// for &book in &to_find {
89/// match book_reviews.get(book) {
90/// Some(review) => println!("{}: {}", book, review),
91/// None => println!("{} is unreviewed.", book)
92/// }
93/// }
94///
95/// // Look up the value for a key (will panic if the key is not found).
96/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
97///
98/// // Iterate over everything.
99/// for (book, review) in &book_reviews {
100/// println!("{}: \"{}\"", book, review);
101/// }
102/// ```
103///
104/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
105/// for more complex methods of getting, setting, updating and removing keys and
106/// their values:
107///
108/// ```
109/// use hashbrown::HashMap;
110///
111/// // type inference lets us omit an explicit type signature (which
112/// // would be `HashMap<&str, u8>` in this example).
113/// let mut player_stats = HashMap::new();
114///
115/// fn random_stat_buff() -> u8 {
116/// // could actually return some random value here - let's just return
117/// // some fixed value for now
118/// 42
119/// }
120///
121/// // insert a key only if it doesn't already exist
122/// player_stats.entry("health").or_insert(100);
123///
124/// // insert a key using a function that provides a new value only if it
125/// // doesn't already exist
126/// player_stats.entry("defence").or_insert_with(random_stat_buff);
127///
128/// // update a key, guarding against the key possibly not being set
129/// let stat = player_stats.entry("attack").or_insert(100);
130/// *stat += random_stat_buff();
131/// ```
132///
133/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
134/// We must also derive [`PartialEq`].
135///
136/// [`RefCell`]: std::cell::RefCell
137/// [`Cell`]: std::cell::Cell
138/// [`default`]: Default::default
139/// [`with_hasher`]: HashMap::with_hasher
140/// [`with_capacity_and_hasher`]: HashMap::with_capacity_and_hasher
141/// [`fnv`]: https://crates.io/crates/fnv
142/// [`foldhash`]: https://crates.io/crates/foldhash
143///
144/// ```
145/// use hashbrown::HashMap;
146///
147/// #[derive(Hash, Eq, PartialEq, Debug)]
148/// struct Viking {
149/// name: String,
150/// country: String,
151/// }
152///
153/// impl Viking {
154/// /// Creates a new Viking.
155/// fn new(name: &str, country: &str) -> Viking {
156/// Viking { name: name.to_string(), country: country.to_string() }
157/// }
158/// }
159///
160/// // Use a HashMap to store the vikings' health points.
161/// let mut vikings = HashMap::new();
162///
163/// vikings.insert(Viking::new("Einar", "Norway"), 25);
164/// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
165/// vikings.insert(Viking::new("Harald", "Iceland"), 12);
166///
167/// // Use derived implementation to print the status of the vikings.
168/// for (viking, health) in &vikings {
169/// println!("{:?} has {} hp", viking, health);
170/// }
171/// ```
172///
173/// A `HashMap` with fixed list of elements can be initialized from an array:
174///
175/// ```
176/// use hashbrown::HashMap;
177///
178/// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
179/// .into_iter().collect();
180/// // use the values stored in map
181/// ```
182pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator = Global> {
183 pub(crate) hash_builder: S,
184 pub(crate) table: RawTable<(K, V), A>,
185}
186
187impl<K: Clone, V: Clone, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A> {
188 fn clone(&self) -> Self {
189 HashMap {
190 hash_builder: self.hash_builder.clone(),
191 table: self.table.clone(),
192 }
193 }
194
195 fn clone_from(&mut self, source: &Self) {
196 self.table.clone_from(&source.table);
197
198 // Update hash_builder only if we successfully cloned all elements.
199 self.hash_builder.clone_from(&source.hash_builder);
200 }
201}
202
203/// Ensures that a single closure type across uses of this which, in turn prevents multiple
204/// instances of any functions like `RawTable::reserve` from being generated
205#[cfg_attr(feature = "inline-more", inline)]
206pub(crate) fn make_hasher<Q, V, S>(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_
207where
208 Q: Hash,
209 S: BuildHasher,
210{
211 move |val| make_hash::<Q, S>(hash_builder, &val.0)
212}
213
214/// Ensures that a single closure type across uses of this which, in turn prevents multiple
215/// instances of any functions like `RawTable::reserve` from being generated
216#[cfg_attr(feature = "inline-more", inline)]
217pub(crate) fn equivalent_key<Q, K, V>(k: &Q) -> impl Fn(&(K, V)) -> bool + '_
218where
219 Q: Equivalent<K> + ?Sized,
220{
221 move |x| k.equivalent(&x.0)
222}
223
224/// Ensures that a single closure type across uses of this which, in turn prevents multiple
225/// instances of any functions like `RawTable::reserve` from being generated
226#[cfg_attr(feature = "inline-more", inline)]
227#[cfg(feature = "raw-entry")]
228pub(crate) fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_
229where
230 Q: Equivalent<K> + ?Sized,
231{
232 move |x| k.equivalent(x)
233}
234
235#[cfg_attr(feature = "inline-more", inline)]
236pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
237where
238 Q: Hash + ?Sized,
239 S: BuildHasher,
240{
241 hash_builder.hash_one(val)
242}
243
244#[cfg(feature = "default-hasher")]
245impl<K, V> HashMap<K, V, DefaultHashBuilder> {
246 /// Creates an empty `HashMap`.
247 ///
248 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
249 /// is first inserted into.
250 ///
251 /// # HashDoS resistance
252 ///
253 /// The `hash_builder` normally use a fixed key by default and that does
254 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
255 /// Users who require HashDoS resistance should explicitly use
256 /// [`std::hash::RandomState`]
257 /// as the hasher when creating a [`HashMap`], for example with
258 /// [`with_hasher`](HashMap::with_hasher) method.
259 ///
260 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use hashbrown::HashMap;
266 /// let mut map: HashMap<&str, i32> = HashMap::new();
267 /// assert_eq!(map.len(), 0);
268 /// assert_eq!(map.capacity(), 0);
269 /// ```
270 #[must_use]
271 #[cfg_attr(feature = "inline-more", inline)]
272 pub fn new() -> Self {
273 Self::default()
274 }
275
276 /// Creates an empty `HashMap` with the specified capacity.
277 ///
278 /// The hash map will be able to hold at least `capacity` elements without
279 /// reallocating. If `capacity` is 0, the hash map will not allocate.
280 ///
281 /// # HashDoS resistance
282 ///
283 /// The `hash_builder` normally use a fixed key by default and that does
284 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
285 /// Users who require HashDoS resistance should explicitly use
286 /// [`std::hash::RandomState`]
287 /// as the hasher when creating a [`HashMap`], for example with
288 /// [`with_capacity_and_hasher`](HashMap::with_capacity_and_hasher) method.
289 ///
290 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// use hashbrown::HashMap;
296 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
297 /// assert_eq!(map.len(), 0);
298 /// assert!(map.capacity() >= 10);
299 /// ```
300 #[must_use]
301 #[cfg_attr(feature = "inline-more", inline)]
302 pub fn with_capacity(capacity: usize) -> Self {
303 Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default())
304 }
305}
306
307#[cfg(feature = "default-hasher")]
308impl<K, V, A: Allocator> HashMap<K, V, DefaultHashBuilder, A> {
309 /// Creates an empty `HashMap` using the given allocator.
310 ///
311 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
312 /// is first inserted into.
313 ///
314 /// # HashDoS resistance
315 ///
316 /// The `hash_builder` normally use a fixed key by default and that does
317 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
318 /// Users who require HashDoS resistance should explicitly use
319 /// [`std::hash::RandomState`]
320 /// as the hasher when creating a [`HashMap`], for example with
321 /// [`with_hasher_in`](HashMap::with_hasher_in) method.
322 ///
323 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
324 ///
325 /// # Examples
326 ///
327 /// ```
328 /// use hashbrown::HashMap;
329 /// use bumpalo::Bump;
330 ///
331 /// let bump = Bump::new();
332 /// let mut map = HashMap::new_in(&bump);
333 ///
334 /// // The created HashMap holds none elements
335 /// assert_eq!(map.len(), 0);
336 ///
337 /// // The created HashMap also doesn't allocate memory
338 /// assert_eq!(map.capacity(), 0);
339 ///
340 /// // Now we insert element inside created HashMap
341 /// map.insert("One", 1);
342 /// // We can see that the HashMap holds 1 element
343 /// assert_eq!(map.len(), 1);
344 /// // And it also allocates some capacity
345 /// assert!(map.capacity() > 1);
346 /// ```
347 #[must_use]
348 #[cfg_attr(feature = "inline-more", inline)]
349 pub fn new_in(alloc: A) -> Self {
350 Self::with_hasher_in(DefaultHashBuilder::default(), alloc)
351 }
352
353 /// Creates an empty `HashMap` with the specified capacity using the given allocator.
354 ///
355 /// The hash map will be able to hold at least `capacity` elements without
356 /// reallocating. If `capacity` is 0, the hash map will not allocate.
357 ///
358 /// # HashDoS resistance
359 ///
360 /// The `hash_builder` normally use a fixed key by default and that does
361 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
362 /// Users who require HashDoS resistance should explicitly use
363 /// [`std::hash::RandomState`]
364 /// as the hasher when creating a [`HashMap`], for example with
365 /// [`with_capacity_and_hasher_in`](HashMap::with_capacity_and_hasher_in) method.
366 ///
367 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// use hashbrown::HashMap;
373 /// use bumpalo::Bump;
374 ///
375 /// let bump = Bump::new();
376 /// let mut map = HashMap::with_capacity_in(5, &bump);
377 ///
378 /// // The created HashMap holds none elements
379 /// assert_eq!(map.len(), 0);
380 /// // But it can hold at least 5 elements without reallocating
381 /// let empty_map_capacity = map.capacity();
382 /// assert!(empty_map_capacity >= 5);
383 ///
384 /// // Now we insert some 5 elements inside created HashMap
385 /// map.insert("One", 1);
386 /// map.insert("Two", 2);
387 /// map.insert("Three", 3);
388 /// map.insert("Four", 4);
389 /// map.insert("Five", 5);
390 ///
391 /// // We can see that the HashMap holds 5 elements
392 /// assert_eq!(map.len(), 5);
393 /// // But its capacity isn't changed
394 /// assert_eq!(map.capacity(), empty_map_capacity)
395 /// ```
396 #[must_use]
397 #[cfg_attr(feature = "inline-more", inline)]
398 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
399 Self::with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc)
400 }
401}
402
403impl<K, V, S> HashMap<K, V, S> {
404 /// Creates an empty `HashMap` which will use the given hash builder to hash
405 /// keys.
406 ///
407 /// The hash map is initially created with a capacity of 0, so it will not
408 /// allocate until it is first inserted into.
409 ///
410 /// # HashDoS resistance
411 ///
412 /// The `hash_builder` normally use a fixed key by default and that does
413 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
414 /// Users who require HashDoS resistance should explicitly use
415 /// [`std::hash::RandomState`]
416 /// as the hasher when creating a [`HashMap`].
417 ///
418 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
419 /// the `HashMap` to be useful, see its documentation for details.
420 ///
421 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// use hashbrown::HashMap;
427 /// use hashbrown::DefaultHashBuilder;
428 ///
429 /// let s = DefaultHashBuilder::default();
430 /// let mut map = HashMap::with_hasher(s);
431 /// assert_eq!(map.len(), 0);
432 /// assert_eq!(map.capacity(), 0);
433 ///
434 /// map.insert(1, 2);
435 /// ```
436 #[must_use]
437 #[cfg_attr(feature = "inline-more", inline)]
438 #[cfg_attr(feature = "rustc-dep-of-std", rustc_const_stable_indirect)]
439 pub const fn with_hasher(hash_builder: S) -> Self {
440 Self {
441 hash_builder,
442 table: RawTable::new(),
443 }
444 }
445
446 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
447 /// to hash the keys.
448 ///
449 /// The hash map will be able to hold at least `capacity` elements without
450 /// reallocating. If `capacity` is 0, the hash map will not allocate.
451 ///
452 /// # HashDoS resistance
453 ///
454 /// The `hash_builder` normally use a fixed key by default and that does
455 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
456 /// Users who require HashDoS resistance should explicitly use
457 /// [`std::hash::RandomState`]
458 /// as the hasher when creating a [`HashMap`].
459 ///
460 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
461 /// the `HashMap` to be useful, see its documentation for details.
462 ///
463 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
464 ///
465 /// # Examples
466 ///
467 /// ```
468 /// use hashbrown::HashMap;
469 /// use hashbrown::DefaultHashBuilder;
470 ///
471 /// let s = DefaultHashBuilder::default();
472 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
473 /// assert_eq!(map.len(), 0);
474 /// assert!(map.capacity() >= 10);
475 ///
476 /// map.insert(1, 2);
477 /// ```
478 #[must_use]
479 #[cfg_attr(feature = "inline-more", inline)]
480 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
481 Self {
482 hash_builder,
483 table: RawTable::with_capacity(capacity),
484 }
485 }
486}
487
488impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
489 /// Returns a reference to the underlying allocator.
490 #[inline]
491 pub fn allocator(&self) -> &A {
492 self.table.allocator()
493 }
494
495 /// Creates an empty `HashMap` which will use the given hash builder to hash
496 /// keys. It will be allocated with the given allocator.
497 ///
498 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
499 /// is first inserted into.
500 ///
501 /// # HashDoS resistance
502 ///
503 /// The `hash_builder` normally use a fixed key by default and that does
504 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
505 /// Users who require HashDoS resistance should explicitly use
506 /// [`std::hash::RandomState`]
507 /// as the hasher when creating a [`HashMap`].
508 ///
509 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
510 ///
511 /// # Examples
512 ///
513 /// ```
514 /// use hashbrown::HashMap;
515 /// use hashbrown::DefaultHashBuilder;
516 ///
517 /// let s = DefaultHashBuilder::default();
518 /// let mut map = HashMap::with_hasher(s);
519 /// map.insert(1, 2);
520 /// ```
521 #[must_use]
522 #[cfg_attr(feature = "inline-more", inline)]
523 #[cfg_attr(feature = "rustc-dep-of-std", rustc_const_stable_indirect)]
524 pub const fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
525 Self {
526 hash_builder,
527 table: RawTable::new_in(alloc),
528 }
529 }
530
531 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
532 /// to hash the keys. It will be allocated with the given allocator.
533 ///
534 /// The hash map will be able to hold at least `capacity` elements without
535 /// reallocating. If `capacity` is 0, the hash map will not allocate.
536 ///
537 /// # HashDoS resistance
538 ///
539 /// The `hash_builder` normally use a fixed key by default and that does
540 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
541 /// Users who require HashDoS resistance should explicitly use
542 /// [`std::hash::RandomState`]
543 /// as the hasher when creating a [`HashMap`].
544 ///
545 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// use hashbrown::HashMap;
551 /// use hashbrown::DefaultHashBuilder;
552 ///
553 /// let s = DefaultHashBuilder::default();
554 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
555 /// map.insert(1, 2);
556 /// ```
557 #[must_use]
558 #[cfg_attr(feature = "inline-more", inline)]
559 pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self {
560 Self {
561 hash_builder,
562 table: RawTable::with_capacity_in(capacity, alloc),
563 }
564 }
565
566 /// Returns a reference to the map's [`BuildHasher`].
567 ///
568 /// # Examples
569 ///
570 /// ```
571 /// use hashbrown::HashMap;
572 /// use hashbrown::DefaultHashBuilder;
573 ///
574 /// let hasher = DefaultHashBuilder::default();
575 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
576 /// let hasher: &DefaultHashBuilder = map.hasher();
577 /// ```
578 #[cfg_attr(feature = "inline-more", inline)]
579 pub fn hasher(&self) -> &S {
580 &self.hash_builder
581 }
582
583 /// Returns the number of elements the map can hold without reallocating.
584 ///
585 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
586 /// more, but is guaranteed to be able to hold at least this many.
587 ///
588 /// # Examples
589 ///
590 /// ```
591 /// use hashbrown::HashMap;
592 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
593 /// assert_eq!(map.len(), 0);
594 /// assert!(map.capacity() >= 100);
595 /// ```
596 #[cfg_attr(feature = "inline-more", inline)]
597 pub fn capacity(&self) -> usize {
598 self.table.capacity()
599 }
600
601 /// An iterator visiting all keys in arbitrary order.
602 /// The iterator element type is `&'a K`.
603 ///
604 /// # Examples
605 ///
606 /// ```
607 /// use hashbrown::HashMap;
608 ///
609 /// let mut map = HashMap::new();
610 /// map.insert("a", 1);
611 /// map.insert("b", 2);
612 /// map.insert("c", 3);
613 /// assert_eq!(map.len(), 3);
614 /// let mut vec: Vec<&str> = Vec::new();
615 ///
616 /// for key in map.keys() {
617 /// println!("{}", key);
618 /// vec.push(*key);
619 /// }
620 ///
621 /// // The `Keys` iterator produces keys in arbitrary order, so the
622 /// // keys must be sorted to test them against a sorted array.
623 /// vec.sort_unstable();
624 /// assert_eq!(vec, ["a", "b", "c"]);
625 ///
626 /// assert_eq!(map.len(), 3);
627 /// ```
628 #[cfg_attr(feature = "inline-more", inline)]
629 pub fn keys(&self) -> Keys<'_, K, V> {
630 Keys { inner: self.iter() }
631 }
632
633 /// An iterator visiting all values in arbitrary order.
634 /// The iterator element type is `&'a V`.
635 ///
636 /// # Examples
637 ///
638 /// ```
639 /// use hashbrown::HashMap;
640 ///
641 /// let mut map = HashMap::new();
642 /// map.insert("a", 1);
643 /// map.insert("b", 2);
644 /// map.insert("c", 3);
645 /// assert_eq!(map.len(), 3);
646 /// let mut vec: Vec<i32> = Vec::new();
647 ///
648 /// for val in map.values() {
649 /// println!("{}", val);
650 /// vec.push(*val);
651 /// }
652 ///
653 /// // The `Values` iterator produces values in arbitrary order, so the
654 /// // values must be sorted to test them against a sorted array.
655 /// vec.sort_unstable();
656 /// assert_eq!(vec, [1, 2, 3]);
657 ///
658 /// assert_eq!(map.len(), 3);
659 /// ```
660 #[cfg_attr(feature = "inline-more", inline)]
661 pub fn values(&self) -> Values<'_, K, V> {
662 Values { inner: self.iter() }
663 }
664
665 /// An iterator visiting all values mutably in arbitrary order.
666 /// The iterator element type is `&'a mut V`.
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// use hashbrown::HashMap;
672 ///
673 /// let mut map = HashMap::new();
674 ///
675 /// map.insert("a", 1);
676 /// map.insert("b", 2);
677 /// map.insert("c", 3);
678 ///
679 /// for val in map.values_mut() {
680 /// *val = *val + 10;
681 /// }
682 ///
683 /// assert_eq!(map.len(), 3);
684 /// let mut vec: Vec<i32> = Vec::new();
685 ///
686 /// for val in map.values() {
687 /// println!("{}", val);
688 /// vec.push(*val);
689 /// }
690 ///
691 /// // The `Values` iterator produces values in arbitrary order, so the
692 /// // values must be sorted to test them against a sorted array.
693 /// vec.sort_unstable();
694 /// assert_eq!(vec, [11, 12, 13]);
695 ///
696 /// assert_eq!(map.len(), 3);
697 /// ```
698 #[cfg_attr(feature = "inline-more", inline)]
699 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
700 ValuesMut {
701 inner: self.iter_mut(),
702 }
703 }
704
705 /// An iterator visiting all key-value pairs in arbitrary order.
706 /// The iterator element type is `(&'a K, &'a V)`.
707 ///
708 /// # Examples
709 ///
710 /// ```
711 /// use hashbrown::HashMap;
712 ///
713 /// let mut map = HashMap::new();
714 /// map.insert("a", 1);
715 /// map.insert("b", 2);
716 /// map.insert("c", 3);
717 /// assert_eq!(map.len(), 3);
718 /// let mut vec: Vec<(&str, i32)> = Vec::new();
719 ///
720 /// for (key, val) in map.iter() {
721 /// println!("key: {} val: {}", key, val);
722 /// vec.push((*key, *val));
723 /// }
724 ///
725 /// // The `Iter` iterator produces items in arbitrary order, so the
726 /// // items must be sorted to test them against a sorted array.
727 /// vec.sort_unstable();
728 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
729 ///
730 /// assert_eq!(map.len(), 3);
731 /// ```
732 #[cfg_attr(feature = "inline-more", inline)]
733 pub fn iter(&self) -> Iter<'_, K, V> {
734 // Here we tie the lifetime of self to the iter.
735 unsafe {
736 Iter {
737 inner: self.table.iter(),
738 marker: PhantomData,
739 }
740 }
741 }
742
743 /// An iterator visiting all key-value pairs in arbitrary order,
744 /// with mutable references to the values.
745 /// The iterator element type is `(&'a K, &'a mut V)`.
746 ///
747 /// # Examples
748 ///
749 /// ```
750 /// use hashbrown::HashMap;
751 ///
752 /// let mut map = HashMap::new();
753 /// map.insert("a", 1);
754 /// map.insert("b", 2);
755 /// map.insert("c", 3);
756 ///
757 /// // Update all values
758 /// for (_, val) in map.iter_mut() {
759 /// *val *= 2;
760 /// }
761 ///
762 /// assert_eq!(map.len(), 3);
763 /// let mut vec: Vec<(&str, i32)> = Vec::new();
764 ///
765 /// for (key, val) in &map {
766 /// println!("key: {} val: {}", key, val);
767 /// vec.push((*key, *val));
768 /// }
769 ///
770 /// // The `Iter` iterator produces items in arbitrary order, so the
771 /// // items must be sorted to test them against a sorted array.
772 /// vec.sort_unstable();
773 /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
774 ///
775 /// assert_eq!(map.len(), 3);
776 /// ```
777 #[cfg_attr(feature = "inline-more", inline)]
778 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
779 // Here we tie the lifetime of self to the iter.
780 unsafe {
781 IterMut {
782 inner: self.table.iter(),
783 marker: PhantomData,
784 }
785 }
786 }
787
788 #[cfg(test)]
789 #[cfg_attr(feature = "inline-more", inline)]
790 fn raw_capacity(&self) -> usize {
791 self.table.num_buckets()
792 }
793
794 /// Returns the number of elements in the map.
795 ///
796 /// # Examples
797 ///
798 /// ```
799 /// use hashbrown::HashMap;
800 ///
801 /// let mut a = HashMap::new();
802 /// assert_eq!(a.len(), 0);
803 /// a.insert(1, "a");
804 /// assert_eq!(a.len(), 1);
805 /// ```
806 #[cfg_attr(feature = "inline-more", inline)]
807 pub fn len(&self) -> usize {
808 self.table.len()
809 }
810
811 /// Returns `true` if the map contains no elements.
812 ///
813 /// # Examples
814 ///
815 /// ```
816 /// use hashbrown::HashMap;
817 ///
818 /// let mut a = HashMap::new();
819 /// assert!(a.is_empty());
820 /// a.insert(1, "a");
821 /// assert!(!a.is_empty());
822 /// ```
823 #[cfg_attr(feature = "inline-more", inline)]
824 pub fn is_empty(&self) -> bool {
825 self.len() == 0
826 }
827
828 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
829 /// allocated memory for reuse.
830 ///
831 /// If the returned iterator is dropped before being fully consumed, it
832 /// drops the remaining key-value pairs. The returned iterator keeps a
833 /// mutable borrow on the vector to optimize its implementation.
834 ///
835 /// # Examples
836 ///
837 /// ```
838 /// use hashbrown::HashMap;
839 ///
840 /// let mut a = HashMap::new();
841 /// a.insert(1, "a");
842 /// a.insert(2, "b");
843 /// let capacity_before_drain = a.capacity();
844 ///
845 /// for (k, v) in a.drain().take(1) {
846 /// assert!(k == 1 || k == 2);
847 /// assert!(v == "a" || v == "b");
848 /// }
849 ///
850 /// // As we can see, the map is empty and contains no element.
851 /// assert!(a.is_empty() && a.len() == 0);
852 /// // But map capacity is equal to old one.
853 /// assert_eq!(a.capacity(), capacity_before_drain);
854 ///
855 /// let mut a = HashMap::new();
856 /// a.insert(1, "a");
857 /// a.insert(2, "b");
858 ///
859 /// { // Iterator is dropped without being consumed.
860 /// let d = a.drain();
861 /// }
862 ///
863 /// // But the map is empty even if we do not use Drain iterator.
864 /// assert!(a.is_empty());
865 /// ```
866 #[cfg_attr(feature = "inline-more", inline)]
867 pub fn drain(&mut self) -> Drain<'_, K, V, A> {
868 Drain {
869 inner: self.table.drain(),
870 }
871 }
872
873 /// Retains only the elements specified by the predicate. Keeps the
874 /// allocated memory for reuse.
875 ///
876 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
877 /// The elements are visited in unsorted (and unspecified) order.
878 ///
879 /// # Examples
880 ///
881 /// ```
882 /// use hashbrown::HashMap;
883 ///
884 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
885 /// assert_eq!(map.len(), 8);
886 ///
887 /// map.retain(|&k, _| k % 2 == 0);
888 ///
889 /// // We can see, that the number of elements inside map is changed.
890 /// assert_eq!(map.len(), 4);
891 ///
892 /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
893 /// vec.sort_unstable();
894 /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
895 /// ```
896 pub fn retain<F>(&mut self, mut f: F)
897 where
898 F: FnMut(&K, &mut V) -> bool,
899 {
900 // Here we only use `iter` as a temporary, preventing use-after-free
901 unsafe {
902 for item in self.table.iter() {
903 let &mut (ref key, ref mut value) = item.as_mut();
904 if !f(key, value) {
905 self.table.erase(item);
906 }
907 }
908 }
909 }
910
911 /// Drains elements which are true under the given predicate,
912 /// and returns an iterator over the removed items.
913 ///
914 /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out
915 /// into another iterator.
916 ///
917 /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of
918 /// whether you choose to keep or remove it.
919 ///
920 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
921 /// or the iteration short-circuits, then the remaining elements will be retained.
922 /// Use [`retain()`] with a negated predicate if you do not need the returned iterator.
923 ///
924 /// Keeps the allocated memory for reuse.
925 ///
926 /// [`retain()`]: HashMap::retain
927 ///
928 /// # Examples
929 ///
930 /// ```
931 /// use hashbrown::HashMap;
932 ///
933 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
934 ///
935 /// let drained: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
936 ///
937 /// let mut evens = drained.keys().cloned().collect::<Vec<_>>();
938 /// let mut odds = map.keys().cloned().collect::<Vec<_>>();
939 /// evens.sort();
940 /// odds.sort();
941 ///
942 /// assert_eq!(evens, vec![0, 2, 4, 6]);
943 /// assert_eq!(odds, vec![1, 3, 5, 7]);
944 ///
945 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
946 ///
947 /// { // Iterator is dropped without being consumed.
948 /// let d = map.extract_if(|k, _v| k % 2 != 0);
949 /// }
950 ///
951 /// // ExtractIf was not exhausted, therefore no elements were drained.
952 /// assert_eq!(map.len(), 8);
953 /// ```
954 #[cfg_attr(feature = "inline-more", inline)]
955 pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F, A>
956 where
957 F: FnMut(&K, &mut V) -> bool,
958 {
959 ExtractIf {
960 f,
961 inner: RawExtractIf {
962 iter: unsafe { self.table.iter() },
963 table: &mut self.table,
964 },
965 }
966 }
967
968 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
969 /// for reuse.
970 ///
971 /// # Examples
972 ///
973 /// ```
974 /// use hashbrown::HashMap;
975 ///
976 /// let mut a = HashMap::new();
977 /// a.insert(1, "a");
978 /// let capacity_before_clear = a.capacity();
979 ///
980 /// a.clear();
981 ///
982 /// // Map is empty.
983 /// assert!(a.is_empty());
984 /// // But map capacity is equal to old one.
985 /// assert_eq!(a.capacity(), capacity_before_clear);
986 /// ```
987 #[cfg_attr(feature = "inline-more", inline)]
988 pub fn clear(&mut self) {
989 self.table.clear();
990 }
991
992 /// Creates a consuming iterator visiting all the keys in arbitrary order.
993 /// The map cannot be used after calling this.
994 /// The iterator element type is `K`.
995 ///
996 /// # Examples
997 ///
998 /// ```
999 /// use hashbrown::HashMap;
1000 ///
1001 /// let mut map = HashMap::new();
1002 /// map.insert("a", 1);
1003 /// map.insert("b", 2);
1004 /// map.insert("c", 3);
1005 ///
1006 /// let mut vec: Vec<&str> = map.into_keys().collect();
1007 ///
1008 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
1009 /// // keys must be sorted to test them against a sorted array.
1010 /// vec.sort_unstable();
1011 /// assert_eq!(vec, ["a", "b", "c"]);
1012 /// ```
1013 #[inline]
1014 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1015 IntoKeys {
1016 inner: self.into_iter(),
1017 }
1018 }
1019
1020 /// Creates a consuming iterator visiting all the values in arbitrary order.
1021 /// The map cannot be used after calling this.
1022 /// The iterator element type is `V`.
1023 ///
1024 /// # Examples
1025 ///
1026 /// ```
1027 /// use hashbrown::HashMap;
1028 ///
1029 /// let mut map = HashMap::new();
1030 /// map.insert("a", 1);
1031 /// map.insert("b", 2);
1032 /// map.insert("c", 3);
1033 ///
1034 /// let mut vec: Vec<i32> = map.into_values().collect();
1035 ///
1036 /// // The `IntoValues` iterator produces values in arbitrary order, so
1037 /// // the values must be sorted to test them against a sorted array.
1038 /// vec.sort_unstable();
1039 /// assert_eq!(vec, [1, 2, 3]);
1040 /// ```
1041 #[inline]
1042 pub fn into_values(self) -> IntoValues<K, V, A> {
1043 IntoValues {
1044 inner: self.into_iter(),
1045 }
1046 }
1047}
1048
1049impl<K, V, S, A> HashMap<K, V, S, A>
1050where
1051 K: Eq + Hash,
1052 S: BuildHasher,
1053 A: Allocator,
1054{
1055 /// Reserves capacity for at least `additional` more elements to be inserted
1056 /// in the `HashMap`. The collection may reserve more space to avoid
1057 /// frequent reallocations.
1058 ///
1059 /// # Panics
1060 ///
1061 /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
1062 /// in case of allocation error. Use [`try_reserve`](HashMap::try_reserve) instead
1063 /// if you want to handle memory allocation failure.
1064 ///
1065 /// [`abort`]: stdalloc::alloc::handle_alloc_error
1066 ///
1067 /// # Examples
1068 ///
1069 /// ```
1070 /// use hashbrown::HashMap;
1071 /// let mut map: HashMap<&str, i32> = HashMap::new();
1072 /// // Map is empty and doesn't allocate memory
1073 /// assert_eq!(map.capacity(), 0);
1074 ///
1075 /// map.reserve(10);
1076 ///
1077 /// // And now map can hold at least 10 elements
1078 /// assert!(map.capacity() >= 10);
1079 /// ```
1080 #[cfg_attr(feature = "inline-more", inline)]
1081 pub fn reserve(&mut self, additional: usize) {
1082 self.table
1083 .reserve(additional, make_hasher::<_, V, S>(&self.hash_builder));
1084 }
1085
1086 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1087 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
1088 /// frequent reallocations.
1089 ///
1090 /// # Errors
1091 ///
1092 /// If the capacity overflows, or the allocator reports a failure, then an error
1093 /// is returned.
1094 ///
1095 /// # Examples
1096 ///
1097 /// ```
1098 /// use hashbrown::HashMap;
1099 ///
1100 /// let mut map: HashMap<&str, isize> = HashMap::new();
1101 /// // Map is empty and doesn't allocate memory
1102 /// assert_eq!(map.capacity(), 0);
1103 ///
1104 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
1105 ///
1106 /// // And now map can hold at least 10 elements
1107 /// assert!(map.capacity() >= 10);
1108 /// ```
1109 /// If the capacity overflows, or the allocator reports a failure, then an error
1110 /// is returned:
1111 /// ```
1112 /// # fn test() {
1113 /// use hashbrown::HashMap;
1114 /// use hashbrown::TryReserveError;
1115 /// let mut map: HashMap<i32, i32> = HashMap::new();
1116 ///
1117 /// match map.try_reserve(usize::MAX) {
1118 /// Err(error) => match error {
1119 /// TryReserveError::CapacityOverflow => {}
1120 /// _ => panic!("TryReserveError::AllocError ?"),
1121 /// },
1122 /// _ => panic!(),
1123 /// }
1124 /// # }
1125 /// # fn main() {
1126 /// # #[cfg(not(miri))]
1127 /// # test()
1128 /// # }
1129 /// ```
1130 #[cfg_attr(feature = "inline-more", inline)]
1131 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1132 self.table
1133 .try_reserve(additional, make_hasher::<_, V, S>(&self.hash_builder))
1134 }
1135
1136 /// Shrinks the capacity of the map as much as possible. It will drop
1137 /// down as much as possible while maintaining the internal rules
1138 /// and possibly leaving some space in accordance with the resize policy.
1139 ///
1140 /// # Examples
1141 ///
1142 /// ```
1143 /// use hashbrown::HashMap;
1144 ///
1145 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1146 /// map.insert(1, 2);
1147 /// map.insert(3, 4);
1148 /// assert!(map.capacity() >= 100);
1149 /// map.shrink_to_fit();
1150 /// assert!(map.capacity() >= 2);
1151 /// ```
1152 #[cfg_attr(feature = "inline-more", inline)]
1153 pub fn shrink_to_fit(&mut self) {
1154 self.table
1155 .shrink_to(0, make_hasher::<_, V, S>(&self.hash_builder));
1156 }
1157
1158 /// Shrinks the capacity of the map with a lower limit. It will drop
1159 /// down no lower than the supplied limit while maintaining the internal rules
1160 /// and possibly leaving some space in accordance with the resize policy.
1161 ///
1162 /// This function does nothing if the current capacity is smaller than the
1163 /// supplied minimum capacity.
1164 ///
1165 /// # Examples
1166 ///
1167 /// ```
1168 /// use hashbrown::HashMap;
1169 ///
1170 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1171 /// map.insert(1, 2);
1172 /// map.insert(3, 4);
1173 /// assert!(map.capacity() >= 100);
1174 /// map.shrink_to(10);
1175 /// assert!(map.capacity() >= 10);
1176 /// map.shrink_to(0);
1177 /// assert!(map.capacity() >= 2);
1178 /// map.shrink_to(10);
1179 /// assert!(map.capacity() >= 2);
1180 /// ```
1181 #[cfg_attr(feature = "inline-more", inline)]
1182 pub fn shrink_to(&mut self, min_capacity: usize) {
1183 self.table
1184 .shrink_to(min_capacity, make_hasher::<_, V, S>(&self.hash_builder));
1185 }
1186
1187 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1188 ///
1189 /// # Examples
1190 ///
1191 /// ```
1192 /// use hashbrown::HashMap;
1193 ///
1194 /// let mut letters = HashMap::new();
1195 ///
1196 /// for ch in "a short treatise on fungi".chars() {
1197 /// let counter = letters.entry(ch).or_insert(0);
1198 /// *counter += 1;
1199 /// }
1200 ///
1201 /// assert_eq!(letters[&'s'], 2);
1202 /// assert_eq!(letters[&'t'], 3);
1203 /// assert_eq!(letters[&'u'], 1);
1204 /// assert_eq!(letters.get(&'y'), None);
1205 /// ```
1206 #[cfg_attr(feature = "inline-more", inline)]
1207 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> {
1208 let hash = make_hash::<K, S>(&self.hash_builder, &key);
1209 if let Some(elem) = self.table.find(hash, equivalent_key(&key)) {
1210 Entry::Occupied(OccupiedEntry {
1211 hash,
1212 elem,
1213 table: self,
1214 })
1215 } else {
1216 Entry::Vacant(VacantEntry {
1217 hash,
1218 key,
1219 table: self,
1220 })
1221 }
1222 }
1223
1224 /// Gets the given key's corresponding entry by reference in the map for in-place manipulation.
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
1229 /// use hashbrown::HashMap;
1230 ///
1231 /// let mut words: HashMap<String, usize> = HashMap::new();
1232 /// let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
1233 /// for (i, &s) in source.iter().enumerate() {
1234 /// let counter = words.entry_ref(s).or_insert(0);
1235 /// *counter += 1;
1236 /// }
1237 ///
1238 /// assert_eq!(words["poneyland"], 3);
1239 /// assert_eq!(words["horseyland"], 1);
1240 /// ```
1241 #[cfg_attr(feature = "inline-more", inline)]
1242 pub fn entry_ref<'a, 'b, Q>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A>
1243 where
1244 Q: Hash + Equivalent<K> + ?Sized,
1245 {
1246 let hash = make_hash::<Q, S>(&self.hash_builder, key);
1247 if let Some(elem) = self.table.find(hash, equivalent_key(key)) {
1248 EntryRef::Occupied(OccupiedEntry {
1249 hash,
1250 elem,
1251 table: self,
1252 })
1253 } else {
1254 EntryRef::Vacant(VacantEntryRef {
1255 hash,
1256 key,
1257 table: self,
1258 })
1259 }
1260 }
1261
1262 /// Returns a reference to the value corresponding to the key.
1263 ///
1264 /// The key may be any borrowed form of the map's key type, but
1265 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1266 /// the key type.
1267 ///
1268 /// # Examples
1269 ///
1270 /// ```
1271 /// use hashbrown::HashMap;
1272 ///
1273 /// let mut map = HashMap::new();
1274 /// map.insert(1, "a");
1275 /// assert_eq!(map.get(&1), Some(&"a"));
1276 /// assert_eq!(map.get(&2), None);
1277 /// ```
1278 #[inline]
1279 pub fn get<Q>(&self, k: &Q) -> Option<&V>
1280 where
1281 Q: Hash + Equivalent<K> + ?Sized,
1282 {
1283 // Avoid `Option::map` because it bloats LLVM IR.
1284 if self.table.is_empty() {
1285 None
1286 } else {
1287 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1288 match self.table.get(hash, equivalent_key(k)) {
1289 Some((_, v)) => Some(v),
1290 None => None,
1291 }
1292 }
1293 }
1294
1295 /// Returns the key-value pair corresponding to the supplied key.
1296 ///
1297 /// The supplied key may be any borrowed form of the map's key type, but
1298 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1299 /// the key type.
1300 ///
1301 /// # Examples
1302 ///
1303 /// ```
1304 /// use hashbrown::HashMap;
1305 ///
1306 /// let mut map = HashMap::new();
1307 /// map.insert(1, "a");
1308 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1309 /// assert_eq!(map.get_key_value(&2), None);
1310 /// ```
1311 #[inline]
1312 pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
1313 where
1314 Q: Hash + Equivalent<K> + ?Sized,
1315 {
1316 // Avoid `Option::map` because it bloats LLVM IR.
1317 if self.table.is_empty() {
1318 None
1319 } else {
1320 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1321 match self.table.get(hash, equivalent_key(k)) {
1322 Some((key, value)) => Some((key, value)),
1323 None => None,
1324 }
1325 }
1326 }
1327
1328 /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
1329 ///
1330 /// The supplied key may be any borrowed form of the map's key type, but
1331 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1332 /// the key type.
1333 ///
1334 /// # Examples
1335 ///
1336 /// ```
1337 /// use hashbrown::HashMap;
1338 ///
1339 /// let mut map = HashMap::new();
1340 /// map.insert(1, "a");
1341 /// let (k, v) = map.get_key_value_mut(&1).unwrap();
1342 /// assert_eq!(k, &1);
1343 /// assert_eq!(v, &mut "a");
1344 /// *v = "b";
1345 /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
1346 /// assert_eq!(map.get_key_value_mut(&2), None);
1347 /// ```
1348 #[inline]
1349 pub fn get_key_value_mut<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
1350 where
1351 Q: Hash + Equivalent<K> + ?Sized,
1352 {
1353 // Avoid `Option::map` because it bloats LLVM IR.
1354 if self.table.is_empty() {
1355 None
1356 } else {
1357 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1358 match self.table.get_mut(hash, equivalent_key(k)) {
1359 Some(&mut (ref key, ref mut value)) => Some((key, value)),
1360 None => None,
1361 }
1362 }
1363 }
1364
1365 /// Returns `true` if the map contains a value for the specified key.
1366 ///
1367 /// The key may be any borrowed form of the map's key type, but
1368 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1369 /// the key type.
1370 ///
1371 /// # Examples
1372 ///
1373 /// ```
1374 /// use hashbrown::HashMap;
1375 ///
1376 /// let mut map = HashMap::new();
1377 /// map.insert(1, "a");
1378 /// assert_eq!(map.contains_key(&1), true);
1379 /// assert_eq!(map.contains_key(&2), false);
1380 /// ```
1381 #[cfg_attr(feature = "inline-more", inline)]
1382 pub fn contains_key<Q>(&self, k: &Q) -> bool
1383 where
1384 Q: Hash + Equivalent<K> + ?Sized,
1385 {
1386 if self.table.is_empty() {
1387 false
1388 } else {
1389 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1390 self.table.get(hash, equivalent_key(k)).is_some()
1391 }
1392 }
1393
1394 /// Returns a mutable reference to the value corresponding to the key.
1395 ///
1396 /// The key may be any borrowed form of the map's key type, but
1397 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1398 /// the key type.
1399 ///
1400 /// # Examples
1401 ///
1402 /// ```
1403 /// use hashbrown::HashMap;
1404 ///
1405 /// let mut map = HashMap::new();
1406 /// map.insert(1, "a");
1407 /// if let Some(x) = map.get_mut(&1) {
1408 /// *x = "b";
1409 /// }
1410 /// assert_eq!(map[&1], "b");
1411 ///
1412 /// assert_eq!(map.get_mut(&2), None);
1413 /// ```
1414 #[cfg_attr(feature = "inline-more", inline)]
1415 pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
1416 where
1417 Q: Hash + Equivalent<K> + ?Sized,
1418 {
1419 // Avoid `Option::map` because it bloats LLVM IR.
1420 if self.table.is_empty() {
1421 None
1422 } else {
1423 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1424 match self.table.get_mut(hash, equivalent_key(k)) {
1425 Some(&mut (_, ref mut v)) => Some(v),
1426 None => None,
1427 }
1428 }
1429 }
1430
1431 /// Attempts to get mutable references to `N` values in the map at once.
1432 ///
1433 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1434 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1435 ///
1436 /// # Panics
1437 ///
1438 /// Panics if any keys are overlapping.
1439 ///
1440 /// # Examples
1441 ///
1442 /// ```
1443 /// use hashbrown::HashMap;
1444 ///
1445 /// let mut libraries = HashMap::new();
1446 /// libraries.insert("Bodleian Library".to_string(), 1602);
1447 /// libraries.insert("Athenæum".to_string(), 1807);
1448 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1449 /// libraries.insert("Library of Congress".to_string(), 1800);
1450 ///
1451 /// // Get Athenæum and Bodleian Library
1452 /// let [Some(a), Some(b)] = libraries.get_disjoint_mut([
1453 /// "Athenæum",
1454 /// "Bodleian Library",
1455 /// ]) else { panic!() };
1456 ///
1457 /// // Assert values of Athenæum and Library of Congress
1458 /// let got = libraries.get_disjoint_mut([
1459 /// "Athenæum",
1460 /// "Library of Congress",
1461 /// ]);
1462 /// assert_eq!(
1463 /// got,
1464 /// [
1465 /// Some(&mut 1807),
1466 /// Some(&mut 1800),
1467 /// ],
1468 /// );
1469 ///
1470 /// // Missing keys result in None
1471 /// let got = libraries.get_disjoint_mut([
1472 /// "Athenæum",
1473 /// "New York Public Library",
1474 /// ]);
1475 /// assert_eq!(
1476 /// got,
1477 /// [
1478 /// Some(&mut 1807),
1479 /// None
1480 /// ]
1481 /// );
1482 /// ```
1483 ///
1484 /// ```should_panic
1485 /// use hashbrown::HashMap;
1486 ///
1487 /// let mut libraries = HashMap::new();
1488 /// libraries.insert("Athenæum".to_string(), 1807);
1489 ///
1490 /// // Duplicate keys panic!
1491 /// let got = libraries.get_disjoint_mut([
1492 /// "Athenæum",
1493 /// "Athenæum",
1494 /// ]);
1495 /// ```
1496 pub fn get_disjoint_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut V>; N]
1497 where
1498 Q: Hash + Equivalent<K> + ?Sized,
1499 {
1500 self.get_disjoint_mut_inner(ks)
1501 .map(|res| res.map(|(_, v)| v))
1502 }
1503
1504 /// Attempts to get mutable references to `N` values in the map at once.
1505 #[deprecated(note = "use `get_disjoint_mut` instead")]
1506 pub fn get_many_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut V>; N]
1507 where
1508 Q: Hash + Equivalent<K> + ?Sized,
1509 {
1510 self.get_disjoint_mut(ks)
1511 }
1512
1513 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1514 /// the values are unique.
1515 ///
1516 /// Returns an array of length `N` with the results of each query. `None` will be used if
1517 /// the key is missing.
1518 ///
1519 /// For a safe alternative see [`get_disjoint_mut`](`HashMap::get_disjoint_mut`).
1520 ///
1521 /// # Safety
1522 ///
1523 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1524 /// references are not used.
1525 ///
1526 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1527 ///
1528 /// # Examples
1529 ///
1530 /// ```
1531 /// use hashbrown::HashMap;
1532 ///
1533 /// let mut libraries = HashMap::new();
1534 /// libraries.insert("Bodleian Library".to_string(), 1602);
1535 /// libraries.insert("Athenæum".to_string(), 1807);
1536 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1537 /// libraries.insert("Library of Congress".to_string(), 1800);
1538 ///
1539 /// // SAFETY: The keys do not overlap.
1540 /// let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([
1541 /// "Athenæum",
1542 /// "Bodleian Library",
1543 /// ]) }) else { panic!() };
1544 ///
1545 /// // SAFETY: The keys do not overlap.
1546 /// let got = unsafe { libraries.get_disjoint_unchecked_mut([
1547 /// "Athenæum",
1548 /// "Library of Congress",
1549 /// ]) };
1550 /// assert_eq!(
1551 /// got,
1552 /// [
1553 /// Some(&mut 1807),
1554 /// Some(&mut 1800),
1555 /// ],
1556 /// );
1557 ///
1558 /// // SAFETY: The keys do not overlap.
1559 /// let got = unsafe { libraries.get_disjoint_unchecked_mut([
1560 /// "Athenæum",
1561 /// "New York Public Library",
1562 /// ]) };
1563 /// // Missing keys result in None
1564 /// assert_eq!(got, [Some(&mut 1807), None]);
1565 /// ```
1566 pub unsafe fn get_disjoint_unchecked_mut<Q, const N: usize>(
1567 &mut self,
1568 ks: [&Q; N],
1569 ) -> [Option<&'_ mut V>; N]
1570 where
1571 Q: Hash + Equivalent<K> + ?Sized,
1572 {
1573 unsafe {
1574 self.get_disjoint_unchecked_mut_inner(ks)
1575 .map(|res| res.map(|(_, v)| v))
1576 }
1577 }
1578
1579 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1580 /// the values are unique.
1581 #[deprecated(note = "use `get_disjoint_unchecked_mut` instead")]
1582 pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
1583 &mut self,
1584 ks: [&Q; N],
1585 ) -> [Option<&'_ mut V>; N]
1586 where
1587 Q: Hash + Equivalent<K> + ?Sized,
1588 {
1589 unsafe { self.get_disjoint_unchecked_mut(ks) }
1590 }
1591
1592 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1593 /// references to the corresponding keys.
1594 ///
1595 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1596 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1597 ///
1598 /// # Panics
1599 ///
1600 /// Panics if any keys are overlapping.
1601 ///
1602 /// # Examples
1603 ///
1604 /// ```
1605 /// use hashbrown::HashMap;
1606 ///
1607 /// let mut libraries = HashMap::new();
1608 /// libraries.insert("Bodleian Library".to_string(), 1602);
1609 /// libraries.insert("Athenæum".to_string(), 1807);
1610 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1611 /// libraries.insert("Library of Congress".to_string(), 1800);
1612 ///
1613 /// let got = libraries.get_disjoint_key_value_mut([
1614 /// "Bodleian Library",
1615 /// "Herzogin-Anna-Amalia-Bibliothek",
1616 /// ]);
1617 /// assert_eq!(
1618 /// got,
1619 /// [
1620 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1621 /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
1622 /// ],
1623 /// );
1624 /// // Missing keys result in None
1625 /// let got = libraries.get_disjoint_key_value_mut([
1626 /// "Bodleian Library",
1627 /// "Gewandhaus",
1628 /// ]);
1629 /// assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]);
1630 /// ```
1631 ///
1632 /// ```should_panic
1633 /// use hashbrown::HashMap;
1634 ///
1635 /// let mut libraries = HashMap::new();
1636 /// libraries.insert("Bodleian Library".to_string(), 1602);
1637 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1638 ///
1639 /// // Duplicate keys result in panic!
1640 /// let got = libraries.get_disjoint_key_value_mut([
1641 /// "Bodleian Library",
1642 /// "Herzogin-Anna-Amalia-Bibliothek",
1643 /// "Herzogin-Anna-Amalia-Bibliothek",
1644 /// ]);
1645 /// ```
1646 pub fn get_disjoint_key_value_mut<Q, const N: usize>(
1647 &mut self,
1648 ks: [&Q; N],
1649 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1650 where
1651 Q: Hash + Equivalent<K> + ?Sized,
1652 {
1653 self.get_disjoint_mut_inner(ks)
1654 .map(|res| res.map(|(k, v)| (&*k, v)))
1655 }
1656
1657 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1658 /// references to the corresponding keys.
1659 #[deprecated(note = "use `get_disjoint_key_value_mut` instead")]
1660 pub fn get_many_key_value_mut<Q, const N: usize>(
1661 &mut self,
1662 ks: [&Q; N],
1663 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1664 where
1665 Q: Hash + Equivalent<K> + ?Sized,
1666 {
1667 self.get_disjoint_key_value_mut(ks)
1668 }
1669
1670 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1671 /// references to the corresponding keys, without validating that the values are unique.
1672 ///
1673 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1674 /// any of the keys are missing.
1675 ///
1676 /// For a safe alternative see [`get_disjoint_key_value_mut`](`HashMap::get_disjoint_key_value_mut`).
1677 ///
1678 /// # Safety
1679 ///
1680 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1681 /// references are not used.
1682 ///
1683 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1684 ///
1685 /// # Examples
1686 ///
1687 /// ```
1688 /// use hashbrown::HashMap;
1689 ///
1690 /// let mut libraries = HashMap::new();
1691 /// libraries.insert("Bodleian Library".to_string(), 1602);
1692 /// libraries.insert("Athenæum".to_string(), 1807);
1693 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1694 /// libraries.insert("Library of Congress".to_string(), 1800);
1695 ///
1696 /// let got = libraries.get_disjoint_key_value_mut([
1697 /// "Bodleian Library",
1698 /// "Herzogin-Anna-Amalia-Bibliothek",
1699 /// ]);
1700 /// assert_eq!(
1701 /// got,
1702 /// [
1703 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1704 /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
1705 /// ],
1706 /// );
1707 /// // Missing keys result in None
1708 /// let got = libraries.get_disjoint_key_value_mut([
1709 /// "Bodleian Library",
1710 /// "Gewandhaus",
1711 /// ]);
1712 /// assert_eq!(
1713 /// got,
1714 /// [
1715 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1716 /// None,
1717 /// ],
1718 /// );
1719 /// ```
1720 pub unsafe fn get_disjoint_key_value_unchecked_mut<Q, const N: usize>(
1721 &mut self,
1722 ks: [&Q; N],
1723 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1724 where
1725 Q: Hash + Equivalent<K> + ?Sized,
1726 {
1727 unsafe {
1728 self.get_disjoint_unchecked_mut_inner(ks)
1729 .map(|res| res.map(|(k, v)| (&*k, v)))
1730 }
1731 }
1732
1733 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1734 /// references to the corresponding keys, without validating that the values are unique.
1735 #[deprecated(note = "use `get_disjoint_key_value_unchecked_mut` instead")]
1736 pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>(
1737 &mut self,
1738 ks: [&Q; N],
1739 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1740 where
1741 Q: Hash + Equivalent<K> + ?Sized,
1742 {
1743 unsafe { self.get_disjoint_key_value_unchecked_mut(ks) }
1744 }
1745
1746 fn get_disjoint_mut_inner<Q, const N: usize>(
1747 &mut self,
1748 ks: [&Q; N],
1749 ) -> [Option<&'_ mut (K, V)>; N]
1750 where
1751 Q: Hash + Equivalent<K> + ?Sized,
1752 {
1753 let hashes = self.build_hashes_inner(ks);
1754 self.table
1755 .get_disjoint_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1756 }
1757
1758 unsafe fn get_disjoint_unchecked_mut_inner<Q, const N: usize>(
1759 &mut self,
1760 ks: [&Q; N],
1761 ) -> [Option<&'_ mut (K, V)>; N]
1762 where
1763 Q: Hash + Equivalent<K> + ?Sized,
1764 {
1765 unsafe {
1766 let hashes = self.build_hashes_inner(ks);
1767 self.table
1768 .get_disjoint_unchecked_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1769 }
1770 }
1771
1772 fn build_hashes_inner<Q, const N: usize>(&self, ks: [&Q; N]) -> [u64; N]
1773 where
1774 Q: Hash + Equivalent<K> + ?Sized,
1775 {
1776 let mut hashes = [0_u64; N];
1777 for i in 0..N {
1778 hashes[i] = make_hash::<Q, S>(&self.hash_builder, ks[i]);
1779 }
1780 hashes
1781 }
1782
1783 /// Inserts a key-value pair into the map.
1784 ///
1785 /// If the map did not have this key present, [`None`] is returned.
1786 ///
1787 /// If the map did have this key present, the value is updated, and the old
1788 /// value is returned. The key is not updated, though; this matters for
1789 /// types that can be `==` without being identical. See the [`std::collections`]
1790 /// module-level documentation for more.
1791 ///
1792 /// # Examples
1793 ///
1794 /// ```
1795 /// use hashbrown::HashMap;
1796 ///
1797 /// let mut map = HashMap::new();
1798 /// assert_eq!(map.insert(37, "a"), None);
1799 /// assert_eq!(map.is_empty(), false);
1800 ///
1801 /// map.insert(37, "b");
1802 /// assert_eq!(map.insert(37, "c"), Some("b"));
1803 /// assert_eq!(map[&37], "c");
1804 /// ```
1805 #[cfg_attr(feature = "inline-more", inline)]
1806 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1807 let hash = make_hash(&self.hash_builder, &k);
1808 let equivalent = equivalent_key(&k);
1809 let hasher = make_hasher(&self.hash_builder);
1810 match self
1811 .table
1812 .find_or_find_insert_index(hash, equivalent, hasher)
1813 {
1814 Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
1815 Err(index) => {
1816 unsafe {
1817 self.table.insert_at_index(hash, index, (k, v));
1818 }
1819 None
1820 }
1821 }
1822 }
1823
1824 /// Insert a key-value pair into the map without checking
1825 /// if the key already exists in the map.
1826 ///
1827 /// This operation is faster than regular insert, because it does not perform
1828 /// lookup before insertion.
1829 ///
1830 /// This operation is useful during initial population of the map.
1831 /// For example, when constructing a map from another map, we know
1832 /// that keys are unique.
1833 ///
1834 /// Returns a reference to the key and value just inserted.
1835 ///
1836 /// # Safety
1837 ///
1838 /// This operation is safe if a key does not exist in the map.
1839 ///
1840 /// However, if a key exists in the map already, the behavior is unspecified:
1841 /// this operation may panic, loop forever, or any following operation with the map
1842 /// may panic, loop forever or return arbitrary result.
1843 ///
1844 /// That said, this operation (and following operations) are guaranteed to
1845 /// not violate memory safety.
1846 ///
1847 /// However this operation is still unsafe because the resulting `HashMap`
1848 /// may be passed to unsafe code which does expect the map to behave
1849 /// correctly, and would cause unsoundness as a result.
1850 ///
1851 /// # Examples
1852 ///
1853 /// ```
1854 /// use hashbrown::HashMap;
1855 ///
1856 /// let mut map1 = HashMap::new();
1857 /// assert_eq!(map1.insert(1, "a"), None);
1858 /// assert_eq!(map1.insert(2, "b"), None);
1859 /// assert_eq!(map1.insert(3, "c"), None);
1860 /// assert_eq!(map1.len(), 3);
1861 ///
1862 /// let mut map2 = HashMap::new();
1863 ///
1864 /// for (key, value) in map1.into_iter() {
1865 /// unsafe {
1866 /// map2.insert_unique_unchecked(key, value);
1867 /// }
1868 /// }
1869 ///
1870 /// let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") };
1871 /// assert_eq!(key, &4);
1872 /// assert_eq!(value, &mut "d");
1873 /// *value = "e";
1874 ///
1875 /// assert_eq!(map2[&1], "a");
1876 /// assert_eq!(map2[&2], "b");
1877 /// assert_eq!(map2[&3], "c");
1878 /// assert_eq!(map2[&4], "e");
1879 /// assert_eq!(map2.len(), 4);
1880 /// ```
1881 #[cfg_attr(feature = "inline-more", inline)]
1882 pub unsafe fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
1883 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1884 let bucket = self
1885 .table
1886 .insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder));
1887 let (k_ref, v_ref) = unsafe { bucket.as_mut() };
1888 (k_ref, v_ref)
1889 }
1890
1891 /// Tries to insert a key-value pair into the map, and returns
1892 /// a mutable reference to the value in the entry.
1893 ///
1894 /// # Errors
1895 ///
1896 /// If the map already had this key present, nothing is updated, and
1897 /// an error containing the occupied entry and the value is returned.
1898 ///
1899 /// # Examples
1900 ///
1901 /// Basic usage:
1902 ///
1903 /// ```
1904 /// use hashbrown::HashMap;
1905 /// use hashbrown::hash_map::OccupiedError;
1906 ///
1907 /// let mut map = HashMap::new();
1908 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1909 ///
1910 /// match map.try_insert(37, "b") {
1911 /// Err(OccupiedError { entry, value }) => {
1912 /// assert_eq!(entry.key(), &37);
1913 /// assert_eq!(entry.get(), &"a");
1914 /// assert_eq!(value, "b");
1915 /// }
1916 /// _ => panic!()
1917 /// }
1918 /// ```
1919 #[cfg_attr(feature = "inline-more", inline)]
1920 pub fn try_insert(
1921 &mut self,
1922 key: K,
1923 value: V,
1924 ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> {
1925 match self.entry(key) {
1926 Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
1927 Entry::Vacant(entry) => Ok(entry.insert(value)),
1928 }
1929 }
1930
1931 /// Removes a key from the map, returning the value at the key if the key
1932 /// was previously in the map. Keeps the allocated memory for reuse.
1933 ///
1934 /// The key may be any borrowed form of the map's key type, but
1935 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1936 /// the key type.
1937 ///
1938 /// # Examples
1939 ///
1940 /// ```
1941 /// use hashbrown::HashMap;
1942 ///
1943 /// let mut map = HashMap::new();
1944 /// // The map is empty
1945 /// assert!(map.is_empty() && map.capacity() == 0);
1946 ///
1947 /// map.insert(1, "a");
1948 ///
1949 /// assert_eq!(map.remove(&1), Some("a"));
1950 /// assert_eq!(map.remove(&1), None);
1951 ///
1952 /// // Now map holds none elements
1953 /// assert!(map.is_empty());
1954 /// ```
1955 #[cfg_attr(feature = "inline-more", inline)]
1956 pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
1957 where
1958 Q: Hash + Equivalent<K> + ?Sized,
1959 {
1960 // Avoid `Option::map` because it bloats LLVM IR.
1961 match self.remove_entry(k) {
1962 Some((_, v)) => Some(v),
1963 None => None,
1964 }
1965 }
1966
1967 /// Removes a key from the map, returning the stored key and value if the
1968 /// key was previously in the map. Keeps the allocated memory for reuse.
1969 ///
1970 /// The key may be any borrowed form of the map's key type, but
1971 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1972 /// the key type.
1973 ///
1974 /// # Examples
1975 ///
1976 /// ```
1977 /// use hashbrown::HashMap;
1978 ///
1979 /// let mut map = HashMap::new();
1980 /// // The map is empty
1981 /// assert!(map.is_empty() && map.capacity() == 0);
1982 ///
1983 /// map.insert(1, "a");
1984 ///
1985 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1986 /// assert_eq!(map.remove(&1), None);
1987 ///
1988 /// // Now map hold none elements
1989 /// assert!(map.is_empty());
1990 /// ```
1991 #[cfg_attr(feature = "inline-more", inline)]
1992 pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
1993 where
1994 Q: Hash + Equivalent<K> + ?Sized,
1995 {
1996 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1997 self.table.remove_entry(hash, equivalent_key(k))
1998 }
1999
2000 /// Returns the total amount of memory allocated internally by the hash
2001 /// set, in bytes.
2002 ///
2003 /// The returned number is informational only. It is intended to be
2004 /// primarily used for memory profiling.
2005 #[inline]
2006 pub fn allocation_size(&self) -> usize {
2007 self.table.allocation_size()
2008 }
2009}
2010
2011impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
2012where
2013 K: Eq + Hash,
2014 V: PartialEq,
2015 S: BuildHasher,
2016 A: Allocator,
2017{
2018 fn eq(&self, other: &Self) -> bool {
2019 if self.len() != other.len() {
2020 return false;
2021 }
2022
2023 self.iter()
2024 .all(|(key, value)| other.get(key).is_some_and(|v| *value == *v))
2025 }
2026}
2027
2028impl<K, V, S, A> Eq for HashMap<K, V, S, A>
2029where
2030 K: Eq + Hash,
2031 V: Eq,
2032 S: BuildHasher,
2033 A: Allocator,
2034{
2035}
2036
2037impl<K, V, S, A> Debug for HashMap<K, V, S, A>
2038where
2039 K: Debug,
2040 V: Debug,
2041 A: Allocator,
2042{
2043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2044 f.debug_map().entries(self.iter()).finish()
2045 }
2046}
2047
2048impl<K, V, S, A> Default for HashMap<K, V, S, A>
2049where
2050 S: Default,
2051 A: Default + Allocator,
2052{
2053 /// Creates an empty `HashMap<K, V, S, A>`, with the `Default` value for the hasher and allocator.
2054 ///
2055 /// # Examples
2056 ///
2057 /// ```
2058 /// use hashbrown::HashMap;
2059 /// use std::hash::RandomState;
2060 ///
2061 /// // You can specify all types of HashMap, including hasher and allocator.
2062 /// // Created map is empty and don't allocate memory
2063 /// let map: HashMap<u32, String> = Default::default();
2064 /// assert_eq!(map.capacity(), 0);
2065 /// let map: HashMap<u32, String, RandomState> = HashMap::default();
2066 /// assert_eq!(map.capacity(), 0);
2067 /// ```
2068 #[cfg_attr(feature = "inline-more", inline)]
2069 fn default() -> Self {
2070 Self::with_hasher_in(Default::default(), Default::default())
2071 }
2072}
2073
2074impl<K, Q, V, S, A> Index<&Q> for HashMap<K, V, S, A>
2075where
2076 K: Eq + Hash,
2077 Q: Hash + Equivalent<K> + ?Sized,
2078 S: BuildHasher,
2079 A: Allocator,
2080{
2081 type Output = V;
2082
2083 /// Returns a reference to the value corresponding to the supplied key.
2084 ///
2085 /// # Panics
2086 ///
2087 /// Panics if the key is not present in the `HashMap`.
2088 ///
2089 /// # Examples
2090 ///
2091 /// ```
2092 /// use hashbrown::HashMap;
2093 ///
2094 /// let map: HashMap<_, _> = [("a", "One"), ("b", "Two")].into();
2095 ///
2096 /// assert_eq!(map[&"a"], "One");
2097 /// assert_eq!(map[&"b"], "Two");
2098 /// ```
2099 #[cfg_attr(feature = "inline-more", inline)]
2100 fn index(&self, key: &Q) -> &V {
2101 self.get(key).expect("no entry found for key")
2102 }
2103}
2104
2105// The default hasher is used to match the std implementation signature
2106#[cfg(feature = "default-hasher")]
2107impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
2108where
2109 K: Eq + Hash,
2110 A: Default + Allocator,
2111{
2112 /// # Examples
2113 ///
2114 /// ```
2115 /// use hashbrown::HashMap;
2116 ///
2117 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
2118 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
2119 /// assert_eq!(map1, map2);
2120 /// ```
2121 fn from(arr: [(K, V); N]) -> Self {
2122 arr.into_iter().collect()
2123 }
2124}
2125
2126/// An iterator over the entries of a `HashMap` in arbitrary order.
2127/// The iterator element type is `(&'a K, &'a V)`.
2128///
2129/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
2130/// documentation for more.
2131///
2132/// [`iter`]: HashMap::iter
2133///
2134/// # Examples
2135///
2136/// ```
2137/// use hashbrown::HashMap;
2138///
2139/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2140///
2141/// let mut iter = map.iter();
2142/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2143///
2144/// // The `Iter` iterator produces items in arbitrary order, so the
2145/// // items must be sorted to test them against a sorted array.
2146/// vec.sort_unstable();
2147/// assert_eq!(vec, [Some((&1, &"a")), Some((&2, &"b")), Some((&3, &"c"))]);
2148///
2149/// // It is fused iterator
2150/// assert_eq!(iter.next(), None);
2151/// assert_eq!(iter.next(), None);
2152/// ```
2153pub struct Iter<'a, K, V> {
2154 inner: RawIter<(K, V)>,
2155 marker: PhantomData<(&'a K, &'a V)>,
2156}
2157
2158// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2159impl<K, V> Clone for Iter<'_, K, V> {
2160 #[cfg_attr(feature = "inline-more", inline)]
2161 fn clone(&self) -> Self {
2162 Iter {
2163 inner: self.inner.clone(),
2164 marker: PhantomData,
2165 }
2166 }
2167}
2168
2169impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
2170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2171 f.debug_list().entries(self.clone()).finish()
2172 }
2173}
2174
2175/// A mutable iterator over the entries of a `HashMap` in arbitrary order.
2176/// The iterator element type is `(&'a K, &'a mut V)`.
2177///
2178/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
2179/// documentation for more.
2180///
2181/// [`iter_mut`]: HashMap::iter_mut
2182///
2183/// # Examples
2184///
2185/// ```
2186/// use hashbrown::HashMap;
2187///
2188/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2189///
2190/// let mut iter = map.iter_mut();
2191/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2192/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2193///
2194/// // It is fused iterator
2195/// assert_eq!(iter.next(), None);
2196/// assert_eq!(iter.next(), None);
2197///
2198/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2199/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2200/// ```
2201pub struct IterMut<'a, K, V> {
2202 inner: RawIter<(K, V)>,
2203 // To ensure invariance with respect to V
2204 marker: PhantomData<(&'a K, &'a mut V)>,
2205}
2206
2207// We override the default Send impl which has K: Sync instead of K: Send. Both
2208// are correct, but this one is more general since it allows keys which
2209// implement Send but not Sync.
2210unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {}
2211
2212impl<K, V> IterMut<'_, K, V> {
2213 /// Returns a iterator of references over the remaining items.
2214 #[cfg_attr(feature = "inline-more", inline)]
2215 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2216 Iter {
2217 inner: self.inner.clone(),
2218 marker: PhantomData,
2219 }
2220 }
2221}
2222
2223/// An owning iterator over the entries of a `HashMap` in arbitrary order.
2224/// The iterator element type is `(K, V)`.
2225///
2226/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
2227/// (provided by the [`IntoIterator`] trait). See its documentation for more.
2228/// The map cannot be used after calling that method.
2229///
2230/// [`into_iter`]: HashMap::into_iter
2231///
2232/// # Examples
2233///
2234/// ```
2235/// use hashbrown::HashMap;
2236///
2237/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2238///
2239/// let mut iter = map.into_iter();
2240/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2241///
2242/// // The `IntoIter` iterator produces items in arbitrary order, so the
2243/// // items must be sorted to test them against a sorted array.
2244/// vec.sort_unstable();
2245/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2246///
2247/// // It is fused iterator
2248/// assert_eq!(iter.next(), None);
2249/// assert_eq!(iter.next(), None);
2250/// ```
2251pub struct IntoIter<K, V, A: Allocator = Global> {
2252 inner: RawIntoIter<(K, V), A>,
2253}
2254
2255impl<K, V, A: Allocator> IntoIter<K, V, A> {
2256 /// Returns a iterator of references over the remaining items.
2257 #[cfg_attr(feature = "inline-more", inline)]
2258 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2259 Iter {
2260 inner: self.inner.iter(),
2261 marker: PhantomData,
2262 }
2263 }
2264}
2265
2266/// An owning iterator over the keys of a `HashMap` in arbitrary order.
2267/// The iterator element type is `K`.
2268///
2269/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
2270/// See its documentation for more.
2271/// The map cannot be used after calling that method.
2272///
2273/// [`into_keys`]: HashMap::into_keys
2274///
2275/// # Examples
2276///
2277/// ```
2278/// use hashbrown::HashMap;
2279///
2280/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2281///
2282/// let mut keys = map.into_keys();
2283/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2284///
2285/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
2286/// // keys must be sorted to test them against a sorted array.
2287/// vec.sort_unstable();
2288/// assert_eq!(vec, [Some(1), Some(2), Some(3)]);
2289///
2290/// // It is fused iterator
2291/// assert_eq!(keys.next(), None);
2292/// assert_eq!(keys.next(), None);
2293/// ```
2294pub struct IntoKeys<K, V, A: Allocator = Global> {
2295 inner: IntoIter<K, V, A>,
2296}
2297
2298impl<K, V, A: Allocator> Default for IntoKeys<K, V, A> {
2299 #[cfg_attr(feature = "inline-more", inline)]
2300 fn default() -> Self {
2301 Self {
2302 inner: Default::default(),
2303 }
2304 }
2305}
2306impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
2307 type Item = K;
2308
2309 #[inline]
2310 fn next(&mut self) -> Option<K> {
2311 self.inner.next().map(|(k, _)| k)
2312 }
2313 #[inline]
2314 fn size_hint(&self) -> (usize, Option<usize>) {
2315 self.inner.size_hint()
2316 }
2317 #[inline]
2318 fn fold<B, F>(self, init: B, mut f: F) -> B
2319 where
2320 Self: Sized,
2321 F: FnMut(B, Self::Item) -> B,
2322 {
2323 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2324 }
2325}
2326
2327impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
2328 #[inline]
2329 fn len(&self) -> usize {
2330 self.inner.len()
2331 }
2332}
2333
2334impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
2335
2336impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
2337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2338 f.debug_list()
2339 .entries(self.inner.iter().map(|(k, _)| k))
2340 .finish()
2341 }
2342}
2343
2344/// An owning iterator over the values of a `HashMap` in arbitrary order.
2345/// The iterator element type is `V`.
2346///
2347/// This `struct` is created by the [`into_values`] method on [`HashMap`].
2348/// See its documentation for more. The map cannot be used after calling that method.
2349///
2350/// [`into_values`]: HashMap::into_values
2351///
2352/// # Examples
2353///
2354/// ```
2355/// use hashbrown::HashMap;
2356///
2357/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2358///
2359/// let mut values = map.into_values();
2360/// let mut vec = vec![values.next(), values.next(), values.next()];
2361///
2362/// // The `IntoValues` iterator produces values in arbitrary order, so
2363/// // the values must be sorted to test them against a sorted array.
2364/// vec.sort_unstable();
2365/// assert_eq!(vec, [Some("a"), Some("b"), Some("c")]);
2366///
2367/// // It is fused iterator
2368/// assert_eq!(values.next(), None);
2369/// assert_eq!(values.next(), None);
2370/// ```
2371pub struct IntoValues<K, V, A: Allocator = Global> {
2372 inner: IntoIter<K, V, A>,
2373}
2374
2375impl<K, V, A: Allocator> Default for IntoValues<K, V, A> {
2376 #[cfg_attr(feature = "inline-more", inline)]
2377 fn default() -> Self {
2378 Self {
2379 inner: Default::default(),
2380 }
2381 }
2382}
2383impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
2384 type Item = V;
2385
2386 #[inline]
2387 fn next(&mut self) -> Option<V> {
2388 self.inner.next().map(|(_, v)| v)
2389 }
2390 #[inline]
2391 fn size_hint(&self) -> (usize, Option<usize>) {
2392 self.inner.size_hint()
2393 }
2394 #[inline]
2395 fn fold<B, F>(self, init: B, mut f: F) -> B
2396 where
2397 Self: Sized,
2398 F: FnMut(B, Self::Item) -> B,
2399 {
2400 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2401 }
2402}
2403
2404impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2405 #[inline]
2406 fn len(&self) -> usize {
2407 self.inner.len()
2408 }
2409}
2410
2411impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2412
2413impl<K, V: Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
2414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2415 f.debug_list()
2416 .entries(self.inner.iter().map(|(_, v)| v))
2417 .finish()
2418 }
2419}
2420
2421/// An iterator over the keys of a `HashMap` in arbitrary order.
2422/// The iterator element type is `&'a K`.
2423///
2424/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
2425/// documentation for more.
2426///
2427/// [`keys`]: HashMap::keys
2428///
2429/// # Examples
2430///
2431/// ```
2432/// use hashbrown::HashMap;
2433///
2434/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2435///
2436/// let mut keys = map.keys();
2437/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2438///
2439/// // The `Keys` iterator produces keys in arbitrary order, so the
2440/// // keys must be sorted to test them against a sorted array.
2441/// vec.sort_unstable();
2442/// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]);
2443///
2444/// // It is fused iterator
2445/// assert_eq!(keys.next(), None);
2446/// assert_eq!(keys.next(), None);
2447/// ```
2448pub struct Keys<'a, K, V> {
2449 inner: Iter<'a, K, V>,
2450}
2451
2452// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2453impl<K, V> Clone for Keys<'_, K, V> {
2454 #[cfg_attr(feature = "inline-more", inline)]
2455 fn clone(&self) -> Self {
2456 Keys {
2457 inner: self.inner.clone(),
2458 }
2459 }
2460}
2461
2462impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
2463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2464 f.debug_list().entries(self.clone()).finish()
2465 }
2466}
2467
2468/// An iterator over the values of a `HashMap` in arbitrary order.
2469/// The iterator element type is `&'a V`.
2470///
2471/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
2472/// documentation for more.
2473///
2474/// [`values`]: HashMap::values
2475///
2476/// # Examples
2477///
2478/// ```
2479/// use hashbrown::HashMap;
2480///
2481/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2482///
2483/// let mut values = map.values();
2484/// let mut vec = vec![values.next(), values.next(), values.next()];
2485///
2486/// // The `Values` iterator produces values in arbitrary order, so the
2487/// // values must be sorted to test them against a sorted array.
2488/// vec.sort_unstable();
2489/// assert_eq!(vec, [Some(&"a"), Some(&"b"), Some(&"c")]);
2490///
2491/// // It is fused iterator
2492/// assert_eq!(values.next(), None);
2493/// assert_eq!(values.next(), None);
2494/// ```
2495pub struct Values<'a, K, V> {
2496 inner: Iter<'a, K, V>,
2497}
2498
2499// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2500impl<K, V> Clone for Values<'_, K, V> {
2501 #[cfg_attr(feature = "inline-more", inline)]
2502 fn clone(&self) -> Self {
2503 Values {
2504 inner: self.inner.clone(),
2505 }
2506 }
2507}
2508
2509impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
2510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2511 f.debug_list().entries(self.clone()).finish()
2512 }
2513}
2514
2515/// A draining iterator over the entries of a `HashMap` in arbitrary
2516/// order. The iterator element type is `(K, V)`.
2517///
2518/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
2519/// documentation for more.
2520///
2521/// [`drain`]: HashMap::drain
2522///
2523/// # Examples
2524///
2525/// ```
2526/// use hashbrown::HashMap;
2527///
2528/// let mut map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2529///
2530/// let mut drain_iter = map.drain();
2531/// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()];
2532///
2533/// // The `Drain` iterator produces items in arbitrary order, so the
2534/// // items must be sorted to test them against a sorted array.
2535/// vec.sort_unstable();
2536/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2537///
2538/// // It is fused iterator
2539/// assert_eq!(drain_iter.next(), None);
2540/// assert_eq!(drain_iter.next(), None);
2541/// ```
2542pub struct Drain<'a, K, V, A: Allocator = Global> {
2543 inner: RawDrain<'a, (K, V), A>,
2544}
2545
2546impl<K, V, A: Allocator> Drain<'_, K, V, A> {
2547 /// Returns a iterator of references over the remaining items.
2548 #[cfg_attr(feature = "inline-more", inline)]
2549 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2550 Iter {
2551 inner: self.inner.iter(),
2552 marker: PhantomData,
2553 }
2554 }
2555}
2556
2557/// A draining iterator over entries of a `HashMap` which don't satisfy the predicate
2558/// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`.
2559///
2560/// This `struct` is created by the [`extract_if`] method on [`HashMap`]. See its
2561/// documentation for more.
2562///
2563/// [`extract_if`]: HashMap::extract_if
2564///
2565/// # Examples
2566///
2567/// ```
2568/// use hashbrown::HashMap;
2569///
2570/// let mut map: HashMap<i32, &str> = [(1, "a"), (2, "b"), (3, "c")].into();
2571///
2572/// let mut extract_if = map.extract_if(|k, _v| k % 2 != 0);
2573/// let mut vec = vec![extract_if.next(), extract_if.next()];
2574///
2575/// // The `ExtractIf` iterator produces items in arbitrary order, so the
2576/// // items must be sorted to test them against a sorted array.
2577/// vec.sort_unstable();
2578/// assert_eq!(vec, [Some((1, "a")),Some((3, "c"))]);
2579///
2580/// // It is fused iterator
2581/// assert_eq!(extract_if.next(), None);
2582/// assert_eq!(extract_if.next(), None);
2583/// drop(extract_if);
2584///
2585/// assert_eq!(map.len(), 1);
2586/// ```
2587#[must_use = "Iterators are lazy unless consumed"]
2588pub struct ExtractIf<'a, K, V, F, A: Allocator = Global> {
2589 f: F,
2590 inner: RawExtractIf<'a, (K, V), A>,
2591}
2592
2593impl<K, V, F, A> Iterator for ExtractIf<'_, K, V, F, A>
2594where
2595 F: FnMut(&K, &mut V) -> bool,
2596 A: Allocator,
2597{
2598 type Item = (K, V);
2599
2600 #[cfg_attr(feature = "inline-more", inline)]
2601 fn next(&mut self) -> Option<Self::Item> {
2602 self.inner.next(|&mut (ref k, ref mut v)| (self.f)(k, v))
2603 }
2604
2605 #[inline]
2606 fn size_hint(&self) -> (usize, Option<usize>) {
2607 (0, self.inner.iter.size_hint().1)
2608 }
2609}
2610
2611impl<K, V, F, A> FusedIterator for ExtractIf<'_, K, V, F, A>
2612where
2613 F: FnMut(&K, &mut V) -> bool,
2614 A: Allocator,
2615{
2616}
2617
2618/// A mutable iterator over the values of a `HashMap` in arbitrary order.
2619/// The iterator element type is `&'a mut V`.
2620///
2621/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
2622/// documentation for more.
2623///
2624/// [`values_mut`]: HashMap::values_mut
2625///
2626/// # Examples
2627///
2628/// ```
2629/// use hashbrown::HashMap;
2630///
2631/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2632///
2633/// let mut values = map.values_mut();
2634/// values.next().map(|v| v.push_str(" Mississippi"));
2635/// values.next().map(|v| v.push_str(" Mississippi"));
2636///
2637/// // It is fused iterator
2638/// assert_eq!(values.next(), None);
2639/// assert_eq!(values.next(), None);
2640///
2641/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2642/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2643/// ```
2644pub struct ValuesMut<'a, K, V> {
2645 inner: IterMut<'a, K, V>,
2646}
2647
2648/// A view into a single entry in a map, which may either be vacant or occupied.
2649///
2650/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2651///
2652/// [`entry`]: HashMap::entry
2653///
2654/// # Examples
2655///
2656/// ```
2657/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2658///
2659/// let mut map = HashMap::new();
2660/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2661/// assert_eq!(map.len(), 3);
2662///
2663/// // Existing key (insert)
2664/// let entry: Entry<_, _, _> = map.entry("a");
2665/// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1);
2666/// assert_eq!(map.len(), 3);
2667/// // Nonexistent key (insert)
2668/// map.entry("d").insert(4);
2669///
2670/// // Existing key (or_insert)
2671/// let v = map.entry("b").or_insert(2);
2672/// assert_eq!(std::mem::replace(v, 2), 20);
2673/// // Nonexistent key (or_insert)
2674/// map.entry("e").or_insert(5);
2675///
2676/// // Existing key (or_insert_with)
2677/// let v = map.entry("c").or_insert_with(|| 3);
2678/// assert_eq!(std::mem::replace(v, 3), 30);
2679/// // Nonexistent key (or_insert_with)
2680/// map.entry("f").or_insert_with(|| 6);
2681///
2682/// println!("Our HashMap: {:?}", map);
2683///
2684/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
2685/// // The `Iter` iterator produces items in arbitrary order, so the
2686/// // items must be sorted to test them against a sorted array.
2687/// vec.sort_unstable();
2688/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]);
2689/// ```
2690pub enum Entry<'a, K, V, S, A = Global>
2691where
2692 A: Allocator,
2693{
2694 /// An occupied entry.
2695 ///
2696 /// # Examples
2697 ///
2698 /// ```
2699 /// use hashbrown::hash_map::{Entry, HashMap};
2700 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into();
2701 ///
2702 /// match map.entry("a") {
2703 /// Entry::Vacant(_) => unreachable!(),
2704 /// Entry::Occupied(_) => { }
2705 /// }
2706 /// ```
2707 Occupied(OccupiedEntry<'a, K, V, S, A>),
2708
2709 /// A vacant entry.
2710 ///
2711 /// # Examples
2712 ///
2713 /// ```
2714 /// use hashbrown::hash_map::{Entry, HashMap};
2715 /// let mut map: HashMap<&str, i32> = HashMap::new();
2716 ///
2717 /// match map.entry("a") {
2718 /// Entry::Occupied(_) => unreachable!(),
2719 /// Entry::Vacant(_) => { }
2720 /// }
2721 /// ```
2722 Vacant(VacantEntry<'a, K, V, S, A>),
2723}
2724
2725impl<K: Debug, V: Debug, S, A: Allocator> Debug for Entry<'_, K, V, S, A> {
2726 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2727 match *self {
2728 Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2729 Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2730 }
2731 }
2732}
2733
2734/// A view into an occupied entry in a [`HashMap`].
2735/// It is part of the [`Entry`] and [`EntryRef`] enums.
2736///
2737/// # Examples
2738///
2739/// ```
2740/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2741///
2742/// let mut map = HashMap::new();
2743/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2744///
2745/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").insert(100);
2746/// assert_eq!(map.len(), 3);
2747///
2748/// // Existing key (insert and update)
2749/// match map.entry("a") {
2750/// Entry::Vacant(_) => unreachable!(),
2751/// Entry::Occupied(mut view) => {
2752/// assert_eq!(view.get(), &100);
2753/// let v = view.get_mut();
2754/// *v *= 10;
2755/// assert_eq!(view.insert(1111), 1000);
2756/// }
2757/// }
2758///
2759/// assert_eq!(map[&"a"], 1111);
2760/// assert_eq!(map.len(), 3);
2761///
2762/// // Existing key (take)
2763/// match map.entry("c") {
2764/// Entry::Vacant(_) => unreachable!(),
2765/// Entry::Occupied(view) => {
2766/// assert_eq!(view.remove_entry(), ("c", 30));
2767/// }
2768/// }
2769/// assert_eq!(map.get(&"c"), None);
2770/// assert_eq!(map.len(), 2);
2771/// ```
2772pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2773 hash: u64,
2774 elem: Bucket<(K, V)>,
2775 table: &'a mut HashMap<K, V, S, A>,
2776}
2777
2778unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
2779where
2780 K: Send,
2781 V: Send,
2782 S: Send,
2783 A: Send + Allocator,
2784{
2785}
2786unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
2787where
2788 K: Sync,
2789 V: Sync,
2790 S: Sync,
2791 A: Sync + Allocator,
2792{
2793}
2794
2795impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedEntry<'_, K, V, S, A> {
2796 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2797 f.debug_struct("OccupiedEntry")
2798 .field("key", self.key())
2799 .field("value", self.get())
2800 .finish()
2801 }
2802}
2803
2804/// A view into a vacant entry in a `HashMap`.
2805/// It is part of the [`Entry`] enum.
2806///
2807/// # Examples
2808///
2809/// ```
2810/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry};
2811///
2812/// let mut map = HashMap::<&str, i32>::new();
2813///
2814/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
2815/// Entry::Vacant(view) => view,
2816/// Entry::Occupied(_) => unreachable!(),
2817/// };
2818/// entry_v.insert(10);
2819/// assert!(map[&"a"] == 10 && map.len() == 1);
2820///
2821/// // Nonexistent key (insert and update)
2822/// match map.entry("b") {
2823/// Entry::Occupied(_) => unreachable!(),
2824/// Entry::Vacant(view) => {
2825/// let value = view.insert(2);
2826/// assert_eq!(*value, 2);
2827/// *value = 20;
2828/// }
2829/// }
2830/// assert!(map[&"b"] == 20 && map.len() == 2);
2831/// ```
2832pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2833 hash: u64,
2834 key: K,
2835 table: &'a mut HashMap<K, V, S, A>,
2836}
2837
2838impl<K: Debug, V, S, A: Allocator> Debug for VacantEntry<'_, K, V, S, A> {
2839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2840 f.debug_tuple("VacantEntry").field(self.key()).finish()
2841 }
2842}
2843
2844/// A view into a single entry in a map, which may either be vacant or occupied,
2845/// with any borrowed form of the map's key type.
2846///
2847///
2848/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
2849///
2850/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
2851/// for the key type. It also require that key may be constructed from the borrowed
2852/// form through the [`ToOwned`] trait.
2853///
2854/// [`entry_ref`]: HashMap::entry_ref
2855///
2856/// # Examples
2857///
2858/// ```
2859/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntry};
2860///
2861/// let mut map = HashMap::new();
2862/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
2863/// assert_eq!(map.len(), 3);
2864///
2865/// // Existing key (insert)
2866/// let key = String::from("a");
2867/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
2868/// let _raw_o: OccupiedEntry<_, _, _, _> = entry.insert(1);
2869/// assert_eq!(map.len(), 3);
2870/// // Nonexistent key (insert)
2871/// map.entry_ref("d").insert(4);
2872///
2873/// // Existing key (or_insert)
2874/// let v = map.entry_ref("b").or_insert(2);
2875/// assert_eq!(std::mem::replace(v, 2), 20);
2876/// // Nonexistent key (or_insert)
2877/// map.entry_ref("e").or_insert(5);
2878///
2879/// // Existing key (or_insert_with)
2880/// let v = map.entry_ref("c").or_insert_with(|| 3);
2881/// assert_eq!(std::mem::replace(v, 3), 30);
2882/// // Nonexistent key (or_insert_with)
2883/// map.entry_ref("f").or_insert_with(|| 6);
2884///
2885/// println!("Our HashMap: {:?}", map);
2886///
2887/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
2888/// assert_eq!(map[key], value)
2889/// }
2890/// assert_eq!(map.len(), 6);
2891/// ```
2892pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
2893where
2894 A: Allocator,
2895{
2896 /// An occupied entry.
2897 ///
2898 /// # Examples
2899 ///
2900 /// ```
2901 /// use hashbrown::hash_map::{EntryRef, HashMap};
2902 /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].into();
2903 ///
2904 /// match map.entry_ref("a") {
2905 /// EntryRef::Vacant(_) => unreachable!(),
2906 /// EntryRef::Occupied(_) => { }
2907 /// }
2908 /// ```
2909 Occupied(OccupiedEntry<'a, K, V, S, A>),
2910
2911 /// A vacant entry.
2912 ///
2913 /// # Examples
2914 ///
2915 /// ```
2916 /// use hashbrown::hash_map::{EntryRef, HashMap};
2917 /// let mut map: HashMap<String, i32> = HashMap::new();
2918 ///
2919 /// match map.entry_ref("a") {
2920 /// EntryRef::Occupied(_) => unreachable!(),
2921 /// EntryRef::Vacant(_) => { }
2922 /// }
2923 /// ```
2924 Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
2925}
2926
2927impl<K, Q, V, S, A> Debug for EntryRef<'_, '_, K, Q, V, S, A>
2928where
2929 K: Debug + Borrow<Q>,
2930 Q: Debug + ?Sized,
2931 V: Debug,
2932 A: Allocator,
2933{
2934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2935 match *self {
2936 EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(),
2937 EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(),
2938 }
2939 }
2940}
2941
2942/// A view into a vacant entry in a `HashMap`.
2943/// It is part of the [`EntryRef`] enum.
2944///
2945/// # Examples
2946///
2947/// ```
2948/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef};
2949///
2950/// let mut map = HashMap::<String, i32>::new();
2951///
2952/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
2953/// EntryRef::Vacant(view) => view,
2954/// EntryRef::Occupied(_) => unreachable!(),
2955/// };
2956/// entry_v.insert(10);
2957/// assert!(map["a"] == 10 && map.len() == 1);
2958///
2959/// // Nonexistent key (insert and update)
2960/// match map.entry_ref("b") {
2961/// EntryRef::Occupied(_) => unreachable!(),
2962/// EntryRef::Vacant(view) => {
2963/// let value = view.insert(2);
2964/// assert_eq!(*value, 2);
2965/// *value = 20;
2966/// }
2967/// }
2968/// assert!(map["b"] == 20 && map.len() == 2);
2969/// ```
2970pub struct VacantEntryRef<'map, 'key, K, Q: ?Sized, V, S, A: Allocator = Global> {
2971 hash: u64,
2972 key: &'key Q,
2973 table: &'map mut HashMap<K, V, S, A>,
2974}
2975
2976impl<K, Q, V, S, A> Debug for VacantEntryRef<'_, '_, K, Q, V, S, A>
2977where
2978 K: Borrow<Q>,
2979 Q: Debug + ?Sized,
2980 A: Allocator,
2981{
2982 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2983 f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
2984 }
2985}
2986
2987/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
2988///
2989/// Contains the occupied entry, and the value that was not inserted.
2990///
2991/// # Examples
2992///
2993/// ```
2994/// use hashbrown::hash_map::{HashMap, OccupiedError};
2995///
2996/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into();
2997///
2998/// // try_insert method returns mutable reference to the value if keys are vacant,
2999/// // but if the map did have key present, nothing is updated, and the provided
3000/// // value is returned inside `Err(_)` variant
3001/// match map.try_insert("a", 100) {
3002/// Err(OccupiedError { mut entry, value }) => {
3003/// assert_eq!(entry.key(), &"a");
3004/// assert_eq!(value, 100);
3005/// assert_eq!(entry.insert(100), 10)
3006/// }
3007/// _ => unreachable!(),
3008/// }
3009/// assert_eq!(map[&"a"], 100);
3010/// ```
3011pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> {
3012 /// The entry in the map that was already occupied.
3013 pub entry: OccupiedEntry<'a, K, V, S, A>,
3014 /// The value which was not inserted, because the entry was already occupied.
3015 pub value: V,
3016}
3017
3018impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedError<'_, K, V, S, A> {
3019 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3020 f.debug_struct("OccupiedError")
3021 .field("key", self.entry.key())
3022 .field("old_value", self.entry.get())
3023 .field("new_value", &self.value)
3024 .finish()
3025 }
3026}
3027
3028impl<K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'_, K, V, S, A> {
3029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3030 write!(
3031 f,
3032 "failed to insert {:?}, key {:?} already exists with value {:?}",
3033 self.value,
3034 self.entry.key(),
3035 self.entry.get(),
3036 )
3037 }
3038}
3039
3040impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
3041 type Item = (&'a K, &'a V);
3042 type IntoIter = Iter<'a, K, V>;
3043
3044 /// Creates an iterator over the entries of a `HashMap` in arbitrary order.
3045 /// The iterator element type is `(&'a K, &'a V)`.
3046 ///
3047 /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
3048 ///
3049 /// [`iter`]: HashMap::iter
3050 ///
3051 /// # Examples
3052 ///
3053 /// ```
3054 /// use hashbrown::HashMap;
3055 /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
3056 /// let mut map_two = HashMap::new();
3057 ///
3058 /// for (key, value) in &map_one {
3059 /// println!("Key: {}, Value: {}", key, value);
3060 /// map_two.insert(*key, *value);
3061 /// }
3062 ///
3063 /// assert_eq!(map_one, map_two);
3064 /// ```
3065 #[cfg_attr(feature = "inline-more", inline)]
3066 fn into_iter(self) -> Iter<'a, K, V> {
3067 self.iter()
3068 }
3069}
3070
3071impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
3072 type Item = (&'a K, &'a mut V);
3073 type IntoIter = IterMut<'a, K, V>;
3074
3075 /// Creates an iterator over the entries of a `HashMap` in arbitrary order
3076 /// with mutable references to the values. The iterator element type is
3077 /// `(&'a K, &'a mut V)`.
3078 ///
3079 /// Return the same `IterMut` struct as by the [`iter_mut`] method on
3080 /// [`HashMap`].
3081 ///
3082 /// [`iter_mut`]: HashMap::iter_mut
3083 ///
3084 /// # Examples
3085 ///
3086 /// ```
3087 /// use hashbrown::HashMap;
3088 /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3089 ///
3090 /// for (key, value) in &mut map {
3091 /// println!("Key: {}, Value: {}", key, value);
3092 /// *value *= 2;
3093 /// }
3094 ///
3095 /// let mut vec = map.iter().collect::<Vec<_>>();
3096 /// // The `Iter` iterator produces items in arbitrary order, so the
3097 /// // items must be sorted to test them against a sorted array.
3098 /// vec.sort_unstable();
3099 /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
3100 /// ```
3101 #[cfg_attr(feature = "inline-more", inline)]
3102 fn into_iter(self) -> IterMut<'a, K, V> {
3103 self.iter_mut()
3104 }
3105}
3106
3107impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
3108 type Item = (K, V);
3109 type IntoIter = IntoIter<K, V, A>;
3110
3111 /// Creates a consuming iterator, that is, one that moves each key-value
3112 /// pair out of the map in arbitrary order. The map cannot be used after
3113 /// calling this.
3114 ///
3115 /// # Examples
3116 ///
3117 /// ```
3118 /// use hashbrown::HashMap;
3119 ///
3120 /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3121 ///
3122 /// // Not possible with .iter()
3123 /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
3124 /// // The `IntoIter` iterator produces items in arbitrary order, so
3125 /// // the items must be sorted to test them against a sorted array.
3126 /// vec.sort_unstable();
3127 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
3128 /// ```
3129 #[cfg_attr(feature = "inline-more", inline)]
3130 fn into_iter(self) -> IntoIter<K, V, A> {
3131 IntoIter {
3132 inner: self.table.into_iter(),
3133 }
3134 }
3135}
3136
3137impl<K, V> Default for Iter<'_, K, V> {
3138 #[cfg_attr(feature = "inline-more", inline)]
3139 fn default() -> Self {
3140 Self {
3141 inner: Default::default(),
3142 marker: PhantomData,
3143 }
3144 }
3145}
3146impl<'a, K, V> Iterator for Iter<'a, K, V> {
3147 type Item = (&'a K, &'a V);
3148
3149 #[cfg_attr(feature = "inline-more", inline)]
3150 fn next(&mut self) -> Option<(&'a K, &'a V)> {
3151 // Avoid `Option::map` because it bloats LLVM IR.
3152 match self.inner.next() {
3153 Some(x) => unsafe {
3154 let r = x.as_ref();
3155 Some((&r.0, &r.1))
3156 },
3157 None => None,
3158 }
3159 }
3160 #[cfg_attr(feature = "inline-more", inline)]
3161 fn size_hint(&self) -> (usize, Option<usize>) {
3162 self.inner.size_hint()
3163 }
3164 #[cfg_attr(feature = "inline-more", inline)]
3165 fn fold<B, F>(self, init: B, mut f: F) -> B
3166 where
3167 Self: Sized,
3168 F: FnMut(B, Self::Item) -> B,
3169 {
3170 self.inner.fold(init, |acc, x| unsafe {
3171 let (k, v) = x.as_ref();
3172 f(acc, (k, v))
3173 })
3174 }
3175}
3176impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
3177 #[cfg_attr(feature = "inline-more", inline)]
3178 fn len(&self) -> usize {
3179 self.inner.len()
3180 }
3181}
3182
3183impl<K, V> FusedIterator for Iter<'_, K, V> {}
3184
3185impl<K, V> Default for IterMut<'_, K, V> {
3186 #[cfg_attr(feature = "inline-more", inline)]
3187 fn default() -> Self {
3188 Self {
3189 inner: Default::default(),
3190 marker: PhantomData,
3191 }
3192 }
3193}
3194impl<'a, K, V> Iterator for IterMut<'a, K, V> {
3195 type Item = (&'a K, &'a mut V);
3196
3197 #[cfg_attr(feature = "inline-more", inline)]
3198 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
3199 // Avoid `Option::map` because it bloats LLVM IR.
3200 match self.inner.next() {
3201 Some(x) => unsafe {
3202 let r = x.as_mut();
3203 Some((&r.0, &mut r.1))
3204 },
3205 None => None,
3206 }
3207 }
3208 #[cfg_attr(feature = "inline-more", inline)]
3209 fn size_hint(&self) -> (usize, Option<usize>) {
3210 self.inner.size_hint()
3211 }
3212 #[cfg_attr(feature = "inline-more", inline)]
3213 fn fold<B, F>(self, init: B, mut f: F) -> B
3214 where
3215 Self: Sized,
3216 F: FnMut(B, Self::Item) -> B,
3217 {
3218 self.inner.fold(init, |acc, x| unsafe {
3219 let (k, v) = x.as_mut();
3220 f(acc, (k, v))
3221 })
3222 }
3223}
3224impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
3225 #[cfg_attr(feature = "inline-more", inline)]
3226 fn len(&self) -> usize {
3227 self.inner.len()
3228 }
3229}
3230impl<K, V> FusedIterator for IterMut<'_, K, V> {}
3231
3232impl<K, V> fmt::Debug for IterMut<'_, K, V>
3233where
3234 K: fmt::Debug,
3235 V: fmt::Debug,
3236{
3237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3238 f.debug_list().entries(self.iter()).finish()
3239 }
3240}
3241
3242impl<K, V, A: Allocator> Default for IntoIter<K, V, A> {
3243 #[cfg_attr(feature = "inline-more", inline)]
3244 fn default() -> Self {
3245 Self {
3246 inner: Default::default(),
3247 }
3248 }
3249}
3250impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
3251 type Item = (K, V);
3252
3253 #[cfg_attr(feature = "inline-more", inline)]
3254 fn next(&mut self) -> Option<(K, V)> {
3255 self.inner.next()
3256 }
3257 #[cfg_attr(feature = "inline-more", inline)]
3258 fn size_hint(&self) -> (usize, Option<usize>) {
3259 self.inner.size_hint()
3260 }
3261 #[cfg_attr(feature = "inline-more", inline)]
3262 fn fold<B, F>(self, init: B, f: F) -> B
3263 where
3264 Self: Sized,
3265 F: FnMut(B, Self::Item) -> B,
3266 {
3267 self.inner.fold(init, f)
3268 }
3269}
3270impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
3271 #[cfg_attr(feature = "inline-more", inline)]
3272 fn len(&self) -> usize {
3273 self.inner.len()
3274 }
3275}
3276impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
3277
3278impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
3279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3280 f.debug_list().entries(self.iter()).finish()
3281 }
3282}
3283
3284impl<K, V> Default for Keys<'_, K, V> {
3285 #[cfg_attr(feature = "inline-more", inline)]
3286 fn default() -> Self {
3287 Self {
3288 inner: Default::default(),
3289 }
3290 }
3291}
3292impl<'a, K, V> Iterator for Keys<'a, K, V> {
3293 type Item = &'a K;
3294
3295 #[cfg_attr(feature = "inline-more", inline)]
3296 fn next(&mut self) -> Option<&'a K> {
3297 // Avoid `Option::map` because it bloats LLVM IR.
3298 match self.inner.next() {
3299 Some((k, _)) => Some(k),
3300 None => None,
3301 }
3302 }
3303 #[cfg_attr(feature = "inline-more", inline)]
3304 fn size_hint(&self) -> (usize, Option<usize>) {
3305 self.inner.size_hint()
3306 }
3307 #[cfg_attr(feature = "inline-more", inline)]
3308 fn fold<B, F>(self, init: B, mut f: F) -> B
3309 where
3310 Self: Sized,
3311 F: FnMut(B, Self::Item) -> B,
3312 {
3313 self.inner.fold(init, |acc, (k, _)| f(acc, k))
3314 }
3315}
3316impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
3317 #[cfg_attr(feature = "inline-more", inline)]
3318 fn len(&self) -> usize {
3319 self.inner.len()
3320 }
3321}
3322impl<K, V> FusedIterator for Keys<'_, K, V> {}
3323
3324impl<K, V> Default for Values<'_, K, V> {
3325 #[cfg_attr(feature = "inline-more", inline)]
3326 fn default() -> Self {
3327 Self {
3328 inner: Default::default(),
3329 }
3330 }
3331}
3332impl<'a, K, V> Iterator for Values<'a, K, V> {
3333 type Item = &'a V;
3334
3335 #[cfg_attr(feature = "inline-more", inline)]
3336 fn next(&mut self) -> Option<&'a V> {
3337 // Avoid `Option::map` because it bloats LLVM IR.
3338 match self.inner.next() {
3339 Some((_, v)) => Some(v),
3340 None => None,
3341 }
3342 }
3343 #[cfg_attr(feature = "inline-more", inline)]
3344 fn size_hint(&self) -> (usize, Option<usize>) {
3345 self.inner.size_hint()
3346 }
3347 #[cfg_attr(feature = "inline-more", inline)]
3348 fn fold<B, F>(self, init: B, mut f: F) -> B
3349 where
3350 Self: Sized,
3351 F: FnMut(B, Self::Item) -> B,
3352 {
3353 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3354 }
3355}
3356impl<K, V> ExactSizeIterator for Values<'_, K, V> {
3357 #[cfg_attr(feature = "inline-more", inline)]
3358 fn len(&self) -> usize {
3359 self.inner.len()
3360 }
3361}
3362impl<K, V> FusedIterator for Values<'_, K, V> {}
3363
3364impl<K, V> Default for ValuesMut<'_, K, V> {
3365 #[cfg_attr(feature = "inline-more", inline)]
3366 fn default() -> Self {
3367 Self {
3368 inner: Default::default(),
3369 }
3370 }
3371}
3372impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
3373 type Item = &'a mut V;
3374
3375 #[cfg_attr(feature = "inline-more", inline)]
3376 fn next(&mut self) -> Option<&'a mut V> {
3377 // Avoid `Option::map` because it bloats LLVM IR.
3378 match self.inner.next() {
3379 Some((_, v)) => Some(v),
3380 None => None,
3381 }
3382 }
3383 #[cfg_attr(feature = "inline-more", inline)]
3384 fn size_hint(&self) -> (usize, Option<usize>) {
3385 self.inner.size_hint()
3386 }
3387 #[cfg_attr(feature = "inline-more", inline)]
3388 fn fold<B, F>(self, init: B, mut f: F) -> B
3389 where
3390 Self: Sized,
3391 F: FnMut(B, Self::Item) -> B,
3392 {
3393 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3394 }
3395}
3396impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
3397 #[cfg_attr(feature = "inline-more", inline)]
3398 fn len(&self) -> usize {
3399 self.inner.len()
3400 }
3401}
3402impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
3403
3404impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
3405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3406 f.debug_list()
3407 .entries(self.inner.iter().map(|(_, val)| val))
3408 .finish()
3409 }
3410}
3411
3412impl<K, V, A: Allocator> Iterator for Drain<'_, K, V, A> {
3413 type Item = (K, V);
3414
3415 #[cfg_attr(feature = "inline-more", inline)]
3416 fn next(&mut self) -> Option<(K, V)> {
3417 self.inner.next()
3418 }
3419 #[cfg_attr(feature = "inline-more", inline)]
3420 fn size_hint(&self) -> (usize, Option<usize>) {
3421 self.inner.size_hint()
3422 }
3423 #[cfg_attr(feature = "inline-more", inline)]
3424 fn fold<B, F>(self, init: B, f: F) -> B
3425 where
3426 Self: Sized,
3427 F: FnMut(B, Self::Item) -> B,
3428 {
3429 self.inner.fold(init, f)
3430 }
3431}
3432impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
3433 #[cfg_attr(feature = "inline-more", inline)]
3434 fn len(&self) -> usize {
3435 self.inner.len()
3436 }
3437}
3438impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
3439
3440impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
3441where
3442 K: fmt::Debug,
3443 V: fmt::Debug,
3444 A: Allocator,
3445{
3446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3447 f.debug_list().entries(self.iter()).finish()
3448 }
3449}
3450
3451impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> {
3452 /// Sets the value of the entry, and returns an `OccupiedEntry`.
3453 ///
3454 /// # Examples
3455 ///
3456 /// ```
3457 /// use hashbrown::HashMap;
3458 ///
3459 /// let mut map: HashMap<&str, u32> = HashMap::new();
3460 /// let entry = map.entry("horseyland").insert(37);
3461 ///
3462 /// assert_eq!(entry.key(), &"horseyland");
3463 /// ```
3464 #[cfg_attr(feature = "inline-more", inline)]
3465 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
3466 where
3467 K: Hash,
3468 S: BuildHasher,
3469 {
3470 match self {
3471 Entry::Occupied(mut entry) => {
3472 entry.insert(value);
3473 entry
3474 }
3475 Entry::Vacant(entry) => entry.insert_entry(value),
3476 }
3477 }
3478
3479 /// Ensures a value is in the entry by inserting the default if empty, and returns
3480 /// a mutable reference to the value in the entry.
3481 ///
3482 /// # Examples
3483 ///
3484 /// ```
3485 /// use hashbrown::HashMap;
3486 ///
3487 /// let mut map: HashMap<&str, u32> = HashMap::new();
3488 ///
3489 /// // nonexistent key
3490 /// map.entry("poneyland").or_insert(3);
3491 /// assert_eq!(map["poneyland"], 3);
3492 ///
3493 /// // existing key
3494 /// *map.entry("poneyland").or_insert(10) *= 2;
3495 /// assert_eq!(map["poneyland"], 6);
3496 /// ```
3497 #[cfg_attr(feature = "inline-more", inline)]
3498 pub fn or_insert(self, default: V) -> &'a mut V
3499 where
3500 K: Hash,
3501 S: BuildHasher,
3502 {
3503 match self {
3504 Entry::Occupied(entry) => entry.into_mut(),
3505 Entry::Vacant(entry) => entry.insert(default),
3506 }
3507 }
3508
3509 /// Ensures a value is in the entry by inserting the default if empty,
3510 /// and returns an [`OccupiedEntry`].
3511 ///
3512 /// # Examples
3513 ///
3514 /// ```
3515 /// use hashbrown::HashMap;
3516 ///
3517 /// let mut map: HashMap<&str, u32> = HashMap::new();
3518 ///
3519 /// // nonexistent key
3520 /// let entry = map.entry("poneyland").or_insert_entry(3);
3521 /// assert_eq!(entry.key(), &"poneyland");
3522 /// assert_eq!(entry.get(), &3);
3523 ///
3524 /// // existing key
3525 /// let mut entry = map.entry("poneyland").or_insert_entry(10);
3526 /// assert_eq!(entry.key(), &"poneyland");
3527 /// assert_eq!(entry.get(), &3);
3528 /// ```
3529 #[cfg_attr(feature = "inline-more", inline)]
3530 pub fn or_insert_entry(self, default: V) -> OccupiedEntry<'a, K, V, S, A>
3531 where
3532 K: Hash,
3533 S: BuildHasher,
3534 {
3535 match self {
3536 Entry::Occupied(entry) => entry,
3537 Entry::Vacant(entry) => entry.insert_entry(default),
3538 }
3539 }
3540
3541 /// Ensures a value is in the entry by inserting the result of the default function if empty,
3542 /// and returns a mutable reference to the value in the entry.
3543 ///
3544 /// # Examples
3545 ///
3546 /// ```
3547 /// use hashbrown::HashMap;
3548 ///
3549 /// let mut map: HashMap<&str, u32> = HashMap::new();
3550 ///
3551 /// // nonexistent key
3552 /// map.entry("poneyland").or_insert_with(|| 3);
3553 /// assert_eq!(map["poneyland"], 3);
3554 ///
3555 /// // existing key
3556 /// *map.entry("poneyland").or_insert_with(|| 10) *= 2;
3557 /// assert_eq!(map["poneyland"], 6);
3558 /// ```
3559 #[cfg_attr(feature = "inline-more", inline)]
3560 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
3561 where
3562 K: Hash,
3563 S: BuildHasher,
3564 {
3565 match self {
3566 Entry::Occupied(entry) => entry.into_mut(),
3567 Entry::Vacant(entry) => entry.insert(default()),
3568 }
3569 }
3570
3571 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
3572 /// This method allows for generating key-derived values for insertion by providing the default
3573 /// function a reference to the key that was moved during the `.entry(key)` method call.
3574 ///
3575 /// The reference to the moved key is provided so that cloning or copying the key is
3576 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
3577 ///
3578 /// # Examples
3579 ///
3580 /// ```
3581 /// use hashbrown::HashMap;
3582 ///
3583 /// let mut map: HashMap<&str, usize> = HashMap::new();
3584 ///
3585 /// // nonexistent key
3586 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
3587 /// assert_eq!(map["poneyland"], 9);
3588 ///
3589 /// // existing key
3590 /// *map.entry("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
3591 /// assert_eq!(map["poneyland"], 18);
3592 /// ```
3593 #[cfg_attr(feature = "inline-more", inline)]
3594 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
3595 where
3596 K: Hash,
3597 S: BuildHasher,
3598 {
3599 match self {
3600 Entry::Occupied(entry) => entry.into_mut(),
3601 Entry::Vacant(entry) => {
3602 let value = default(entry.key());
3603 entry.insert(value)
3604 }
3605 }
3606 }
3607
3608 /// Returns a reference to this entry's key.
3609 ///
3610 /// # Examples
3611 ///
3612 /// ```
3613 /// use hashbrown::HashMap;
3614 ///
3615 /// let mut map: HashMap<&str, u32> = HashMap::new();
3616 /// map.entry("poneyland").or_insert(3);
3617 /// // existing key
3618 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3619 /// // nonexistent key
3620 /// assert_eq!(map.entry("horseland").key(), &"horseland");
3621 /// ```
3622 #[cfg_attr(feature = "inline-more", inline)]
3623 pub fn key(&self) -> &K {
3624 match *self {
3625 Entry::Occupied(ref entry) => entry.key(),
3626 Entry::Vacant(ref entry) => entry.key(),
3627 }
3628 }
3629
3630 /// Provides in-place mutable access to an occupied entry before any
3631 /// potential inserts into the map.
3632 ///
3633 /// # Examples
3634 ///
3635 /// ```
3636 /// use hashbrown::HashMap;
3637 ///
3638 /// let mut map: HashMap<&str, u32> = HashMap::new();
3639 ///
3640 /// map.entry("poneyland")
3641 /// .and_modify(|e| { *e += 1 })
3642 /// .or_insert(42);
3643 /// assert_eq!(map["poneyland"], 42);
3644 ///
3645 /// map.entry("poneyland")
3646 /// .and_modify(|e| { *e += 1 })
3647 /// .or_insert(42);
3648 /// assert_eq!(map["poneyland"], 43);
3649 /// ```
3650 #[cfg_attr(feature = "inline-more", inline)]
3651 pub fn and_modify<F>(self, f: F) -> Self
3652 where
3653 F: FnOnce(&mut V),
3654 {
3655 match self {
3656 Entry::Occupied(mut entry) => {
3657 f(entry.get_mut());
3658 Entry::Occupied(entry)
3659 }
3660 Entry::Vacant(entry) => Entry::Vacant(entry),
3661 }
3662 }
3663
3664 /// Provides shared access to the key and owned access to the value of
3665 /// an occupied entry and allows to replace or remove it based on the
3666 /// value of the returned option.
3667 ///
3668 /// # Examples
3669 ///
3670 /// ```
3671 /// use hashbrown::HashMap;
3672 /// use hashbrown::hash_map::Entry;
3673 ///
3674 /// let mut map: HashMap<&str, u32> = HashMap::new();
3675 ///
3676 /// let entry = map
3677 /// .entry("poneyland")
3678 /// .and_replace_entry_with(|_k, _v| panic!());
3679 ///
3680 /// match entry {
3681 /// Entry::Vacant(e) => {
3682 /// assert_eq!(e.key(), &"poneyland");
3683 /// }
3684 /// Entry::Occupied(_) => panic!(),
3685 /// }
3686 ///
3687 /// map.insert("poneyland", 42);
3688 ///
3689 /// let entry = map
3690 /// .entry("poneyland")
3691 /// .and_replace_entry_with(|k, v| {
3692 /// assert_eq!(k, &"poneyland");
3693 /// assert_eq!(v, 42);
3694 /// Some(v + 1)
3695 /// });
3696 ///
3697 /// match entry {
3698 /// Entry::Occupied(e) => {
3699 /// assert_eq!(e.key(), &"poneyland");
3700 /// assert_eq!(e.get(), &43);
3701 /// }
3702 /// Entry::Vacant(_) => panic!(),
3703 /// }
3704 ///
3705 /// assert_eq!(map["poneyland"], 43);
3706 ///
3707 /// let entry = map
3708 /// .entry("poneyland")
3709 /// .and_replace_entry_with(|_k, _v| None);
3710 ///
3711 /// match entry {
3712 /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"),
3713 /// Entry::Occupied(_) => panic!(),
3714 /// }
3715 ///
3716 /// assert!(!map.contains_key("poneyland"));
3717 /// ```
3718 #[cfg_attr(feature = "inline-more", inline)]
3719 pub fn and_replace_entry_with<F>(self, f: F) -> Self
3720 where
3721 F: FnOnce(&K, V) -> Option<V>,
3722 {
3723 match self {
3724 Entry::Occupied(entry) => entry.replace_entry_with(f),
3725 Entry::Vacant(_) => self,
3726 }
3727 }
3728
3729 /// Converts the `Entry` into a mutable reference to the underlying map.
3730 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
3731 match self {
3732 Entry::Occupied(entry) => entry.table,
3733 Entry::Vacant(entry) => entry.table,
3734 }
3735 }
3736}
3737
3738impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> {
3739 /// Ensures a value is in the entry by inserting the default value if empty,
3740 /// and returns a mutable reference to the value in the entry.
3741 ///
3742 /// # Examples
3743 ///
3744 /// ```
3745 /// use hashbrown::HashMap;
3746 ///
3747 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
3748 ///
3749 /// // nonexistent key
3750 /// map.entry("poneyland").or_default();
3751 /// assert_eq!(map["poneyland"], None);
3752 ///
3753 /// map.insert("horseland", Some(3));
3754 ///
3755 /// // existing key
3756 /// assert_eq!(map.entry("horseland").or_default(), &mut Some(3));
3757 /// ```
3758 #[cfg_attr(feature = "inline-more", inline)]
3759 pub fn or_default(self) -> &'a mut V
3760 where
3761 K: Hash,
3762 S: BuildHasher,
3763 {
3764 match self {
3765 Entry::Occupied(entry) => entry.into_mut(),
3766 Entry::Vacant(entry) => entry.insert(Default::default()),
3767 }
3768 }
3769}
3770
3771impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> {
3772 /// Gets a reference to the key in the entry.
3773 ///
3774 /// # Examples
3775 ///
3776 /// ```
3777 /// use hashbrown::hash_map::{Entry, HashMap};
3778 ///
3779 /// let mut map: HashMap<&str, u32> = HashMap::new();
3780 /// map.entry("poneyland").or_insert(12);
3781 ///
3782 /// match map.entry("poneyland") {
3783 /// Entry::Vacant(_) => panic!(),
3784 /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"),
3785 /// }
3786 /// ```
3787 #[cfg_attr(feature = "inline-more", inline)]
3788 pub fn key(&self) -> &K {
3789 unsafe { &self.elem.as_ref().0 }
3790 }
3791
3792 /// Replaces the key in the entry with a new one.
3793 ///
3794 /// # Panics
3795 ///
3796 /// This method panics if `key` is not equivalent to the key in the entry.
3797 ///
3798 /// # Examples
3799 ///
3800 /// ```
3801 /// use hashbrown::hash_map::{Entry, HashMap};
3802 ///
3803 /// let mut map: HashMap<&str, u32> = HashMap::new();
3804 ///
3805 /// let old_key = "poneyland";
3806 /// let new_key = Box::leak(old_key.to_owned().into_boxed_str());
3807 /// map.entry(old_key).or_insert(12);
3808 /// match map.entry("poneyland") {
3809 /// Entry::Vacant(_) => panic!(),
3810 /// Entry::Occupied(mut entry) => {
3811 /// let replaced = entry.replace_key(new_key);
3812 /// assert!(std::ptr::eq(replaced, old_key));
3813 /// assert!(std::ptr::eq(*entry.key(), new_key));
3814 /// },
3815 /// }
3816 ///
3817 /// # // appease miri; no memory leaks here!
3818 /// # drop(map);
3819 /// # unsafe {
3820 /// # Box::from_raw(new_key);
3821 /// # }
3822 /// ```
3823 #[cfg_attr(feature = "inline-more", inline)]
3824 pub fn replace_key(&mut self, key: K) -> K
3825 where
3826 K: Equivalent<K>,
3827 {
3828 assert!(
3829 self.key().equivalent(&key),
3830 "replaced key is not equivalent to the one in the entry"
3831 );
3832
3833 // SAFETY: We verified that the keys were equivalent.
3834 unsafe { self.replace_key_unchecked(key) }
3835 }
3836
3837 /// Replaces the key in the entry with a new one, without checking the
3838 /// equivalence of the key.
3839 ///
3840 /// # Safety
3841 ///
3842 /// This operation is safe if you replace the key with an equivalent one.
3843 ///
3844 /// Additionally, this operation (and following operations) are guaranteed
3845 /// to not violate memory safety.
3846 ///
3847 /// However this operation is still unsafe because the resulting `HashMap`
3848 /// may be passed to unsafe code which does expect the map to behave
3849 /// correctly. If the map has keys at unexpected positions inside it,
3850 /// future operations may panic, loop forever, or return unexpected results,
3851 /// potentially violating memory safety.
3852 ///
3853 /// # Examples
3854 ///
3855 /// ```
3856 /// use hashbrown::hash_map::{Entry, HashMap};
3857 ///
3858 /// let mut map: HashMap<&str, u32> = HashMap::new();
3859 ///
3860 /// let old_key = "poneyland";
3861 /// let new_key = Box::leak(old_key.to_owned().into_boxed_str());
3862 /// map.entry(old_key).or_insert(12);
3863 /// match map.entry("poneyland") {
3864 /// Entry::Vacant(_) => panic!(),
3865 /// Entry::Occupied(mut entry) => {
3866 /// let replaced = unsafe { entry.replace_key_unchecked(new_key) };
3867 /// assert!(std::ptr::eq(replaced, old_key));
3868 /// assert!(std::ptr::eq(*entry.key(), new_key));
3869 /// },
3870 /// }
3871 ///
3872 /// # // appease miri; no memory leaks here!
3873 /// # drop(map);
3874 /// # unsafe {
3875 /// # Box::from_raw(new_key);
3876 /// # }
3877 /// ```
3878 #[cfg_attr(feature = "inline-more", inline)]
3879 pub unsafe fn replace_key_unchecked(&mut self, key: K) -> K {
3880 mem::replace(unsafe { &mut self.elem.as_mut().0 }, key)
3881 }
3882
3883 /// Take the ownership of the key and value from the map.
3884 /// Keeps the allocated memory for reuse.
3885 ///
3886 /// # Examples
3887 ///
3888 /// ```
3889 /// use hashbrown::HashMap;
3890 /// use hashbrown::hash_map::Entry;
3891 ///
3892 /// let mut map: HashMap<&str, u32> = HashMap::new();
3893 /// // The map is empty
3894 /// assert!(map.is_empty() && map.capacity() == 0);
3895 ///
3896 /// map.entry("poneyland").or_insert(12);
3897 ///
3898 /// if let Entry::Occupied(o) = map.entry("poneyland") {
3899 /// // We delete the entry from the map.
3900 /// assert_eq!(o.remove_entry(), ("poneyland", 12));
3901 /// }
3902 ///
3903 /// assert_eq!(map.contains_key("poneyland"), false);
3904 /// // Now map hold none elements
3905 /// assert!(map.is_empty());
3906 /// ```
3907 #[cfg_attr(feature = "inline-more", inline)]
3908 pub fn remove_entry(self) -> (K, V) {
3909 unsafe { self.table.table.remove(self.elem).0 }
3910 }
3911
3912 /// Gets a reference to the value in the entry.
3913 ///
3914 /// # Examples
3915 ///
3916 /// ```
3917 /// use hashbrown::HashMap;
3918 /// use hashbrown::hash_map::Entry;
3919 ///
3920 /// let mut map: HashMap<&str, u32> = HashMap::new();
3921 /// map.entry("poneyland").or_insert(12);
3922 ///
3923 /// match map.entry("poneyland") {
3924 /// Entry::Vacant(_) => panic!(),
3925 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12),
3926 /// }
3927 /// ```
3928 #[cfg_attr(feature = "inline-more", inline)]
3929 pub fn get(&self) -> &V {
3930 unsafe { &self.elem.as_ref().1 }
3931 }
3932
3933 /// Gets a mutable reference to the value in the entry.
3934 ///
3935 /// If you need a reference to the `OccupiedEntry` which may outlive the
3936 /// destruction of the `Entry` value, see [`into_mut`].
3937 ///
3938 /// [`into_mut`]: #method.into_mut
3939 ///
3940 /// # Examples
3941 ///
3942 /// ```
3943 /// use hashbrown::HashMap;
3944 /// use hashbrown::hash_map::Entry;
3945 ///
3946 /// let mut map: HashMap<&str, u32> = HashMap::new();
3947 /// map.entry("poneyland").or_insert(12);
3948 ///
3949 /// assert_eq!(map["poneyland"], 12);
3950 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
3951 /// *o.get_mut() += 10;
3952 /// assert_eq!(*o.get(), 22);
3953 ///
3954 /// // We can use the same Entry multiple times.
3955 /// *o.get_mut() += 2;
3956 /// }
3957 ///
3958 /// assert_eq!(map["poneyland"], 24);
3959 /// ```
3960 #[cfg_attr(feature = "inline-more", inline)]
3961 pub fn get_mut(&mut self) -> &mut V {
3962 unsafe { &mut self.elem.as_mut().1 }
3963 }
3964
3965 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
3966 /// with a lifetime bound to the map itself.
3967 ///
3968 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
3969 ///
3970 /// [`get_mut`]: #method.get_mut
3971 ///
3972 /// # Examples
3973 ///
3974 /// ```
3975 /// use hashbrown::hash_map::{Entry, HashMap};
3976 ///
3977 /// let mut map: HashMap<&str, u32> = HashMap::new();
3978 /// map.entry("poneyland").or_insert(12);
3979 ///
3980 /// assert_eq!(map["poneyland"], 12);
3981 ///
3982 /// let value: &mut u32;
3983 /// match map.entry("poneyland") {
3984 /// Entry::Occupied(entry) => value = entry.into_mut(),
3985 /// Entry::Vacant(_) => panic!(),
3986 /// }
3987 /// *value += 10;
3988 ///
3989 /// assert_eq!(map["poneyland"], 22);
3990 /// ```
3991 #[cfg_attr(feature = "inline-more", inline)]
3992 pub fn into_mut(self) -> &'a mut V {
3993 unsafe { &mut self.elem.as_mut().1 }
3994 }
3995
3996 /// Converts the `OccupiedEntry` into a reference to the key and a
3997 /// mutable reference to the value in the entry with a lifetime bound to the
3998 /// map itself.
3999 ///
4000 /// If you need multiple references to the `OccupiedEntry`, see [`key`] and
4001 /// [`get_mut`].
4002 ///
4003 /// [`key`]: Self::key
4004 /// [`get_mut`]: Self::get_mut
4005 ///
4006 /// # Examples
4007 ///
4008 /// ```
4009 /// use hashbrown::hash_map::{Entry, HashMap};
4010 ///
4011 /// let mut map: HashMap<&str, u32> = HashMap::new();
4012 /// map.entry("poneyland").or_insert(12);
4013 ///
4014 /// assert_eq!(map["poneyland"], 12);
4015 ///
4016 /// let key_val: (&&str, &mut u32);
4017 /// match map.entry("poneyland") {
4018 /// Entry::Occupied(entry) => key_val = entry.into_entry(),
4019 /// Entry::Vacant(_) => panic!(),
4020 /// }
4021 /// *key_val.1 += 10;
4022 ///
4023 /// assert_eq!(key_val, (&"poneyland", &mut 22));
4024 /// assert_eq!(map["poneyland"], 22);
4025 /// ```
4026 #[cfg_attr(feature = "inline-more", inline)]
4027 pub fn into_entry(self) -> (&'a K, &'a mut V) {
4028 let (key, val) = unsafe { self.elem.as_mut() };
4029 (key, val)
4030 }
4031
4032 /// Sets the value of the entry, and returns the entry's old value.
4033 ///
4034 /// # Examples
4035 ///
4036 /// ```
4037 /// use hashbrown::HashMap;
4038 /// use hashbrown::hash_map::Entry;
4039 ///
4040 /// let mut map: HashMap<&str, u32> = HashMap::new();
4041 /// map.entry("poneyland").or_insert(12);
4042 ///
4043 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
4044 /// assert_eq!(o.insert(15), 12);
4045 /// }
4046 ///
4047 /// assert_eq!(map["poneyland"], 15);
4048 /// ```
4049 #[cfg_attr(feature = "inline-more", inline)]
4050 pub fn insert(&mut self, value: V) -> V {
4051 mem::replace(self.get_mut(), value)
4052 }
4053
4054 /// Takes the value out of the entry, and returns it.
4055 /// Keeps the allocated memory for reuse.
4056 ///
4057 /// # Examples
4058 ///
4059 /// ```
4060 /// use hashbrown::HashMap;
4061 /// use hashbrown::hash_map::Entry;
4062 ///
4063 /// let mut map: HashMap<&str, u32> = HashMap::new();
4064 /// // The map is empty
4065 /// assert!(map.is_empty() && map.capacity() == 0);
4066 ///
4067 /// map.entry("poneyland").or_insert(12);
4068 ///
4069 /// if let Entry::Occupied(o) = map.entry("poneyland") {
4070 /// assert_eq!(o.remove(), 12);
4071 /// }
4072 ///
4073 /// assert_eq!(map.contains_key("poneyland"), false);
4074 /// // Now map hold none elements
4075 /// assert!(map.is_empty());
4076 /// ```
4077 #[cfg_attr(feature = "inline-more", inline)]
4078 pub fn remove(self) -> V {
4079 self.remove_entry().1
4080 }
4081
4082 /// Provides shared access to the key and owned access to the value of
4083 /// the entry and allows to replace or remove it based on the
4084 /// value of the returned option.
4085 ///
4086 /// # Examples
4087 ///
4088 /// ```
4089 /// use hashbrown::HashMap;
4090 /// use hashbrown::hash_map::Entry;
4091 ///
4092 /// let mut map: HashMap<&str, u32> = HashMap::new();
4093 /// map.insert("poneyland", 42);
4094 ///
4095 /// let entry = match map.entry("poneyland") {
4096 /// Entry::Occupied(e) => {
4097 /// e.replace_entry_with(|k, v| {
4098 /// assert_eq!(k, &"poneyland");
4099 /// assert_eq!(v, 42);
4100 /// Some(v + 1)
4101 /// })
4102 /// }
4103 /// Entry::Vacant(_) => panic!(),
4104 /// };
4105 ///
4106 /// match entry {
4107 /// Entry::Occupied(e) => {
4108 /// assert_eq!(e.key(), &"poneyland");
4109 /// assert_eq!(e.get(), &43);
4110 /// }
4111 /// Entry::Vacant(_) => panic!(),
4112 /// }
4113 ///
4114 /// assert_eq!(map["poneyland"], 43);
4115 ///
4116 /// let entry = match map.entry("poneyland") {
4117 /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None),
4118 /// Entry::Vacant(_) => panic!(),
4119 /// };
4120 ///
4121 /// match entry {
4122 /// Entry::Vacant(e) => {
4123 /// assert_eq!(e.key(), &"poneyland");
4124 /// }
4125 /// Entry::Occupied(_) => panic!(),
4126 /// }
4127 ///
4128 /// assert!(!map.contains_key("poneyland"));
4129 /// ```
4130 #[cfg_attr(feature = "inline-more", inline)]
4131 pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
4132 where
4133 F: FnOnce(&K, V) -> Option<V>,
4134 {
4135 unsafe {
4136 let mut spare_key = None;
4137
4138 self.table
4139 .table
4140 .replace_bucket_with(self.elem.clone(), |(key, value)| {
4141 if let Some(new_value) = f(&key, value) {
4142 Some((key, new_value))
4143 } else {
4144 spare_key = Some(key);
4145 None
4146 }
4147 });
4148
4149 if let Some(key) = spare_key {
4150 Entry::Vacant(VacantEntry {
4151 hash: self.hash,
4152 key,
4153 table: self.table,
4154 })
4155 } else {
4156 Entry::Occupied(self)
4157 }
4158 }
4159 }
4160
4161 /// Converts the `OccupiedEntry` into a mutable reference to the underlying map.
4162 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
4163 self.table
4164 }
4165}
4166
4167impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> {
4168 /// Gets a reference to the key that would be used when inserting a value
4169 /// through the `VacantEntry`.
4170 ///
4171 /// # Examples
4172 ///
4173 /// ```
4174 /// use hashbrown::HashMap;
4175 ///
4176 /// let mut map: HashMap<&str, u32> = HashMap::new();
4177 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
4178 /// ```
4179 #[cfg_attr(feature = "inline-more", inline)]
4180 pub fn key(&self) -> &K {
4181 &self.key
4182 }
4183
4184 /// Take ownership of the key.
4185 ///
4186 /// # Examples
4187 ///
4188 /// ```
4189 /// use hashbrown::hash_map::{Entry, HashMap};
4190 ///
4191 /// let mut map: HashMap<&str, u32> = HashMap::new();
4192 ///
4193 /// match map.entry("poneyland") {
4194 /// Entry::Occupied(_) => panic!(),
4195 /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"),
4196 /// }
4197 /// ```
4198 #[cfg_attr(feature = "inline-more", inline)]
4199 pub fn into_key(self) -> K {
4200 self.key
4201 }
4202
4203 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4204 /// and returns a mutable reference to it.
4205 ///
4206 /// # Examples
4207 ///
4208 /// ```
4209 /// use hashbrown::HashMap;
4210 /// use hashbrown::hash_map::Entry;
4211 ///
4212 /// let mut map: HashMap<&str, u32> = HashMap::new();
4213 ///
4214 /// if let Entry::Vacant(o) = map.entry("poneyland") {
4215 /// o.insert(37);
4216 /// }
4217 /// assert_eq!(map["poneyland"], 37);
4218 /// ```
4219 #[cfg_attr(feature = "inline-more", inline)]
4220 pub fn insert(self, value: V) -> &'a mut V
4221 where
4222 K: Hash,
4223 S: BuildHasher,
4224 {
4225 let table = &mut self.table.table;
4226 let entry = table.insert_entry(
4227 self.hash,
4228 (self.key, value),
4229 make_hasher::<_, V, S>(&self.table.hash_builder),
4230 );
4231 &mut entry.1
4232 }
4233
4234 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4235 /// and returns an [`OccupiedEntry`].
4236 ///
4237 /// # Examples
4238 ///
4239 /// ```
4240 /// use hashbrown::HashMap;
4241 /// use hashbrown::hash_map::Entry;
4242 ///
4243 /// let mut map: HashMap<&str, u32> = HashMap::new();
4244 ///
4245 /// if let Entry::Vacant(v) = map.entry("poneyland") {
4246 /// let o = v.insert_entry(37);
4247 /// assert_eq!(o.get(), &37);
4248 /// }
4249 /// ```
4250 #[cfg_attr(feature = "inline-more", inline)]
4251 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4252 where
4253 K: Hash,
4254 S: BuildHasher,
4255 {
4256 let elem = self.table.table.insert(
4257 self.hash,
4258 (self.key, value),
4259 make_hasher::<_, V, S>(&self.table.hash_builder),
4260 );
4261 OccupiedEntry {
4262 hash: self.hash,
4263 elem,
4264 table: self.table,
4265 }
4266 }
4267
4268 /// Converts the `VacantEntry` into a mutable reference to the underlying map.
4269 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
4270 self.table
4271 }
4272}
4273
4274impl<'a, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, '_, K, Q, V, S, A> {
4275 /// Sets the value of the entry, and returns an `OccupiedEntry`.
4276 ///
4277 /// # Examples
4278 ///
4279 /// ```
4280 /// use hashbrown::HashMap;
4281 ///
4282 /// let mut map: HashMap<String, u32> = HashMap::new();
4283 /// let entry = map.entry_ref("horseyland").insert(37);
4284 ///
4285 /// assert_eq!(entry.key(), "horseyland");
4286 /// ```
4287 #[cfg_attr(feature = "inline-more", inline)]
4288 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4289 where
4290 K: Hash,
4291 Q: ToOwned<Owned = K>,
4292 S: BuildHasher,
4293 {
4294 match self {
4295 EntryRef::Occupied(mut entry) => {
4296 entry.insert(value);
4297 entry
4298 }
4299 EntryRef::Vacant(entry) => entry.insert_entry(value),
4300 }
4301 }
4302
4303 /// Ensures a value is in the entry by inserting the default if empty, and returns
4304 /// a mutable reference to the value in the entry.
4305 ///
4306 /// # Examples
4307 ///
4308 /// ```
4309 /// use hashbrown::HashMap;
4310 ///
4311 /// let mut map: HashMap<String, u32> = HashMap::new();
4312 ///
4313 /// // nonexistent key
4314 /// map.entry_ref("poneyland").or_insert(3);
4315 /// assert_eq!(map["poneyland"], 3);
4316 ///
4317 /// // existing key
4318 /// *map.entry_ref("poneyland").or_insert(10) *= 2;
4319 /// assert_eq!(map["poneyland"], 6);
4320 /// ```
4321 #[cfg_attr(feature = "inline-more", inline)]
4322 pub fn or_insert(self, default: V) -> &'a mut V
4323 where
4324 K: Hash,
4325 Q: ToOwned<Owned = K>,
4326 S: BuildHasher,
4327 {
4328 match self {
4329 EntryRef::Occupied(entry) => entry.into_mut(),
4330 EntryRef::Vacant(entry) => entry.insert(default),
4331 }
4332 }
4333
4334 /// Ensures a value is in the entry by inserting the result of the default function if empty,
4335 /// and returns a mutable reference to the value in the entry.
4336 ///
4337 /// # Examples
4338 ///
4339 /// ```
4340 /// use hashbrown::HashMap;
4341 ///
4342 /// let mut map: HashMap<String, u32> = HashMap::new();
4343 ///
4344 /// // nonexistent key
4345 /// map.entry_ref("poneyland").or_insert_with(|| 3);
4346 /// assert_eq!(map["poneyland"], 3);
4347 ///
4348 /// // existing key
4349 /// *map.entry_ref("poneyland").or_insert_with(|| 10) *= 2;
4350 /// assert_eq!(map["poneyland"], 6);
4351 /// ```
4352 #[cfg_attr(feature = "inline-more", inline)]
4353 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
4354 where
4355 K: Hash,
4356 Q: ToOwned<Owned = K>,
4357 S: BuildHasher,
4358 {
4359 match self {
4360 EntryRef::Occupied(entry) => entry.into_mut(),
4361 EntryRef::Vacant(entry) => entry.insert(default()),
4362 }
4363 }
4364
4365 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
4366 /// This method allows for generating key-derived values for insertion by providing the default
4367 /// function an access to the borrower form of the key.
4368 ///
4369 /// # Examples
4370 ///
4371 /// ```
4372 /// use hashbrown::HashMap;
4373 ///
4374 /// let mut map: HashMap<String, usize> = HashMap::new();
4375 ///
4376 /// // nonexistent key
4377 /// map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count());
4378 /// assert_eq!(map["poneyland"], 9);
4379 ///
4380 /// // existing key
4381 /// *map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
4382 /// assert_eq!(map["poneyland"], 18);
4383 /// ```
4384 #[cfg_attr(feature = "inline-more", inline)]
4385 pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V
4386 where
4387 K: Hash + Borrow<Q>,
4388 Q: ToOwned<Owned = K>,
4389 S: BuildHasher,
4390 {
4391 match self {
4392 EntryRef::Occupied(entry) => entry.into_mut(),
4393 EntryRef::Vacant(entry) => {
4394 let value = default(entry.key);
4395 entry.insert(value)
4396 }
4397 }
4398 }
4399
4400 /// Returns a reference to this entry's key.
4401 ///
4402 /// # Examples
4403 ///
4404 /// ```
4405 /// use hashbrown::HashMap;
4406 ///
4407 /// let mut map: HashMap<String, u32> = HashMap::new();
4408 /// map.entry_ref("poneyland").or_insert(3);
4409 /// // existing key
4410 /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland");
4411 /// // nonexistent key
4412 /// assert_eq!(map.entry_ref("horseland").key(), "horseland");
4413 /// ```
4414 #[cfg_attr(feature = "inline-more", inline)]
4415 pub fn key(&self) -> &Q
4416 where
4417 K: Borrow<Q>,
4418 {
4419 match *self {
4420 EntryRef::Occupied(ref entry) => entry.key().borrow(),
4421 EntryRef::Vacant(ref entry) => entry.key(),
4422 }
4423 }
4424
4425 /// Provides in-place mutable access to an occupied entry before any
4426 /// potential inserts into the map.
4427 ///
4428 /// # Examples
4429 ///
4430 /// ```
4431 /// use hashbrown::HashMap;
4432 ///
4433 /// let mut map: HashMap<String, u32> = HashMap::new();
4434 ///
4435 /// map.entry_ref("poneyland")
4436 /// .and_modify(|e| { *e += 1 })
4437 /// .or_insert(42);
4438 /// assert_eq!(map["poneyland"], 42);
4439 ///
4440 /// map.entry_ref("poneyland")
4441 /// .and_modify(|e| { *e += 1 })
4442 /// .or_insert(42);
4443 /// assert_eq!(map["poneyland"], 43);
4444 /// ```
4445 #[cfg_attr(feature = "inline-more", inline)]
4446 pub fn and_modify<F>(self, f: F) -> Self
4447 where
4448 F: FnOnce(&mut V),
4449 {
4450 match self {
4451 EntryRef::Occupied(mut entry) => {
4452 f(entry.get_mut());
4453 EntryRef::Occupied(entry)
4454 }
4455 EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
4456 }
4457 }
4458
4459 /// Converts the `EntryRef` into a mutable reference to the underlying map.
4460 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
4461 match self {
4462 EntryRef::Occupied(entry) => entry.table,
4463 EntryRef::Vacant(entry) => entry.table,
4464 }
4465 }
4466}
4467
4468impl<'a, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, '_, K, Q, V, S, A> {
4469 /// Ensures a value is in the entry by inserting the default value if empty,
4470 /// and returns a mutable reference to the value in the entry.
4471 ///
4472 /// # Examples
4473 ///
4474 /// ```
4475 /// use hashbrown::HashMap;
4476 ///
4477 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4478 ///
4479 /// // nonexistent key
4480 /// map.entry_ref("poneyland").or_default();
4481 /// assert_eq!(map["poneyland"], None);
4482 ///
4483 /// map.insert("horseland".to_string(), Some(3));
4484 ///
4485 /// // existing key
4486 /// assert_eq!(map.entry_ref("horseland").or_default(), &mut Some(3));
4487 /// ```
4488 #[cfg_attr(feature = "inline-more", inline)]
4489 pub fn or_default(self) -> &'a mut V
4490 where
4491 K: Hash,
4492 Q: ToOwned<Owned = K>,
4493 S: BuildHasher,
4494 {
4495 match self {
4496 EntryRef::Occupied(entry) => entry.into_mut(),
4497 EntryRef::Vacant(entry) => entry.insert(Default::default()),
4498 }
4499 }
4500
4501 /// Ensures a value is in the entry by inserting the default value if empty,
4502 /// and returns an [`OccupiedEntry`].
4503 ///
4504 /// # Examples
4505 ///
4506 /// ```
4507 /// use hashbrown::HashMap;
4508 ///
4509 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4510 ///
4511 /// // nonexistent key
4512 /// let entry = map.entry_ref("poneyland").or_default_entry();
4513 /// assert_eq!(entry.key(), &"poneyland");
4514 /// assert_eq!(entry.get(), &None);
4515 ///
4516 /// // existing key
4517 /// map.insert("horseland".to_string(), Some(3));
4518 /// let entry = map.entry_ref("horseland").or_default_entry();
4519 /// assert_eq!(entry.key(), &"horseland");
4520 /// assert_eq!(entry.get(), &Some(3));
4521 /// ```
4522 #[cfg_attr(feature = "inline-more", inline)]
4523 pub fn or_default_entry(self) -> OccupiedEntry<'a, K, V, S, A>
4524 where
4525 K: Hash,
4526 Q: ToOwned<Owned = K>,
4527 S: BuildHasher,
4528 {
4529 match self {
4530 EntryRef::Occupied(entry) => entry,
4531 EntryRef::Vacant(entry) => entry.insert_entry(Default::default()),
4532 }
4533 }
4534}
4535
4536impl<'map, 'key, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'map, 'key, K, Q, V, S, A> {
4537 /// Gets a reference to the key that would be used when inserting a value
4538 /// through the `VacantEntryRef`.
4539 ///
4540 /// # Examples
4541 ///
4542 /// ```
4543 /// use hashbrown::HashMap;
4544 ///
4545 /// let mut map: HashMap<String, u32> = HashMap::new();
4546 /// let key: &str = "poneyland";
4547 /// assert_eq!(map.entry_ref(key).key(), "poneyland");
4548 /// ```
4549 #[cfg_attr(feature = "inline-more", inline)]
4550 pub fn key(&self) -> &'key Q {
4551 self.key
4552 }
4553
4554 /// Sets the value of the entry with the `VacantEntryRef`'s key,
4555 /// and returns a mutable reference to it.
4556 ///
4557 /// # Examples
4558 ///
4559 /// ```
4560 /// use hashbrown::HashMap;
4561 /// use hashbrown::hash_map::EntryRef;
4562 ///
4563 /// let mut map: HashMap<String, u32> = HashMap::new();
4564 /// let key: &str = "poneyland";
4565 ///
4566 /// if let EntryRef::Vacant(o) = map.entry_ref(key) {
4567 /// o.insert(37);
4568 /// }
4569 /// assert_eq!(map["poneyland"], 37);
4570 /// ```
4571 #[cfg_attr(feature = "inline-more", inline)]
4572 pub fn insert(self, value: V) -> &'map mut V
4573 where
4574 K: Hash,
4575 Q: ToOwned<Owned = K>,
4576 S: BuildHasher,
4577 {
4578 let table = &mut self.table.table;
4579 let entry = table.insert_entry(
4580 self.hash,
4581 (self.key.to_owned(), value),
4582 make_hasher::<_, V, S>(&self.table.hash_builder),
4583 );
4584 &mut entry.1
4585 }
4586
4587 /// Sets the key and value of the entry and returns a mutable reference to
4588 /// the inserted value.
4589 ///
4590 /// Unlike [`VacantEntryRef::insert`], this method allows the key to be
4591 /// explicitly specified, which is useful for key types that don't implement
4592 /// `ToOwned`.
4593 ///
4594 /// # Panics
4595 ///
4596 /// This method panics if `key` is not equivalent to the key used to create
4597 /// the `VacantEntryRef`.
4598 ///
4599 /// # Example
4600 ///
4601 /// ```
4602 /// use hashbrown::hash_map::EntryRef;
4603 /// use hashbrown::HashMap;
4604 ///
4605 /// let mut map = HashMap::<(String, String), char>::new();
4606 /// let k = ("c".to_string(), "C".to_string());
4607 /// let v = match map.entry_ref(&k) {
4608 /// // Insert cannot be used here because tuples do not implement ToOwned.
4609 /// // However this works because we can manually clone instead.
4610 /// EntryRef::Vacant(r) => r.insert_with_key(k.clone(), 'c'),
4611 /// // In this branch we avoid the clone.
4612 /// EntryRef::Occupied(r) => r.into_mut(),
4613 /// };
4614 /// assert_eq!(*v, 'c');
4615 /// ```
4616 #[cfg_attr(feature = "inline-more", inline)]
4617 pub fn insert_with_key(self, key: K, value: V) -> &'map mut V
4618 where
4619 K: Hash,
4620 Q: Equivalent<K>,
4621 S: BuildHasher,
4622 {
4623 self.insert_entry_with_key(key, value).into_mut()
4624 }
4625
4626 /// Sets the key and value of the entry and returns a mutable reference to
4627 /// the inserted value, without checking the equivalence of the key.
4628 ///
4629 /// See [`insert_with_key`](Self::insert_with_key) for more information.
4630 ///
4631 /// # Safety
4632 ///
4633 /// This operation is safe if the keys are equivalent.
4634 ///
4635 /// Additionally, this operation (and following operations) are guaranteed
4636 /// to not violate memory safety.
4637 ///
4638 /// However this operation is still unsafe because the resulting `HashMap`
4639 /// may be passed to unsafe code which does expect the map to behave
4640 /// correctly. If the map has keys at unexpected positions inside it,
4641 /// future operations may panic, loop forever, or return unexpected results,
4642 /// potentially violating memory safety.
4643 ///
4644 /// # Example
4645 ///
4646 /// ```
4647 /// use hashbrown::hash_map::EntryRef;
4648 /// use hashbrown::HashMap;
4649 ///
4650 /// let mut map = HashMap::<(String, String), char>::new();
4651 /// let k = ("c".to_string(), "C".to_string());
4652 /// let v = match map.entry_ref(&k) {
4653 /// // SAFETY: We trust the `Clone` implementation to return an equivalent value
4654 /// EntryRef::Vacant(r) => unsafe { r.insert_with_key_unchecked(k.clone(), 'c') },
4655 /// // In this branch we avoid the clone.
4656 /// EntryRef::Occupied(r) => r.into_mut(),
4657 /// };
4658 /// assert_eq!(*v, 'c');
4659 /// ```
4660 #[cfg_attr(feature = "inline-more", inline)]
4661 pub unsafe fn insert_with_key_unchecked(self, key: K, value: V) -> &'map mut V
4662 where
4663 K: Hash,
4664 S: BuildHasher,
4665 {
4666 // SAFETY: Guaranteed by caller.
4667 unsafe { self.insert_entry_with_key_unchecked(key, value) }.into_mut()
4668 }
4669
4670 /// Sets the value of the entry with the [`VacantEntryRef`]'s key,
4671 /// and returns an [`OccupiedEntry`].
4672 ///
4673 /// # Examples
4674 ///
4675 /// ```
4676 /// use hashbrown::HashMap;
4677 /// use hashbrown::hash_map::EntryRef;
4678 ///
4679 /// let mut map: HashMap<&str, u32> = HashMap::new();
4680 ///
4681 /// if let EntryRef::Vacant(v) = map.entry_ref(&"poneyland") {
4682 /// let o = v.insert_entry(37);
4683 /// assert_eq!(o.get(), &37);
4684 /// }
4685 /// ```
4686 #[cfg_attr(feature = "inline-more", inline)]
4687 pub fn insert_entry(self, value: V) -> OccupiedEntry<'map, K, V, S, A>
4688 where
4689 K: Hash,
4690 Q: ToOwned<Owned = K>,
4691 S: BuildHasher,
4692 {
4693 let elem = self.table.table.insert(
4694 self.hash,
4695 (self.key.to_owned(), value),
4696 make_hasher::<_, V, S>(&self.table.hash_builder),
4697 );
4698 OccupiedEntry {
4699 hash: self.hash,
4700 elem,
4701 table: self.table,
4702 }
4703 }
4704
4705 /// Sets the key and value of the entry and returns an [`OccupiedEntry`].
4706 ///
4707 /// Unlike [`VacantEntryRef::insert_entry`], this method allows the key to
4708 /// be explicitly specified, which is useful for key types that don't
4709 /// implement `ToOwned`.
4710 ///
4711 /// # Panics
4712 ///
4713 /// This method panics if `key` is not equivalent to the key used to create
4714 /// the `VacantEntryRef`.
4715 ///
4716 /// # Example
4717 ///
4718 /// ```
4719 /// use hashbrown::hash_map::EntryRef;
4720 /// use hashbrown::HashMap;
4721 ///
4722 /// let mut map = HashMap::<(String, String), char>::new();
4723 /// let k = ("c".to_string(), "C".to_string());
4724 /// let r = match map.entry_ref(&k) {
4725 /// // Insert cannot be used here because tuples do not implement ToOwned.
4726 /// // However this works because we can manually clone instead.
4727 /// EntryRef::Vacant(r) => r.insert_entry_with_key(k.clone(), 'c'),
4728 /// // In this branch we avoid the clone.
4729 /// EntryRef::Occupied(r) => r,
4730 /// };
4731 /// assert_eq!(r.get(), &'c');
4732 /// ```
4733 #[cfg_attr(feature = "inline-more", inline)]
4734 pub fn insert_entry_with_key(self, key: K, value: V) -> OccupiedEntry<'map, K, V, S, A>
4735 where
4736 K: Hash,
4737 Q: Equivalent<K>,
4738 S: BuildHasher,
4739 {
4740 assert!(
4741 (self.key).equivalent(&key),
4742 "key used for Entry creation is not equivalent to the one used for insertion"
4743 );
4744 // SAFETY: We checked equivalence first.
4745 unsafe { self.insert_entry_with_key_unchecked(key, value) }
4746 }
4747
4748 /// Sets the key and value of the entry and returns an [`OccupiedEntry`],
4749 /// without checking the equivalence of the key.
4750 ///
4751 /// See [`insert_entry_with_key`](Self::insert_entry_with_key) for more information.
4752 ///
4753 /// # Safety
4754 ///
4755 /// This operation is safe if the keys are equivalent.
4756 ///
4757 /// Additionally, this operation (and following operations) are guaranteed
4758 /// to not violate memory safety.
4759 ///
4760 /// However this operation is still unsafe because the resulting `HashMap`
4761 /// may be passed to unsafe code which does expect the map to behave
4762 /// correctly. If the map has keys at unexpected positions inside it,
4763 /// future operations may panic, loop forever, or return unexpected results,
4764 /// potentially violating memory safety.
4765 ///
4766 /// # Example
4767 ///
4768 /// ```
4769 /// use hashbrown::hash_map::EntryRef;
4770 /// use hashbrown::HashMap;
4771 ///
4772 /// let mut map = HashMap::<(String, String), char>::new();
4773 /// let k = ("c".to_string(), "C".to_string());
4774 /// let r = match map.entry_ref(&k) {
4775 /// // SAFETY: We trust the `Clone` implementation to return an equivalent key
4776 /// EntryRef::Vacant(r) => unsafe { r.insert_entry_with_key_unchecked(k.clone(), 'c') },
4777 /// // In this branch we avoid the clone.
4778 /// EntryRef::Occupied(r) => r,
4779 /// };
4780 /// assert_eq!(r.get(), &'c');
4781 /// ```
4782 #[cfg_attr(feature = "inline-more", inline)]
4783 pub unsafe fn insert_entry_with_key_unchecked(
4784 self,
4785 key: K,
4786 value: V,
4787 ) -> OccupiedEntry<'map, K, V, S, A>
4788 where
4789 K: Hash,
4790 S: BuildHasher,
4791 {
4792 let elem = self.table.table.insert(
4793 self.hash,
4794 (key, value),
4795 make_hasher::<_, V, S>(&self.table.hash_builder),
4796 );
4797 OccupiedEntry {
4798 hash: self.hash,
4799 elem,
4800 table: self.table,
4801 }
4802 }
4803
4804 /// Converts the `VacantEntryRef` into a mutable reference to the underlying map.
4805 pub fn into_map(self) -> &'map mut HashMap<K, V, S, A> {
4806 self.table
4807 }
4808}
4809
4810impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A>
4811where
4812 K: Eq + Hash,
4813 S: BuildHasher + Default,
4814 A: Default + Allocator,
4815{
4816 #[cfg_attr(feature = "inline-more", inline)]
4817 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
4818 let iter = iter.into_iter();
4819 let mut map =
4820 Self::with_capacity_and_hasher_in(iter.size_hint().0, S::default(), A::default());
4821 iter.for_each(|(k, v)| {
4822 map.insert(k, v);
4823 });
4824 map
4825 }
4826}
4827
4828/// Inserts all new key-values from the iterator and replaces values with existing
4829/// keys with new values returned from the iterator.
4830impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
4831where
4832 K: Eq + Hash,
4833 S: BuildHasher,
4834 A: Allocator,
4835{
4836 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4837 /// Replace values with existing keys with new values returned from the iterator.
4838 ///
4839 /// # Examples
4840 ///
4841 /// ```
4842 /// use hashbrown::hash_map::HashMap;
4843 ///
4844 /// let mut map = HashMap::new();
4845 /// map.insert(1, 100);
4846 ///
4847 /// let some_iter = [(1, 1), (2, 2)].into_iter();
4848 /// map.extend(some_iter);
4849 /// // Replace values with existing keys with new values returned from the iterator.
4850 /// // So that the map.get(&1) doesn't return Some(&100).
4851 /// assert_eq!(map.get(&1), Some(&1));
4852 ///
4853 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4854 /// map.extend(some_vec);
4855 ///
4856 /// let some_arr = [(5, 5), (6, 6)];
4857 /// map.extend(some_arr);
4858 /// let old_map_len = map.len();
4859 ///
4860 /// // You can also extend from another HashMap
4861 /// let mut new_map = HashMap::new();
4862 /// new_map.extend(map);
4863 /// assert_eq!(new_map.len(), old_map_len);
4864 ///
4865 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4866 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4867 /// // items must be sorted to test them against a sorted array.
4868 /// vec.sort_unstable();
4869 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4870 /// ```
4871 #[cfg_attr(feature = "inline-more", inline)]
4872 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
4873 // Keys may be already present or show multiple times in the iterator.
4874 // Reserve the entire hint lower bound if the map is empty.
4875 // Otherwise reserve half the hint (rounded up), so the map
4876 // will only resize twice in the worst case.
4877 let iter = iter.into_iter();
4878 let reserve = if self.is_empty() {
4879 iter.size_hint().0
4880 } else {
4881 iter.size_hint().0.div_ceil(2)
4882 };
4883 self.reserve(reserve);
4884 iter.for_each(move |(k, v)| {
4885 self.insert(k, v);
4886 });
4887 }
4888
4889 #[inline]
4890 #[cfg(feature = "nightly")]
4891 fn extend_one(&mut self, (k, v): (K, V)) {
4892 self.insert(k, v);
4893 }
4894
4895 #[inline]
4896 #[cfg(feature = "nightly")]
4897 fn extend_reserve(&mut self, additional: usize) {
4898 // Keys may be already present or show multiple times in the iterator.
4899 // Reserve the entire hint lower bound if the map is empty.
4900 // Otherwise reserve half the hint (rounded up), so the map
4901 // will only resize twice in the worst case.
4902 let reserve = if self.is_empty() {
4903 additional
4904 } else {
4905 additional.div_ceil(2)
4906 };
4907 self.reserve(reserve);
4908 }
4909}
4910
4911/// Inserts all new key-values from the iterator and replaces values with existing
4912/// keys with new values returned from the iterator.
4913impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
4914where
4915 K: Eq + Hash + Copy,
4916 V: Copy,
4917 S: BuildHasher,
4918 A: Allocator,
4919{
4920 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4921 /// Replace values with existing keys with new values returned from the iterator.
4922 /// The keys and values must implement [`Copy`] trait.
4923 ///
4924 /// # Examples
4925 ///
4926 /// ```
4927 /// use hashbrown::hash_map::HashMap;
4928 ///
4929 /// let mut map = HashMap::new();
4930 /// map.insert(1, 100);
4931 ///
4932 /// let arr = [(1, 1), (2, 2)];
4933 /// let some_iter = arr.iter().map(|(k, v)| (k, v));
4934 /// map.extend(some_iter);
4935 /// // Replace values with existing keys with new values returned from the iterator.
4936 /// // So that the map.get(&1) doesn't return Some(&100).
4937 /// assert_eq!(map.get(&1), Some(&1));
4938 ///
4939 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4940 /// map.extend(some_vec.iter().map(|(k, v)| (k, v)));
4941 ///
4942 /// let some_arr = [(5, 5), (6, 6)];
4943 /// map.extend(some_arr.iter().map(|(k, v)| (k, v)));
4944 ///
4945 /// // You can also extend from another HashMap
4946 /// let mut new_map = HashMap::new();
4947 /// new_map.extend(&map);
4948 /// assert_eq!(new_map, map);
4949 ///
4950 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4951 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4952 /// // items must be sorted to test them against a sorted array.
4953 /// vec.sort_unstable();
4954 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4955 /// ```
4956 #[cfg_attr(feature = "inline-more", inline)]
4957 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
4958 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
4959 }
4960
4961 #[inline]
4962 #[cfg(feature = "nightly")]
4963 fn extend_one(&mut self, (k, v): (&'a K, &'a V)) {
4964 self.insert(*k, *v);
4965 }
4966
4967 #[inline]
4968 #[cfg(feature = "nightly")]
4969 fn extend_reserve(&mut self, additional: usize) {
4970 Extend::<(K, V)>::extend_reserve(self, additional);
4971 }
4972}
4973
4974/// Inserts all new key-values from the iterator and replaces values with existing
4975/// keys with new values returned from the iterator.
4976impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A>
4977where
4978 K: Eq + Hash + Copy,
4979 V: Copy,
4980 S: BuildHasher,
4981 A: Allocator,
4982{
4983 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4984 /// Replace values with existing keys with new values returned from the iterator.
4985 /// The keys and values must implement [`Copy`] trait.
4986 ///
4987 /// # Examples
4988 ///
4989 /// ```
4990 /// use hashbrown::hash_map::HashMap;
4991 ///
4992 /// let mut map = HashMap::new();
4993 /// map.insert(1, 100);
4994 ///
4995 /// let arr = [(1, 1), (2, 2)];
4996 /// let some_iter = arr.iter();
4997 /// map.extend(some_iter);
4998 /// // Replace values with existing keys with new values returned from the iterator.
4999 /// // So that the map.get(&1) doesn't return Some(&100).
5000 /// assert_eq!(map.get(&1), Some(&1));
5001 ///
5002 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
5003 /// map.extend(&some_vec);
5004 ///
5005 /// let some_arr = [(5, 5), (6, 6)];
5006 /// map.extend(&some_arr);
5007 ///
5008 /// let mut vec: Vec<_> = map.into_iter().collect();
5009 /// // The `IntoIter` iterator produces items in arbitrary order, so the
5010 /// // items must be sorted to test them against a sorted array.
5011 /// vec.sort_unstable();
5012 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
5013 /// ```
5014 #[cfg_attr(feature = "inline-more", inline)]
5015 fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
5016 self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
5017 }
5018
5019 #[inline]
5020 #[cfg(feature = "nightly")]
5021 fn extend_one(&mut self, &(k, v): &'a (K, V)) {
5022 self.insert(k, v);
5023 }
5024
5025 #[inline]
5026 #[cfg(feature = "nightly")]
5027 fn extend_reserve(&mut self, additional: usize) {
5028 Extend::<(K, V)>::extend_reserve(self, additional);
5029 }
5030}
5031
5032#[expect(dead_code)]
5033fn assert_covariance() {
5034 fn map_key<'new, S: BuildHasher, A: Allocator>(
5035 v: HashMap<&'static str, u8, S, A>,
5036 ) -> HashMap<&'new str, u8, S, A> {
5037 v
5038 }
5039 fn map_val<'new, S: BuildHasher, A: Allocator>(
5040 v: HashMap<u8, &'static str, S, A>,
5041 ) -> HashMap<u8, &'new str, S, A> {
5042 v
5043 }
5044 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
5045 v
5046 }
5047 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
5048 v
5049 }
5050 fn into_iter_key<'new, A: Allocator>(
5051 v: IntoIter<&'static str, u8, A>,
5052 ) -> IntoIter<&'new str, u8, A> {
5053 v
5054 }
5055 fn into_iter_val<'new, A: Allocator>(
5056 v: IntoIter<u8, &'static str, A>,
5057 ) -> IntoIter<u8, &'new str, A> {
5058 v
5059 }
5060 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
5061 v
5062 }
5063 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
5064 v
5065 }
5066 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
5067 v
5068 }
5069 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
5070 v
5071 }
5072 fn drain<'new, A: Allocator>(
5073 d: Drain<'static, &'static str, &'static str, A>,
5074 ) -> Drain<'new, &'new str, &'new str, A> {
5075 d
5076 }
5077}
5078
5079#[cfg(test)]
5080mod test_map {
5081 use super::DefaultHashBuilder;
5082 use super::Entry::{Occupied, Vacant};
5083 use super::EntryRef;
5084 use super::HashMap;
5085 use crate::alloc::{AllocError, Allocator, Global};
5086 use core::alloc::Layout;
5087 use core::ptr::NonNull;
5088 use core::sync::atomic::{AtomicI8, Ordering};
5089 use rand::{Rng, SeedableRng, rngs::SmallRng};
5090 use std::borrow::ToOwned;
5091 use std::cell::RefCell;
5092 use std::vec::Vec;
5093 use stdalloc::string::String;
5094 use stdalloc::sync::Arc;
5095
5096 #[test]
5097 fn test_zero_capacities() {
5098 type HM = HashMap<i32, i32>;
5099
5100 let m = HM::new();
5101 assert_eq!(m.capacity(), 0);
5102
5103 let m = HM::default();
5104 assert_eq!(m.capacity(), 0);
5105
5106 let m = HM::with_hasher(DefaultHashBuilder::default());
5107 assert_eq!(m.capacity(), 0);
5108
5109 let m = HM::with_capacity(0);
5110 assert_eq!(m.capacity(), 0);
5111
5112 let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
5113 assert_eq!(m.capacity(), 0);
5114
5115 let mut m = HM::new();
5116 m.insert(1, 1);
5117 m.insert(2, 2);
5118 m.remove(&1);
5119 m.remove(&2);
5120 m.shrink_to_fit();
5121 assert_eq!(m.capacity(), 0);
5122
5123 let mut m = HM::new();
5124 m.reserve(0);
5125 assert_eq!(m.capacity(), 0);
5126 }
5127
5128 #[test]
5129 fn test_create_capacity_zero() {
5130 let mut m = HashMap::with_capacity(0);
5131
5132 assert!(m.insert(1, 1).is_none());
5133
5134 assert!(m.contains_key(&1));
5135 assert!(!m.contains_key(&0));
5136 }
5137
5138 #[test]
5139 fn test_insert() {
5140 let mut m = HashMap::new();
5141 assert_eq!(m.len(), 0);
5142 assert!(m.insert(1, 2).is_none());
5143 assert_eq!(m.len(), 1);
5144 assert!(m.insert(2, 4).is_none());
5145 assert_eq!(m.len(), 2);
5146 assert_eq!(*m.get(&1).unwrap(), 2);
5147 assert_eq!(*m.get(&2).unwrap(), 4);
5148 }
5149
5150 #[test]
5151 fn test_clone() {
5152 let mut m = HashMap::new();
5153 assert_eq!(m.len(), 0);
5154 assert!(m.insert(1, 2).is_none());
5155 assert_eq!(m.len(), 1);
5156 assert!(m.insert(2, 4).is_none());
5157 assert_eq!(m.len(), 2);
5158 let m2 = m.clone();
5159 assert_eq!(*m2.get(&1).unwrap(), 2);
5160 assert_eq!(*m2.get(&2).unwrap(), 4);
5161 assert_eq!(m2.len(), 2);
5162 }
5163
5164 #[test]
5165 fn test_clone_from() {
5166 let mut m = HashMap::new();
5167 let mut m2 = HashMap::new();
5168 assert_eq!(m.len(), 0);
5169 assert!(m.insert(1, 2).is_none());
5170 assert_eq!(m.len(), 1);
5171 assert!(m.insert(2, 4).is_none());
5172 assert_eq!(m.len(), 2);
5173 m2.clone_from(&m);
5174 assert_eq!(*m2.get(&1).unwrap(), 2);
5175 assert_eq!(*m2.get(&2).unwrap(), 4);
5176 assert_eq!(m2.len(), 2);
5177 }
5178
5179 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = const { RefCell::new(Vec::new()) } }
5180
5181 #[derive(Hash, PartialEq, Eq)]
5182 struct Droppable {
5183 k: usize,
5184 }
5185
5186 impl Droppable {
5187 fn new(k: usize) -> Droppable {
5188 DROP_VECTOR.with(|slot| {
5189 slot.borrow_mut()[k] += 1;
5190 });
5191
5192 Droppable { k }
5193 }
5194 }
5195
5196 impl Drop for Droppable {
5197 fn drop(&mut self) {
5198 DROP_VECTOR.with(|slot| {
5199 slot.borrow_mut()[self.k] -= 1;
5200 });
5201 }
5202 }
5203
5204 impl Clone for Droppable {
5205 fn clone(&self) -> Self {
5206 Droppable::new(self.k)
5207 }
5208 }
5209
5210 #[test]
5211 fn test_drops() {
5212 DROP_VECTOR.with(|slot| {
5213 *slot.borrow_mut() = vec![0; 200];
5214 });
5215
5216 {
5217 let mut m = HashMap::new();
5218
5219 DROP_VECTOR.with(|v| {
5220 for i in 0..200 {
5221 assert_eq!(v.borrow()[i], 0);
5222 }
5223 });
5224
5225 for i in 0..100 {
5226 let d1 = Droppable::new(i);
5227 let d2 = Droppable::new(i + 100);
5228 m.insert(d1, d2);
5229 }
5230
5231 DROP_VECTOR.with(|v| {
5232 for i in 0..200 {
5233 assert_eq!(v.borrow()[i], 1);
5234 }
5235 });
5236
5237 for i in 0..50 {
5238 let k = Droppable::new(i);
5239 let v = m.remove(&k);
5240
5241 assert!(v.is_some());
5242
5243 DROP_VECTOR.with(|v| {
5244 assert_eq!(v.borrow()[i], 1);
5245 assert_eq!(v.borrow()[i + 100], 1);
5246 });
5247 }
5248
5249 DROP_VECTOR.with(|v| {
5250 for i in 0..50 {
5251 assert_eq!(v.borrow()[i], 0);
5252 assert_eq!(v.borrow()[i + 100], 0);
5253 }
5254
5255 for i in 50..100 {
5256 assert_eq!(v.borrow()[i], 1);
5257 assert_eq!(v.borrow()[i + 100], 1);
5258 }
5259 });
5260 }
5261
5262 DROP_VECTOR.with(|v| {
5263 for i in 0..200 {
5264 assert_eq!(v.borrow()[i], 0);
5265 }
5266 });
5267 }
5268
5269 #[test]
5270 fn test_into_iter_drops() {
5271 DROP_VECTOR.with(|v| {
5272 *v.borrow_mut() = vec![0; 200];
5273 });
5274
5275 let hm = {
5276 let mut hm = HashMap::new();
5277
5278 DROP_VECTOR.with(|v| {
5279 for i in 0..200 {
5280 assert_eq!(v.borrow()[i], 0);
5281 }
5282 });
5283
5284 for i in 0..100 {
5285 let d1 = Droppable::new(i);
5286 let d2 = Droppable::new(i + 100);
5287 hm.insert(d1, d2);
5288 }
5289
5290 DROP_VECTOR.with(|v| {
5291 for i in 0..200 {
5292 assert_eq!(v.borrow()[i], 1);
5293 }
5294 });
5295
5296 hm
5297 };
5298
5299 // By the way, ensure that cloning doesn't screw up the dropping.
5300 drop(hm.clone());
5301
5302 {
5303 let mut half = hm.into_iter().take(50);
5304
5305 DROP_VECTOR.with(|v| {
5306 for i in 0..200 {
5307 assert_eq!(v.borrow()[i], 1);
5308 }
5309 });
5310
5311 for _ in half.by_ref() {}
5312
5313 DROP_VECTOR.with(|v| {
5314 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
5315
5316 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
5317
5318 assert_eq!(nk, 50);
5319 assert_eq!(nv, 50);
5320 });
5321 };
5322
5323 DROP_VECTOR.with(|v| {
5324 for i in 0..200 {
5325 assert_eq!(v.borrow()[i], 0);
5326 }
5327 });
5328 }
5329
5330 #[test]
5331 fn test_empty_remove() {
5332 let mut m: HashMap<i32, bool> = HashMap::new();
5333 assert_eq!(m.remove(&0), None);
5334 }
5335
5336 #[test]
5337 fn test_empty_entry() {
5338 let mut m: HashMap<i32, bool> = HashMap::new();
5339 match m.entry(0) {
5340 Occupied(_) => panic!(),
5341 Vacant(_) => {}
5342 }
5343 assert!(*m.entry(0).or_insert(true));
5344 assert_eq!(m.len(), 1);
5345 }
5346
5347 #[test]
5348 fn test_empty_entry_ref() {
5349 let mut m: HashMap<std::string::String, bool> = HashMap::new();
5350 match m.entry_ref("poneyland") {
5351 EntryRef::Occupied(_) => panic!(),
5352 EntryRef::Vacant(_) => {}
5353 }
5354 assert!(*m.entry_ref("poneyland").or_insert(true));
5355 assert_eq!(m.len(), 1);
5356 }
5357
5358 #[test]
5359 fn test_empty_iter() {
5360 let mut m: HashMap<i32, bool> = HashMap::new();
5361 assert_eq!(m.drain().next(), None);
5362 assert_eq!(m.keys().next(), None);
5363 assert_eq!(m.values().next(), None);
5364 assert_eq!(m.values_mut().next(), None);
5365 assert_eq!(m.iter().next(), None);
5366 assert_eq!(m.iter_mut().next(), None);
5367 assert_eq!(m.len(), 0);
5368 assert!(m.is_empty());
5369 assert_eq!(m.into_iter().next(), None);
5370 }
5371
5372 #[test]
5373 #[cfg_attr(miri, ignore)] // FIXME: takes too long
5374 fn test_lots_of_insertions() {
5375 let mut m = HashMap::new();
5376
5377 // Try this a few times to make sure we never screw up the hashmap's
5378 // internal state.
5379 for _ in 0..10 {
5380 assert!(m.is_empty());
5381
5382 for i in 1..1001 {
5383 assert!(m.insert(i, i).is_none());
5384
5385 for j in 1..=i {
5386 let r = m.get(&j);
5387 assert_eq!(r, Some(&j));
5388 }
5389
5390 for j in i + 1..1001 {
5391 let r = m.get(&j);
5392 assert_eq!(r, None);
5393 }
5394 }
5395
5396 for i in 1001..2001 {
5397 assert!(!m.contains_key(&i));
5398 }
5399
5400 // remove forwards
5401 for i in 1..1001 {
5402 assert!(m.remove(&i).is_some());
5403
5404 for j in 1..=i {
5405 assert!(!m.contains_key(&j));
5406 }
5407
5408 for j in i + 1..1001 {
5409 assert!(m.contains_key(&j));
5410 }
5411 }
5412
5413 for i in 1..1001 {
5414 assert!(!m.contains_key(&i));
5415 }
5416
5417 for i in 1..1001 {
5418 assert!(m.insert(i, i).is_none());
5419 }
5420
5421 // remove backwards
5422 for i in (1..1001).rev() {
5423 assert!(m.remove(&i).is_some());
5424
5425 for j in i..1001 {
5426 assert!(!m.contains_key(&j));
5427 }
5428
5429 for j in 1..i {
5430 assert!(m.contains_key(&j));
5431 }
5432 }
5433 }
5434 }
5435
5436 #[test]
5437 fn test_find_mut() {
5438 let mut m = HashMap::new();
5439 assert!(m.insert(1, 12).is_none());
5440 assert!(m.insert(2, 8).is_none());
5441 assert!(m.insert(5, 14).is_none());
5442 let new = 100;
5443 match m.get_mut(&5) {
5444 None => panic!(),
5445 Some(x) => *x = new,
5446 }
5447 assert_eq!(m.get(&5), Some(&new));
5448 let mut hashmap: HashMap<i32, String> = HashMap::default();
5449 let key = &1;
5450 let result = hashmap.get_mut(key);
5451 assert!(result.is_none());
5452 }
5453
5454 #[test]
5455 fn test_insert_overwrite() {
5456 let mut m = HashMap::new();
5457 assert!(m.insert(1, 2).is_none());
5458 assert_eq!(*m.get(&1).unwrap(), 2);
5459 assert!(m.insert(1, 3).is_some());
5460 assert_eq!(*m.get(&1).unwrap(), 3);
5461 }
5462
5463 #[test]
5464 fn test_insert_conflicts() {
5465 let mut m = HashMap::with_capacity(4);
5466 assert!(m.insert(1, 2).is_none());
5467 assert!(m.insert(5, 3).is_none());
5468 assert!(m.insert(9, 4).is_none());
5469 assert_eq!(*m.get(&9).unwrap(), 4);
5470 assert_eq!(*m.get(&5).unwrap(), 3);
5471 assert_eq!(*m.get(&1).unwrap(), 2);
5472 }
5473
5474 #[test]
5475 fn test_conflict_remove() {
5476 let mut m = HashMap::with_capacity(4);
5477 assert!(m.insert(1, 2).is_none());
5478 assert_eq!(*m.get(&1).unwrap(), 2);
5479 assert!(m.insert(5, 3).is_none());
5480 assert_eq!(*m.get(&1).unwrap(), 2);
5481 assert_eq!(*m.get(&5).unwrap(), 3);
5482 assert!(m.insert(9, 4).is_none());
5483 assert_eq!(*m.get(&1).unwrap(), 2);
5484 assert_eq!(*m.get(&5).unwrap(), 3);
5485 assert_eq!(*m.get(&9).unwrap(), 4);
5486 assert!(m.remove(&1).is_some());
5487 assert_eq!(*m.get(&9).unwrap(), 4);
5488 assert_eq!(*m.get(&5).unwrap(), 3);
5489 }
5490
5491 #[test]
5492 fn test_insert_unique_unchecked() {
5493 let mut map = HashMap::new();
5494 let (k1, v1) = unsafe { map.insert_unique_unchecked(10, 11) };
5495 assert_eq!((&10, &mut 11), (k1, v1));
5496 let (k2, v2) = unsafe { map.insert_unique_unchecked(20, 21) };
5497 assert_eq!((&20, &mut 21), (k2, v2));
5498 assert_eq!(Some(&11), map.get(&10));
5499 assert_eq!(Some(&21), map.get(&20));
5500 assert_eq!(None, map.get(&30));
5501 }
5502
5503 #[test]
5504 fn test_is_empty() {
5505 let mut m = HashMap::with_capacity(4);
5506 assert!(m.insert(1, 2).is_none());
5507 assert!(!m.is_empty());
5508 assert!(m.remove(&1).is_some());
5509 assert!(m.is_empty());
5510 }
5511
5512 #[test]
5513 fn test_remove() {
5514 let mut m = HashMap::new();
5515 m.insert(1, 2);
5516 assert_eq!(m.remove(&1), Some(2));
5517 assert_eq!(m.remove(&1), None);
5518 }
5519
5520 #[test]
5521 fn test_remove_entry() {
5522 let mut m = HashMap::new();
5523 m.insert(1, 2);
5524 assert_eq!(m.remove_entry(&1), Some((1, 2)));
5525 assert_eq!(m.remove(&1), None);
5526 }
5527
5528 #[test]
5529 fn test_iterate() {
5530 let mut m = HashMap::with_capacity(4);
5531 for i in 0..32 {
5532 assert!(m.insert(i, i * 2).is_none());
5533 }
5534 assert_eq!(m.len(), 32);
5535
5536 let mut observed: u32 = 0;
5537
5538 for (k, v) in &m {
5539 assert_eq!(*v, *k * 2);
5540 observed |= 1 << *k;
5541 }
5542 assert_eq!(observed, 0xFFFF_FFFF);
5543 }
5544
5545 #[test]
5546 fn test_keys() {
5547 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5548 let map: HashMap<_, _> = vec.into_iter().collect();
5549 let keys: Vec<_> = map.keys().copied().collect();
5550 assert_eq!(keys.len(), 3);
5551 assert!(keys.contains(&1));
5552 assert!(keys.contains(&2));
5553 assert!(keys.contains(&3));
5554 }
5555
5556 #[test]
5557 fn test_values() {
5558 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5559 let map: HashMap<_, _> = vec.into_iter().collect();
5560 let values: Vec<_> = map.values().copied().collect();
5561 assert_eq!(values.len(), 3);
5562 assert!(values.contains(&'a'));
5563 assert!(values.contains(&'b'));
5564 assert!(values.contains(&'c'));
5565 }
5566
5567 #[test]
5568 fn test_values_mut() {
5569 let vec = vec![(1, 1), (2, 2), (3, 3)];
5570 let mut map: HashMap<_, _> = vec.into_iter().collect();
5571 for value in map.values_mut() {
5572 *value *= 2;
5573 }
5574 let values: Vec<_> = map.values().copied().collect();
5575 assert_eq!(values.len(), 3);
5576 assert!(values.contains(&2));
5577 assert!(values.contains(&4));
5578 assert!(values.contains(&6));
5579 }
5580
5581 #[test]
5582 fn test_into_keys() {
5583 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5584 let map: HashMap<_, _> = vec.into_iter().collect();
5585 let keys: Vec<_> = map.into_keys().collect();
5586
5587 assert_eq!(keys.len(), 3);
5588 assert!(keys.contains(&1));
5589 assert!(keys.contains(&2));
5590 assert!(keys.contains(&3));
5591 }
5592
5593 #[test]
5594 fn test_into_values() {
5595 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5596 let map: HashMap<_, _> = vec.into_iter().collect();
5597 let values: Vec<_> = map.into_values().collect();
5598
5599 assert_eq!(values.len(), 3);
5600 assert!(values.contains(&'a'));
5601 assert!(values.contains(&'b'));
5602 assert!(values.contains(&'c'));
5603 }
5604
5605 #[test]
5606 fn test_find() {
5607 let mut m = HashMap::new();
5608 assert!(m.get(&1).is_none());
5609 m.insert(1, 2);
5610 match m.get(&1) {
5611 None => panic!(),
5612 Some(v) => assert_eq!(*v, 2),
5613 }
5614 }
5615
5616 #[test]
5617 fn test_eq() {
5618 let mut m1 = HashMap::new();
5619 m1.insert(1, 2);
5620 m1.insert(2, 3);
5621 m1.insert(3, 4);
5622
5623 let mut m2 = HashMap::new();
5624 m2.insert(1, 2);
5625 m2.insert(2, 3);
5626
5627 assert_ne!(m1, m2);
5628
5629 m2.insert(3, 4);
5630
5631 assert_eq!(m1, m2);
5632 }
5633
5634 #[test]
5635 fn test_show() {
5636 let mut map = HashMap::new();
5637 let empty: HashMap<i32, i32> = HashMap::new();
5638
5639 map.insert(1, 2);
5640 map.insert(3, 4);
5641
5642 let map_str = format!("{map:?}");
5643
5644 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
5645 assert_eq!(format!("{empty:?}"), "{}");
5646 }
5647
5648 #[test]
5649 fn test_expand() {
5650 let mut m = HashMap::new();
5651
5652 assert_eq!(m.len(), 0);
5653 assert!(m.is_empty());
5654
5655 let mut i = 0;
5656 let old_raw_cap = m.raw_capacity();
5657 while old_raw_cap == m.raw_capacity() {
5658 m.insert(i, i);
5659 i += 1;
5660 }
5661
5662 assert_eq!(m.len(), i);
5663 assert!(!m.is_empty());
5664 }
5665
5666 #[test]
5667 fn test_behavior_resize_policy() {
5668 let mut m = HashMap::new();
5669
5670 assert_eq!(m.len(), 0);
5671 assert_eq!(m.raw_capacity(), 1);
5672 assert!(m.is_empty());
5673
5674 m.insert(0, 0);
5675 m.remove(&0);
5676 assert!(m.is_empty());
5677 let initial_raw_cap = m.raw_capacity();
5678 m.reserve(initial_raw_cap);
5679 let raw_cap = m.raw_capacity();
5680
5681 assert_eq!(raw_cap, initial_raw_cap * 2);
5682
5683 let mut i = 0;
5684 for _ in 0..raw_cap * 3 / 4 {
5685 m.insert(i, i);
5686 i += 1;
5687 }
5688 // three quarters full
5689
5690 assert_eq!(m.len(), i);
5691 assert_eq!(m.raw_capacity(), raw_cap);
5692
5693 for _ in 0..raw_cap / 4 {
5694 m.insert(i, i);
5695 i += 1;
5696 }
5697 // half full
5698
5699 let new_raw_cap = m.raw_capacity();
5700 assert_eq!(new_raw_cap, raw_cap * 2);
5701
5702 for _ in 0..raw_cap / 2 - 1 {
5703 i -= 1;
5704 m.remove(&i);
5705 assert_eq!(m.raw_capacity(), new_raw_cap);
5706 }
5707 // A little more than one quarter full.
5708 m.shrink_to_fit();
5709 assert_eq!(m.raw_capacity(), raw_cap);
5710 // again, a little more than half full
5711 for _ in 0..raw_cap / 2 {
5712 i -= 1;
5713 m.remove(&i);
5714 }
5715 m.shrink_to_fit();
5716
5717 assert_eq!(m.len(), i);
5718 assert!(!m.is_empty());
5719 assert_eq!(m.raw_capacity(), initial_raw_cap);
5720 }
5721
5722 #[test]
5723 fn test_reserve_shrink_to_fit() {
5724 let mut m = HashMap::new();
5725 m.insert(0, 0);
5726 m.remove(&0);
5727 assert!(m.capacity() >= m.len());
5728 for i in 0..128 {
5729 m.insert(i, i);
5730 }
5731 m.reserve(256);
5732
5733 let usable_cap = m.capacity();
5734 for i in 128..(128 + 256) {
5735 m.insert(i, i);
5736 assert_eq!(m.capacity(), usable_cap);
5737 }
5738
5739 for i in 100..(128 + 256) {
5740 assert_eq!(m.remove(&i), Some(i));
5741 }
5742 m.shrink_to_fit();
5743
5744 assert_eq!(m.len(), 100);
5745 assert!(!m.is_empty());
5746 assert!(m.capacity() >= m.len());
5747
5748 for i in 0..100 {
5749 assert_eq!(m.remove(&i), Some(i));
5750 }
5751 m.shrink_to_fit();
5752 m.insert(0, 0);
5753
5754 assert_eq!(m.len(), 1);
5755 assert!(m.capacity() >= m.len());
5756 assert_eq!(m.remove(&0), Some(0));
5757 }
5758
5759 #[test]
5760 fn test_from_iter() {
5761 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5762
5763 let map: HashMap<_, _> = xs.iter().copied().collect();
5764
5765 for &(k, v) in &xs {
5766 assert_eq!(map.get(&k), Some(&v));
5767 }
5768
5769 assert_eq!(map.iter().len(), xs.len() - 1);
5770 }
5771
5772 #[test]
5773 fn test_size_hint() {
5774 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5775
5776 let map: HashMap<_, _> = xs.iter().copied().collect();
5777
5778 let mut iter = map.iter();
5779
5780 for _ in iter.by_ref().take(3) {}
5781
5782 assert_eq!(iter.size_hint(), (3, Some(3)));
5783 }
5784
5785 #[test]
5786 fn test_iter_len() {
5787 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5788
5789 let map: HashMap<_, _> = xs.iter().copied().collect();
5790
5791 let mut iter = map.iter();
5792
5793 for _ in iter.by_ref().take(3) {}
5794
5795 assert_eq!(iter.len(), 3);
5796 }
5797
5798 #[test]
5799 fn test_mut_size_hint() {
5800 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5801
5802 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5803
5804 let mut iter = map.iter_mut();
5805
5806 for _ in iter.by_ref().take(3) {}
5807
5808 assert_eq!(iter.size_hint(), (3, Some(3)));
5809 }
5810
5811 #[test]
5812 fn test_iter_mut_len() {
5813 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5814
5815 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5816
5817 let mut iter = map.iter_mut();
5818
5819 for _ in iter.by_ref().take(3) {}
5820
5821 assert_eq!(iter.len(), 3);
5822 }
5823
5824 #[test]
5825 fn test_index() {
5826 let mut map = HashMap::new();
5827
5828 map.insert(1, 2);
5829 map.insert(2, 1);
5830 map.insert(3, 4);
5831
5832 assert_eq!(map[&2], 1);
5833 }
5834
5835 #[test]
5836 #[should_panic]
5837 fn test_index_nonexistent() {
5838 let mut map = HashMap::new();
5839
5840 map.insert(1, 2);
5841 map.insert(2, 1);
5842 map.insert(3, 4);
5843
5844 _ = map[&4];
5845 }
5846
5847 #[test]
5848 fn test_entry() {
5849 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
5850
5851 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5852
5853 // Existing key (insert)
5854 match map.entry(1) {
5855 Vacant(_) => unreachable!(),
5856 Occupied(mut view) => {
5857 assert_eq!(view.get(), &10);
5858 assert_eq!(view.insert(100), 10);
5859 }
5860 }
5861 assert_eq!(map.get(&1).unwrap(), &100);
5862 assert_eq!(map.len(), 6);
5863
5864 // Existing key (update)
5865 match map.entry(2) {
5866 Vacant(_) => unreachable!(),
5867 Occupied(mut view) => {
5868 let v = view.get_mut();
5869 let new_v = (*v) * 10;
5870 *v = new_v;
5871 }
5872 }
5873 assert_eq!(map.get(&2).unwrap(), &200);
5874 assert_eq!(map.len(), 6);
5875
5876 // Existing key (take)
5877 match map.entry(3) {
5878 Vacant(_) => unreachable!(),
5879 Occupied(view) => {
5880 assert_eq!(view.remove(), 30);
5881 }
5882 }
5883 assert_eq!(map.get(&3), None);
5884 assert_eq!(map.len(), 5);
5885
5886 // Inexistent key (insert)
5887 match map.entry(10) {
5888 Occupied(_) => unreachable!(),
5889 Vacant(view) => {
5890 assert_eq!(*view.insert(1000), 1000);
5891 }
5892 }
5893 assert_eq!(map.get(&10).unwrap(), &1000);
5894 assert_eq!(map.len(), 6);
5895 }
5896
5897 #[test]
5898 fn test_entry_ref() {
5899 let xs = [
5900 ("One".to_owned(), 10),
5901 ("Two".to_owned(), 20),
5902 ("Three".to_owned(), 30),
5903 ("Four".to_owned(), 40),
5904 ("Five".to_owned(), 50),
5905 ("Six".to_owned(), 60),
5906 ];
5907
5908 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
5909
5910 // Existing key (insert)
5911 match map.entry_ref("One") {
5912 EntryRef::Vacant(_) => unreachable!(),
5913 EntryRef::Occupied(mut view) => {
5914 assert_eq!(view.get(), &10);
5915 assert_eq!(view.insert(100), 10);
5916 }
5917 }
5918 assert_eq!(map.get("One").unwrap(), &100);
5919 assert_eq!(map.len(), 6);
5920
5921 // Existing key (update)
5922 match map.entry_ref("Two") {
5923 EntryRef::Vacant(_) => unreachable!(),
5924 EntryRef::Occupied(mut view) => {
5925 let v = view.get_mut();
5926 let new_v = (*v) * 10;
5927 *v = new_v;
5928 }
5929 }
5930 assert_eq!(map.get("Two").unwrap(), &200);
5931 assert_eq!(map.len(), 6);
5932
5933 // Existing key (take)
5934 match map.entry_ref("Three") {
5935 EntryRef::Vacant(_) => unreachable!(),
5936 EntryRef::Occupied(view) => {
5937 assert_eq!(view.remove(), 30);
5938 }
5939 }
5940 assert_eq!(map.get("Three"), None);
5941 assert_eq!(map.len(), 5);
5942
5943 // Inexistent key (insert)
5944 match map.entry_ref("Ten") {
5945 EntryRef::Occupied(_) => unreachable!(),
5946 EntryRef::Vacant(view) => {
5947 assert_eq!(*view.insert(1000), 1000);
5948 }
5949 }
5950 assert_eq!(map.get("Ten").unwrap(), &1000);
5951 assert_eq!(map.len(), 6);
5952 }
5953
5954 #[test]
5955 fn test_entry_take_doesnt_corrupt() {
5956 #![expect(deprecated)] //rand
5957 // Test for #19292
5958 fn check(m: &HashMap<i32, ()>) {
5959 for k in m.keys() {
5960 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5961 }
5962 }
5963
5964 let mut m = HashMap::new();
5965
5966 let mut rng = {
5967 let seed = u64::from_le_bytes(*b"testseed");
5968 SmallRng::seed_from_u64(seed)
5969 };
5970
5971 // Populate the map with some items.
5972 for _ in 0..50 {
5973 let x = rng.gen_range(-10..10);
5974 m.insert(x, ());
5975 }
5976
5977 for _ in 0..1000 {
5978 let x = rng.gen_range(-10..10);
5979 match m.entry(x) {
5980 Vacant(_) => {}
5981 Occupied(e) => {
5982 e.remove();
5983 }
5984 }
5985
5986 check(&m);
5987 }
5988 }
5989
5990 #[test]
5991 fn test_entry_ref_take_doesnt_corrupt() {
5992 #![expect(deprecated)] //rand
5993 // Test for #19292
5994 fn check(m: &HashMap<std::string::String, ()>) {
5995 for k in m.keys() {
5996 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5997 }
5998 }
5999
6000 let mut m = HashMap::new();
6001
6002 let mut rng = {
6003 let seed = u64::from_le_bytes(*b"testseed");
6004 SmallRng::seed_from_u64(seed)
6005 };
6006
6007 // Populate the map with some items.
6008 for _ in 0..50 {
6009 let mut x = std::string::String::with_capacity(1);
6010 x.push(rng.gen_range('a'..='z'));
6011 m.insert(x, ());
6012 }
6013
6014 for _ in 0..1000 {
6015 let mut x = std::string::String::with_capacity(1);
6016 x.push(rng.gen_range('a'..='z'));
6017 match m.entry_ref(x.as_str()) {
6018 EntryRef::Vacant(_) => {}
6019 EntryRef::Occupied(e) => {
6020 e.remove();
6021 }
6022 }
6023
6024 check(&m);
6025 }
6026 }
6027
6028 #[test]
6029 fn test_extend_ref_k_ref_v() {
6030 let mut a = HashMap::new();
6031 a.insert(1, "one");
6032 let mut b = HashMap::new();
6033 b.insert(2, "two");
6034 b.insert(3, "three");
6035
6036 a.extend(&b);
6037
6038 assert_eq!(a.len(), 3);
6039 assert_eq!(a[&1], "one");
6040 assert_eq!(a[&2], "two");
6041 assert_eq!(a[&3], "three");
6042 }
6043
6044 #[test]
6045 fn test_extend_ref_kv_tuple() {
6046 use std::ops::AddAssign;
6047 let mut a = HashMap::new();
6048 a.insert(0, 0);
6049
6050 fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
6051 let mut outs: [(T, T); N] = [(start, start); N];
6052 let mut element = step;
6053 outs.iter_mut().skip(1).for_each(|(k, v)| {
6054 *k += element;
6055 *v += element;
6056 element += step;
6057 });
6058 outs
6059 }
6060
6061 let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
6062 let iter = for_iter.iter();
6063 let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
6064 a.extend(iter);
6065 a.extend(&vec);
6066 a.extend(create_arr::<i32, 100>(200, 1));
6067
6068 assert_eq!(a.len(), 300);
6069
6070 for item in 0..300 {
6071 assert_eq!(a[&item], item);
6072 }
6073 }
6074
6075 #[test]
6076 fn test_capacity_not_less_than_len() {
6077 let mut a = HashMap::new();
6078 let mut item = 0;
6079
6080 for _ in 0..116 {
6081 a.insert(item, 0);
6082 item += 1;
6083 }
6084
6085 assert!(a.capacity() > a.len());
6086
6087 let free = a.capacity() - a.len();
6088 for _ in 0..free {
6089 a.insert(item, 0);
6090 item += 1;
6091 }
6092
6093 assert_eq!(a.len(), a.capacity());
6094
6095 // Insert at capacity should cause allocation.
6096 a.insert(item, 0);
6097 assert!(a.capacity() > a.len());
6098 }
6099
6100 #[test]
6101 fn test_occupied_entry_key() {
6102 let mut a = HashMap::new();
6103 let key = "hello there";
6104 let value = "value goes here";
6105 assert!(a.is_empty());
6106 a.insert(key, value);
6107 assert_eq!(a.len(), 1);
6108 assert_eq!(a[key], value);
6109
6110 match a.entry(key) {
6111 Vacant(_) => panic!(),
6112 Occupied(e) => assert_eq!(key, *e.key()),
6113 }
6114 assert_eq!(a.len(), 1);
6115 assert_eq!(a[key], value);
6116 }
6117
6118 #[test]
6119 fn test_occupied_entry_ref_key() {
6120 let mut a = HashMap::new();
6121 let key = "hello there";
6122 let value = "value goes here";
6123 assert!(a.is_empty());
6124 a.insert(key.to_owned(), value);
6125 assert_eq!(a.len(), 1);
6126 assert_eq!(a[key], value);
6127
6128 match a.entry_ref(key) {
6129 EntryRef::Vacant(_) => panic!(),
6130 EntryRef::Occupied(e) => assert_eq!(key, e.key()),
6131 }
6132 assert_eq!(a.len(), 1);
6133 assert_eq!(a[key], value);
6134 }
6135
6136 #[test]
6137 fn test_vacant_entry_key() {
6138 let mut a = HashMap::new();
6139 let key = "hello there";
6140 let value = "value goes here";
6141
6142 assert!(a.is_empty());
6143 match a.entry(key) {
6144 Occupied(_) => panic!(),
6145 Vacant(e) => {
6146 assert_eq!(key, *e.key());
6147 e.insert(value);
6148 }
6149 }
6150 assert_eq!(a.len(), 1);
6151 assert_eq!(a[key], value);
6152 }
6153
6154 #[test]
6155 fn test_vacant_entry_ref_key() {
6156 let mut a: HashMap<std::string::String, &str> = HashMap::new();
6157 let key = "hello there";
6158 let value = "value goes here";
6159
6160 assert!(a.is_empty());
6161 match a.entry_ref(key) {
6162 EntryRef::Occupied(_) => panic!(),
6163 EntryRef::Vacant(e) => {
6164 assert_eq!(key, e.key());
6165 e.insert(value);
6166 }
6167 }
6168 assert_eq!(a.len(), 1);
6169 assert_eq!(a[key], value);
6170 }
6171
6172 #[test]
6173 fn test_occupied_entry_replace_entry_with() {
6174 let mut a = HashMap::new();
6175
6176 let key = "a key";
6177 let value = "an initial value";
6178 let new_value = "a new value";
6179
6180 let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
6181 assert_eq!(k, &key);
6182 assert_eq!(v, value);
6183 Some(new_value)
6184 });
6185
6186 match entry {
6187 Occupied(e) => {
6188 assert_eq!(e.key(), &key);
6189 assert_eq!(e.get(), &new_value);
6190 }
6191 Vacant(_) => panic!(),
6192 }
6193
6194 assert_eq!(a[key], new_value);
6195 assert_eq!(a.len(), 1);
6196
6197 let entry = match a.entry(key) {
6198 Occupied(e) => e.replace_entry_with(|k, v| {
6199 assert_eq!(k, &key);
6200 assert_eq!(v, new_value);
6201 None
6202 }),
6203 Vacant(_) => panic!(),
6204 };
6205
6206 match entry {
6207 Vacant(e) => assert_eq!(e.key(), &key),
6208 Occupied(_) => panic!(),
6209 }
6210
6211 assert!(!a.contains_key(key));
6212 assert_eq!(a.len(), 0);
6213 }
6214
6215 #[test]
6216 fn test_entry_and_replace_entry_with() {
6217 let mut a = HashMap::new();
6218
6219 let key = "a key";
6220 let value = "an initial value";
6221 let new_value = "a new value";
6222
6223 let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
6224
6225 match entry {
6226 Vacant(e) => assert_eq!(e.key(), &key),
6227 Occupied(_) => panic!(),
6228 }
6229
6230 a.insert(key, value);
6231
6232 let entry = a.entry(key).and_replace_entry_with(|k, v| {
6233 assert_eq!(k, &key);
6234 assert_eq!(v, value);
6235 Some(new_value)
6236 });
6237
6238 match entry {
6239 Occupied(e) => {
6240 assert_eq!(e.key(), &key);
6241 assert_eq!(e.get(), &new_value);
6242 }
6243 Vacant(_) => panic!(),
6244 }
6245
6246 assert_eq!(a[key], new_value);
6247 assert_eq!(a.len(), 1);
6248
6249 let entry = a.entry(key).and_replace_entry_with(|k, v| {
6250 assert_eq!(k, &key);
6251 assert_eq!(v, new_value);
6252 None
6253 });
6254
6255 match entry {
6256 Vacant(e) => assert_eq!(e.key(), &key),
6257 Occupied(_) => panic!(),
6258 }
6259
6260 assert!(!a.contains_key(key));
6261 assert_eq!(a.len(), 0);
6262 }
6263
6264 #[test]
6265 fn test_replace_entry_with_doesnt_corrupt() {
6266 #![expect(deprecated)] //rand
6267 // Test for #19292
6268 fn check(m: &HashMap<i32, ()>) {
6269 for k in m.keys() {
6270 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
6271 }
6272 }
6273
6274 let mut m = HashMap::new();
6275
6276 let mut rng = {
6277 let seed = u64::from_le_bytes(*b"testseed");
6278 SmallRng::seed_from_u64(seed)
6279 };
6280
6281 // Populate the map with some items.
6282 for _ in 0..50 {
6283 let x = rng.gen_range(-10..10);
6284 m.insert(x, ());
6285 }
6286
6287 for _ in 0..1000 {
6288 let x = rng.gen_range(-10..10);
6289 m.entry(x).and_replace_entry_with(|_, _| None);
6290 check(&m);
6291 }
6292 }
6293
6294 #[test]
6295 fn test_retain() {
6296 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
6297
6298 map.retain(|&k, _| k % 2 == 0);
6299 assert_eq!(map.len(), 50);
6300 assert_eq!(map[&2], 20);
6301 assert_eq!(map[&4], 40);
6302 assert_eq!(map[&6], 60);
6303 }
6304
6305 #[test]
6306 fn test_extract_if() {
6307 {
6308 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
6309 let drained = map.extract_if(|&k, _| k % 2 == 0);
6310 let mut out = drained.collect::<Vec<_>>();
6311 out.sort_unstable();
6312 assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
6313 assert_eq!(map.len(), 4);
6314 }
6315 {
6316 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
6317 map.extract_if(|&k, _| k % 2 == 0).for_each(drop);
6318 assert_eq!(map.len(), 4);
6319 }
6320 }
6321
6322 #[test]
6323 #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613)
6324 fn test_try_reserve() {
6325 use crate::TryReserveError::{AllocError, CapacityOverflow};
6326
6327 const MAX_ISIZE: usize = isize::MAX as usize;
6328
6329 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
6330
6331 if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
6332 } else {
6333 panic!("usize::MAX should trigger an overflow!");
6334 }
6335
6336 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
6337 } else {
6338 panic!("isize::MAX should trigger an overflow!");
6339 }
6340
6341 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
6342 } else {
6343 // This may succeed if there is enough free memory. Attempt to
6344 // allocate a few more hashmaps to ensure the allocation will fail.
6345 let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
6346 let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
6347 let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
6348 let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
6349 let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
6350 if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
6351 } else {
6352 panic!("isize::MAX / 5 should trigger an OOM!");
6353 }
6354 }
6355 }
6356
6357 #[test]
6358 fn test_const_with_hasher() {
6359 use core::hash::BuildHasher;
6360 use std::collections::hash_map::DefaultHasher;
6361
6362 #[derive(Clone)]
6363 struct MyHasher;
6364 impl BuildHasher for MyHasher {
6365 type Hasher = DefaultHasher;
6366
6367 fn build_hasher(&self) -> DefaultHasher {
6368 DefaultHasher::new()
6369 }
6370 }
6371
6372 const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> =
6373 HashMap::with_hasher(MyHasher);
6374
6375 let mut map = EMPTY_MAP;
6376 map.insert(17, "seventeen".to_owned());
6377 assert_eq!("seventeen", map[&17]);
6378 }
6379
6380 #[test]
6381 fn test_get_disjoint_mut() {
6382 let mut map = HashMap::new();
6383 map.insert("foo".to_owned(), 0);
6384 map.insert("bar".to_owned(), 10);
6385 map.insert("baz".to_owned(), 20);
6386 map.insert("qux".to_owned(), 30);
6387
6388 let xs = map.get_disjoint_mut(["foo", "qux"]);
6389 assert_eq!(xs, [Some(&mut 0), Some(&mut 30)]);
6390
6391 let xs = map.get_disjoint_mut(["foo", "dud"]);
6392 assert_eq!(xs, [Some(&mut 0), None]);
6393
6394 let ys = map.get_disjoint_key_value_mut(["bar", "baz"]);
6395 assert_eq!(
6396 ys,
6397 [
6398 Some((&"bar".to_owned(), &mut 10)),
6399 Some((&"baz".to_owned(), &mut 20))
6400 ],
6401 );
6402
6403 let ys = map.get_disjoint_key_value_mut(["bar", "dip"]);
6404 assert_eq!(ys, [Some((&"bar".to_owned(), &mut 10)), None]);
6405 }
6406
6407 #[test]
6408 #[should_panic = "duplicate keys found"]
6409 fn test_get_disjoint_mut_duplicate() {
6410 let mut map = HashMap::new();
6411 map.insert("foo".to_owned(), 0);
6412
6413 let _xs = map.get_disjoint_mut(["foo", "foo"]);
6414 }
6415
6416 #[test]
6417 #[should_panic = "panic in drop"]
6418 fn test_clone_from_double_drop() {
6419 #[derive(Clone)]
6420 struct CheckedDrop {
6421 panic_in_drop: bool,
6422 dropped: bool,
6423 }
6424 impl Drop for CheckedDrop {
6425 fn drop(&mut self) {
6426 if self.panic_in_drop {
6427 self.dropped = true;
6428 panic!("panic in drop");
6429 }
6430 assert!(!self.dropped, "double drop");
6431 self.dropped = true;
6432 }
6433 }
6434 const DISARMED: CheckedDrop = CheckedDrop {
6435 panic_in_drop: false,
6436 dropped: false,
6437 };
6438 const ARMED: CheckedDrop = CheckedDrop {
6439 panic_in_drop: true,
6440 dropped: false,
6441 };
6442
6443 let mut map1 = HashMap::new();
6444 map1.insert(1, DISARMED);
6445 map1.insert(2, DISARMED);
6446 map1.insert(3, DISARMED);
6447 map1.insert(4, DISARMED);
6448
6449 let mut map2 = HashMap::new();
6450 map2.insert(1, DISARMED);
6451 map2.insert(2, ARMED);
6452 map2.insert(3, DISARMED);
6453 map2.insert(4, DISARMED);
6454
6455 map2.clone_from(&map1);
6456 }
6457
6458 #[test]
6459 #[should_panic = "panic in clone"]
6460 fn test_clone_from_memory_leaks() {
6461 use stdalloc::vec::Vec;
6462
6463 struct CheckedClone {
6464 panic_in_clone: bool,
6465 need_drop: Vec<i32>,
6466 }
6467 impl Clone for CheckedClone {
6468 fn clone(&self) -> Self {
6469 assert!(!self.panic_in_clone, "panic in clone");
6470 Self {
6471 panic_in_clone: self.panic_in_clone,
6472 need_drop: self.need_drop.clone(),
6473 }
6474 }
6475 }
6476 let mut map1 = HashMap::new();
6477 map1.insert(
6478 1,
6479 CheckedClone {
6480 panic_in_clone: false,
6481 need_drop: vec![0, 1, 2],
6482 },
6483 );
6484 map1.insert(
6485 2,
6486 CheckedClone {
6487 panic_in_clone: false,
6488 need_drop: vec![3, 4, 5],
6489 },
6490 );
6491 map1.insert(
6492 3,
6493 CheckedClone {
6494 panic_in_clone: true,
6495 need_drop: vec![6, 7, 8],
6496 },
6497 );
6498 let _map2 = map1.clone();
6499 }
6500
6501 struct MyAllocInner {
6502 drop_count: Arc<AtomicI8>,
6503 }
6504
6505 #[derive(Clone)]
6506 struct MyAlloc {
6507 _inner: Arc<MyAllocInner>,
6508 }
6509
6510 impl MyAlloc {
6511 fn new(drop_count: Arc<AtomicI8>) -> Self {
6512 MyAlloc {
6513 _inner: Arc::new(MyAllocInner { drop_count }),
6514 }
6515 }
6516 }
6517
6518 impl Drop for MyAllocInner {
6519 fn drop(&mut self) {
6520 println!("MyAlloc freed.");
6521 self.drop_count.fetch_sub(1, Ordering::SeqCst);
6522 }
6523 }
6524
6525 unsafe impl Allocator for MyAlloc {
6526 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
6527 let g = Global;
6528 g.allocate(layout)
6529 }
6530
6531 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
6532 unsafe {
6533 let g = Global;
6534 g.deallocate(ptr, layout);
6535 }
6536 }
6537 }
6538
6539 #[test]
6540 fn test_hashmap_into_iter_bug() {
6541 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
6542
6543 {
6544 let mut map = HashMap::with_capacity_in(10, MyAlloc::new(dropped.clone()));
6545 for i in 0..10 {
6546 map.entry(i).or_insert_with(|| "i".to_owned());
6547 }
6548
6549 for (k, v) in map {
6550 println!("{k}, {v}");
6551 }
6552 }
6553
6554 // All allocator clones should already be dropped.
6555 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6556 }
6557
6558 #[test]
6559 fn test_hashmap_into_iter_unallocated_drops_allocator() {
6560 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
6561
6562 {
6563 let map: HashMap<i32, i32, _, _> = HashMap::with_hasher_in(
6564 DefaultHashBuilder::default(),
6565 MyAlloc::new(dropped.clone()),
6566 );
6567
6568 for _ in map {}
6569 }
6570
6571 // The table never allocated, but the allocator must still be dropped.
6572 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6573 }
6574
6575 #[derive(Debug)]
6576 struct CheckedCloneDrop<T> {
6577 panic_in_clone: bool,
6578 panic_in_drop: bool,
6579 dropped: bool,
6580 data: T,
6581 }
6582
6583 impl<T> CheckedCloneDrop<T> {
6584 fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
6585 CheckedCloneDrop {
6586 panic_in_clone,
6587 panic_in_drop,
6588 dropped: false,
6589 data,
6590 }
6591 }
6592 }
6593
6594 impl<T: Clone> Clone for CheckedCloneDrop<T> {
6595 fn clone(&self) -> Self {
6596 assert!(!self.panic_in_clone, "panic in clone");
6597 Self {
6598 panic_in_clone: self.panic_in_clone,
6599 panic_in_drop: self.panic_in_drop,
6600 dropped: self.dropped,
6601 data: self.data.clone(),
6602 }
6603 }
6604 }
6605
6606 impl<T> Drop for CheckedCloneDrop<T> {
6607 fn drop(&mut self) {
6608 if self.panic_in_drop {
6609 self.dropped = true;
6610 panic!("panic in drop");
6611 }
6612 assert!(!self.dropped, "double drop");
6613 self.dropped = true;
6614 }
6615 }
6616
6617 /// Return hashmap with predefined distribution of elements.
6618 /// All elements will be located in the same order as elements
6619 /// returned by iterator.
6620 ///
6621 /// This function does not panic, but returns an error as a `String`
6622 /// to distinguish between a test panic and an error in the input data.
6623 fn get_test_map<I, T, A>(
6624 iter: I,
6625 mut fun: impl FnMut(u64) -> T,
6626 alloc: A,
6627 ) -> Result<HashMap<u64, CheckedCloneDrop<T>, DefaultHashBuilder, A>, String>
6628 where
6629 I: Iterator<Item = (bool, bool)> + Clone + ExactSizeIterator,
6630 A: Allocator,
6631 T: PartialEq + core::fmt::Debug,
6632 {
6633 use crate::scopeguard::guard;
6634
6635 let mut map: HashMap<u64, CheckedCloneDrop<T>, _, A> =
6636 HashMap::with_capacity_in(iter.size_hint().0, alloc);
6637 {
6638 let mut guard = guard(&mut map, |map| {
6639 for (_, value) in map.iter_mut() {
6640 value.panic_in_drop = false;
6641 }
6642 });
6643
6644 let mut count = 0;
6645 // Hash and Key must be equal to each other for controlling the elements placement.
6646 for (panic_in_clone, panic_in_drop) in iter.clone() {
6647 if core::mem::needs_drop::<T>() && panic_in_drop {
6648 return Err(String::from(
6649 "panic_in_drop can be set with a type that doesn't need to be dropped",
6650 ));
6651 }
6652 guard.table.insert(
6653 count,
6654 (
6655 count,
6656 CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)),
6657 ),
6658 |(k, _)| *k,
6659 );
6660 count += 1;
6661 }
6662
6663 // Let's check that all elements are located as we wanted
6664 let mut check_count = 0;
6665 for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) {
6666 if *key != check_count {
6667 return Err(format!(
6668 "key != check_count,\nkey: `{key}`,\ncheck_count: `{check_count}`"
6669 ));
6670 }
6671 if value.dropped
6672 || value.panic_in_clone != panic_in_clone
6673 || value.panic_in_drop != panic_in_drop
6674 || value.data != fun(check_count)
6675 {
6676 return Err(format!(
6677 "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \
6678 `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`",
6679 value,
6680 panic_in_clone,
6681 panic_in_drop,
6682 false,
6683 fun(check_count)
6684 ));
6685 }
6686 check_count += 1;
6687 }
6688
6689 if guard.len() != check_count as usize {
6690 return Err(format!(
6691 "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`",
6692 guard.len(),
6693 check_count
6694 ));
6695 }
6696
6697 if count != check_count {
6698 return Err(format!(
6699 "count != check_count,\ncount: `{count}`,\ncheck_count: `{check_count}`"
6700 ));
6701 }
6702 core::mem::forget(guard);
6703 }
6704 Ok(map)
6705 }
6706
6707 const DISARMED: bool = false;
6708 const ARMED: bool = true;
6709
6710 const ARMED_FLAGS: [bool; 8] = [
6711 DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6712 ];
6713
6714 const DISARMED_FLAGS: [bool; 8] = [
6715 DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6716 ];
6717
6718 #[test]
6719 #[should_panic = "panic in clone"]
6720 fn test_clone_memory_leaks_and_double_drop_one() {
6721 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6722
6723 {
6724 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6725
6726 let map: HashMap<u64, CheckedCloneDrop<Vec<u64>>, DefaultHashBuilder, MyAlloc> =
6727 match get_test_map(
6728 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6729 |n| vec![n],
6730 MyAlloc::new(dropped.clone()),
6731 ) {
6732 Ok(map) => map,
6733 Err(msg) => panic!("{msg}"),
6734 };
6735
6736 // Clone should normally clone a few elements, and then (when the
6737 // clone function panics), deallocate both its own memory, memory
6738 // of `dropped: Arc<AtomicI8>` and the memory of already cloned
6739 // elements (Vec<i32> memory inside CheckedCloneDrop).
6740 let _map2 = map.clone();
6741 }
6742 }
6743
6744 #[test]
6745 #[should_panic = "panic in drop"]
6746 fn test_clone_memory_leaks_and_double_drop_two() {
6747 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6748
6749 {
6750 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6751
6752 let map: HashMap<u64, CheckedCloneDrop<u64>, DefaultHashBuilder, _> = match get_test_map(
6753 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6754 |n| n,
6755 MyAlloc::new(dropped.clone()),
6756 ) {
6757 Ok(map) => map,
6758 Err(msg) => panic!("{msg}"),
6759 };
6760
6761 let mut map2 = match get_test_map(
6762 DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS),
6763 |n| n,
6764 MyAlloc::new(dropped.clone()),
6765 ) {
6766 Ok(map) => map,
6767 Err(msg) => panic!("{msg}"),
6768 };
6769
6770 // The `clone_from` should try to drop the elements of `map2` without
6771 // double drop and leaking the allocator. Elements that have not been
6772 // dropped leak their memory.
6773 map2.clone_from(&map);
6774 }
6775 }
6776
6777 /// We check that we have a working table if the clone operation from another
6778 /// thread ended in a panic (when buckets of maps are equal to each other).
6779 #[test]
6780 #[cfg(panic = "unwind")]
6781 fn test_catch_panic_clone_from_when_len_is_equal() {
6782 use std::thread;
6783
6784 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6785
6786 {
6787 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6788
6789 let mut map = match get_test_map(
6790 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6791 |n| vec![n],
6792 MyAlloc::new(dropped.clone()),
6793 ) {
6794 Ok(map) => map,
6795 Err(msg) => panic!("{msg}"),
6796 };
6797
6798 thread::scope(|s| {
6799 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6800 let scope_map =
6801 match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| vec![n * 2], MyAlloc::new(dropped.clone())) {
6802 Ok(map) => map,
6803 Err(msg) => return msg,
6804 };
6805 if map.table.num_buckets() != scope_map.table.num_buckets() {
6806 return format!(
6807 "map.table.num_buckets() != scope_map.table.num_buckets(),\nleft: `{}`,\nright: `{}`",
6808 map.table.num_buckets(), scope_map.table.num_buckets()
6809 );
6810 }
6811 map.clone_from(&scope_map);
6812 "We must fail the cloning!!!".to_owned()
6813 });
6814 if let Ok(msg) = result.join() {
6815 panic!("{msg}")
6816 }
6817 });
6818
6819 // Let's check that all iterators work fine and do not return elements
6820 // (especially `RawIterRange`, which does not depend on the number of
6821 // elements in the table, but looks directly at the control bytes)
6822 //
6823 // SAFETY: We know for sure that `RawTable` will outlive
6824 // the returned `RawIter / RawIterRange` iterator.
6825 assert_eq!(map.len(), 0);
6826 assert_eq!(map.iter().count(), 0);
6827 assert_eq!(unsafe { map.table.iter().count() }, 0);
6828 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6829
6830 for idx in 0..map.table.num_buckets() {
6831 let idx = idx as u64;
6832 assert!(
6833 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6834 "Index: {idx}"
6835 );
6836 }
6837 }
6838
6839 // All allocator clones should already be dropped.
6840 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6841 }
6842
6843 /// We check that we have a working table if the clone operation from another
6844 /// thread ended in a panic (when buckets of maps are not equal to each other).
6845 #[test]
6846 #[cfg(panic = "unwind")]
6847 fn test_catch_panic_clone_from_when_len_is_not_equal() {
6848 use std::thread;
6849
6850 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6851
6852 {
6853 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6854
6855 let mut map = match get_test_map(
6856 [DISARMED].into_iter().zip([DISARMED]),
6857 |n| vec![n],
6858 MyAlloc::new(dropped.clone()),
6859 ) {
6860 Ok(map) => map,
6861 Err(msg) => panic!("{msg}"),
6862 };
6863
6864 thread::scope(|s| {
6865 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6866 let scope_map = match get_test_map(
6867 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6868 |n| vec![n * 2],
6869 MyAlloc::new(dropped.clone()),
6870 ) {
6871 Ok(map) => map,
6872 Err(msg) => return msg,
6873 };
6874 if map.table.num_buckets() == scope_map.table.num_buckets() {
6875 return format!(
6876 "map.table.num_buckets() == scope_map.table.num_buckets(): `{}`",
6877 map.table.num_buckets()
6878 );
6879 }
6880 map.clone_from(&scope_map);
6881 "We must fail the cloning!!!".to_owned()
6882 });
6883 if let Ok(msg) = result.join() {
6884 panic!("{msg}")
6885 }
6886 });
6887
6888 // Let's check that all iterators work fine and do not return elements
6889 // (especially `RawIterRange`, which does not depend on the number of
6890 // elements in the table, but looks directly at the control bytes)
6891 //
6892 // SAFETY: We know for sure that `RawTable` will outlive
6893 // the returned `RawIter / RawIterRange` iterator.
6894 assert_eq!(map.len(), 0);
6895 assert_eq!(map.iter().count(), 0);
6896 assert_eq!(unsafe { map.table.iter().count() }, 0);
6897 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6898
6899 for idx in 0..map.table.num_buckets() {
6900 let idx = idx as u64;
6901 assert!(
6902 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6903 "Index: {idx}"
6904 );
6905 }
6906 }
6907
6908 // All allocator clones should already be dropped.
6909 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6910 }
6911
6912 #[test]
6913 fn test_allocation_info() {
6914 assert_eq!(HashMap::<(), ()>::new().allocation_size(), 0);
6915 assert_eq!(HashMap::<u32, u32>::new().allocation_size(), 0);
6916 assert!(HashMap::<u32, u32>::with_capacity(1).allocation_size() > size_of::<u32>());
6917 }
6918}
6919
6920#[cfg(all(test, unix, any(feature = "nightly", feature = "allocator-api2")))]
6921mod test_map_with_mmap_allocations {
6922 use super::HashMap;
6923 use crate::raw::prev_pow2;
6924 use core::alloc::Layout;
6925 use core::ptr::{NonNull, null_mut};
6926
6927 #[cfg(feature = "nightly")]
6928 use core::alloc::{AllocError, Allocator};
6929
6930 #[cfg(all(feature = "allocator-api2", not(feature = "nightly")))]
6931 use allocator_api2::alloc::{AllocError, Allocator};
6932
6933 /// This is not a production quality allocator, just good enough for
6934 /// some basic tests.
6935 #[derive(Clone, Copy, Debug)]
6936 struct MmapAllocator {
6937 /// Guarantee this is a power of 2.
6938 page_size: usize,
6939 }
6940
6941 impl MmapAllocator {
6942 fn new() -> Result<Self, AllocError> {
6943 let result = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
6944 if result < 1 {
6945 return Err(AllocError);
6946 }
6947
6948 let page_size = result as usize;
6949 if page_size.is_power_of_two() {
6950 Ok(Self { page_size })
6951 } else {
6952 Err(AllocError)
6953 }
6954 }
6955
6956 fn fit_to_page_size(&self, n: usize) -> Result<usize, AllocError> {
6957 // If n=0, give a single page (wasteful, I know).
6958 let n = if n == 0 { self.page_size } else { n };
6959
6960 match n & (self.page_size - 1) {
6961 0 => Ok(n),
6962 rem => n.checked_add(self.page_size - rem).ok_or(AllocError),
6963 }
6964 }
6965 }
6966
6967 unsafe impl Allocator for MmapAllocator {
6968 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
6969 if layout.align() > self.page_size {
6970 return Err(AllocError);
6971 }
6972
6973 let null = null_mut();
6974 let len = self.fit_to_page_size(layout.size())? as libc::size_t;
6975 let prot = libc::PROT_READ | libc::PROT_WRITE;
6976 let flags = libc::MAP_PRIVATE | libc::MAP_ANON;
6977 let addr = unsafe { libc::mmap(null, len, prot, flags, -1, 0) };
6978
6979 // mmap returns MAP_FAILED on failure, not Null.
6980 if addr == libc::MAP_FAILED {
6981 return Err(AllocError);
6982 }
6983
6984 if let Some(data) = NonNull::new(addr.cast()) {
6985 // SAFETY: this is NonNull::slice_from_raw_parts.
6986 Ok(unsafe {
6987 NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(data.as_ptr(), len))
6988 })
6989 } else {
6990 // This branch shouldn't be taken in practice, but since we
6991 // cannot return null as a valid pointer in our type system,
6992 // we attempt to handle it.
6993 _ = unsafe { libc::munmap(addr, len) };
6994 Err(AllocError)
6995 }
6996 }
6997
6998 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
6999 unsafe {
7000 // If they allocated it with this layout, it must round correctly.
7001 let size = self.fit_to_page_size(layout.size()).unwrap();
7002 let _result = libc::munmap(ptr.as_ptr().cast(), size);
7003 debug_assert_eq!(0, _result);
7004 }
7005 }
7006 }
7007
7008 #[test]
7009 fn test_tiny_allocation_gets_rounded_to_page_size() {
7010 let alloc = MmapAllocator::new().unwrap();
7011 let mut map: HashMap<usize, (), _, _> = HashMap::with_capacity_in(1, alloc);
7012
7013 // Size of an element plus its control byte.
7014 let rough_bucket_size = size_of::<(usize, ())>() + 1;
7015
7016 // Accounting for some misc. padding that's likely in the allocation
7017 // due to rounding to group width, etc.
7018 let overhead = 3 * size_of::<usize>();
7019 let num_buckets = (alloc.page_size - overhead) / rough_bucket_size;
7020 // Buckets are always powers of 2.
7021 let min_elems = prev_pow2(num_buckets);
7022 // Real load-factor is 7/8, but this is a lower estimation, so 1/2.
7023 let min_capacity = min_elems >> 1;
7024 let capacity = map.capacity();
7025 assert!(
7026 capacity >= min_capacity,
7027 "failed: {capacity} >= {min_capacity}"
7028 );
7029
7030 // Fill it up.
7031 for i in 0..capacity {
7032 map.insert(i, ());
7033 }
7034 // Capacity should not have changed and it should be full.
7035 assert_eq!(capacity, map.len());
7036 assert_eq!(capacity, map.capacity());
7037
7038 // Alright, make it grow.
7039 map.insert(capacity, ());
7040 assert!(
7041 capacity < map.capacity(),
7042 "failed: {capacity} < {}",
7043 map.capacity()
7044 );
7045 }
7046}