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