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> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2612
2613/// A mutable iterator over the values of a `HashMap` in arbitrary order.
2614/// The iterator element type is `&'a mut V`.
2615///
2616/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
2617/// documentation for more.
2618///
2619/// [`values_mut`]: HashMap::values_mut
2620///
2621/// # Examples
2622///
2623/// ```
2624/// use hashbrown::HashMap;
2625///
2626/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2627///
2628/// let mut values = map.values_mut();
2629/// values.next().map(|v| v.push_str(" Mississippi"));
2630/// values.next().map(|v| v.push_str(" Mississippi"));
2631///
2632/// // It is fused iterator
2633/// assert_eq!(values.next(), None);
2634/// assert_eq!(values.next(), None);
2635///
2636/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2637/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2638/// ```
2639pub struct ValuesMut<'a, K, V> {
2640 inner: IterMut<'a, K, V>,
2641}
2642
2643/// A view into a single entry in a map, which may either be vacant or occupied.
2644///
2645/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2646///
2647/// [`entry`]: HashMap::entry
2648///
2649/// # Examples
2650///
2651/// ```
2652/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2653///
2654/// let mut map = HashMap::new();
2655/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2656/// assert_eq!(map.len(), 3);
2657///
2658/// // Existing key (insert)
2659/// let entry: Entry<_, _, _> = map.entry("a");
2660/// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1);
2661/// assert_eq!(map.len(), 3);
2662/// // Nonexistent key (insert)
2663/// map.entry("d").insert(4);
2664///
2665/// // Existing key (or_insert)
2666/// let v = map.entry("b").or_insert(2);
2667/// assert_eq!(std::mem::replace(v, 2), 20);
2668/// // Nonexistent key (or_insert)
2669/// map.entry("e").or_insert(5);
2670///
2671/// // Existing key (or_insert_with)
2672/// let v = map.entry("c").or_insert_with(|| 3);
2673/// assert_eq!(std::mem::replace(v, 3), 30);
2674/// // Nonexistent key (or_insert_with)
2675/// map.entry("f").or_insert_with(|| 6);
2676///
2677/// println!("Our HashMap: {:?}", map);
2678///
2679/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
2680/// // The `Iter` iterator produces items in arbitrary order, so the
2681/// // items must be sorted to test them against a sorted array.
2682/// vec.sort_unstable();
2683/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]);
2684/// ```
2685pub enum Entry<'a, K, V, S, A = Global>
2686where
2687 A: Allocator,
2688{
2689 /// An occupied entry.
2690 ///
2691 /// # Examples
2692 ///
2693 /// ```
2694 /// use hashbrown::hash_map::{Entry, HashMap};
2695 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into();
2696 ///
2697 /// match map.entry("a") {
2698 /// Entry::Vacant(_) => unreachable!(),
2699 /// Entry::Occupied(_) => { }
2700 /// }
2701 /// ```
2702 Occupied(OccupiedEntry<'a, K, V, S, A>),
2703
2704 /// A vacant entry.
2705 ///
2706 /// # Examples
2707 ///
2708 /// ```
2709 /// use hashbrown::hash_map::{Entry, HashMap};
2710 /// let mut map: HashMap<&str, i32> = HashMap::new();
2711 ///
2712 /// match map.entry("a") {
2713 /// Entry::Occupied(_) => unreachable!(),
2714 /// Entry::Vacant(_) => { }
2715 /// }
2716 /// ```
2717 Vacant(VacantEntry<'a, K, V, S, A>),
2718}
2719
2720impl<K: Debug, V: Debug, S, A: Allocator> Debug for Entry<'_, K, V, S, A> {
2721 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2722 match *self {
2723 Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2724 Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2725 }
2726 }
2727}
2728
2729/// A view into an occupied entry in a [`HashMap`].
2730/// It is part of the [`Entry`] and [`EntryRef`] enums.
2731///
2732/// # Examples
2733///
2734/// ```
2735/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2736///
2737/// let mut map = HashMap::new();
2738/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2739///
2740/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").insert(100);
2741/// assert_eq!(map.len(), 3);
2742///
2743/// // Existing key (insert and update)
2744/// match map.entry("a") {
2745/// Entry::Vacant(_) => unreachable!(),
2746/// Entry::Occupied(mut view) => {
2747/// assert_eq!(view.get(), &100);
2748/// let v = view.get_mut();
2749/// *v *= 10;
2750/// assert_eq!(view.insert(1111), 1000);
2751/// }
2752/// }
2753///
2754/// assert_eq!(map[&"a"], 1111);
2755/// assert_eq!(map.len(), 3);
2756///
2757/// // Existing key (take)
2758/// match map.entry("c") {
2759/// Entry::Vacant(_) => unreachable!(),
2760/// Entry::Occupied(view) => {
2761/// assert_eq!(view.remove_entry(), ("c", 30));
2762/// }
2763/// }
2764/// assert_eq!(map.get(&"c"), None);
2765/// assert_eq!(map.len(), 2);
2766/// ```
2767pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2768 hash: u64,
2769 elem: Bucket<(K, V)>,
2770 table: &'a mut HashMap<K, V, S, A>,
2771}
2772
2773unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
2774where
2775 K: Send,
2776 V: Send,
2777 S: Send,
2778 A: Send + Allocator,
2779{
2780}
2781unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
2782where
2783 K: Sync,
2784 V: Sync,
2785 S: Sync,
2786 A: Sync + Allocator,
2787{
2788}
2789
2790impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedEntry<'_, K, V, S, A> {
2791 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2792 f.debug_struct("OccupiedEntry")
2793 .field("key", self.key())
2794 .field("value", self.get())
2795 .finish()
2796 }
2797}
2798
2799/// A view into a vacant entry in a `HashMap`.
2800/// It is part of the [`Entry`] enum.
2801///
2802/// # Examples
2803///
2804/// ```
2805/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry};
2806///
2807/// let mut map = HashMap::<&str, i32>::new();
2808///
2809/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
2810/// Entry::Vacant(view) => view,
2811/// Entry::Occupied(_) => unreachable!(),
2812/// };
2813/// entry_v.insert(10);
2814/// assert!(map[&"a"] == 10 && map.len() == 1);
2815///
2816/// // Nonexistent key (insert and update)
2817/// match map.entry("b") {
2818/// Entry::Occupied(_) => unreachable!(),
2819/// Entry::Vacant(view) => {
2820/// let value = view.insert(2);
2821/// assert_eq!(*value, 2);
2822/// *value = 20;
2823/// }
2824/// }
2825/// assert!(map[&"b"] == 20 && map.len() == 2);
2826/// ```
2827pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2828 hash: u64,
2829 key: K,
2830 table: &'a mut HashMap<K, V, S, A>,
2831}
2832
2833impl<K: Debug, V, S, A: Allocator> Debug for VacantEntry<'_, K, V, S, A> {
2834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2835 f.debug_tuple("VacantEntry").field(self.key()).finish()
2836 }
2837}
2838
2839/// A view into a single entry in a map, which may either be vacant or occupied,
2840/// with any borrowed form of the map's key type.
2841///
2842///
2843/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
2844///
2845/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
2846/// for the key type. It also require that key may be constructed from the borrowed
2847/// form through the [`ToOwned`] trait.
2848///
2849/// [`entry_ref`]: HashMap::entry_ref
2850///
2851/// # Examples
2852///
2853/// ```
2854/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntry};
2855///
2856/// let mut map = HashMap::new();
2857/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
2858/// assert_eq!(map.len(), 3);
2859///
2860/// // Existing key (insert)
2861/// let key = String::from("a");
2862/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
2863/// let _raw_o: OccupiedEntry<_, _, _, _> = entry.insert(1);
2864/// assert_eq!(map.len(), 3);
2865/// // Nonexistent key (insert)
2866/// map.entry_ref("d").insert(4);
2867///
2868/// // Existing key (or_insert)
2869/// let v = map.entry_ref("b").or_insert(2);
2870/// assert_eq!(std::mem::replace(v, 2), 20);
2871/// // Nonexistent key (or_insert)
2872/// map.entry_ref("e").or_insert(5);
2873///
2874/// // Existing key (or_insert_with)
2875/// let v = map.entry_ref("c").or_insert_with(|| 3);
2876/// assert_eq!(std::mem::replace(v, 3), 30);
2877/// // Nonexistent key (or_insert_with)
2878/// map.entry_ref("f").or_insert_with(|| 6);
2879///
2880/// println!("Our HashMap: {:?}", map);
2881///
2882/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
2883/// assert_eq!(map[key], value)
2884/// }
2885/// assert_eq!(map.len(), 6);
2886/// ```
2887pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
2888where
2889 A: Allocator,
2890{
2891 /// An occupied entry.
2892 ///
2893 /// # Examples
2894 ///
2895 /// ```
2896 /// use hashbrown::hash_map::{EntryRef, HashMap};
2897 /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].into();
2898 ///
2899 /// match map.entry_ref("a") {
2900 /// EntryRef::Vacant(_) => unreachable!(),
2901 /// EntryRef::Occupied(_) => { }
2902 /// }
2903 /// ```
2904 Occupied(OccupiedEntry<'a, K, V, S, A>),
2905
2906 /// A vacant entry.
2907 ///
2908 /// # Examples
2909 ///
2910 /// ```
2911 /// use hashbrown::hash_map::{EntryRef, HashMap};
2912 /// let mut map: HashMap<String, i32> = HashMap::new();
2913 ///
2914 /// match map.entry_ref("a") {
2915 /// EntryRef::Occupied(_) => unreachable!(),
2916 /// EntryRef::Vacant(_) => { }
2917 /// }
2918 /// ```
2919 Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
2920}
2921
2922impl<K, Q, V, S, A> Debug for EntryRef<'_, '_, K, Q, V, S, A>
2923where
2924 K: Debug + Borrow<Q>,
2925 Q: Debug + ?Sized,
2926 V: Debug,
2927 A: Allocator,
2928{
2929 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2930 match *self {
2931 EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(),
2932 EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(),
2933 }
2934 }
2935}
2936
2937/// A view into a vacant entry in a `HashMap`.
2938/// It is part of the [`EntryRef`] enum.
2939///
2940/// # Examples
2941///
2942/// ```
2943/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef};
2944///
2945/// let mut map = HashMap::<String, i32>::new();
2946///
2947/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
2948/// EntryRef::Vacant(view) => view,
2949/// EntryRef::Occupied(_) => unreachable!(),
2950/// };
2951/// entry_v.insert(10);
2952/// assert!(map["a"] == 10 && map.len() == 1);
2953///
2954/// // Nonexistent key (insert and update)
2955/// match map.entry_ref("b") {
2956/// EntryRef::Occupied(_) => unreachable!(),
2957/// EntryRef::Vacant(view) => {
2958/// let value = view.insert(2);
2959/// assert_eq!(*value, 2);
2960/// *value = 20;
2961/// }
2962/// }
2963/// assert!(map["b"] == 20 && map.len() == 2);
2964/// ```
2965pub struct VacantEntryRef<'map, 'key, K, Q: ?Sized, V, S, A: Allocator = Global> {
2966 hash: u64,
2967 key: &'key Q,
2968 table: &'map mut HashMap<K, V, S, A>,
2969}
2970
2971impl<K, Q, V, S, A> Debug for VacantEntryRef<'_, '_, K, Q, V, S, A>
2972where
2973 K: Borrow<Q>,
2974 Q: Debug + ?Sized,
2975 A: Allocator,
2976{
2977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2978 f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
2979 }
2980}
2981
2982/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
2983///
2984/// Contains the occupied entry, and the value that was not inserted.
2985///
2986/// # Examples
2987///
2988/// ```
2989/// use hashbrown::hash_map::{HashMap, OccupiedError};
2990///
2991/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into();
2992///
2993/// // try_insert method returns mutable reference to the value if keys are vacant,
2994/// // but if the map did have key present, nothing is updated, and the provided
2995/// // value is returned inside `Err(_)` variant
2996/// match map.try_insert("a", 100) {
2997/// Err(OccupiedError { mut entry, value }) => {
2998/// assert_eq!(entry.key(), &"a");
2999/// assert_eq!(value, 100);
3000/// assert_eq!(entry.insert(100), 10)
3001/// }
3002/// _ => unreachable!(),
3003/// }
3004/// assert_eq!(map[&"a"], 100);
3005/// ```
3006pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> {
3007 /// The entry in the map that was already occupied.
3008 pub entry: OccupiedEntry<'a, K, V, S, A>,
3009 /// The value which was not inserted, because the entry was already occupied.
3010 pub value: V,
3011}
3012
3013impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedError<'_, K, V, S, A> {
3014 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3015 f.debug_struct("OccupiedError")
3016 .field("key", self.entry.key())
3017 .field("old_value", self.entry.get())
3018 .field("new_value", &self.value)
3019 .finish()
3020 }
3021}
3022
3023impl<K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'_, K, V, S, A> {
3024 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3025 write!(
3026 f,
3027 "failed to insert {:?}, key {:?} already exists with value {:?}",
3028 self.value,
3029 self.entry.key(),
3030 self.entry.get(),
3031 )
3032 }
3033}
3034
3035impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
3036 type Item = (&'a K, &'a V);
3037 type IntoIter = Iter<'a, K, V>;
3038
3039 /// Creates an iterator over the entries of a `HashMap` in arbitrary order.
3040 /// The iterator element type is `(&'a K, &'a V)`.
3041 ///
3042 /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
3043 ///
3044 /// [`iter`]: HashMap::iter
3045 ///
3046 /// # Examples
3047 ///
3048 /// ```
3049 /// use hashbrown::HashMap;
3050 /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
3051 /// let mut map_two = HashMap::new();
3052 ///
3053 /// for (key, value) in &map_one {
3054 /// println!("Key: {}, Value: {}", key, value);
3055 /// map_two.insert(*key, *value);
3056 /// }
3057 ///
3058 /// assert_eq!(map_one, map_two);
3059 /// ```
3060 #[cfg_attr(feature = "inline-more", inline)]
3061 fn into_iter(self) -> Iter<'a, K, V> {
3062 self.iter()
3063 }
3064}
3065
3066impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
3067 type Item = (&'a K, &'a mut V);
3068 type IntoIter = IterMut<'a, K, V>;
3069
3070 /// Creates an iterator over the entries of a `HashMap` in arbitrary order
3071 /// with mutable references to the values. The iterator element type is
3072 /// `(&'a K, &'a mut V)`.
3073 ///
3074 /// Return the same `IterMut` struct as by the [`iter_mut`] method on
3075 /// [`HashMap`].
3076 ///
3077 /// [`iter_mut`]: HashMap::iter_mut
3078 ///
3079 /// # Examples
3080 ///
3081 /// ```
3082 /// use hashbrown::HashMap;
3083 /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3084 ///
3085 /// for (key, value) in &mut map {
3086 /// println!("Key: {}, Value: {}", key, value);
3087 /// *value *= 2;
3088 /// }
3089 ///
3090 /// let mut vec = map.iter().collect::<Vec<_>>();
3091 /// // The `Iter` iterator produces items in arbitrary order, so the
3092 /// // items must be sorted to test them against a sorted array.
3093 /// vec.sort_unstable();
3094 /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
3095 /// ```
3096 #[cfg_attr(feature = "inline-more", inline)]
3097 fn into_iter(self) -> IterMut<'a, K, V> {
3098 self.iter_mut()
3099 }
3100}
3101
3102impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
3103 type Item = (K, V);
3104 type IntoIter = IntoIter<K, V, A>;
3105
3106 /// Creates a consuming iterator, that is, one that moves each key-value
3107 /// pair out of the map in arbitrary order. The map cannot be used after
3108 /// calling this.
3109 ///
3110 /// # Examples
3111 ///
3112 /// ```
3113 /// use hashbrown::HashMap;
3114 ///
3115 /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3116 ///
3117 /// // Not possible with .iter()
3118 /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
3119 /// // The `IntoIter` iterator produces items in arbitrary order, so
3120 /// // the items must be sorted to test them against a sorted array.
3121 /// vec.sort_unstable();
3122 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
3123 /// ```
3124 #[cfg_attr(feature = "inline-more", inline)]
3125 fn into_iter(self) -> IntoIter<K, V, A> {
3126 IntoIter {
3127 inner: self.table.into_iter(),
3128 }
3129 }
3130}
3131
3132impl<K, V> Default for Iter<'_, K, V> {
3133 #[cfg_attr(feature = "inline-more", inline)]
3134 fn default() -> Self {
3135 Self {
3136 inner: Default::default(),
3137 marker: PhantomData,
3138 }
3139 }
3140}
3141impl<'a, K, V> Iterator for Iter<'a, K, V> {
3142 type Item = (&'a K, &'a V);
3143
3144 #[cfg_attr(feature = "inline-more", inline)]
3145 fn next(&mut self) -> Option<(&'a K, &'a V)> {
3146 // Avoid `Option::map` because it bloats LLVM IR.
3147 match self.inner.next() {
3148 Some(x) => unsafe {
3149 let r = x.as_ref();
3150 Some((&r.0, &r.1))
3151 },
3152 None => None,
3153 }
3154 }
3155 #[cfg_attr(feature = "inline-more", inline)]
3156 fn size_hint(&self) -> (usize, Option<usize>) {
3157 self.inner.size_hint()
3158 }
3159 #[cfg_attr(feature = "inline-more", inline)]
3160 fn fold<B, F>(self, init: B, mut f: F) -> B
3161 where
3162 Self: Sized,
3163 F: FnMut(B, Self::Item) -> B,
3164 {
3165 self.inner.fold(init, |acc, x| unsafe {
3166 let (k, v) = x.as_ref();
3167 f(acc, (k, v))
3168 })
3169 }
3170}
3171impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
3172 #[cfg_attr(feature = "inline-more", inline)]
3173 fn len(&self) -> usize {
3174 self.inner.len()
3175 }
3176}
3177
3178impl<K, V> FusedIterator for Iter<'_, K, V> {}
3179
3180impl<K, V> Default for IterMut<'_, K, V> {
3181 #[cfg_attr(feature = "inline-more", inline)]
3182 fn default() -> Self {
3183 Self {
3184 inner: Default::default(),
3185 marker: PhantomData,
3186 }
3187 }
3188}
3189impl<'a, K, V> Iterator for IterMut<'a, K, V> {
3190 type Item = (&'a K, &'a mut V);
3191
3192 #[cfg_attr(feature = "inline-more", inline)]
3193 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
3194 // Avoid `Option::map` because it bloats LLVM IR.
3195 match self.inner.next() {
3196 Some(x) => unsafe {
3197 let r = x.as_mut();
3198 Some((&r.0, &mut r.1))
3199 },
3200 None => None,
3201 }
3202 }
3203 #[cfg_attr(feature = "inline-more", inline)]
3204 fn size_hint(&self) -> (usize, Option<usize>) {
3205 self.inner.size_hint()
3206 }
3207 #[cfg_attr(feature = "inline-more", inline)]
3208 fn fold<B, F>(self, init: B, mut f: F) -> B
3209 where
3210 Self: Sized,
3211 F: FnMut(B, Self::Item) -> B,
3212 {
3213 self.inner.fold(init, |acc, x| unsafe {
3214 let (k, v) = x.as_mut();
3215 f(acc, (k, v))
3216 })
3217 }
3218}
3219impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
3220 #[cfg_attr(feature = "inline-more", inline)]
3221 fn len(&self) -> usize {
3222 self.inner.len()
3223 }
3224}
3225impl<K, V> FusedIterator for IterMut<'_, K, V> {}
3226
3227impl<K, V> fmt::Debug for IterMut<'_, K, V>
3228where
3229 K: fmt::Debug,
3230 V: fmt::Debug,
3231{
3232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3233 f.debug_list().entries(self.iter()).finish()
3234 }
3235}
3236
3237impl<K, V, A: Allocator> Default for IntoIter<K, V, A> {
3238 #[cfg_attr(feature = "inline-more", inline)]
3239 fn default() -> Self {
3240 Self {
3241 inner: Default::default(),
3242 }
3243 }
3244}
3245impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
3246 type Item = (K, V);
3247
3248 #[cfg_attr(feature = "inline-more", inline)]
3249 fn next(&mut self) -> Option<(K, V)> {
3250 self.inner.next()
3251 }
3252 #[cfg_attr(feature = "inline-more", inline)]
3253 fn size_hint(&self) -> (usize, Option<usize>) {
3254 self.inner.size_hint()
3255 }
3256 #[cfg_attr(feature = "inline-more", inline)]
3257 fn fold<B, F>(self, init: B, f: F) -> B
3258 where
3259 Self: Sized,
3260 F: FnMut(B, Self::Item) -> B,
3261 {
3262 self.inner.fold(init, f)
3263 }
3264}
3265impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
3266 #[cfg_attr(feature = "inline-more", inline)]
3267 fn len(&self) -> usize {
3268 self.inner.len()
3269 }
3270}
3271impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
3272
3273impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
3274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3275 f.debug_list().entries(self.iter()).finish()
3276 }
3277}
3278
3279impl<K, V> Default for Keys<'_, K, V> {
3280 #[cfg_attr(feature = "inline-more", inline)]
3281 fn default() -> Self {
3282 Self {
3283 inner: Default::default(),
3284 }
3285 }
3286}
3287impl<'a, K, V> Iterator for Keys<'a, K, V> {
3288 type Item = &'a K;
3289
3290 #[cfg_attr(feature = "inline-more", inline)]
3291 fn next(&mut self) -> Option<&'a K> {
3292 // Avoid `Option::map` because it bloats LLVM IR.
3293 match self.inner.next() {
3294 Some((k, _)) => Some(k),
3295 None => None,
3296 }
3297 }
3298 #[cfg_attr(feature = "inline-more", inline)]
3299 fn size_hint(&self) -> (usize, Option<usize>) {
3300 self.inner.size_hint()
3301 }
3302 #[cfg_attr(feature = "inline-more", inline)]
3303 fn fold<B, F>(self, init: B, mut f: F) -> B
3304 where
3305 Self: Sized,
3306 F: FnMut(B, Self::Item) -> B,
3307 {
3308 self.inner.fold(init, |acc, (k, _)| f(acc, k))
3309 }
3310}
3311impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
3312 #[cfg_attr(feature = "inline-more", inline)]
3313 fn len(&self) -> usize {
3314 self.inner.len()
3315 }
3316}
3317impl<K, V> FusedIterator for Keys<'_, K, V> {}
3318
3319impl<K, V> Default for Values<'_, K, V> {
3320 #[cfg_attr(feature = "inline-more", inline)]
3321 fn default() -> Self {
3322 Self {
3323 inner: Default::default(),
3324 }
3325 }
3326}
3327impl<'a, K, V> Iterator for Values<'a, K, V> {
3328 type Item = &'a V;
3329
3330 #[cfg_attr(feature = "inline-more", inline)]
3331 fn next(&mut self) -> Option<&'a V> {
3332 // Avoid `Option::map` because it bloats LLVM IR.
3333 match self.inner.next() {
3334 Some((_, v)) => Some(v),
3335 None => None,
3336 }
3337 }
3338 #[cfg_attr(feature = "inline-more", inline)]
3339 fn size_hint(&self) -> (usize, Option<usize>) {
3340 self.inner.size_hint()
3341 }
3342 #[cfg_attr(feature = "inline-more", inline)]
3343 fn fold<B, F>(self, init: B, mut f: F) -> B
3344 where
3345 Self: Sized,
3346 F: FnMut(B, Self::Item) -> B,
3347 {
3348 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3349 }
3350}
3351impl<K, V> ExactSizeIterator for Values<'_, K, V> {
3352 #[cfg_attr(feature = "inline-more", inline)]
3353 fn len(&self) -> usize {
3354 self.inner.len()
3355 }
3356}
3357impl<K, V> FusedIterator for Values<'_, K, V> {}
3358
3359impl<K, V> Default for ValuesMut<'_, K, V> {
3360 #[cfg_attr(feature = "inline-more", inline)]
3361 fn default() -> Self {
3362 Self {
3363 inner: Default::default(),
3364 }
3365 }
3366}
3367impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
3368 type Item = &'a mut V;
3369
3370 #[cfg_attr(feature = "inline-more", inline)]
3371 fn next(&mut self) -> Option<&'a mut V> {
3372 // Avoid `Option::map` because it bloats LLVM IR.
3373 match self.inner.next() {
3374 Some((_, v)) => Some(v),
3375 None => None,
3376 }
3377 }
3378 #[cfg_attr(feature = "inline-more", inline)]
3379 fn size_hint(&self) -> (usize, Option<usize>) {
3380 self.inner.size_hint()
3381 }
3382 #[cfg_attr(feature = "inline-more", inline)]
3383 fn fold<B, F>(self, init: B, mut f: F) -> B
3384 where
3385 Self: Sized,
3386 F: FnMut(B, Self::Item) -> B,
3387 {
3388 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3389 }
3390}
3391impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
3392 #[cfg_attr(feature = "inline-more", inline)]
3393 fn len(&self) -> usize {
3394 self.inner.len()
3395 }
3396}
3397impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
3398
3399impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
3400 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3401 f.debug_list()
3402 .entries(self.inner.iter().map(|(_, val)| val))
3403 .finish()
3404 }
3405}
3406
3407impl<K, V, A: Allocator> Iterator for Drain<'_, K, V, A> {
3408 type Item = (K, V);
3409
3410 #[cfg_attr(feature = "inline-more", inline)]
3411 fn next(&mut self) -> Option<(K, V)> {
3412 self.inner.next()
3413 }
3414 #[cfg_attr(feature = "inline-more", inline)]
3415 fn size_hint(&self) -> (usize, Option<usize>) {
3416 self.inner.size_hint()
3417 }
3418 #[cfg_attr(feature = "inline-more", inline)]
3419 fn fold<B, F>(self, init: B, f: F) -> B
3420 where
3421 Self: Sized,
3422 F: FnMut(B, Self::Item) -> B,
3423 {
3424 self.inner.fold(init, f)
3425 }
3426}
3427impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
3428 #[cfg_attr(feature = "inline-more", inline)]
3429 fn len(&self) -> usize {
3430 self.inner.len()
3431 }
3432}
3433impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
3434
3435impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
3436where
3437 K: fmt::Debug,
3438 V: fmt::Debug,
3439 A: Allocator,
3440{
3441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3442 f.debug_list().entries(self.iter()).finish()
3443 }
3444}
3445
3446impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> {
3447 /// Sets the value of the entry, and returns an `OccupiedEntry`.
3448 ///
3449 /// # Examples
3450 ///
3451 /// ```
3452 /// use hashbrown::HashMap;
3453 ///
3454 /// let mut map: HashMap<&str, u32> = HashMap::new();
3455 /// let entry = map.entry("horseyland").insert(37);
3456 ///
3457 /// assert_eq!(entry.key(), &"horseyland");
3458 /// ```
3459 #[cfg_attr(feature = "inline-more", inline)]
3460 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
3461 where
3462 K: Hash,
3463 S: BuildHasher,
3464 {
3465 match self {
3466 Entry::Occupied(mut entry) => {
3467 entry.insert(value);
3468 entry
3469 }
3470 Entry::Vacant(entry) => entry.insert_entry(value),
3471 }
3472 }
3473
3474 /// Ensures a value is in the entry by inserting the default if empty, and returns
3475 /// a mutable reference to the value in the entry.
3476 ///
3477 /// # Examples
3478 ///
3479 /// ```
3480 /// use hashbrown::HashMap;
3481 ///
3482 /// let mut map: HashMap<&str, u32> = HashMap::new();
3483 ///
3484 /// // nonexistent key
3485 /// map.entry("poneyland").or_insert(3);
3486 /// assert_eq!(map["poneyland"], 3);
3487 ///
3488 /// // existing key
3489 /// *map.entry("poneyland").or_insert(10) *= 2;
3490 /// assert_eq!(map["poneyland"], 6);
3491 /// ```
3492 #[cfg_attr(feature = "inline-more", inline)]
3493 pub fn or_insert(self, default: V) -> &'a mut V
3494 where
3495 K: Hash,
3496 S: BuildHasher,
3497 {
3498 match self {
3499 Entry::Occupied(entry) => entry.into_mut(),
3500 Entry::Vacant(entry) => entry.insert(default),
3501 }
3502 }
3503
3504 /// Ensures a value is in the entry by inserting the default if empty,
3505 /// and returns an [`OccupiedEntry`].
3506 ///
3507 /// # Examples
3508 ///
3509 /// ```
3510 /// use hashbrown::HashMap;
3511 ///
3512 /// let mut map: HashMap<&str, u32> = HashMap::new();
3513 ///
3514 /// // nonexistent key
3515 /// let entry = map.entry("poneyland").or_insert_entry(3);
3516 /// assert_eq!(entry.key(), &"poneyland");
3517 /// assert_eq!(entry.get(), &3);
3518 ///
3519 /// // existing key
3520 /// let mut entry = map.entry("poneyland").or_insert_entry(10);
3521 /// assert_eq!(entry.key(), &"poneyland");
3522 /// assert_eq!(entry.get(), &3);
3523 /// ```
3524 #[cfg_attr(feature = "inline-more", inline)]
3525 pub fn or_insert_entry(self, default: V) -> OccupiedEntry<'a, K, V, S, A>
3526 where
3527 K: Hash,
3528 S: BuildHasher,
3529 {
3530 match self {
3531 Entry::Occupied(entry) => entry,
3532 Entry::Vacant(entry) => entry.insert_entry(default),
3533 }
3534 }
3535
3536 /// Ensures a value is in the entry by inserting the result of the default function if empty,
3537 /// and returns a mutable reference to the value in the entry.
3538 ///
3539 /// # Examples
3540 ///
3541 /// ```
3542 /// use hashbrown::HashMap;
3543 ///
3544 /// let mut map: HashMap<&str, u32> = HashMap::new();
3545 ///
3546 /// // nonexistent key
3547 /// map.entry("poneyland").or_insert_with(|| 3);
3548 /// assert_eq!(map["poneyland"], 3);
3549 ///
3550 /// // existing key
3551 /// *map.entry("poneyland").or_insert_with(|| 10) *= 2;
3552 /// assert_eq!(map["poneyland"], 6);
3553 /// ```
3554 #[cfg_attr(feature = "inline-more", inline)]
3555 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
3556 where
3557 K: Hash,
3558 S: BuildHasher,
3559 {
3560 match self {
3561 Entry::Occupied(entry) => entry.into_mut(),
3562 Entry::Vacant(entry) => entry.insert(default()),
3563 }
3564 }
3565
3566 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
3567 /// This method allows for generating key-derived values for insertion by providing the default
3568 /// function a reference to the key that was moved during the `.entry(key)` method call.
3569 ///
3570 /// The reference to the moved key is provided so that cloning or copying the key is
3571 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
3572 ///
3573 /// # Examples
3574 ///
3575 /// ```
3576 /// use hashbrown::HashMap;
3577 ///
3578 /// let mut map: HashMap<&str, usize> = HashMap::new();
3579 ///
3580 /// // nonexistent key
3581 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
3582 /// assert_eq!(map["poneyland"], 9);
3583 ///
3584 /// // existing key
3585 /// *map.entry("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
3586 /// assert_eq!(map["poneyland"], 18);
3587 /// ```
3588 #[cfg_attr(feature = "inline-more", inline)]
3589 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
3590 where
3591 K: Hash,
3592 S: BuildHasher,
3593 {
3594 match self {
3595 Entry::Occupied(entry) => entry.into_mut(),
3596 Entry::Vacant(entry) => {
3597 let value = default(entry.key());
3598 entry.insert(value)
3599 }
3600 }
3601 }
3602
3603 /// Returns a reference to this entry's key.
3604 ///
3605 /// # Examples
3606 ///
3607 /// ```
3608 /// use hashbrown::HashMap;
3609 ///
3610 /// let mut map: HashMap<&str, u32> = HashMap::new();
3611 /// map.entry("poneyland").or_insert(3);
3612 /// // existing key
3613 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3614 /// // nonexistent key
3615 /// assert_eq!(map.entry("horseland").key(), &"horseland");
3616 /// ```
3617 #[cfg_attr(feature = "inline-more", inline)]
3618 pub fn key(&self) -> &K {
3619 match *self {
3620 Entry::Occupied(ref entry) => entry.key(),
3621 Entry::Vacant(ref entry) => entry.key(),
3622 }
3623 }
3624
3625 /// Provides in-place mutable access to an occupied entry before any
3626 /// potential inserts into the map.
3627 ///
3628 /// # Examples
3629 ///
3630 /// ```
3631 /// use hashbrown::HashMap;
3632 ///
3633 /// let mut map: HashMap<&str, u32> = HashMap::new();
3634 ///
3635 /// map.entry("poneyland")
3636 /// .and_modify(|e| { *e += 1 })
3637 /// .or_insert(42);
3638 /// assert_eq!(map["poneyland"], 42);
3639 ///
3640 /// map.entry("poneyland")
3641 /// .and_modify(|e| { *e += 1 })
3642 /// .or_insert(42);
3643 /// assert_eq!(map["poneyland"], 43);
3644 /// ```
3645 #[cfg_attr(feature = "inline-more", inline)]
3646 pub fn and_modify<F>(self, f: F) -> Self
3647 where
3648 F: FnOnce(&mut V),
3649 {
3650 match self {
3651 Entry::Occupied(mut entry) => {
3652 f(entry.get_mut());
3653 Entry::Occupied(entry)
3654 }
3655 Entry::Vacant(entry) => Entry::Vacant(entry),
3656 }
3657 }
3658
3659 /// Provides shared access to the key and owned access to the value of
3660 /// an occupied entry and allows to replace or remove it based on the
3661 /// value of the returned option.
3662 ///
3663 /// # Examples
3664 ///
3665 /// ```
3666 /// use hashbrown::HashMap;
3667 /// use hashbrown::hash_map::Entry;
3668 ///
3669 /// let mut map: HashMap<&str, u32> = HashMap::new();
3670 ///
3671 /// let entry = map
3672 /// .entry("poneyland")
3673 /// .and_replace_entry_with(|_k, _v| panic!());
3674 ///
3675 /// match entry {
3676 /// Entry::Vacant(e) => {
3677 /// assert_eq!(e.key(), &"poneyland");
3678 /// }
3679 /// Entry::Occupied(_) => panic!(),
3680 /// }
3681 ///
3682 /// map.insert("poneyland", 42);
3683 ///
3684 /// let entry = map
3685 /// .entry("poneyland")
3686 /// .and_replace_entry_with(|k, v| {
3687 /// assert_eq!(k, &"poneyland");
3688 /// assert_eq!(v, 42);
3689 /// Some(v + 1)
3690 /// });
3691 ///
3692 /// match entry {
3693 /// Entry::Occupied(e) => {
3694 /// assert_eq!(e.key(), &"poneyland");
3695 /// assert_eq!(e.get(), &43);
3696 /// }
3697 /// Entry::Vacant(_) => panic!(),
3698 /// }
3699 ///
3700 /// assert_eq!(map["poneyland"], 43);
3701 ///
3702 /// let entry = map
3703 /// .entry("poneyland")
3704 /// .and_replace_entry_with(|_k, _v| None);
3705 ///
3706 /// match entry {
3707 /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"),
3708 /// Entry::Occupied(_) => panic!(),
3709 /// }
3710 ///
3711 /// assert!(!map.contains_key("poneyland"));
3712 /// ```
3713 #[cfg_attr(feature = "inline-more", inline)]
3714 pub fn and_replace_entry_with<F>(self, f: F) -> Self
3715 where
3716 F: FnOnce(&K, V) -> Option<V>,
3717 {
3718 match self {
3719 Entry::Occupied(entry) => entry.replace_entry_with(f),
3720 Entry::Vacant(_) => self,
3721 }
3722 }
3723
3724 /// Converts the `Entry` into a mutable reference to the underlying map.
3725 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
3726 match self {
3727 Entry::Occupied(entry) => entry.table,
3728 Entry::Vacant(entry) => entry.table,
3729 }
3730 }
3731}
3732
3733impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> {
3734 /// Ensures a value is in the entry by inserting the default value if empty,
3735 /// and returns a mutable reference to the value in the entry.
3736 ///
3737 /// # Examples
3738 ///
3739 /// ```
3740 /// use hashbrown::HashMap;
3741 ///
3742 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
3743 ///
3744 /// // nonexistent key
3745 /// map.entry("poneyland").or_default();
3746 /// assert_eq!(map["poneyland"], None);
3747 ///
3748 /// map.insert("horseland", Some(3));
3749 ///
3750 /// // existing key
3751 /// assert_eq!(map.entry("horseland").or_default(), &mut Some(3));
3752 /// ```
3753 #[cfg_attr(feature = "inline-more", inline)]
3754 pub fn or_default(self) -> &'a mut V
3755 where
3756 K: Hash,
3757 S: BuildHasher,
3758 {
3759 match self {
3760 Entry::Occupied(entry) => entry.into_mut(),
3761 Entry::Vacant(entry) => entry.insert(Default::default()),
3762 }
3763 }
3764}
3765
3766impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> {
3767 /// Gets a reference to the key in the entry.
3768 ///
3769 /// # Examples
3770 ///
3771 /// ```
3772 /// use hashbrown::hash_map::{Entry, HashMap};
3773 ///
3774 /// let mut map: HashMap<&str, u32> = HashMap::new();
3775 /// map.entry("poneyland").or_insert(12);
3776 ///
3777 /// match map.entry("poneyland") {
3778 /// Entry::Vacant(_) => panic!(),
3779 /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"),
3780 /// }
3781 /// ```
3782 #[cfg_attr(feature = "inline-more", inline)]
3783 pub fn key(&self) -> &K {
3784 unsafe { &self.elem.as_ref().0 }
3785 }
3786
3787 /// Replaces the key in the entry with a new one.
3788 ///
3789 /// # Panics
3790 ///
3791 /// This method panics if `key` is not equivalent to the key in the entry.
3792 ///
3793 /// # Examples
3794 ///
3795 /// ```
3796 /// use hashbrown::hash_map::{Entry, HashMap};
3797 ///
3798 /// let mut map: HashMap<&str, u32> = HashMap::new();
3799 ///
3800 /// let old_key = "poneyland";
3801 /// let new_key = Box::leak(old_key.to_owned().into_boxed_str());
3802 /// map.entry(old_key).or_insert(12);
3803 /// match map.entry("poneyland") {
3804 /// Entry::Vacant(_) => panic!(),
3805 /// Entry::Occupied(mut entry) => {
3806 /// let replaced = entry.replace_key(new_key);
3807 /// assert!(std::ptr::eq(replaced, old_key));
3808 /// assert!(std::ptr::eq(*entry.key(), new_key));
3809 /// },
3810 /// }
3811 ///
3812 /// # // appease miri; no memory leaks here!
3813 /// # drop(map);
3814 /// # unsafe {
3815 /// # Box::from_raw(new_key);
3816 /// # }
3817 /// ```
3818 #[cfg_attr(feature = "inline-more", inline)]
3819 pub fn replace_key(&mut self, key: K) -> K
3820 where
3821 K: Equivalent<K>,
3822 {
3823 assert!(
3824 self.key().equivalent(&key),
3825 "replaced key is not equivalent to the one in the entry"
3826 );
3827
3828 // SAFETY: We verified that the keys were equivalent.
3829 unsafe { self.replace_key_unchecked(key) }
3830 }
3831
3832 /// Replaces the key in the entry with a new one, without checking the
3833 /// equivalence of the key.
3834 ///
3835 /// # Safety
3836 ///
3837 /// This operation is safe if you replace the key with an equivalent one.
3838 ///
3839 /// Additionally, this operation (and following operations) are guaranteed
3840 /// to not violate memory safety.
3841 ///
3842 /// However this operation is still unsafe because the resulting `HashMap`
3843 /// may be passed to unsafe code which does expect the map to behave
3844 /// correctly. If the map has keys at unexpected positions inside it,
3845 /// future operations may panic, loop forever, or return unexpected results,
3846 /// potentially violating memory safety.
3847 ///
3848 /// # Examples
3849 ///
3850 /// ```
3851 /// use hashbrown::hash_map::{Entry, HashMap};
3852 ///
3853 /// let mut map: HashMap<&str, u32> = HashMap::new();
3854 ///
3855 /// let old_key = "poneyland";
3856 /// let new_key = Box::leak(old_key.to_owned().into_boxed_str());
3857 /// map.entry(old_key).or_insert(12);
3858 /// match map.entry("poneyland") {
3859 /// Entry::Vacant(_) => panic!(),
3860 /// Entry::Occupied(mut entry) => {
3861 /// let replaced = unsafe { entry.replace_key_unchecked(new_key) };
3862 /// assert!(std::ptr::eq(replaced, old_key));
3863 /// assert!(std::ptr::eq(*entry.key(), new_key));
3864 /// },
3865 /// }
3866 ///
3867 /// # // appease miri; no memory leaks here!
3868 /// # drop(map);
3869 /// # unsafe {
3870 /// # Box::from_raw(new_key);
3871 /// # }
3872 /// ```
3873 #[cfg_attr(feature = "inline-more", inline)]
3874 pub unsafe fn replace_key_unchecked(&mut self, key: K) -> K {
3875 mem::replace(unsafe { &mut self.elem.as_mut().0 }, key)
3876 }
3877
3878 /// Take the ownership of the key and value from the map.
3879 /// Keeps the allocated memory for reuse.
3880 ///
3881 /// # Examples
3882 ///
3883 /// ```
3884 /// use hashbrown::HashMap;
3885 /// use hashbrown::hash_map::Entry;
3886 ///
3887 /// let mut map: HashMap<&str, u32> = HashMap::new();
3888 /// // The map is empty
3889 /// assert!(map.is_empty() && map.capacity() == 0);
3890 ///
3891 /// map.entry("poneyland").or_insert(12);
3892 ///
3893 /// if let Entry::Occupied(o) = map.entry("poneyland") {
3894 /// // We delete the entry from the map.
3895 /// assert_eq!(o.remove_entry(), ("poneyland", 12));
3896 /// }
3897 ///
3898 /// assert_eq!(map.contains_key("poneyland"), false);
3899 /// // Now map hold none elements
3900 /// assert!(map.is_empty());
3901 /// ```
3902 #[cfg_attr(feature = "inline-more", inline)]
3903 pub fn remove_entry(self) -> (K, V) {
3904 unsafe { self.table.table.remove(self.elem).0 }
3905 }
3906
3907 /// Gets a reference to the value in the entry.
3908 ///
3909 /// # Examples
3910 ///
3911 /// ```
3912 /// use hashbrown::HashMap;
3913 /// use hashbrown::hash_map::Entry;
3914 ///
3915 /// let mut map: HashMap<&str, u32> = HashMap::new();
3916 /// map.entry("poneyland").or_insert(12);
3917 ///
3918 /// match map.entry("poneyland") {
3919 /// Entry::Vacant(_) => panic!(),
3920 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12),
3921 /// }
3922 /// ```
3923 #[cfg_attr(feature = "inline-more", inline)]
3924 pub fn get(&self) -> &V {
3925 unsafe { &self.elem.as_ref().1 }
3926 }
3927
3928 /// Gets a mutable reference to the value in the entry.
3929 ///
3930 /// If you need a reference to the `OccupiedEntry` which may outlive the
3931 /// destruction of the `Entry` value, see [`into_mut`].
3932 ///
3933 /// [`into_mut`]: #method.into_mut
3934 ///
3935 /// # Examples
3936 ///
3937 /// ```
3938 /// use hashbrown::HashMap;
3939 /// use hashbrown::hash_map::Entry;
3940 ///
3941 /// let mut map: HashMap<&str, u32> = HashMap::new();
3942 /// map.entry("poneyland").or_insert(12);
3943 ///
3944 /// assert_eq!(map["poneyland"], 12);
3945 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
3946 /// *o.get_mut() += 10;
3947 /// assert_eq!(*o.get(), 22);
3948 ///
3949 /// // We can use the same Entry multiple times.
3950 /// *o.get_mut() += 2;
3951 /// }
3952 ///
3953 /// assert_eq!(map["poneyland"], 24);
3954 /// ```
3955 #[cfg_attr(feature = "inline-more", inline)]
3956 pub fn get_mut(&mut self) -> &mut V {
3957 unsafe { &mut self.elem.as_mut().1 }
3958 }
3959
3960 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
3961 /// with a lifetime bound to the map itself.
3962 ///
3963 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
3964 ///
3965 /// [`get_mut`]: #method.get_mut
3966 ///
3967 /// # Examples
3968 ///
3969 /// ```
3970 /// use hashbrown::hash_map::{Entry, HashMap};
3971 ///
3972 /// let mut map: HashMap<&str, u32> = HashMap::new();
3973 /// map.entry("poneyland").or_insert(12);
3974 ///
3975 /// assert_eq!(map["poneyland"], 12);
3976 ///
3977 /// let value: &mut u32;
3978 /// match map.entry("poneyland") {
3979 /// Entry::Occupied(entry) => value = entry.into_mut(),
3980 /// Entry::Vacant(_) => panic!(),
3981 /// }
3982 /// *value += 10;
3983 ///
3984 /// assert_eq!(map["poneyland"], 22);
3985 /// ```
3986 #[cfg_attr(feature = "inline-more", inline)]
3987 pub fn into_mut(self) -> &'a mut V {
3988 unsafe { &mut self.elem.as_mut().1 }
3989 }
3990
3991 /// Converts the `OccupiedEntry` into a reference to the key and a
3992 /// mutable reference to the value in the entry with a lifetime bound to the
3993 /// map itself.
3994 ///
3995 /// If you need multiple references to the `OccupiedEntry`, see [`key`] and
3996 /// [`get_mut`].
3997 ///
3998 /// [`key`]: Self::key
3999 /// [`get_mut`]: Self::get_mut
4000 ///
4001 /// # Examples
4002 ///
4003 /// ```
4004 /// use hashbrown::hash_map::{Entry, HashMap};
4005 ///
4006 /// let mut map: HashMap<&str, u32> = HashMap::new();
4007 /// map.entry("poneyland").or_insert(12);
4008 ///
4009 /// assert_eq!(map["poneyland"], 12);
4010 ///
4011 /// let key_val: (&&str, &mut u32);
4012 /// match map.entry("poneyland") {
4013 /// Entry::Occupied(entry) => key_val = entry.into_entry(),
4014 /// Entry::Vacant(_) => panic!(),
4015 /// }
4016 /// *key_val.1 += 10;
4017 ///
4018 /// assert_eq!(key_val, (&"poneyland", &mut 22));
4019 /// assert_eq!(map["poneyland"], 22);
4020 /// ```
4021 #[cfg_attr(feature = "inline-more", inline)]
4022 pub fn into_entry(self) -> (&'a K, &'a mut V) {
4023 let (key, val) = unsafe { self.elem.as_mut() };
4024 (key, val)
4025 }
4026
4027 /// Sets the value of the entry, and returns the entry's old value.
4028 ///
4029 /// # Examples
4030 ///
4031 /// ```
4032 /// use hashbrown::HashMap;
4033 /// use hashbrown::hash_map::Entry;
4034 ///
4035 /// let mut map: HashMap<&str, u32> = HashMap::new();
4036 /// map.entry("poneyland").or_insert(12);
4037 ///
4038 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
4039 /// assert_eq!(o.insert(15), 12);
4040 /// }
4041 ///
4042 /// assert_eq!(map["poneyland"], 15);
4043 /// ```
4044 #[cfg_attr(feature = "inline-more", inline)]
4045 pub fn insert(&mut self, value: V) -> V {
4046 mem::replace(self.get_mut(), value)
4047 }
4048
4049 /// Takes the value out of the entry, and returns it.
4050 /// Keeps the allocated memory for reuse.
4051 ///
4052 /// # Examples
4053 ///
4054 /// ```
4055 /// use hashbrown::HashMap;
4056 /// use hashbrown::hash_map::Entry;
4057 ///
4058 /// let mut map: HashMap<&str, u32> = HashMap::new();
4059 /// // The map is empty
4060 /// assert!(map.is_empty() && map.capacity() == 0);
4061 ///
4062 /// map.entry("poneyland").or_insert(12);
4063 ///
4064 /// if let Entry::Occupied(o) = map.entry("poneyland") {
4065 /// assert_eq!(o.remove(), 12);
4066 /// }
4067 ///
4068 /// assert_eq!(map.contains_key("poneyland"), false);
4069 /// // Now map hold none elements
4070 /// assert!(map.is_empty());
4071 /// ```
4072 #[cfg_attr(feature = "inline-more", inline)]
4073 pub fn remove(self) -> V {
4074 self.remove_entry().1
4075 }
4076
4077 /// Provides shared access to the key and owned access to the value of
4078 /// the entry and allows to replace or remove it based on the
4079 /// value of the returned option.
4080 ///
4081 /// # Examples
4082 ///
4083 /// ```
4084 /// use hashbrown::HashMap;
4085 /// use hashbrown::hash_map::Entry;
4086 ///
4087 /// let mut map: HashMap<&str, u32> = HashMap::new();
4088 /// map.insert("poneyland", 42);
4089 ///
4090 /// let entry = match map.entry("poneyland") {
4091 /// Entry::Occupied(e) => {
4092 /// e.replace_entry_with(|k, v| {
4093 /// assert_eq!(k, &"poneyland");
4094 /// assert_eq!(v, 42);
4095 /// Some(v + 1)
4096 /// })
4097 /// }
4098 /// Entry::Vacant(_) => panic!(),
4099 /// };
4100 ///
4101 /// match entry {
4102 /// Entry::Occupied(e) => {
4103 /// assert_eq!(e.key(), &"poneyland");
4104 /// assert_eq!(e.get(), &43);
4105 /// }
4106 /// Entry::Vacant(_) => panic!(),
4107 /// }
4108 ///
4109 /// assert_eq!(map["poneyland"], 43);
4110 ///
4111 /// let entry = match map.entry("poneyland") {
4112 /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None),
4113 /// Entry::Vacant(_) => panic!(),
4114 /// };
4115 ///
4116 /// match entry {
4117 /// Entry::Vacant(e) => {
4118 /// assert_eq!(e.key(), &"poneyland");
4119 /// }
4120 /// Entry::Occupied(_) => panic!(),
4121 /// }
4122 ///
4123 /// assert!(!map.contains_key("poneyland"));
4124 /// ```
4125 #[cfg_attr(feature = "inline-more", inline)]
4126 pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
4127 where
4128 F: FnOnce(&K, V) -> Option<V>,
4129 {
4130 unsafe {
4131 let mut spare_key = None;
4132
4133 self.table
4134 .table
4135 .replace_bucket_with(self.elem.clone(), |(key, value)| {
4136 if let Some(new_value) = f(&key, value) {
4137 Some((key, new_value))
4138 } else {
4139 spare_key = Some(key);
4140 None
4141 }
4142 });
4143
4144 if let Some(key) = spare_key {
4145 Entry::Vacant(VacantEntry {
4146 hash: self.hash,
4147 key,
4148 table: self.table,
4149 })
4150 } else {
4151 Entry::Occupied(self)
4152 }
4153 }
4154 }
4155
4156 /// Converts the `OccupiedEntry` into a mutable reference to the underlying map.
4157 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
4158 self.table
4159 }
4160}
4161
4162impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> {
4163 /// Gets a reference to the key that would be used when inserting a value
4164 /// through the `VacantEntry`.
4165 ///
4166 /// # Examples
4167 ///
4168 /// ```
4169 /// use hashbrown::HashMap;
4170 ///
4171 /// let mut map: HashMap<&str, u32> = HashMap::new();
4172 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
4173 /// ```
4174 #[cfg_attr(feature = "inline-more", inline)]
4175 pub fn key(&self) -> &K {
4176 &self.key
4177 }
4178
4179 /// Take ownership of the key.
4180 ///
4181 /// # Examples
4182 ///
4183 /// ```
4184 /// use hashbrown::hash_map::{Entry, HashMap};
4185 ///
4186 /// let mut map: HashMap<&str, u32> = HashMap::new();
4187 ///
4188 /// match map.entry("poneyland") {
4189 /// Entry::Occupied(_) => panic!(),
4190 /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"),
4191 /// }
4192 /// ```
4193 #[cfg_attr(feature = "inline-more", inline)]
4194 pub fn into_key(self) -> K {
4195 self.key
4196 }
4197
4198 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4199 /// and returns a mutable reference to it.
4200 ///
4201 /// # Examples
4202 ///
4203 /// ```
4204 /// use hashbrown::HashMap;
4205 /// use hashbrown::hash_map::Entry;
4206 ///
4207 /// let mut map: HashMap<&str, u32> = HashMap::new();
4208 ///
4209 /// if let Entry::Vacant(o) = map.entry("poneyland") {
4210 /// o.insert(37);
4211 /// }
4212 /// assert_eq!(map["poneyland"], 37);
4213 /// ```
4214 #[cfg_attr(feature = "inline-more", inline)]
4215 pub fn insert(self, value: V) -> &'a mut V
4216 where
4217 K: Hash,
4218 S: BuildHasher,
4219 {
4220 let table = &mut self.table.table;
4221 let entry = table.insert_entry(
4222 self.hash,
4223 (self.key, value),
4224 make_hasher::<_, V, S>(&self.table.hash_builder),
4225 );
4226 &mut entry.1
4227 }
4228
4229 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4230 /// and returns an [`OccupiedEntry`].
4231 ///
4232 /// # Examples
4233 ///
4234 /// ```
4235 /// use hashbrown::HashMap;
4236 /// use hashbrown::hash_map::Entry;
4237 ///
4238 /// let mut map: HashMap<&str, u32> = HashMap::new();
4239 ///
4240 /// if let Entry::Vacant(v) = map.entry("poneyland") {
4241 /// let o = v.insert_entry(37);
4242 /// assert_eq!(o.get(), &37);
4243 /// }
4244 /// ```
4245 #[cfg_attr(feature = "inline-more", inline)]
4246 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4247 where
4248 K: Hash,
4249 S: BuildHasher,
4250 {
4251 let elem = self.table.table.insert(
4252 self.hash,
4253 (self.key, value),
4254 make_hasher::<_, V, S>(&self.table.hash_builder),
4255 );
4256 OccupiedEntry {
4257 hash: self.hash,
4258 elem,
4259 table: self.table,
4260 }
4261 }
4262
4263 /// Converts the `VacantEntry` into a mutable reference to the underlying map.
4264 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
4265 self.table
4266 }
4267}
4268
4269impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
4270 /// Sets the value of the entry, and returns an `OccupiedEntry`.
4271 ///
4272 /// # Examples
4273 ///
4274 /// ```
4275 /// use hashbrown::HashMap;
4276 ///
4277 /// let mut map: HashMap<String, u32> = HashMap::new();
4278 /// let entry = map.entry_ref("horseyland").insert(37);
4279 ///
4280 /// assert_eq!(entry.key(), "horseyland");
4281 /// ```
4282 #[cfg_attr(feature = "inline-more", inline)]
4283 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4284 where
4285 K: Hash,
4286 Q: ToOwned<Owned = K>,
4287 S: BuildHasher,
4288 {
4289 match self {
4290 EntryRef::Occupied(mut entry) => {
4291 entry.insert(value);
4292 entry
4293 }
4294 EntryRef::Vacant(entry) => entry.insert_entry(value),
4295 }
4296 }
4297
4298 /// Ensures a value is in the entry by inserting the default if empty, and returns
4299 /// a mutable reference to the value in the entry.
4300 ///
4301 /// # Examples
4302 ///
4303 /// ```
4304 /// use hashbrown::HashMap;
4305 ///
4306 /// let mut map: HashMap<String, u32> = HashMap::new();
4307 ///
4308 /// // nonexistent key
4309 /// map.entry_ref("poneyland").or_insert(3);
4310 /// assert_eq!(map["poneyland"], 3);
4311 ///
4312 /// // existing key
4313 /// *map.entry_ref("poneyland").or_insert(10) *= 2;
4314 /// assert_eq!(map["poneyland"], 6);
4315 /// ```
4316 #[cfg_attr(feature = "inline-more", inline)]
4317 pub fn or_insert(self, default: V) -> &'a mut V
4318 where
4319 K: Hash,
4320 Q: ToOwned<Owned = K>,
4321 S: BuildHasher,
4322 {
4323 match self {
4324 EntryRef::Occupied(entry) => entry.into_mut(),
4325 EntryRef::Vacant(entry) => entry.insert(default),
4326 }
4327 }
4328
4329 /// Ensures a value is in the entry by inserting the result of the default function if empty,
4330 /// and returns a mutable reference to the value in the entry.
4331 ///
4332 /// # Examples
4333 ///
4334 /// ```
4335 /// use hashbrown::HashMap;
4336 ///
4337 /// let mut map: HashMap<String, u32> = HashMap::new();
4338 ///
4339 /// // nonexistent key
4340 /// map.entry_ref("poneyland").or_insert_with(|| 3);
4341 /// assert_eq!(map["poneyland"], 3);
4342 ///
4343 /// // existing key
4344 /// *map.entry_ref("poneyland").or_insert_with(|| 10) *= 2;
4345 /// assert_eq!(map["poneyland"], 6);
4346 /// ```
4347 #[cfg_attr(feature = "inline-more", inline)]
4348 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
4349 where
4350 K: Hash,
4351 Q: ToOwned<Owned = K>,
4352 S: BuildHasher,
4353 {
4354 match self {
4355 EntryRef::Occupied(entry) => entry.into_mut(),
4356 EntryRef::Vacant(entry) => entry.insert(default()),
4357 }
4358 }
4359
4360 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
4361 /// This method allows for generating key-derived values for insertion by providing the default
4362 /// function an access to the borrower form of the key.
4363 ///
4364 /// # Examples
4365 ///
4366 /// ```
4367 /// use hashbrown::HashMap;
4368 ///
4369 /// let mut map: HashMap<String, usize> = HashMap::new();
4370 ///
4371 /// // nonexistent key
4372 /// map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count());
4373 /// assert_eq!(map["poneyland"], 9);
4374 ///
4375 /// // existing key
4376 /// *map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
4377 /// assert_eq!(map["poneyland"], 18);
4378 /// ```
4379 #[cfg_attr(feature = "inline-more", inline)]
4380 pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V
4381 where
4382 K: Hash + Borrow<Q>,
4383 Q: ToOwned<Owned = K>,
4384 S: BuildHasher,
4385 {
4386 match self {
4387 EntryRef::Occupied(entry) => entry.into_mut(),
4388 EntryRef::Vacant(entry) => {
4389 let value = default(entry.key);
4390 entry.insert(value)
4391 }
4392 }
4393 }
4394
4395 /// Returns a reference to this entry's key.
4396 ///
4397 /// # Examples
4398 ///
4399 /// ```
4400 /// use hashbrown::HashMap;
4401 ///
4402 /// let mut map: HashMap<String, u32> = HashMap::new();
4403 /// map.entry_ref("poneyland").or_insert(3);
4404 /// // existing key
4405 /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland");
4406 /// // nonexistent key
4407 /// assert_eq!(map.entry_ref("horseland").key(), "horseland");
4408 /// ```
4409 #[cfg_attr(feature = "inline-more", inline)]
4410 pub fn key(&self) -> &Q
4411 where
4412 K: Borrow<Q>,
4413 {
4414 match *self {
4415 EntryRef::Occupied(ref entry) => entry.key().borrow(),
4416 EntryRef::Vacant(ref entry) => entry.key(),
4417 }
4418 }
4419
4420 /// Provides in-place mutable access to an occupied entry before any
4421 /// potential inserts into the map.
4422 ///
4423 /// # Examples
4424 ///
4425 /// ```
4426 /// use hashbrown::HashMap;
4427 ///
4428 /// let mut map: HashMap<String, u32> = HashMap::new();
4429 ///
4430 /// map.entry_ref("poneyland")
4431 /// .and_modify(|e| { *e += 1 })
4432 /// .or_insert(42);
4433 /// assert_eq!(map["poneyland"], 42);
4434 ///
4435 /// map.entry_ref("poneyland")
4436 /// .and_modify(|e| { *e += 1 })
4437 /// .or_insert(42);
4438 /// assert_eq!(map["poneyland"], 43);
4439 /// ```
4440 #[cfg_attr(feature = "inline-more", inline)]
4441 pub fn and_modify<F>(self, f: F) -> Self
4442 where
4443 F: FnOnce(&mut V),
4444 {
4445 match self {
4446 EntryRef::Occupied(mut entry) => {
4447 f(entry.get_mut());
4448 EntryRef::Occupied(entry)
4449 }
4450 EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
4451 }
4452 }
4453
4454 /// Converts the `EntryRef` into a mutable reference to the underlying map.
4455 pub fn into_map(self) -> &'a mut HashMap<K, V, S, A> {
4456 match self {
4457 EntryRef::Occupied(entry) => entry.table,
4458 EntryRef::Vacant(entry) => entry.table,
4459 }
4460 }
4461}
4462
4463impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
4464 /// Ensures a value is in the entry by inserting the default value if empty,
4465 /// and returns a mutable reference to the value in the entry.
4466 ///
4467 /// # Examples
4468 ///
4469 /// ```
4470 /// use hashbrown::HashMap;
4471 ///
4472 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4473 ///
4474 /// // nonexistent key
4475 /// map.entry_ref("poneyland").or_default();
4476 /// assert_eq!(map["poneyland"], None);
4477 ///
4478 /// map.insert("horseland".to_string(), Some(3));
4479 ///
4480 /// // existing key
4481 /// assert_eq!(map.entry_ref("horseland").or_default(), &mut Some(3));
4482 /// ```
4483 #[cfg_attr(feature = "inline-more", inline)]
4484 pub fn or_default(self) -> &'a mut V
4485 where
4486 K: Hash,
4487 Q: ToOwned<Owned = K>,
4488 S: BuildHasher,
4489 {
4490 match self {
4491 EntryRef::Occupied(entry) => entry.into_mut(),
4492 EntryRef::Vacant(entry) => entry.insert(Default::default()),
4493 }
4494 }
4495
4496 /// Ensures a value is in the entry by inserting the default value if empty,
4497 /// and returns an [`OccupiedEntry`].
4498 ///
4499 /// # Examples
4500 ///
4501 /// ```
4502 /// use hashbrown::HashMap;
4503 ///
4504 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4505 ///
4506 /// // nonexistent key
4507 /// let entry = map.entry_ref("poneyland").or_default_entry();
4508 /// assert_eq!(entry.key(), &"poneyland");
4509 /// assert_eq!(entry.get(), &None);
4510 ///
4511 /// // existing key
4512 /// map.insert("horseland".to_string(), Some(3));
4513 /// let entry = map.entry_ref("horseland").or_default_entry();
4514 /// assert_eq!(entry.key(), &"horseland");
4515 /// assert_eq!(entry.get(), &Some(3));
4516 /// ```
4517 #[cfg_attr(feature = "inline-more", inline)]
4518 pub fn or_default_entry(self) -> OccupiedEntry<'a, K, V, S, A>
4519 where
4520 K: Hash,
4521 Q: ToOwned<Owned = K>,
4522 S: BuildHasher,
4523 {
4524 match self {
4525 EntryRef::Occupied(entry) => entry,
4526 EntryRef::Vacant(entry) => entry.insert_entry(Default::default()),
4527 }
4528 }
4529}
4530
4531impl<'map, 'key, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'map, 'key, K, Q, V, S, A> {
4532 /// Gets a reference to the key that would be used when inserting a value
4533 /// through the `VacantEntryRef`.
4534 ///
4535 /// # Examples
4536 ///
4537 /// ```
4538 /// use hashbrown::HashMap;
4539 ///
4540 /// let mut map: HashMap<String, u32> = HashMap::new();
4541 /// let key: &str = "poneyland";
4542 /// assert_eq!(map.entry_ref(key).key(), "poneyland");
4543 /// ```
4544 #[cfg_attr(feature = "inline-more", inline)]
4545 pub fn key(&self) -> &'key Q {
4546 self.key
4547 }
4548
4549 /// Sets the value of the entry with the `VacantEntryRef`'s key,
4550 /// and returns a mutable reference to it.
4551 ///
4552 /// # Examples
4553 ///
4554 /// ```
4555 /// use hashbrown::HashMap;
4556 /// use hashbrown::hash_map::EntryRef;
4557 ///
4558 /// let mut map: HashMap<String, u32> = HashMap::new();
4559 /// let key: &str = "poneyland";
4560 ///
4561 /// if let EntryRef::Vacant(o) = map.entry_ref(key) {
4562 /// o.insert(37);
4563 /// }
4564 /// assert_eq!(map["poneyland"], 37);
4565 /// ```
4566 #[cfg_attr(feature = "inline-more", inline)]
4567 pub fn insert(self, value: V) -> &'map mut V
4568 where
4569 K: Hash,
4570 Q: ToOwned<Owned = K>,
4571 S: BuildHasher,
4572 {
4573 let table = &mut self.table.table;
4574 let entry = table.insert_entry(
4575 self.hash,
4576 (self.key.to_owned(), value),
4577 make_hasher::<_, V, S>(&self.table.hash_builder),
4578 );
4579 &mut entry.1
4580 }
4581
4582 /// Sets the key and value of the entry and returns a mutable reference to
4583 /// the inserted value.
4584 ///
4585 /// Unlike [`VacantEntryRef::insert`], this method allows the key to be
4586 /// explicitly specified, which is useful for key types that don't implement
4587 /// `ToOwned`.
4588 ///
4589 /// # Panics
4590 ///
4591 /// This method panics if `key` is not equivalent to the key used to create
4592 /// the `VacantEntryRef`.
4593 ///
4594 /// # Example
4595 ///
4596 /// ```
4597 /// use hashbrown::hash_map::EntryRef;
4598 /// use hashbrown::HashMap;
4599 ///
4600 /// let mut map = HashMap::<(String, String), char>::new();
4601 /// let k = ("c".to_string(), "C".to_string());
4602 /// let v = match map.entry_ref(&k) {
4603 /// // Insert cannot be used here because tuples do not implement ToOwned.
4604 /// // However this works because we can manually clone instead.
4605 /// EntryRef::Vacant(r) => r.insert_with_key(k.clone(), 'c'),
4606 /// // In this branch we avoid the clone.
4607 /// EntryRef::Occupied(r) => r.into_mut(),
4608 /// };
4609 /// assert_eq!(*v, 'c');
4610 /// ```
4611 #[cfg_attr(feature = "inline-more", inline)]
4612 pub fn insert_with_key(self, key: K, value: V) -> &'map mut V
4613 where
4614 K: Hash,
4615 Q: Equivalent<K>,
4616 S: BuildHasher,
4617 {
4618 self.insert_entry_with_key(key, value).into_mut()
4619 }
4620
4621 /// Sets the key and value of the entry and returns a mutable reference to
4622 /// the inserted value, without checking the equivalence of the key.
4623 ///
4624 /// See [`insert_with_key`](Self::insert_with_key) for more information.
4625 ///
4626 /// # Safety
4627 ///
4628 /// This operation is safe if the keys are equivalent.
4629 ///
4630 /// Additionally, this operation (and following operations) are guaranteed
4631 /// to not violate memory safety.
4632 ///
4633 /// However this operation is still unsafe because the resulting `HashMap`
4634 /// may be passed to unsafe code which does expect the map to behave
4635 /// correctly. If the map has keys at unexpected positions inside it,
4636 /// future operations may panic, loop forever, or return unexpected results,
4637 /// potentially violating memory safety.
4638 ///
4639 /// # Example
4640 ///
4641 /// ```
4642 /// use hashbrown::hash_map::EntryRef;
4643 /// use hashbrown::HashMap;
4644 ///
4645 /// let mut map = HashMap::<(String, String), char>::new();
4646 /// let k = ("c".to_string(), "C".to_string());
4647 /// let v = match map.entry_ref(&k) {
4648 /// // SAFETY: We trust the `Clone` implementation to return an equivalent value
4649 /// EntryRef::Vacant(r) => unsafe { r.insert_with_key_unchecked(k.clone(), 'c') },
4650 /// // In this branch we avoid the clone.
4651 /// EntryRef::Occupied(r) => r.into_mut(),
4652 /// };
4653 /// assert_eq!(*v, 'c');
4654 /// ```
4655 #[cfg_attr(feature = "inline-more", inline)]
4656 pub unsafe fn insert_with_key_unchecked(self, key: K, value: V) -> &'map mut V
4657 where
4658 K: Hash,
4659 S: BuildHasher,
4660 {
4661 // SAFETY: Guaranteed by caller.
4662 unsafe { self.insert_entry_with_key_unchecked(key, value) }.into_mut()
4663 }
4664
4665 /// Sets the value of the entry with the [`VacantEntryRef`]'s key,
4666 /// and returns an [`OccupiedEntry`].
4667 ///
4668 /// # Examples
4669 ///
4670 /// ```
4671 /// use hashbrown::HashMap;
4672 /// use hashbrown::hash_map::EntryRef;
4673 ///
4674 /// let mut map: HashMap<&str, u32> = HashMap::new();
4675 ///
4676 /// if let EntryRef::Vacant(v) = map.entry_ref(&"poneyland") {
4677 /// let o = v.insert_entry(37);
4678 /// assert_eq!(o.get(), &37);
4679 /// }
4680 /// ```
4681 #[cfg_attr(feature = "inline-more", inline)]
4682 pub fn insert_entry(self, value: V) -> OccupiedEntry<'map, K, V, S, A>
4683 where
4684 K: Hash,
4685 Q: ToOwned<Owned = K>,
4686 S: BuildHasher,
4687 {
4688 let elem = self.table.table.insert(
4689 self.hash,
4690 (self.key.to_owned(), value),
4691 make_hasher::<_, V, S>(&self.table.hash_builder),
4692 );
4693 OccupiedEntry {
4694 hash: self.hash,
4695 elem,
4696 table: self.table,
4697 }
4698 }
4699
4700 /// Sets the key and value of the entry and returns an [`OccupiedEntry`].
4701 ///
4702 /// Unlike [`VacantEntryRef::insert_entry`], this method allows the key to
4703 /// be explicitly specified, which is useful for key types that don't
4704 /// implement `ToOwned`.
4705 ///
4706 /// # Panics
4707 ///
4708 /// This method panics if `key` is not equivalent to the key used to create
4709 /// the `VacantEntryRef`.
4710 ///
4711 /// # Example
4712 ///
4713 /// ```
4714 /// use hashbrown::hash_map::EntryRef;
4715 /// use hashbrown::HashMap;
4716 ///
4717 /// let mut map = HashMap::<(String, String), char>::new();
4718 /// let k = ("c".to_string(), "C".to_string());
4719 /// let r = match map.entry_ref(&k) {
4720 /// // Insert cannot be used here because tuples do not implement ToOwned.
4721 /// // However this works because we can manually clone instead.
4722 /// EntryRef::Vacant(r) => r.insert_entry_with_key(k.clone(), 'c'),
4723 /// // In this branch we avoid the clone.
4724 /// EntryRef::Occupied(r) => r,
4725 /// };
4726 /// assert_eq!(r.get(), &'c');
4727 /// ```
4728 #[cfg_attr(feature = "inline-more", inline)]
4729 pub fn insert_entry_with_key(self, key: K, value: V) -> OccupiedEntry<'map, K, V, S, A>
4730 where
4731 K: Hash,
4732 Q: Equivalent<K>,
4733 S: BuildHasher,
4734 {
4735 assert!(
4736 (self.key).equivalent(&key),
4737 "key used for Entry creation is not equivalent to the one used for insertion"
4738 );
4739 // SAFETY: We checked equivalence first.
4740 unsafe { self.insert_entry_with_key_unchecked(key, value) }
4741 }
4742
4743 /// Sets the key and value of the entry and returns an [`OccupiedEntry`],
4744 /// without checking the equivalence of the key.
4745 ///
4746 /// See [`insert_entry_with_key`](Self::insert_entry_with_key) for more information.
4747 ///
4748 /// # Safety
4749 ///
4750 /// This operation is safe if the keys are equivalent.
4751 ///
4752 /// Additionally, this operation (and following operations) are guaranteed
4753 /// to not violate memory safety.
4754 ///
4755 /// However this operation is still unsafe because the resulting `HashMap`
4756 /// may be passed to unsafe code which does expect the map to behave
4757 /// correctly. If the map has keys at unexpected positions inside it,
4758 /// future operations may panic, loop forever, or return unexpected results,
4759 /// potentially violating memory safety.
4760 ///
4761 /// # Example
4762 ///
4763 /// ```
4764 /// use hashbrown::hash_map::EntryRef;
4765 /// use hashbrown::HashMap;
4766 ///
4767 /// let mut map = HashMap::<(String, String), char>::new();
4768 /// let k = ("c".to_string(), "C".to_string());
4769 /// let r = match map.entry_ref(&k) {
4770 /// // SAFETY: We trust the `Clone` implementation to return an equivalent key
4771 /// EntryRef::Vacant(r) => unsafe { r.insert_entry_with_key_unchecked(k.clone(), 'c') },
4772 /// // In this branch we avoid the clone.
4773 /// EntryRef::Occupied(r) => r,
4774 /// };
4775 /// assert_eq!(r.get(), &'c');
4776 /// ```
4777 #[cfg_attr(feature = "inline-more", inline)]
4778 pub unsafe fn insert_entry_with_key_unchecked(
4779 self,
4780 key: K,
4781 value: V,
4782 ) -> OccupiedEntry<'map, K, V, S, A>
4783 where
4784 K: Hash,
4785 S: BuildHasher,
4786 {
4787 let elem = self.table.table.insert(
4788 self.hash,
4789 (key, value),
4790 make_hasher::<_, V, S>(&self.table.hash_builder),
4791 );
4792 OccupiedEntry {
4793 hash: self.hash,
4794 elem,
4795 table: self.table,
4796 }
4797 }
4798
4799 /// Converts the `VacantEntryRef` into a mutable reference to the underlying map.
4800 pub fn into_map(self) -> &'map mut HashMap<K, V, S, A> {
4801 self.table
4802 }
4803}
4804
4805impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A>
4806where
4807 K: Eq + Hash,
4808 S: BuildHasher + Default,
4809 A: Default + Allocator,
4810{
4811 #[cfg_attr(feature = "inline-more", inline)]
4812 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
4813 let iter = iter.into_iter();
4814 let mut map =
4815 Self::with_capacity_and_hasher_in(iter.size_hint().0, S::default(), A::default());
4816 iter.for_each(|(k, v)| {
4817 map.insert(k, v);
4818 });
4819 map
4820 }
4821}
4822
4823/// Inserts all new key-values from the iterator and replaces values with existing
4824/// keys with new values returned from the iterator.
4825impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
4826where
4827 K: Eq + Hash,
4828 S: BuildHasher,
4829 A: Allocator,
4830{
4831 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4832 /// Replace values with existing keys with new values returned from the iterator.
4833 ///
4834 /// # Examples
4835 ///
4836 /// ```
4837 /// use hashbrown::hash_map::HashMap;
4838 ///
4839 /// let mut map = HashMap::new();
4840 /// map.insert(1, 100);
4841 ///
4842 /// let some_iter = [(1, 1), (2, 2)].into_iter();
4843 /// map.extend(some_iter);
4844 /// // Replace values with existing keys with new values returned from the iterator.
4845 /// // So that the map.get(&1) doesn't return Some(&100).
4846 /// assert_eq!(map.get(&1), Some(&1));
4847 ///
4848 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4849 /// map.extend(some_vec);
4850 ///
4851 /// let some_arr = [(5, 5), (6, 6)];
4852 /// map.extend(some_arr);
4853 /// let old_map_len = map.len();
4854 ///
4855 /// // You can also extend from another HashMap
4856 /// let mut new_map = HashMap::new();
4857 /// new_map.extend(map);
4858 /// assert_eq!(new_map.len(), old_map_len);
4859 ///
4860 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4861 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4862 /// // items must be sorted to test them against a sorted array.
4863 /// vec.sort_unstable();
4864 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4865 /// ```
4866 #[cfg_attr(feature = "inline-more", inline)]
4867 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
4868 // Keys may be already present or show multiple times in the iterator.
4869 // Reserve the entire hint lower bound if the map is empty.
4870 // Otherwise reserve half the hint (rounded up), so the map
4871 // will only resize twice in the worst case.
4872 let iter = iter.into_iter();
4873 let reserve = if self.is_empty() {
4874 iter.size_hint().0
4875 } else {
4876 iter.size_hint().0.div_ceil(2)
4877 };
4878 self.reserve(reserve);
4879 iter.for_each(move |(k, v)| {
4880 self.insert(k, v);
4881 });
4882 }
4883
4884 #[inline]
4885 #[cfg(feature = "nightly")]
4886 fn extend_one(&mut self, (k, v): (K, V)) {
4887 self.insert(k, v);
4888 }
4889
4890 #[inline]
4891 #[cfg(feature = "nightly")]
4892 fn extend_reserve(&mut self, additional: usize) {
4893 // Keys may be already present or show multiple times in the iterator.
4894 // Reserve the entire hint lower bound if the map is empty.
4895 // Otherwise reserve half the hint (rounded up), so the map
4896 // will only resize twice in the worst case.
4897 let reserve = if self.is_empty() {
4898 additional
4899 } else {
4900 additional.div_ceil(2)
4901 };
4902 self.reserve(reserve);
4903 }
4904}
4905
4906/// Inserts all new key-values from the iterator and replaces values with existing
4907/// keys with new values returned from the iterator.
4908impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
4909where
4910 K: Eq + Hash + Copy,
4911 V: Copy,
4912 S: BuildHasher,
4913 A: Allocator,
4914{
4915 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4916 /// Replace values with existing keys with new values returned from the iterator.
4917 /// The keys and values must implement [`Copy`] trait.
4918 ///
4919 /// # Examples
4920 ///
4921 /// ```
4922 /// use hashbrown::hash_map::HashMap;
4923 ///
4924 /// let mut map = HashMap::new();
4925 /// map.insert(1, 100);
4926 ///
4927 /// let arr = [(1, 1), (2, 2)];
4928 /// let some_iter = arr.iter().map(|(k, v)| (k, v));
4929 /// map.extend(some_iter);
4930 /// // Replace values with existing keys with new values returned from the iterator.
4931 /// // So that the map.get(&1) doesn't return Some(&100).
4932 /// assert_eq!(map.get(&1), Some(&1));
4933 ///
4934 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4935 /// map.extend(some_vec.iter().map(|(k, v)| (k, v)));
4936 ///
4937 /// let some_arr = [(5, 5), (6, 6)];
4938 /// map.extend(some_arr.iter().map(|(k, v)| (k, v)));
4939 ///
4940 /// // You can also extend from another HashMap
4941 /// let mut new_map = HashMap::new();
4942 /// new_map.extend(&map);
4943 /// assert_eq!(new_map, map);
4944 ///
4945 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4946 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4947 /// // items must be sorted to test them against a sorted array.
4948 /// vec.sort_unstable();
4949 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4950 /// ```
4951 #[cfg_attr(feature = "inline-more", inline)]
4952 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
4953 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
4954 }
4955
4956 #[inline]
4957 #[cfg(feature = "nightly")]
4958 fn extend_one(&mut self, (k, v): (&'a K, &'a V)) {
4959 self.insert(*k, *v);
4960 }
4961
4962 #[inline]
4963 #[cfg(feature = "nightly")]
4964 fn extend_reserve(&mut self, additional: usize) {
4965 Extend::<(K, V)>::extend_reserve(self, additional);
4966 }
4967}
4968
4969/// Inserts all new key-values from the iterator and replaces values with existing
4970/// keys with new values returned from the iterator.
4971impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A>
4972where
4973 K: Eq + Hash + Copy,
4974 V: Copy,
4975 S: BuildHasher,
4976 A: Allocator,
4977{
4978 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4979 /// Replace values with existing keys with new values returned from the iterator.
4980 /// The keys and values must implement [`Copy`] trait.
4981 ///
4982 /// # Examples
4983 ///
4984 /// ```
4985 /// use hashbrown::hash_map::HashMap;
4986 ///
4987 /// let mut map = HashMap::new();
4988 /// map.insert(1, 100);
4989 ///
4990 /// let arr = [(1, 1), (2, 2)];
4991 /// let some_iter = arr.iter();
4992 /// map.extend(some_iter);
4993 /// // Replace values with existing keys with new values returned from the iterator.
4994 /// // So that the map.get(&1) doesn't return Some(&100).
4995 /// assert_eq!(map.get(&1), Some(&1));
4996 ///
4997 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4998 /// map.extend(&some_vec);
4999 ///
5000 /// let some_arr = [(5, 5), (6, 6)];
5001 /// map.extend(&some_arr);
5002 ///
5003 /// let mut vec: Vec<_> = map.into_iter().collect();
5004 /// // The `IntoIter` iterator produces items in arbitrary order, so the
5005 /// // items must be sorted to test them against a sorted array.
5006 /// vec.sort_unstable();
5007 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
5008 /// ```
5009 #[cfg_attr(feature = "inline-more", inline)]
5010 fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
5011 self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
5012 }
5013
5014 #[inline]
5015 #[cfg(feature = "nightly")]
5016 fn extend_one(&mut self, &(k, v): &'a (K, V)) {
5017 self.insert(k, v);
5018 }
5019
5020 #[inline]
5021 #[cfg(feature = "nightly")]
5022 fn extend_reserve(&mut self, additional: usize) {
5023 Extend::<(K, V)>::extend_reserve(self, additional);
5024 }
5025}
5026
5027#[expect(dead_code)]
5028fn assert_covariance() {
5029 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
5030 v
5031 }
5032 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
5033 v
5034 }
5035 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
5036 v
5037 }
5038 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
5039 v
5040 }
5041 fn into_iter_key<'new, A: Allocator>(
5042 v: IntoIter<&'static str, u8, A>,
5043 ) -> IntoIter<&'new str, u8, A> {
5044 v
5045 }
5046 fn into_iter_val<'new, A: Allocator>(
5047 v: IntoIter<u8, &'static str, A>,
5048 ) -> IntoIter<u8, &'new str, A> {
5049 v
5050 }
5051 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
5052 v
5053 }
5054 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
5055 v
5056 }
5057 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
5058 v
5059 }
5060 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
5061 v
5062 }
5063 fn drain<'new>(
5064 d: Drain<'static, &'static str, &'static str>,
5065 ) -> Drain<'new, &'new str, &'new str> {
5066 d
5067 }
5068}
5069
5070#[cfg(test)]
5071mod test_map {
5072 use super::DefaultHashBuilder;
5073 use super::Entry::{Occupied, Vacant};
5074 use super::EntryRef;
5075 use super::HashMap;
5076 use crate::alloc::{AllocError, Allocator, Global};
5077 use core::alloc::Layout;
5078 use core::ptr::NonNull;
5079 use core::sync::atomic::{AtomicI8, Ordering};
5080 use rand::{Rng, SeedableRng, rngs::SmallRng};
5081 use std::borrow::ToOwned;
5082 use std::cell::RefCell;
5083 use std::vec::Vec;
5084 use stdalloc::string::String;
5085 use stdalloc::sync::Arc;
5086
5087 #[test]
5088 fn test_zero_capacities() {
5089 type HM = HashMap<i32, i32>;
5090
5091 let m = HM::new();
5092 assert_eq!(m.capacity(), 0);
5093
5094 let m = HM::default();
5095 assert_eq!(m.capacity(), 0);
5096
5097 let m = HM::with_hasher(DefaultHashBuilder::default());
5098 assert_eq!(m.capacity(), 0);
5099
5100 let m = HM::with_capacity(0);
5101 assert_eq!(m.capacity(), 0);
5102
5103 let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
5104 assert_eq!(m.capacity(), 0);
5105
5106 let mut m = HM::new();
5107 m.insert(1, 1);
5108 m.insert(2, 2);
5109 m.remove(&1);
5110 m.remove(&2);
5111 m.shrink_to_fit();
5112 assert_eq!(m.capacity(), 0);
5113
5114 let mut m = HM::new();
5115 m.reserve(0);
5116 assert_eq!(m.capacity(), 0);
5117 }
5118
5119 #[test]
5120 fn test_create_capacity_zero() {
5121 let mut m = HashMap::with_capacity(0);
5122
5123 assert!(m.insert(1, 1).is_none());
5124
5125 assert!(m.contains_key(&1));
5126 assert!(!m.contains_key(&0));
5127 }
5128
5129 #[test]
5130 fn test_insert() {
5131 let mut m = HashMap::new();
5132 assert_eq!(m.len(), 0);
5133 assert!(m.insert(1, 2).is_none());
5134 assert_eq!(m.len(), 1);
5135 assert!(m.insert(2, 4).is_none());
5136 assert_eq!(m.len(), 2);
5137 assert_eq!(*m.get(&1).unwrap(), 2);
5138 assert_eq!(*m.get(&2).unwrap(), 4);
5139 }
5140
5141 #[test]
5142 fn test_clone() {
5143 let mut m = HashMap::new();
5144 assert_eq!(m.len(), 0);
5145 assert!(m.insert(1, 2).is_none());
5146 assert_eq!(m.len(), 1);
5147 assert!(m.insert(2, 4).is_none());
5148 assert_eq!(m.len(), 2);
5149 let m2 = m.clone();
5150 assert_eq!(*m2.get(&1).unwrap(), 2);
5151 assert_eq!(*m2.get(&2).unwrap(), 4);
5152 assert_eq!(m2.len(), 2);
5153 }
5154
5155 #[test]
5156 fn test_clone_from() {
5157 let mut m = HashMap::new();
5158 let mut m2 = HashMap::new();
5159 assert_eq!(m.len(), 0);
5160 assert!(m.insert(1, 2).is_none());
5161 assert_eq!(m.len(), 1);
5162 assert!(m.insert(2, 4).is_none());
5163 assert_eq!(m.len(), 2);
5164 m2.clone_from(&m);
5165 assert_eq!(*m2.get(&1).unwrap(), 2);
5166 assert_eq!(*m2.get(&2).unwrap(), 4);
5167 assert_eq!(m2.len(), 2);
5168 }
5169
5170 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = const { RefCell::new(Vec::new()) } }
5171
5172 #[derive(Hash, PartialEq, Eq)]
5173 struct Droppable {
5174 k: usize,
5175 }
5176
5177 impl Droppable {
5178 fn new(k: usize) -> Droppable {
5179 DROP_VECTOR.with(|slot| {
5180 slot.borrow_mut()[k] += 1;
5181 });
5182
5183 Droppable { k }
5184 }
5185 }
5186
5187 impl Drop for Droppable {
5188 fn drop(&mut self) {
5189 DROP_VECTOR.with(|slot| {
5190 slot.borrow_mut()[self.k] -= 1;
5191 });
5192 }
5193 }
5194
5195 impl Clone for Droppable {
5196 fn clone(&self) -> Self {
5197 Droppable::new(self.k)
5198 }
5199 }
5200
5201 #[test]
5202 fn test_drops() {
5203 DROP_VECTOR.with(|slot| {
5204 *slot.borrow_mut() = vec![0; 200];
5205 });
5206
5207 {
5208 let mut m = HashMap::new();
5209
5210 DROP_VECTOR.with(|v| {
5211 for i in 0..200 {
5212 assert_eq!(v.borrow()[i], 0);
5213 }
5214 });
5215
5216 for i in 0..100 {
5217 let d1 = Droppable::new(i);
5218 let d2 = Droppable::new(i + 100);
5219 m.insert(d1, d2);
5220 }
5221
5222 DROP_VECTOR.with(|v| {
5223 for i in 0..200 {
5224 assert_eq!(v.borrow()[i], 1);
5225 }
5226 });
5227
5228 for i in 0..50 {
5229 let k = Droppable::new(i);
5230 let v = m.remove(&k);
5231
5232 assert!(v.is_some());
5233
5234 DROP_VECTOR.with(|v| {
5235 assert_eq!(v.borrow()[i], 1);
5236 assert_eq!(v.borrow()[i + 100], 1);
5237 });
5238 }
5239
5240 DROP_VECTOR.with(|v| {
5241 for i in 0..50 {
5242 assert_eq!(v.borrow()[i], 0);
5243 assert_eq!(v.borrow()[i + 100], 0);
5244 }
5245
5246 for i in 50..100 {
5247 assert_eq!(v.borrow()[i], 1);
5248 assert_eq!(v.borrow()[i + 100], 1);
5249 }
5250 });
5251 }
5252
5253 DROP_VECTOR.with(|v| {
5254 for i in 0..200 {
5255 assert_eq!(v.borrow()[i], 0);
5256 }
5257 });
5258 }
5259
5260 #[test]
5261 fn test_into_iter_drops() {
5262 DROP_VECTOR.with(|v| {
5263 *v.borrow_mut() = vec![0; 200];
5264 });
5265
5266 let hm = {
5267 let mut hm = HashMap::new();
5268
5269 DROP_VECTOR.with(|v| {
5270 for i in 0..200 {
5271 assert_eq!(v.borrow()[i], 0);
5272 }
5273 });
5274
5275 for i in 0..100 {
5276 let d1 = Droppable::new(i);
5277 let d2 = Droppable::new(i + 100);
5278 hm.insert(d1, d2);
5279 }
5280
5281 DROP_VECTOR.with(|v| {
5282 for i in 0..200 {
5283 assert_eq!(v.borrow()[i], 1);
5284 }
5285 });
5286
5287 hm
5288 };
5289
5290 // By the way, ensure that cloning doesn't screw up the dropping.
5291 drop(hm.clone());
5292
5293 {
5294 let mut half = hm.into_iter().take(50);
5295
5296 DROP_VECTOR.with(|v| {
5297 for i in 0..200 {
5298 assert_eq!(v.borrow()[i], 1);
5299 }
5300 });
5301
5302 for _ in half.by_ref() {}
5303
5304 DROP_VECTOR.with(|v| {
5305 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
5306
5307 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
5308
5309 assert_eq!(nk, 50);
5310 assert_eq!(nv, 50);
5311 });
5312 };
5313
5314 DROP_VECTOR.with(|v| {
5315 for i in 0..200 {
5316 assert_eq!(v.borrow()[i], 0);
5317 }
5318 });
5319 }
5320
5321 #[test]
5322 fn test_empty_remove() {
5323 let mut m: HashMap<i32, bool> = HashMap::new();
5324 assert_eq!(m.remove(&0), None);
5325 }
5326
5327 #[test]
5328 fn test_empty_entry() {
5329 let mut m: HashMap<i32, bool> = HashMap::new();
5330 match m.entry(0) {
5331 Occupied(_) => panic!(),
5332 Vacant(_) => {}
5333 }
5334 assert!(*m.entry(0).or_insert(true));
5335 assert_eq!(m.len(), 1);
5336 }
5337
5338 #[test]
5339 fn test_empty_entry_ref() {
5340 let mut m: HashMap<std::string::String, bool> = HashMap::new();
5341 match m.entry_ref("poneyland") {
5342 EntryRef::Occupied(_) => panic!(),
5343 EntryRef::Vacant(_) => {}
5344 }
5345 assert!(*m.entry_ref("poneyland").or_insert(true));
5346 assert_eq!(m.len(), 1);
5347 }
5348
5349 #[test]
5350 fn test_empty_iter() {
5351 let mut m: HashMap<i32, bool> = HashMap::new();
5352 assert_eq!(m.drain().next(), None);
5353 assert_eq!(m.keys().next(), None);
5354 assert_eq!(m.values().next(), None);
5355 assert_eq!(m.values_mut().next(), None);
5356 assert_eq!(m.iter().next(), None);
5357 assert_eq!(m.iter_mut().next(), None);
5358 assert_eq!(m.len(), 0);
5359 assert!(m.is_empty());
5360 assert_eq!(m.into_iter().next(), None);
5361 }
5362
5363 #[test]
5364 #[cfg_attr(miri, ignore)] // FIXME: takes too long
5365 fn test_lots_of_insertions() {
5366 let mut m = HashMap::new();
5367
5368 // Try this a few times to make sure we never screw up the hashmap's
5369 // internal state.
5370 for _ in 0..10 {
5371 assert!(m.is_empty());
5372
5373 for i in 1..1001 {
5374 assert!(m.insert(i, i).is_none());
5375
5376 for j in 1..=i {
5377 let r = m.get(&j);
5378 assert_eq!(r, Some(&j));
5379 }
5380
5381 for j in i + 1..1001 {
5382 let r = m.get(&j);
5383 assert_eq!(r, None);
5384 }
5385 }
5386
5387 for i in 1001..2001 {
5388 assert!(!m.contains_key(&i));
5389 }
5390
5391 // remove forwards
5392 for i in 1..1001 {
5393 assert!(m.remove(&i).is_some());
5394
5395 for j in 1..=i {
5396 assert!(!m.contains_key(&j));
5397 }
5398
5399 for j in i + 1..1001 {
5400 assert!(m.contains_key(&j));
5401 }
5402 }
5403
5404 for i in 1..1001 {
5405 assert!(!m.contains_key(&i));
5406 }
5407
5408 for i in 1..1001 {
5409 assert!(m.insert(i, i).is_none());
5410 }
5411
5412 // remove backwards
5413 for i in (1..1001).rev() {
5414 assert!(m.remove(&i).is_some());
5415
5416 for j in i..1001 {
5417 assert!(!m.contains_key(&j));
5418 }
5419
5420 for j in 1..i {
5421 assert!(m.contains_key(&j));
5422 }
5423 }
5424 }
5425 }
5426
5427 #[test]
5428 fn test_find_mut() {
5429 let mut m = HashMap::new();
5430 assert!(m.insert(1, 12).is_none());
5431 assert!(m.insert(2, 8).is_none());
5432 assert!(m.insert(5, 14).is_none());
5433 let new = 100;
5434 match m.get_mut(&5) {
5435 None => panic!(),
5436 Some(x) => *x = new,
5437 }
5438 assert_eq!(m.get(&5), Some(&new));
5439 let mut hashmap: HashMap<i32, String> = HashMap::default();
5440 let key = &1;
5441 let result = hashmap.get_mut(key);
5442 assert!(result.is_none());
5443 }
5444
5445 #[test]
5446 fn test_insert_overwrite() {
5447 let mut m = HashMap::new();
5448 assert!(m.insert(1, 2).is_none());
5449 assert_eq!(*m.get(&1).unwrap(), 2);
5450 assert!(m.insert(1, 3).is_some());
5451 assert_eq!(*m.get(&1).unwrap(), 3);
5452 }
5453
5454 #[test]
5455 fn test_insert_conflicts() {
5456 let mut m = HashMap::with_capacity(4);
5457 assert!(m.insert(1, 2).is_none());
5458 assert!(m.insert(5, 3).is_none());
5459 assert!(m.insert(9, 4).is_none());
5460 assert_eq!(*m.get(&9).unwrap(), 4);
5461 assert_eq!(*m.get(&5).unwrap(), 3);
5462 assert_eq!(*m.get(&1).unwrap(), 2);
5463 }
5464
5465 #[test]
5466 fn test_conflict_remove() {
5467 let mut m = HashMap::with_capacity(4);
5468 assert!(m.insert(1, 2).is_none());
5469 assert_eq!(*m.get(&1).unwrap(), 2);
5470 assert!(m.insert(5, 3).is_none());
5471 assert_eq!(*m.get(&1).unwrap(), 2);
5472 assert_eq!(*m.get(&5).unwrap(), 3);
5473 assert!(m.insert(9, 4).is_none());
5474 assert_eq!(*m.get(&1).unwrap(), 2);
5475 assert_eq!(*m.get(&5).unwrap(), 3);
5476 assert_eq!(*m.get(&9).unwrap(), 4);
5477 assert!(m.remove(&1).is_some());
5478 assert_eq!(*m.get(&9).unwrap(), 4);
5479 assert_eq!(*m.get(&5).unwrap(), 3);
5480 }
5481
5482 #[test]
5483 fn test_insert_unique_unchecked() {
5484 let mut map = HashMap::new();
5485 let (k1, v1) = unsafe { map.insert_unique_unchecked(10, 11) };
5486 assert_eq!((&10, &mut 11), (k1, v1));
5487 let (k2, v2) = unsafe { map.insert_unique_unchecked(20, 21) };
5488 assert_eq!((&20, &mut 21), (k2, v2));
5489 assert_eq!(Some(&11), map.get(&10));
5490 assert_eq!(Some(&21), map.get(&20));
5491 assert_eq!(None, map.get(&30));
5492 }
5493
5494 #[test]
5495 fn test_is_empty() {
5496 let mut m = HashMap::with_capacity(4);
5497 assert!(m.insert(1, 2).is_none());
5498 assert!(!m.is_empty());
5499 assert!(m.remove(&1).is_some());
5500 assert!(m.is_empty());
5501 }
5502
5503 #[test]
5504 fn test_remove() {
5505 let mut m = HashMap::new();
5506 m.insert(1, 2);
5507 assert_eq!(m.remove(&1), Some(2));
5508 assert_eq!(m.remove(&1), None);
5509 }
5510
5511 #[test]
5512 fn test_remove_entry() {
5513 let mut m = HashMap::new();
5514 m.insert(1, 2);
5515 assert_eq!(m.remove_entry(&1), Some((1, 2)));
5516 assert_eq!(m.remove(&1), None);
5517 }
5518
5519 #[test]
5520 fn test_iterate() {
5521 let mut m = HashMap::with_capacity(4);
5522 for i in 0..32 {
5523 assert!(m.insert(i, i * 2).is_none());
5524 }
5525 assert_eq!(m.len(), 32);
5526
5527 let mut observed: u32 = 0;
5528
5529 for (k, v) in &m {
5530 assert_eq!(*v, *k * 2);
5531 observed |= 1 << *k;
5532 }
5533 assert_eq!(observed, 0xFFFF_FFFF);
5534 }
5535
5536 #[test]
5537 fn test_keys() {
5538 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5539 let map: HashMap<_, _> = vec.into_iter().collect();
5540 let keys: Vec<_> = map.keys().copied().collect();
5541 assert_eq!(keys.len(), 3);
5542 assert!(keys.contains(&1));
5543 assert!(keys.contains(&2));
5544 assert!(keys.contains(&3));
5545 }
5546
5547 #[test]
5548 fn test_values() {
5549 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5550 let map: HashMap<_, _> = vec.into_iter().collect();
5551 let values: Vec<_> = map.values().copied().collect();
5552 assert_eq!(values.len(), 3);
5553 assert!(values.contains(&'a'));
5554 assert!(values.contains(&'b'));
5555 assert!(values.contains(&'c'));
5556 }
5557
5558 #[test]
5559 fn test_values_mut() {
5560 let vec = vec![(1, 1), (2, 2), (3, 3)];
5561 let mut map: HashMap<_, _> = vec.into_iter().collect();
5562 for value in map.values_mut() {
5563 *value *= 2;
5564 }
5565 let values: Vec<_> = map.values().copied().collect();
5566 assert_eq!(values.len(), 3);
5567 assert!(values.contains(&2));
5568 assert!(values.contains(&4));
5569 assert!(values.contains(&6));
5570 }
5571
5572 #[test]
5573 fn test_into_keys() {
5574 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5575 let map: HashMap<_, _> = vec.into_iter().collect();
5576 let keys: Vec<_> = map.into_keys().collect();
5577
5578 assert_eq!(keys.len(), 3);
5579 assert!(keys.contains(&1));
5580 assert!(keys.contains(&2));
5581 assert!(keys.contains(&3));
5582 }
5583
5584 #[test]
5585 fn test_into_values() {
5586 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5587 let map: HashMap<_, _> = vec.into_iter().collect();
5588 let values: Vec<_> = map.into_values().collect();
5589
5590 assert_eq!(values.len(), 3);
5591 assert!(values.contains(&'a'));
5592 assert!(values.contains(&'b'));
5593 assert!(values.contains(&'c'));
5594 }
5595
5596 #[test]
5597 fn test_find() {
5598 let mut m = HashMap::new();
5599 assert!(m.get(&1).is_none());
5600 m.insert(1, 2);
5601 match m.get(&1) {
5602 None => panic!(),
5603 Some(v) => assert_eq!(*v, 2),
5604 }
5605 }
5606
5607 #[test]
5608 fn test_eq() {
5609 let mut m1 = HashMap::new();
5610 m1.insert(1, 2);
5611 m1.insert(2, 3);
5612 m1.insert(3, 4);
5613
5614 let mut m2 = HashMap::new();
5615 m2.insert(1, 2);
5616 m2.insert(2, 3);
5617
5618 assert!(m1 != m2);
5619
5620 m2.insert(3, 4);
5621
5622 assert_eq!(m1, m2);
5623 }
5624
5625 #[test]
5626 fn test_show() {
5627 let mut map = HashMap::new();
5628 let empty: HashMap<i32, i32> = HashMap::new();
5629
5630 map.insert(1, 2);
5631 map.insert(3, 4);
5632
5633 let map_str = format!("{map:?}");
5634
5635 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
5636 assert_eq!(format!("{empty:?}"), "{}");
5637 }
5638
5639 #[test]
5640 fn test_expand() {
5641 let mut m = HashMap::new();
5642
5643 assert_eq!(m.len(), 0);
5644 assert!(m.is_empty());
5645
5646 let mut i = 0;
5647 let old_raw_cap = m.raw_capacity();
5648 while old_raw_cap == m.raw_capacity() {
5649 m.insert(i, i);
5650 i += 1;
5651 }
5652
5653 assert_eq!(m.len(), i);
5654 assert!(!m.is_empty());
5655 }
5656
5657 #[test]
5658 fn test_behavior_resize_policy() {
5659 let mut m = HashMap::new();
5660
5661 assert_eq!(m.len(), 0);
5662 assert_eq!(m.raw_capacity(), 1);
5663 assert!(m.is_empty());
5664
5665 m.insert(0, 0);
5666 m.remove(&0);
5667 assert!(m.is_empty());
5668 let initial_raw_cap = m.raw_capacity();
5669 m.reserve(initial_raw_cap);
5670 let raw_cap = m.raw_capacity();
5671
5672 assert_eq!(raw_cap, initial_raw_cap * 2);
5673
5674 let mut i = 0;
5675 for _ in 0..raw_cap * 3 / 4 {
5676 m.insert(i, i);
5677 i += 1;
5678 }
5679 // three quarters full
5680
5681 assert_eq!(m.len(), i);
5682 assert_eq!(m.raw_capacity(), raw_cap);
5683
5684 for _ in 0..raw_cap / 4 {
5685 m.insert(i, i);
5686 i += 1;
5687 }
5688 // half full
5689
5690 let new_raw_cap = m.raw_capacity();
5691 assert_eq!(new_raw_cap, raw_cap * 2);
5692
5693 for _ in 0..raw_cap / 2 - 1 {
5694 i -= 1;
5695 m.remove(&i);
5696 assert_eq!(m.raw_capacity(), new_raw_cap);
5697 }
5698 // A little more than one quarter full.
5699 m.shrink_to_fit();
5700 assert_eq!(m.raw_capacity(), raw_cap);
5701 // again, a little more than half full
5702 for _ in 0..raw_cap / 2 {
5703 i -= 1;
5704 m.remove(&i);
5705 }
5706 m.shrink_to_fit();
5707
5708 assert_eq!(m.len(), i);
5709 assert!(!m.is_empty());
5710 assert_eq!(m.raw_capacity(), initial_raw_cap);
5711 }
5712
5713 #[test]
5714 fn test_reserve_shrink_to_fit() {
5715 let mut m = HashMap::new();
5716 m.insert(0, 0);
5717 m.remove(&0);
5718 assert!(m.capacity() >= m.len());
5719 for i in 0..128 {
5720 m.insert(i, i);
5721 }
5722 m.reserve(256);
5723
5724 let usable_cap = m.capacity();
5725 for i in 128..(128 + 256) {
5726 m.insert(i, i);
5727 assert_eq!(m.capacity(), usable_cap);
5728 }
5729
5730 for i in 100..(128 + 256) {
5731 assert_eq!(m.remove(&i), Some(i));
5732 }
5733 m.shrink_to_fit();
5734
5735 assert_eq!(m.len(), 100);
5736 assert!(!m.is_empty());
5737 assert!(m.capacity() >= m.len());
5738
5739 for i in 0..100 {
5740 assert_eq!(m.remove(&i), Some(i));
5741 }
5742 m.shrink_to_fit();
5743 m.insert(0, 0);
5744
5745 assert_eq!(m.len(), 1);
5746 assert!(m.capacity() >= m.len());
5747 assert_eq!(m.remove(&0), Some(0));
5748 }
5749
5750 #[test]
5751 fn test_from_iter() {
5752 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5753
5754 let map: HashMap<_, _> = xs.iter().copied().collect();
5755
5756 for &(k, v) in &xs {
5757 assert_eq!(map.get(&k), Some(&v));
5758 }
5759
5760 assert_eq!(map.iter().len(), xs.len() - 1);
5761 }
5762
5763 #[test]
5764 fn test_size_hint() {
5765 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5766
5767 let map: HashMap<_, _> = xs.iter().copied().collect();
5768
5769 let mut iter = map.iter();
5770
5771 for _ in iter.by_ref().take(3) {}
5772
5773 assert_eq!(iter.size_hint(), (3, Some(3)));
5774 }
5775
5776 #[test]
5777 fn test_iter_len() {
5778 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5779
5780 let map: HashMap<_, _> = xs.iter().copied().collect();
5781
5782 let mut iter = map.iter();
5783
5784 for _ in iter.by_ref().take(3) {}
5785
5786 assert_eq!(iter.len(), 3);
5787 }
5788
5789 #[test]
5790 fn test_mut_size_hint() {
5791 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5792
5793 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5794
5795 let mut iter = map.iter_mut();
5796
5797 for _ in iter.by_ref().take(3) {}
5798
5799 assert_eq!(iter.size_hint(), (3, Some(3)));
5800 }
5801
5802 #[test]
5803 fn test_iter_mut_len() {
5804 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5805
5806 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5807
5808 let mut iter = map.iter_mut();
5809
5810 for _ in iter.by_ref().take(3) {}
5811
5812 assert_eq!(iter.len(), 3);
5813 }
5814
5815 #[test]
5816 fn test_index() {
5817 let mut map = HashMap::new();
5818
5819 map.insert(1, 2);
5820 map.insert(2, 1);
5821 map.insert(3, 4);
5822
5823 assert_eq!(map[&2], 1);
5824 }
5825
5826 #[test]
5827 #[should_panic]
5828 fn test_index_nonexistent() {
5829 let mut map = HashMap::new();
5830
5831 map.insert(1, 2);
5832 map.insert(2, 1);
5833 map.insert(3, 4);
5834
5835 _ = map[&4];
5836 }
5837
5838 #[test]
5839 fn test_entry() {
5840 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
5841
5842 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5843
5844 // Existing key (insert)
5845 match map.entry(1) {
5846 Vacant(_) => unreachable!(),
5847 Occupied(mut view) => {
5848 assert_eq!(view.get(), &10);
5849 assert_eq!(view.insert(100), 10);
5850 }
5851 }
5852 assert_eq!(map.get(&1).unwrap(), &100);
5853 assert_eq!(map.len(), 6);
5854
5855 // Existing key (update)
5856 match map.entry(2) {
5857 Vacant(_) => unreachable!(),
5858 Occupied(mut view) => {
5859 let v = view.get_mut();
5860 let new_v = (*v) * 10;
5861 *v = new_v;
5862 }
5863 }
5864 assert_eq!(map.get(&2).unwrap(), &200);
5865 assert_eq!(map.len(), 6);
5866
5867 // Existing key (take)
5868 match map.entry(3) {
5869 Vacant(_) => unreachable!(),
5870 Occupied(view) => {
5871 assert_eq!(view.remove(), 30);
5872 }
5873 }
5874 assert_eq!(map.get(&3), None);
5875 assert_eq!(map.len(), 5);
5876
5877 // Inexistent key (insert)
5878 match map.entry(10) {
5879 Occupied(_) => unreachable!(),
5880 Vacant(view) => {
5881 assert_eq!(*view.insert(1000), 1000);
5882 }
5883 }
5884 assert_eq!(map.get(&10).unwrap(), &1000);
5885 assert_eq!(map.len(), 6);
5886 }
5887
5888 #[test]
5889 fn test_entry_ref() {
5890 let xs = [
5891 ("One".to_owned(), 10),
5892 ("Two".to_owned(), 20),
5893 ("Three".to_owned(), 30),
5894 ("Four".to_owned(), 40),
5895 ("Five".to_owned(), 50),
5896 ("Six".to_owned(), 60),
5897 ];
5898
5899 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
5900
5901 // Existing key (insert)
5902 match map.entry_ref("One") {
5903 EntryRef::Vacant(_) => unreachable!(),
5904 EntryRef::Occupied(mut view) => {
5905 assert_eq!(view.get(), &10);
5906 assert_eq!(view.insert(100), 10);
5907 }
5908 }
5909 assert_eq!(map.get("One").unwrap(), &100);
5910 assert_eq!(map.len(), 6);
5911
5912 // Existing key (update)
5913 match map.entry_ref("Two") {
5914 EntryRef::Vacant(_) => unreachable!(),
5915 EntryRef::Occupied(mut view) => {
5916 let v = view.get_mut();
5917 let new_v = (*v) * 10;
5918 *v = new_v;
5919 }
5920 }
5921 assert_eq!(map.get("Two").unwrap(), &200);
5922 assert_eq!(map.len(), 6);
5923
5924 // Existing key (take)
5925 match map.entry_ref("Three") {
5926 EntryRef::Vacant(_) => unreachable!(),
5927 EntryRef::Occupied(view) => {
5928 assert_eq!(view.remove(), 30);
5929 }
5930 }
5931 assert_eq!(map.get("Three"), None);
5932 assert_eq!(map.len(), 5);
5933
5934 // Inexistent key (insert)
5935 match map.entry_ref("Ten") {
5936 EntryRef::Occupied(_) => unreachable!(),
5937 EntryRef::Vacant(view) => {
5938 assert_eq!(*view.insert(1000), 1000);
5939 }
5940 }
5941 assert_eq!(map.get("Ten").unwrap(), &1000);
5942 assert_eq!(map.len(), 6);
5943 }
5944
5945 #[test]
5946 fn test_entry_take_doesnt_corrupt() {
5947 #![expect(deprecated)] //rand
5948 // Test for #19292
5949 fn check(m: &HashMap<i32, ()>) {
5950 for k in m.keys() {
5951 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5952 }
5953 }
5954
5955 let mut m = HashMap::new();
5956
5957 let mut rng = {
5958 let seed = u64::from_le_bytes(*b"testseed");
5959 SmallRng::seed_from_u64(seed)
5960 };
5961
5962 // Populate the map with some items.
5963 for _ in 0..50 {
5964 let x = rng.gen_range(-10..10);
5965 m.insert(x, ());
5966 }
5967
5968 for _ in 0..1000 {
5969 let x = rng.gen_range(-10..10);
5970 match m.entry(x) {
5971 Vacant(_) => {}
5972 Occupied(e) => {
5973 e.remove();
5974 }
5975 }
5976
5977 check(&m);
5978 }
5979 }
5980
5981 #[test]
5982 fn test_entry_ref_take_doesnt_corrupt() {
5983 #![expect(deprecated)] //rand
5984 // Test for #19292
5985 fn check(m: &HashMap<std::string::String, ()>) {
5986 for k in m.keys() {
5987 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5988 }
5989 }
5990
5991 let mut m = HashMap::new();
5992
5993 let mut rng = {
5994 let seed = u64::from_le_bytes(*b"testseed");
5995 SmallRng::seed_from_u64(seed)
5996 };
5997
5998 // Populate the map with some items.
5999 for _ in 0..50 {
6000 let mut x = std::string::String::with_capacity(1);
6001 x.push(rng.gen_range('a'..='z'));
6002 m.insert(x, ());
6003 }
6004
6005 for _ in 0..1000 {
6006 let mut x = std::string::String::with_capacity(1);
6007 x.push(rng.gen_range('a'..='z'));
6008 match m.entry_ref(x.as_str()) {
6009 EntryRef::Vacant(_) => {}
6010 EntryRef::Occupied(e) => {
6011 e.remove();
6012 }
6013 }
6014
6015 check(&m);
6016 }
6017 }
6018
6019 #[test]
6020 fn test_extend_ref_k_ref_v() {
6021 let mut a = HashMap::new();
6022 a.insert(1, "one");
6023 let mut b = HashMap::new();
6024 b.insert(2, "two");
6025 b.insert(3, "three");
6026
6027 a.extend(&b);
6028
6029 assert_eq!(a.len(), 3);
6030 assert_eq!(a[&1], "one");
6031 assert_eq!(a[&2], "two");
6032 assert_eq!(a[&3], "three");
6033 }
6034
6035 #[test]
6036 fn test_extend_ref_kv_tuple() {
6037 use std::ops::AddAssign;
6038 let mut a = HashMap::new();
6039 a.insert(0, 0);
6040
6041 fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
6042 let mut outs: [(T, T); N] = [(start, start); N];
6043 let mut element = step;
6044 outs.iter_mut().skip(1).for_each(|(k, v)| {
6045 *k += element;
6046 *v += element;
6047 element += step;
6048 });
6049 outs
6050 }
6051
6052 let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
6053 let iter = for_iter.iter();
6054 let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
6055 a.extend(iter);
6056 a.extend(&vec);
6057 a.extend(create_arr::<i32, 100>(200, 1));
6058
6059 assert_eq!(a.len(), 300);
6060
6061 for item in 0..300 {
6062 assert_eq!(a[&item], item);
6063 }
6064 }
6065
6066 #[test]
6067 fn test_capacity_not_less_than_len() {
6068 let mut a = HashMap::new();
6069 let mut item = 0;
6070
6071 for _ in 0..116 {
6072 a.insert(item, 0);
6073 item += 1;
6074 }
6075
6076 assert!(a.capacity() > a.len());
6077
6078 let free = a.capacity() - a.len();
6079 for _ in 0..free {
6080 a.insert(item, 0);
6081 item += 1;
6082 }
6083
6084 assert_eq!(a.len(), a.capacity());
6085
6086 // Insert at capacity should cause allocation.
6087 a.insert(item, 0);
6088 assert!(a.capacity() > a.len());
6089 }
6090
6091 #[test]
6092 fn test_occupied_entry_key() {
6093 let mut a = HashMap::new();
6094 let key = "hello there";
6095 let value = "value goes here";
6096 assert!(a.is_empty());
6097 a.insert(key, value);
6098 assert_eq!(a.len(), 1);
6099 assert_eq!(a[key], value);
6100
6101 match a.entry(key) {
6102 Vacant(_) => panic!(),
6103 Occupied(e) => assert_eq!(key, *e.key()),
6104 }
6105 assert_eq!(a.len(), 1);
6106 assert_eq!(a[key], value);
6107 }
6108
6109 #[test]
6110 fn test_occupied_entry_ref_key() {
6111 let mut a = HashMap::new();
6112 let key = "hello there";
6113 let value = "value goes here";
6114 assert!(a.is_empty());
6115 a.insert(key.to_owned(), value);
6116 assert_eq!(a.len(), 1);
6117 assert_eq!(a[key], value);
6118
6119 match a.entry_ref(key) {
6120 EntryRef::Vacant(_) => panic!(),
6121 EntryRef::Occupied(e) => assert_eq!(key, e.key()),
6122 }
6123 assert_eq!(a.len(), 1);
6124 assert_eq!(a[key], value);
6125 }
6126
6127 #[test]
6128 fn test_vacant_entry_key() {
6129 let mut a = HashMap::new();
6130 let key = "hello there";
6131 let value = "value goes here";
6132
6133 assert!(a.is_empty());
6134 match a.entry(key) {
6135 Occupied(_) => panic!(),
6136 Vacant(e) => {
6137 assert_eq!(key, *e.key());
6138 e.insert(value);
6139 }
6140 }
6141 assert_eq!(a.len(), 1);
6142 assert_eq!(a[key], value);
6143 }
6144
6145 #[test]
6146 fn test_vacant_entry_ref_key() {
6147 let mut a: HashMap<std::string::String, &str> = HashMap::new();
6148 let key = "hello there";
6149 let value = "value goes here";
6150
6151 assert!(a.is_empty());
6152 match a.entry_ref(key) {
6153 EntryRef::Occupied(_) => panic!(),
6154 EntryRef::Vacant(e) => {
6155 assert_eq!(key, e.key());
6156 e.insert(value);
6157 }
6158 }
6159 assert_eq!(a.len(), 1);
6160 assert_eq!(a[key], value);
6161 }
6162
6163 #[test]
6164 fn test_occupied_entry_replace_entry_with() {
6165 let mut a = HashMap::new();
6166
6167 let key = "a key";
6168 let value = "an initial value";
6169 let new_value = "a new value";
6170
6171 let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
6172 assert_eq!(k, &key);
6173 assert_eq!(v, value);
6174 Some(new_value)
6175 });
6176
6177 match entry {
6178 Occupied(e) => {
6179 assert_eq!(e.key(), &key);
6180 assert_eq!(e.get(), &new_value);
6181 }
6182 Vacant(_) => panic!(),
6183 }
6184
6185 assert_eq!(a[key], new_value);
6186 assert_eq!(a.len(), 1);
6187
6188 let entry = match a.entry(key) {
6189 Occupied(e) => e.replace_entry_with(|k, v| {
6190 assert_eq!(k, &key);
6191 assert_eq!(v, new_value);
6192 None
6193 }),
6194 Vacant(_) => panic!(),
6195 };
6196
6197 match entry {
6198 Vacant(e) => assert_eq!(e.key(), &key),
6199 Occupied(_) => panic!(),
6200 }
6201
6202 assert!(!a.contains_key(key));
6203 assert_eq!(a.len(), 0);
6204 }
6205
6206 #[test]
6207 fn test_entry_and_replace_entry_with() {
6208 let mut a = HashMap::new();
6209
6210 let key = "a key";
6211 let value = "an initial value";
6212 let new_value = "a new value";
6213
6214 let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
6215
6216 match entry {
6217 Vacant(e) => assert_eq!(e.key(), &key),
6218 Occupied(_) => panic!(),
6219 }
6220
6221 a.insert(key, value);
6222
6223 let entry = a.entry(key).and_replace_entry_with(|k, v| {
6224 assert_eq!(k, &key);
6225 assert_eq!(v, value);
6226 Some(new_value)
6227 });
6228
6229 match entry {
6230 Occupied(e) => {
6231 assert_eq!(e.key(), &key);
6232 assert_eq!(e.get(), &new_value);
6233 }
6234 Vacant(_) => panic!(),
6235 }
6236
6237 assert_eq!(a[key], new_value);
6238 assert_eq!(a.len(), 1);
6239
6240 let entry = a.entry(key).and_replace_entry_with(|k, v| {
6241 assert_eq!(k, &key);
6242 assert_eq!(v, new_value);
6243 None
6244 });
6245
6246 match entry {
6247 Vacant(e) => assert_eq!(e.key(), &key),
6248 Occupied(_) => panic!(),
6249 }
6250
6251 assert!(!a.contains_key(key));
6252 assert_eq!(a.len(), 0);
6253 }
6254
6255 #[test]
6256 fn test_replace_entry_with_doesnt_corrupt() {
6257 #![expect(deprecated)] //rand
6258 // Test for #19292
6259 fn check(m: &HashMap<i32, ()>) {
6260 for k in m.keys() {
6261 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
6262 }
6263 }
6264
6265 let mut m = HashMap::new();
6266
6267 let mut rng = {
6268 let seed = u64::from_le_bytes(*b"testseed");
6269 SmallRng::seed_from_u64(seed)
6270 };
6271
6272 // Populate the map with some items.
6273 for _ in 0..50 {
6274 let x = rng.gen_range(-10..10);
6275 m.insert(x, ());
6276 }
6277
6278 for _ in 0..1000 {
6279 let x = rng.gen_range(-10..10);
6280 m.entry(x).and_replace_entry_with(|_, _| None);
6281 check(&m);
6282 }
6283 }
6284
6285 #[test]
6286 fn test_retain() {
6287 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
6288
6289 map.retain(|&k, _| k % 2 == 0);
6290 assert_eq!(map.len(), 50);
6291 assert_eq!(map[&2], 20);
6292 assert_eq!(map[&4], 40);
6293 assert_eq!(map[&6], 60);
6294 }
6295
6296 #[test]
6297 fn test_extract_if() {
6298 {
6299 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
6300 let drained = map.extract_if(|&k, _| k % 2 == 0);
6301 let mut out = drained.collect::<Vec<_>>();
6302 out.sort_unstable();
6303 assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
6304 assert_eq!(map.len(), 4);
6305 }
6306 {
6307 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
6308 map.extract_if(|&k, _| k % 2 == 0).for_each(drop);
6309 assert_eq!(map.len(), 4);
6310 }
6311 }
6312
6313 #[test]
6314 #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613)
6315 fn test_try_reserve() {
6316 use crate::TryReserveError::{AllocError, CapacityOverflow};
6317
6318 const MAX_ISIZE: usize = isize::MAX as usize;
6319
6320 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
6321
6322 if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
6323 } else {
6324 panic!("usize::MAX should trigger an overflow!");
6325 }
6326
6327 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
6328 } else {
6329 panic!("isize::MAX should trigger an overflow!");
6330 }
6331
6332 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
6333 } else {
6334 // This may succeed if there is enough free memory. Attempt to
6335 // allocate a few more hashmaps to ensure the allocation will fail.
6336 let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
6337 let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
6338 let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
6339 let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
6340 let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
6341 if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
6342 } else {
6343 panic!("isize::MAX / 5 should trigger an OOM!");
6344 }
6345 }
6346 }
6347
6348 #[test]
6349 fn test_const_with_hasher() {
6350 use core::hash::BuildHasher;
6351 use std::collections::hash_map::DefaultHasher;
6352
6353 #[derive(Clone)]
6354 struct MyHasher;
6355 impl BuildHasher for MyHasher {
6356 type Hasher = DefaultHasher;
6357
6358 fn build_hasher(&self) -> DefaultHasher {
6359 DefaultHasher::new()
6360 }
6361 }
6362
6363 const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> =
6364 HashMap::with_hasher(MyHasher);
6365
6366 let mut map = EMPTY_MAP;
6367 map.insert(17, "seventeen".to_owned());
6368 assert_eq!("seventeen", map[&17]);
6369 }
6370
6371 #[test]
6372 fn test_get_disjoint_mut() {
6373 let mut map = HashMap::new();
6374 map.insert("foo".to_owned(), 0);
6375 map.insert("bar".to_owned(), 10);
6376 map.insert("baz".to_owned(), 20);
6377 map.insert("qux".to_owned(), 30);
6378
6379 let xs = map.get_disjoint_mut(["foo", "qux"]);
6380 assert_eq!(xs, [Some(&mut 0), Some(&mut 30)]);
6381
6382 let xs = map.get_disjoint_mut(["foo", "dud"]);
6383 assert_eq!(xs, [Some(&mut 0), None]);
6384
6385 let ys = map.get_disjoint_key_value_mut(["bar", "baz"]);
6386 assert_eq!(
6387 ys,
6388 [
6389 Some((&"bar".to_owned(), &mut 10)),
6390 Some((&"baz".to_owned(), &mut 20))
6391 ],
6392 );
6393
6394 let ys = map.get_disjoint_key_value_mut(["bar", "dip"]);
6395 assert_eq!(ys, [Some((&"bar".to_owned(), &mut 10)), None]);
6396 }
6397
6398 #[test]
6399 #[should_panic = "duplicate keys found"]
6400 fn test_get_disjoint_mut_duplicate() {
6401 let mut map = HashMap::new();
6402 map.insert("foo".to_owned(), 0);
6403
6404 let _xs = map.get_disjoint_mut(["foo", "foo"]);
6405 }
6406
6407 #[test]
6408 #[should_panic = "panic in drop"]
6409 fn test_clone_from_double_drop() {
6410 #[derive(Clone)]
6411 struct CheckedDrop {
6412 panic_in_drop: bool,
6413 dropped: bool,
6414 }
6415 impl Drop for CheckedDrop {
6416 fn drop(&mut self) {
6417 if self.panic_in_drop {
6418 self.dropped = true;
6419 panic!("panic in drop");
6420 }
6421 if self.dropped {
6422 panic!("double drop");
6423 }
6424 self.dropped = true;
6425 }
6426 }
6427 const DISARMED: CheckedDrop = CheckedDrop {
6428 panic_in_drop: false,
6429 dropped: false,
6430 };
6431 const ARMED: CheckedDrop = CheckedDrop {
6432 panic_in_drop: true,
6433 dropped: false,
6434 };
6435
6436 let mut map1 = HashMap::new();
6437 map1.insert(1, DISARMED);
6438 map1.insert(2, DISARMED);
6439 map1.insert(3, DISARMED);
6440 map1.insert(4, DISARMED);
6441
6442 let mut map2 = HashMap::new();
6443 map2.insert(1, DISARMED);
6444 map2.insert(2, ARMED);
6445 map2.insert(3, DISARMED);
6446 map2.insert(4, DISARMED);
6447
6448 map2.clone_from(&map1);
6449 }
6450
6451 #[test]
6452 #[should_panic = "panic in clone"]
6453 fn test_clone_from_memory_leaks() {
6454 use stdalloc::vec::Vec;
6455
6456 struct CheckedClone {
6457 panic_in_clone: bool,
6458 need_drop: Vec<i32>,
6459 }
6460 impl Clone for CheckedClone {
6461 fn clone(&self) -> Self {
6462 if self.panic_in_clone {
6463 panic!("panic in clone")
6464 }
6465 Self {
6466 panic_in_clone: self.panic_in_clone,
6467 need_drop: self.need_drop.clone(),
6468 }
6469 }
6470 }
6471 let mut map1 = HashMap::new();
6472 map1.insert(
6473 1,
6474 CheckedClone {
6475 panic_in_clone: false,
6476 need_drop: vec![0, 1, 2],
6477 },
6478 );
6479 map1.insert(
6480 2,
6481 CheckedClone {
6482 panic_in_clone: false,
6483 need_drop: vec![3, 4, 5],
6484 },
6485 );
6486 map1.insert(
6487 3,
6488 CheckedClone {
6489 panic_in_clone: true,
6490 need_drop: vec![6, 7, 8],
6491 },
6492 );
6493 let _map2 = map1.clone();
6494 }
6495
6496 struct MyAllocInner {
6497 drop_count: Arc<AtomicI8>,
6498 }
6499
6500 #[derive(Clone)]
6501 struct MyAlloc {
6502 _inner: Arc<MyAllocInner>,
6503 }
6504
6505 impl MyAlloc {
6506 fn new(drop_count: Arc<AtomicI8>) -> Self {
6507 MyAlloc {
6508 _inner: Arc::new(MyAllocInner { drop_count }),
6509 }
6510 }
6511 }
6512
6513 impl Drop for MyAllocInner {
6514 fn drop(&mut self) {
6515 println!("MyAlloc freed.");
6516 self.drop_count.fetch_sub(1, Ordering::SeqCst);
6517 }
6518 }
6519
6520 unsafe impl Allocator for MyAlloc {
6521 fn allocate(&self, layout: Layout) -> std::result::Result<NonNull<[u8]>, AllocError> {
6522 let g = Global;
6523 g.allocate(layout)
6524 }
6525
6526 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
6527 unsafe {
6528 let g = Global;
6529 g.deallocate(ptr, layout);
6530 }
6531 }
6532 }
6533
6534 #[test]
6535 fn test_hashmap_into_iter_bug() {
6536 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
6537
6538 {
6539 let mut map = HashMap::with_capacity_in(10, MyAlloc::new(dropped.clone()));
6540 for i in 0..10 {
6541 map.entry(i).or_insert_with(|| "i".to_owned());
6542 }
6543
6544 for (k, v) in map {
6545 println!("{k}, {v}");
6546 }
6547 }
6548
6549 // All allocator clones should already be dropped.
6550 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6551 }
6552
6553 #[derive(Debug)]
6554 struct CheckedCloneDrop<T> {
6555 panic_in_clone: bool,
6556 panic_in_drop: bool,
6557 dropped: bool,
6558 data: T,
6559 }
6560
6561 impl<T> CheckedCloneDrop<T> {
6562 fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
6563 CheckedCloneDrop {
6564 panic_in_clone,
6565 panic_in_drop,
6566 dropped: false,
6567 data,
6568 }
6569 }
6570 }
6571
6572 impl<T: Clone> Clone for CheckedCloneDrop<T> {
6573 fn clone(&self) -> Self {
6574 if self.panic_in_clone {
6575 panic!("panic in clone")
6576 }
6577 Self {
6578 panic_in_clone: self.panic_in_clone,
6579 panic_in_drop: self.panic_in_drop,
6580 dropped: self.dropped,
6581 data: self.data.clone(),
6582 }
6583 }
6584 }
6585
6586 impl<T> Drop for CheckedCloneDrop<T> {
6587 fn drop(&mut self) {
6588 if self.panic_in_drop {
6589 self.dropped = true;
6590 panic!("panic in drop");
6591 }
6592 if self.dropped {
6593 panic!("double drop");
6594 }
6595 self.dropped = true;
6596 }
6597 }
6598
6599 /// Return hashmap with predefined distribution of elements.
6600 /// All elements will be located in the same order as elements
6601 /// returned by iterator.
6602 ///
6603 /// This function does not panic, but returns an error as a `String`
6604 /// to distinguish between a test panic and an error in the input data.
6605 fn get_test_map<I, T, A>(
6606 iter: I,
6607 mut fun: impl FnMut(u64) -> T,
6608 alloc: A,
6609 ) -> Result<HashMap<u64, CheckedCloneDrop<T>, DefaultHashBuilder, A>, String>
6610 where
6611 I: Iterator<Item = (bool, bool)> + Clone + ExactSizeIterator,
6612 A: Allocator,
6613 T: PartialEq + core::fmt::Debug,
6614 {
6615 use crate::scopeguard::guard;
6616
6617 let mut map: HashMap<u64, CheckedCloneDrop<T>, _, A> =
6618 HashMap::with_capacity_in(iter.size_hint().0, alloc);
6619 {
6620 let mut guard = guard(&mut map, |map| {
6621 for (_, value) in map.iter_mut() {
6622 value.panic_in_drop = false;
6623 }
6624 });
6625
6626 let mut count = 0;
6627 // Hash and Key must be equal to each other for controlling the elements placement.
6628 for (panic_in_clone, panic_in_drop) in iter.clone() {
6629 if core::mem::needs_drop::<T>() && panic_in_drop {
6630 return Err(String::from(
6631 "panic_in_drop can be set with a type that doesn't need to be dropped",
6632 ));
6633 }
6634 guard.table.insert(
6635 count,
6636 (
6637 count,
6638 CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)),
6639 ),
6640 |(k, _)| *k,
6641 );
6642 count += 1;
6643 }
6644
6645 // Let's check that all elements are located as we wanted
6646 let mut check_count = 0;
6647 for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) {
6648 if *key != check_count {
6649 return Err(format!(
6650 "key != check_count,\nkey: `{key}`,\ncheck_count: `{check_count}`"
6651 ));
6652 }
6653 if value.dropped
6654 || value.panic_in_clone != panic_in_clone
6655 || value.panic_in_drop != panic_in_drop
6656 || value.data != fun(check_count)
6657 {
6658 return Err(format!(
6659 "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \
6660 `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`",
6661 value,
6662 panic_in_clone,
6663 panic_in_drop,
6664 false,
6665 fun(check_count)
6666 ));
6667 }
6668 check_count += 1;
6669 }
6670
6671 if guard.len() != check_count as usize {
6672 return Err(format!(
6673 "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`",
6674 guard.len(),
6675 check_count
6676 ));
6677 }
6678
6679 if count != check_count {
6680 return Err(format!(
6681 "count != check_count,\ncount: `{count}`,\ncheck_count: `{check_count}`"
6682 ));
6683 }
6684 core::mem::forget(guard);
6685 }
6686 Ok(map)
6687 }
6688
6689 const DISARMED: bool = false;
6690 const ARMED: bool = true;
6691
6692 const ARMED_FLAGS: [bool; 8] = [
6693 DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6694 ];
6695
6696 const DISARMED_FLAGS: [bool; 8] = [
6697 DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6698 ];
6699
6700 #[test]
6701 #[should_panic = "panic in clone"]
6702 fn test_clone_memory_leaks_and_double_drop_one() {
6703 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6704
6705 {
6706 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6707
6708 let map: HashMap<u64, CheckedCloneDrop<Vec<u64>>, DefaultHashBuilder, MyAlloc> =
6709 match get_test_map(
6710 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6711 |n| vec![n],
6712 MyAlloc::new(dropped.clone()),
6713 ) {
6714 Ok(map) => map,
6715 Err(msg) => panic!("{msg}"),
6716 };
6717
6718 // Clone should normally clone a few elements, and then (when the
6719 // clone function panics), deallocate both its own memory, memory
6720 // of `dropped: Arc<AtomicI8>` and the memory of already cloned
6721 // elements (Vec<i32> memory inside CheckedCloneDrop).
6722 let _map2 = map.clone();
6723 }
6724 }
6725
6726 #[test]
6727 #[should_panic = "panic in drop"]
6728 fn test_clone_memory_leaks_and_double_drop_two() {
6729 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6730
6731 {
6732 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6733
6734 let map: HashMap<u64, CheckedCloneDrop<u64>, DefaultHashBuilder, _> = match get_test_map(
6735 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6736 |n| n,
6737 MyAlloc::new(dropped.clone()),
6738 ) {
6739 Ok(map) => map,
6740 Err(msg) => panic!("{msg}"),
6741 };
6742
6743 let mut map2 = match get_test_map(
6744 DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS),
6745 |n| n,
6746 MyAlloc::new(dropped.clone()),
6747 ) {
6748 Ok(map) => map,
6749 Err(msg) => panic!("{msg}"),
6750 };
6751
6752 // The `clone_from` should try to drop the elements of `map2` without
6753 // double drop and leaking the allocator. Elements that have not been
6754 // dropped leak their memory.
6755 map2.clone_from(&map);
6756 }
6757 }
6758
6759 /// We check that we have a working table if the clone operation from another
6760 /// thread ended in a panic (when buckets of maps are equal to each other).
6761 #[test]
6762 #[cfg(panic = "unwind")]
6763 fn test_catch_panic_clone_from_when_len_is_equal() {
6764 use std::thread;
6765
6766 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6767
6768 {
6769 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6770
6771 let mut map = match get_test_map(
6772 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6773 |n| vec![n],
6774 MyAlloc::new(dropped.clone()),
6775 ) {
6776 Ok(map) => map,
6777 Err(msg) => panic!("{msg}"),
6778 };
6779
6780 thread::scope(|s| {
6781 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6782 let scope_map =
6783 match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| vec![n * 2], MyAlloc::new(dropped.clone())) {
6784 Ok(map) => map,
6785 Err(msg) => return msg,
6786 };
6787 if map.table.num_buckets() != scope_map.table.num_buckets() {
6788 return format!(
6789 "map.table.num_buckets() != scope_map.table.num_buckets(),\nleft: `{}`,\nright: `{}`",
6790 map.table.num_buckets(), scope_map.table.num_buckets()
6791 );
6792 }
6793 map.clone_from(&scope_map);
6794 "We must fail the cloning!!!".to_owned()
6795 });
6796 if let Ok(msg) = result.join() {
6797 panic!("{msg}")
6798 }
6799 });
6800
6801 // Let's check that all iterators work fine and do not return elements
6802 // (especially `RawIterRange`, which does not depend on the number of
6803 // elements in the table, but looks directly at the control bytes)
6804 //
6805 // SAFETY: We know for sure that `RawTable` will outlive
6806 // the returned `RawIter / RawIterRange` iterator.
6807 assert_eq!(map.len(), 0);
6808 assert_eq!(map.iter().count(), 0);
6809 assert_eq!(unsafe { map.table.iter().count() }, 0);
6810 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6811
6812 for idx in 0..map.table.num_buckets() {
6813 let idx = idx as u64;
6814 assert!(
6815 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6816 "Index: {idx}"
6817 );
6818 }
6819 }
6820
6821 // All allocator clones should already be dropped.
6822 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6823 }
6824
6825 /// We check that we have a working table if the clone operation from another
6826 /// thread ended in a panic (when buckets of maps are not equal to each other).
6827 #[test]
6828 #[cfg(panic = "unwind")]
6829 fn test_catch_panic_clone_from_when_len_is_not_equal() {
6830 use std::thread;
6831
6832 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6833
6834 {
6835 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6836
6837 let mut map = match get_test_map(
6838 [DISARMED].into_iter().zip([DISARMED]),
6839 |n| vec![n],
6840 MyAlloc::new(dropped.clone()),
6841 ) {
6842 Ok(map) => map,
6843 Err(msg) => panic!("{msg}"),
6844 };
6845
6846 thread::scope(|s| {
6847 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6848 let scope_map = match get_test_map(
6849 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6850 |n| vec![n * 2],
6851 MyAlloc::new(dropped.clone()),
6852 ) {
6853 Ok(map) => map,
6854 Err(msg) => return msg,
6855 };
6856 if map.table.num_buckets() == scope_map.table.num_buckets() {
6857 return format!(
6858 "map.table.num_buckets() == scope_map.table.num_buckets(): `{}`",
6859 map.table.num_buckets()
6860 );
6861 }
6862 map.clone_from(&scope_map);
6863 "We must fail the cloning!!!".to_owned()
6864 });
6865 if let Ok(msg) = result.join() {
6866 panic!("{msg}")
6867 }
6868 });
6869
6870 // Let's check that all iterators work fine and do not return elements
6871 // (especially `RawIterRange`, which does not depend on the number of
6872 // elements in the table, but looks directly at the control bytes)
6873 //
6874 // SAFETY: We know for sure that `RawTable` will outlive
6875 // the returned `RawIter / RawIterRange` iterator.
6876 assert_eq!(map.len(), 0);
6877 assert_eq!(map.iter().count(), 0);
6878 assert_eq!(unsafe { map.table.iter().count() }, 0);
6879 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6880
6881 for idx in 0..map.table.num_buckets() {
6882 let idx = idx as u64;
6883 assert!(
6884 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6885 "Index: {idx}"
6886 );
6887 }
6888 }
6889
6890 // All allocator clones should already be dropped.
6891 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6892 }
6893
6894 #[test]
6895 fn test_allocation_info() {
6896 assert_eq!(HashMap::<(), ()>::new().allocation_size(), 0);
6897 assert_eq!(HashMap::<u32, u32>::new().allocation_size(), 0);
6898 assert!(
6899 HashMap::<u32, u32>::with_capacity(1).allocation_size() > core::mem::size_of::<u32>()
6900 );
6901 }
6902}
6903
6904#[cfg(all(test, unix, any(feature = "nightly", feature = "allocator-api2")))]
6905mod test_map_with_mmap_allocations {
6906 use super::HashMap;
6907 use crate::raw::prev_pow2;
6908 use core::alloc::Layout;
6909 use core::ptr::{NonNull, null_mut};
6910
6911 #[cfg(feature = "nightly")]
6912 use core::alloc::{AllocError, Allocator};
6913
6914 #[cfg(all(feature = "allocator-api2", not(feature = "nightly")))]
6915 use allocator_api2::alloc::{AllocError, Allocator};
6916
6917 /// This is not a production quality allocator, just good enough for
6918 /// some basic tests.
6919 #[derive(Clone, Copy, Debug)]
6920 struct MmapAllocator {
6921 /// Guarantee this is a power of 2.
6922 page_size: usize,
6923 }
6924
6925 impl MmapAllocator {
6926 fn new() -> Result<Self, AllocError> {
6927 let result = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
6928 if result < 1 {
6929 return Err(AllocError);
6930 }
6931
6932 let page_size = result as usize;
6933 if page_size.is_power_of_two() {
6934 Ok(Self { page_size })
6935 } else {
6936 Err(AllocError)
6937 }
6938 }
6939
6940 fn fit_to_page_size(&self, n: usize) -> Result<usize, AllocError> {
6941 // If n=0, give a single page (wasteful, I know).
6942 let n = if n == 0 { self.page_size } else { n };
6943
6944 match n & (self.page_size - 1) {
6945 0 => Ok(n),
6946 rem => n.checked_add(self.page_size - rem).ok_or(AllocError),
6947 }
6948 }
6949 }
6950
6951 unsafe impl Allocator for MmapAllocator {
6952 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
6953 if layout.align() > self.page_size {
6954 return Err(AllocError);
6955 }
6956
6957 let null = null_mut();
6958 let len = self.fit_to_page_size(layout.size())? as libc::size_t;
6959 let prot = libc::PROT_READ | libc::PROT_WRITE;
6960 let flags = libc::MAP_PRIVATE | libc::MAP_ANON;
6961 let addr = unsafe { libc::mmap(null, len, prot, flags, -1, 0) };
6962
6963 // mmap returns MAP_FAILED on failure, not Null.
6964 if addr == libc::MAP_FAILED {
6965 return Err(AllocError);
6966 }
6967
6968 if let Some(data) = NonNull::new(addr.cast()) {
6969 // SAFETY: this is NonNull::slice_from_raw_parts.
6970 Ok(unsafe {
6971 NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(data.as_ptr(), len))
6972 })
6973 } else {
6974 // This branch shouldn't be taken in practice, but since we
6975 // cannot return null as a valid pointer in our type system,
6976 // we attempt to handle it.
6977 _ = unsafe { libc::munmap(addr, len) };
6978 Err(AllocError)
6979 }
6980 }
6981
6982 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
6983 unsafe {
6984 // If they allocated it with this layout, it must round correctly.
6985 let size = self.fit_to_page_size(layout.size()).unwrap();
6986 let _result = libc::munmap(ptr.as_ptr().cast(), size);
6987 debug_assert_eq!(0, _result);
6988 }
6989 }
6990 }
6991
6992 #[test]
6993 fn test_tiny_allocation_gets_rounded_to_page_size() {
6994 let alloc = MmapAllocator::new().unwrap();
6995 let mut map: HashMap<usize, (), _, _> = HashMap::with_capacity_in(1, alloc);
6996
6997 // Size of an element plus its control byte.
6998 let rough_bucket_size = core::mem::size_of::<(usize, ())>() + 1;
6999
7000 // Accounting for some misc. padding that's likely in the allocation
7001 // due to rounding to group width, etc.
7002 let overhead = 3 * core::mem::size_of::<usize>();
7003 let num_buckets = (alloc.page_size - overhead) / rough_bucket_size;
7004 // Buckets are always powers of 2.
7005 let min_elems = prev_pow2(num_buckets);
7006 // Real load-factor is 7/8, but this is a lower estimation, so 1/2.
7007 let min_capacity = min_elems >> 1;
7008 let capacity = map.capacity();
7009 assert!(
7010 capacity >= min_capacity,
7011 "failed: {capacity} >= {min_capacity}"
7012 );
7013
7014 // Fill it up.
7015 for i in 0..capacity {
7016 map.insert(i, ());
7017 }
7018 // Capacity should not have changed and it should be full.
7019 assert_eq!(capacity, map.len());
7020 assert_eq!(capacity, map.capacity());
7021
7022 // Alright, make it grow.
7023 map.insert(capacity, ());
7024 assert!(
7025 capacity < map.capacity(),
7026 "failed: {capacity} < {}",
7027 map.capacity()
7028 );
7029 }
7030}