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