std/collections/hash/
map.rs

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