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"]
1689pub struct ExtractIf<'a, K, V, F> {
1690    base: base::ExtractIf<'a, K, V, F>,
1691}
1692
1693/// A mutable iterator over the values of a `HashMap`.
1694///
1695/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1696/// documentation for more.
1697///
1698/// [`values_mut`]: HashMap::values_mut
1699///
1700/// # Example
1701///
1702/// ```
1703/// use std::collections::HashMap;
1704///
1705/// let mut map = HashMap::from([
1706///     ("a", 1),
1707/// ]);
1708/// let iter_values = map.values_mut();
1709/// ```
1710#[stable(feature = "map_values_mut", since = "1.10.0")]
1711#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_values_mut_ty")]
1712pub struct ValuesMut<'a, K: 'a, V: 'a> {
1713    inner: IterMut<'a, K, V>,
1714}
1715
1716#[stable(feature = "default_iters_hash", since = "1.83.0")]
1717impl<K, V> Default for ValuesMut<'_, K, V> {
1718    #[inline]
1719    fn default() -> Self {
1720        ValuesMut { inner: Default::default() }
1721    }
1722}
1723
1724/// An owning iterator over the keys of a `HashMap`.
1725///
1726/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1727/// See its documentation for more.
1728///
1729/// [`into_keys`]: HashMap::into_keys
1730///
1731/// # Example
1732///
1733/// ```
1734/// use std::collections::HashMap;
1735///
1736/// let map = HashMap::from([
1737///     ("a", 1),
1738/// ]);
1739/// let iter_keys = map.into_keys();
1740/// ```
1741#[stable(feature = "map_into_keys_values", since = "1.54.0")]
1742pub struct IntoKeys<K, V> {
1743    inner: IntoIter<K, V>,
1744}
1745
1746#[stable(feature = "default_iters_hash", since = "1.83.0")]
1747impl<K, V> Default for IntoKeys<K, V> {
1748    #[inline]
1749    fn default() -> Self {
1750        IntoKeys { inner: Default::default() }
1751    }
1752}
1753
1754/// An owning iterator over the values of a `HashMap`.
1755///
1756/// This `struct` is created by the [`into_values`] method on [`HashMap`].
1757/// See its documentation for more.
1758///
1759/// [`into_values`]: HashMap::into_values
1760///
1761/// # Example
1762///
1763/// ```
1764/// use std::collections::HashMap;
1765///
1766/// let map = HashMap::from([
1767///     ("a", 1),
1768/// ]);
1769/// let iter_keys = map.into_values();
1770/// ```
1771#[stable(feature = "map_into_keys_values", since = "1.54.0")]
1772pub struct IntoValues<K, V> {
1773    inner: IntoIter<K, V>,
1774}
1775
1776#[stable(feature = "default_iters_hash", since = "1.83.0")]
1777impl<K, V> Default for IntoValues<K, V> {
1778    #[inline]
1779    fn default() -> Self {
1780        IntoValues { inner: Default::default() }
1781    }
1782}
1783
1784/// A view into a single entry in a map, which may either be vacant or occupied.
1785///
1786/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1787///
1788/// [`entry`]: HashMap::entry
1789#[stable(feature = "rust1", since = "1.0.0")]
1790#[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
1791pub enum Entry<'a, K: 'a, V: 'a> {
1792    /// An occupied entry.
1793    #[stable(feature = "rust1", since = "1.0.0")]
1794    Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1795
1796    /// A vacant entry.
1797    #[stable(feature = "rust1", since = "1.0.0")]
1798    Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1799}
1800
1801#[stable(feature = "debug_hash_map", since = "1.12.0")]
1802impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1803    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1804        match *self {
1805            Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1806            Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1807        }
1808    }
1809}
1810
1811/// A view into an occupied entry in a `HashMap`.
1812/// It is part of the [`Entry`] enum.
1813#[stable(feature = "rust1", since = "1.0.0")]
1814pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1815    base: base::RustcOccupiedEntry<'a, K, V>,
1816}
1817
1818#[stable(feature = "debug_hash_map", since = "1.12.0")]
1819impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1821        f.debug_struct("OccupiedEntry")
1822            .field("key", self.key())
1823            .field("value", self.get())
1824            .finish_non_exhaustive()
1825    }
1826}
1827
1828/// A view into a vacant entry in a `HashMap`.
1829/// It is part of the [`Entry`] enum.
1830#[stable(feature = "rust1", since = "1.0.0")]
1831pub struct VacantEntry<'a, K: 'a, V: 'a> {
1832    base: base::RustcVacantEntry<'a, K, V>,
1833}
1834
1835#[stable(feature = "debug_hash_map", since = "1.12.0")]
1836impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1837    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1838        f.debug_tuple("VacantEntry").field(self.key()).finish()
1839    }
1840}
1841
1842/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1843///
1844/// Contains the occupied entry, and the value that was not inserted.
1845#[unstable(feature = "map_try_insert", issue = "82766")]
1846pub struct OccupiedError<'a, K: 'a, V: 'a> {
1847    /// The entry in the map that was already occupied.
1848    pub entry: OccupiedEntry<'a, K, V>,
1849    /// The value which was not inserted, because the entry was already occupied.
1850    pub value: V,
1851}
1852
1853#[unstable(feature = "map_try_insert", issue = "82766")]
1854impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V> {
1855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1856        f.debug_struct("OccupiedError")
1857            .field("key", self.entry.key())
1858            .field("old_value", self.entry.get())
1859            .field("new_value", &self.value)
1860            .finish_non_exhaustive()
1861    }
1862}
1863
1864#[unstable(feature = "map_try_insert", issue = "82766")]
1865impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> {
1866    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1867        write!(
1868            f,
1869            "failed to insert {:?}, key {:?} already exists with value {:?}",
1870            self.value,
1871            self.entry.key(),
1872            self.entry.get(),
1873        )
1874    }
1875}
1876
1877#[unstable(feature = "map_try_insert", issue = "82766")]
1878impl<'a, K: Debug, V: Debug> Error for OccupiedError<'a, K, V> {}
1879
1880#[stable(feature = "rust1", since = "1.0.0")]
1881impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1882    type Item = (&'a K, &'a V);
1883    type IntoIter = Iter<'a, K, V>;
1884
1885    #[inline]
1886    #[rustc_lint_query_instability]
1887    fn into_iter(self) -> Iter<'a, K, V> {
1888        self.iter()
1889    }
1890}
1891
1892#[stable(feature = "rust1", since = "1.0.0")]
1893impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1894    type Item = (&'a K, &'a mut V);
1895    type IntoIter = IterMut<'a, K, V>;
1896
1897    #[inline]
1898    #[rustc_lint_query_instability]
1899    fn into_iter(self) -> IterMut<'a, K, V> {
1900        self.iter_mut()
1901    }
1902}
1903
1904#[stable(feature = "rust1", since = "1.0.0")]
1905impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1906    type Item = (K, V);
1907    type IntoIter = IntoIter<K, V>;
1908
1909    /// Creates a consuming iterator, that is, one that moves each key-value
1910    /// pair out of the map in arbitrary order. The map cannot be used after
1911    /// calling this.
1912    ///
1913    /// # Examples
1914    ///
1915    /// ```
1916    /// use std::collections::HashMap;
1917    ///
1918    /// let map = HashMap::from([
1919    ///     ("a", 1),
1920    ///     ("b", 2),
1921    ///     ("c", 3),
1922    /// ]);
1923    ///
1924    /// // Not possible with .iter()
1925    /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1926    /// ```
1927    #[inline]
1928    #[rustc_lint_query_instability]
1929    fn into_iter(self) -> IntoIter<K, V> {
1930        IntoIter { base: self.base.into_iter() }
1931    }
1932}
1933
1934#[stable(feature = "rust1", since = "1.0.0")]
1935impl<'a, K, V> Iterator for Iter<'a, K, V> {
1936    type Item = (&'a K, &'a V);
1937
1938    #[inline]
1939    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1940        self.base.next()
1941    }
1942    #[inline]
1943    fn size_hint(&self) -> (usize, Option<usize>) {
1944        self.base.size_hint()
1945    }
1946    #[inline]
1947    fn count(self) -> usize {
1948        self.base.len()
1949    }
1950    #[inline]
1951    fn fold<B, F>(self, init: B, f: F) -> B
1952    where
1953        Self: Sized,
1954        F: FnMut(B, Self::Item) -> B,
1955    {
1956        self.base.fold(init, f)
1957    }
1958}
1959#[stable(feature = "rust1", since = "1.0.0")]
1960impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1961    #[inline]
1962    fn len(&self) -> usize {
1963        self.base.len()
1964    }
1965}
1966
1967#[stable(feature = "fused", since = "1.26.0")]
1968impl<K, V> FusedIterator for Iter<'_, K, V> {}
1969
1970#[stable(feature = "rust1", since = "1.0.0")]
1971impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1972    type Item = (&'a K, &'a mut V);
1973
1974    #[inline]
1975    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1976        self.base.next()
1977    }
1978    #[inline]
1979    fn size_hint(&self) -> (usize, Option<usize>) {
1980        self.base.size_hint()
1981    }
1982    #[inline]
1983    fn count(self) -> usize {
1984        self.base.len()
1985    }
1986    #[inline]
1987    fn fold<B, F>(self, init: B, f: F) -> B
1988    where
1989        Self: Sized,
1990        F: FnMut(B, Self::Item) -> B,
1991    {
1992        self.base.fold(init, f)
1993    }
1994}
1995#[stable(feature = "rust1", since = "1.0.0")]
1996impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1997    #[inline]
1998    fn len(&self) -> usize {
1999        self.base.len()
2000    }
2001}
2002#[stable(feature = "fused", since = "1.26.0")]
2003impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2004
2005#[stable(feature = "std_debug", since = "1.16.0")]
2006impl<K, V> fmt::Debug for IterMut<'_, K, V>
2007where
2008    K: fmt::Debug,
2009    V: fmt::Debug,
2010{
2011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2012        f.debug_list().entries(self.iter()).finish()
2013    }
2014}
2015
2016#[stable(feature = "rust1", since = "1.0.0")]
2017impl<K, V> Iterator for IntoIter<K, V> {
2018    type Item = (K, V);
2019
2020    #[inline]
2021    fn next(&mut self) -> Option<(K, V)> {
2022        self.base.next()
2023    }
2024    #[inline]
2025    fn size_hint(&self) -> (usize, Option<usize>) {
2026        self.base.size_hint()
2027    }
2028    #[inline]
2029    fn count(self) -> usize {
2030        self.base.len()
2031    }
2032    #[inline]
2033    fn fold<B, F>(self, init: B, f: F) -> B
2034    where
2035        Self: Sized,
2036        F: FnMut(B, Self::Item) -> B,
2037    {
2038        self.base.fold(init, f)
2039    }
2040}
2041#[stable(feature = "rust1", since = "1.0.0")]
2042impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2043    #[inline]
2044    fn len(&self) -> usize {
2045        self.base.len()
2046    }
2047}
2048#[stable(feature = "fused", since = "1.26.0")]
2049impl<K, V> FusedIterator for IntoIter<K, V> {}
2050
2051#[stable(feature = "std_debug", since = "1.16.0")]
2052impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2053    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2054        f.debug_list().entries(self.iter()).finish()
2055    }
2056}
2057
2058#[stable(feature = "rust1", since = "1.0.0")]
2059impl<'a, K, V> Iterator for Keys<'a, K, V> {
2060    type Item = &'a K;
2061
2062    #[inline]
2063    fn next(&mut self) -> Option<&'a K> {
2064        self.inner.next().map(|(k, _)| k)
2065    }
2066    #[inline]
2067    fn size_hint(&self) -> (usize, Option<usize>) {
2068        self.inner.size_hint()
2069    }
2070    #[inline]
2071    fn count(self) -> usize {
2072        self.inner.len()
2073    }
2074    #[inline]
2075    fn fold<B, F>(self, init: B, mut f: F) -> B
2076    where
2077        Self: Sized,
2078        F: FnMut(B, Self::Item) -> B,
2079    {
2080        self.inner.fold(init, |acc, (k, _)| f(acc, k))
2081    }
2082}
2083#[stable(feature = "rust1", since = "1.0.0")]
2084impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2085    #[inline]
2086    fn len(&self) -> usize {
2087        self.inner.len()
2088    }
2089}
2090#[stable(feature = "fused", since = "1.26.0")]
2091impl<K, V> FusedIterator for Keys<'_, K, V> {}
2092
2093#[stable(feature = "rust1", since = "1.0.0")]
2094impl<'a, K, V> Iterator for Values<'a, K, V> {
2095    type Item = &'a V;
2096
2097    #[inline]
2098    fn next(&mut self) -> Option<&'a V> {
2099        self.inner.next().map(|(_, v)| v)
2100    }
2101    #[inline]
2102    fn size_hint(&self) -> (usize, Option<usize>) {
2103        self.inner.size_hint()
2104    }
2105    #[inline]
2106    fn count(self) -> usize {
2107        self.inner.len()
2108    }
2109    #[inline]
2110    fn fold<B, F>(self, init: B, mut f: F) -> B
2111    where
2112        Self: Sized,
2113        F: FnMut(B, Self::Item) -> B,
2114    {
2115        self.inner.fold(init, |acc, (_, v)| f(acc, v))
2116    }
2117}
2118#[stable(feature = "rust1", since = "1.0.0")]
2119impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2120    #[inline]
2121    fn len(&self) -> usize {
2122        self.inner.len()
2123    }
2124}
2125#[stable(feature = "fused", since = "1.26.0")]
2126impl<K, V> FusedIterator for Values<'_, K, V> {}
2127
2128#[stable(feature = "map_values_mut", since = "1.10.0")]
2129impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2130    type Item = &'a mut V;
2131
2132    #[inline]
2133    fn next(&mut self) -> Option<&'a mut V> {
2134        self.inner.next().map(|(_, v)| v)
2135    }
2136    #[inline]
2137    fn size_hint(&self) -> (usize, Option<usize>) {
2138        self.inner.size_hint()
2139    }
2140    #[inline]
2141    fn count(self) -> usize {
2142        self.inner.len()
2143    }
2144    #[inline]
2145    fn fold<B, F>(self, init: B, mut f: F) -> B
2146    where
2147        Self: Sized,
2148        F: FnMut(B, Self::Item) -> B,
2149    {
2150        self.inner.fold(init, |acc, (_, v)| f(acc, v))
2151    }
2152}
2153#[stable(feature = "map_values_mut", since = "1.10.0")]
2154impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2155    #[inline]
2156    fn len(&self) -> usize {
2157        self.inner.len()
2158    }
2159}
2160#[stable(feature = "fused", since = "1.26.0")]
2161impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2162
2163#[stable(feature = "std_debug", since = "1.16.0")]
2164impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2166        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2167    }
2168}
2169
2170#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2171impl<K, V> Iterator for IntoKeys<K, V> {
2172    type Item = K;
2173
2174    #[inline]
2175    fn next(&mut self) -> Option<K> {
2176        self.inner.next().map(|(k, _)| k)
2177    }
2178    #[inline]
2179    fn size_hint(&self) -> (usize, Option<usize>) {
2180        self.inner.size_hint()
2181    }
2182    #[inline]
2183    fn count(self) -> usize {
2184        self.inner.len()
2185    }
2186    #[inline]
2187    fn fold<B, F>(self, init: B, mut f: F) -> B
2188    where
2189        Self: Sized,
2190        F: FnMut(B, Self::Item) -> B,
2191    {
2192        self.inner.fold(init, |acc, (k, _)| f(acc, k))
2193    }
2194}
2195#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2196impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2197    #[inline]
2198    fn len(&self) -> usize {
2199        self.inner.len()
2200    }
2201}
2202#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2203impl<K, V> FusedIterator for IntoKeys<K, V> {}
2204
2205#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2206impl<K: Debug, V> fmt::Debug for IntoKeys<K, V> {
2207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2208        f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2209    }
2210}
2211
2212#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2213impl<K, V> Iterator for IntoValues<K, V> {
2214    type Item = V;
2215
2216    #[inline]
2217    fn next(&mut self) -> Option<V> {
2218        self.inner.next().map(|(_, v)| v)
2219    }
2220    #[inline]
2221    fn size_hint(&self) -> (usize, Option<usize>) {
2222        self.inner.size_hint()
2223    }
2224    #[inline]
2225    fn count(self) -> usize {
2226        self.inner.len()
2227    }
2228    #[inline]
2229    fn fold<B, F>(self, init: B, mut f: F) -> B
2230    where
2231        Self: Sized,
2232        F: FnMut(B, Self::Item) -> B,
2233    {
2234        self.inner.fold(init, |acc, (_, v)| f(acc, v))
2235    }
2236}
2237#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2238impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2239    #[inline]
2240    fn len(&self) -> usize {
2241        self.inner.len()
2242    }
2243}
2244#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2245impl<K, V> FusedIterator for IntoValues<K, V> {}
2246
2247#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2248impl<K, V: Debug> fmt::Debug for IntoValues<K, V> {
2249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2250        f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2251    }
2252}
2253
2254#[stable(feature = "drain", since = "1.6.0")]
2255impl<'a, K, V> Iterator for Drain<'a, K, V> {
2256    type Item = (K, V);
2257
2258    #[inline]
2259    fn next(&mut self) -> Option<(K, V)> {
2260        self.base.next()
2261    }
2262    #[inline]
2263    fn size_hint(&self) -> (usize, Option<usize>) {
2264        self.base.size_hint()
2265    }
2266    #[inline]
2267    fn fold<B, F>(self, init: B, f: F) -> B
2268    where
2269        Self: Sized,
2270        F: FnMut(B, Self::Item) -> B,
2271    {
2272        self.base.fold(init, f)
2273    }
2274}
2275#[stable(feature = "drain", since = "1.6.0")]
2276impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2277    #[inline]
2278    fn len(&self) -> usize {
2279        self.base.len()
2280    }
2281}
2282#[stable(feature = "fused", since = "1.26.0")]
2283impl<K, V> FusedIterator for Drain<'_, K, V> {}
2284
2285#[stable(feature = "std_debug", since = "1.16.0")]
2286impl<K, V> fmt::Debug for Drain<'_, K, V>
2287where
2288    K: fmt::Debug,
2289    V: fmt::Debug,
2290{
2291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2292        f.debug_list().entries(self.iter()).finish()
2293    }
2294}
2295
2296#[stable(feature = "hash_extract_if", since = "1.88.0")]
2297impl<K, V, F> Iterator for ExtractIf<'_, K, V, F>
2298where
2299    F: FnMut(&K, &mut V) -> bool,
2300{
2301    type Item = (K, V);
2302
2303    #[inline]
2304    fn next(&mut self) -> Option<(K, V)> {
2305        self.base.next()
2306    }
2307    #[inline]
2308    fn size_hint(&self) -> (usize, Option<usize>) {
2309        self.base.size_hint()
2310    }
2311}
2312
2313#[stable(feature = "hash_extract_if", since = "1.88.0")]
2314impl<K, V, F> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2315
2316#[stable(feature = "hash_extract_if", since = "1.88.0")]
2317impl<K, V, F> fmt::Debug for ExtractIf<'_, K, V, F>
2318where
2319    K: fmt::Debug,
2320    V: fmt::Debug,
2321{
2322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2323        f.debug_struct("ExtractIf").finish_non_exhaustive()
2324    }
2325}
2326
2327impl<'a, K, V> Entry<'a, K, V> {
2328    /// Ensures a value is in the entry by inserting the default if empty, and returns
2329    /// a mutable reference to the value in the entry.
2330    ///
2331    /// # Examples
2332    ///
2333    /// ```
2334    /// use std::collections::HashMap;
2335    ///
2336    /// let mut map: HashMap<&str, u32> = HashMap::new();
2337    ///
2338    /// map.entry("poneyland").or_insert(3);
2339    /// assert_eq!(map["poneyland"], 3);
2340    ///
2341    /// *map.entry("poneyland").or_insert(10) *= 2;
2342    /// assert_eq!(map["poneyland"], 6);
2343    /// ```
2344    #[inline]
2345    #[stable(feature = "rust1", since = "1.0.0")]
2346    pub fn or_insert(self, default: V) -> &'a mut V {
2347        match self {
2348            Occupied(entry) => entry.into_mut(),
2349            Vacant(entry) => entry.insert(default),
2350        }
2351    }
2352
2353    /// Ensures a value is in the entry by inserting the result of the default function if empty,
2354    /// and returns a mutable reference to the value in the entry.
2355    ///
2356    /// # Examples
2357    ///
2358    /// ```
2359    /// use std::collections::HashMap;
2360    ///
2361    /// let mut map = HashMap::new();
2362    /// let value = "hoho";
2363    ///
2364    /// map.entry("poneyland").or_insert_with(|| value);
2365    ///
2366    /// assert_eq!(map["poneyland"], "hoho");
2367    /// ```
2368    #[inline]
2369    #[stable(feature = "rust1", since = "1.0.0")]
2370    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2371        match self {
2372            Occupied(entry) => entry.into_mut(),
2373            Vacant(entry) => entry.insert(default()),
2374        }
2375    }
2376
2377    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2378    /// This method allows for generating key-derived values for insertion by providing the default
2379    /// function a reference to the key that was moved during the `.entry(key)` method call.
2380    ///
2381    /// The reference to the moved key is provided so that cloning or copying the key is
2382    /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2383    ///
2384    /// # Examples
2385    ///
2386    /// ```
2387    /// use std::collections::HashMap;
2388    ///
2389    /// let mut map: HashMap<&str, usize> = HashMap::new();
2390    ///
2391    /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2392    ///
2393    /// assert_eq!(map["poneyland"], 9);
2394    /// ```
2395    #[inline]
2396    #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2397    pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2398        match self {
2399            Occupied(entry) => entry.into_mut(),
2400            Vacant(entry) => {
2401                let value = default(entry.key());
2402                entry.insert(value)
2403            }
2404        }
2405    }
2406
2407    /// Returns a reference to this entry's key.
2408    ///
2409    /// # Examples
2410    ///
2411    /// ```
2412    /// use std::collections::HashMap;
2413    ///
2414    /// let mut map: HashMap<&str, u32> = HashMap::new();
2415    /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2416    /// ```
2417    #[inline]
2418    #[stable(feature = "map_entry_keys", since = "1.10.0")]
2419    pub fn key(&self) -> &K {
2420        match *self {
2421            Occupied(ref entry) => entry.key(),
2422            Vacant(ref entry) => entry.key(),
2423        }
2424    }
2425
2426    /// Provides in-place mutable access to an occupied entry before any
2427    /// potential inserts into the map.
2428    ///
2429    /// # Examples
2430    ///
2431    /// ```
2432    /// use std::collections::HashMap;
2433    ///
2434    /// let mut map: HashMap<&str, u32> = HashMap::new();
2435    ///
2436    /// map.entry("poneyland")
2437    ///    .and_modify(|e| { *e += 1 })
2438    ///    .or_insert(42);
2439    /// assert_eq!(map["poneyland"], 42);
2440    ///
2441    /// map.entry("poneyland")
2442    ///    .and_modify(|e| { *e += 1 })
2443    ///    .or_insert(42);
2444    /// assert_eq!(map["poneyland"], 43);
2445    /// ```
2446    #[inline]
2447    #[stable(feature = "entry_and_modify", since = "1.26.0")]
2448    pub fn and_modify<F>(self, f: F) -> Self
2449    where
2450        F: FnOnce(&mut V),
2451    {
2452        match self {
2453            Occupied(mut entry) => {
2454                f(entry.get_mut());
2455                Occupied(entry)
2456            }
2457            Vacant(entry) => Vacant(entry),
2458        }
2459    }
2460
2461    /// Sets the value of the entry, and returns an `OccupiedEntry`.
2462    ///
2463    /// # Examples
2464    ///
2465    /// ```
2466    /// use std::collections::HashMap;
2467    ///
2468    /// let mut map: HashMap<&str, String> = HashMap::new();
2469    /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2470    ///
2471    /// assert_eq!(entry.key(), &"poneyland");
2472    /// ```
2473    #[inline]
2474    #[stable(feature = "entry_insert", since = "1.83.0")]
2475    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2476        match self {
2477            Occupied(mut entry) => {
2478                entry.insert(value);
2479                entry
2480            }
2481            Vacant(entry) => entry.insert_entry(value),
2482        }
2483    }
2484}
2485
2486impl<'a, K, V: Default> Entry<'a, K, V> {
2487    /// Ensures a value is in the entry by inserting the default value if empty,
2488    /// and returns a mutable reference to the value in the entry.
2489    ///
2490    /// # Examples
2491    ///
2492    /// ```
2493    /// # fn main() {
2494    /// use std::collections::HashMap;
2495    ///
2496    /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2497    /// map.entry("poneyland").or_default();
2498    ///
2499    /// assert_eq!(map["poneyland"], None);
2500    /// # }
2501    /// ```
2502    #[inline]
2503    #[stable(feature = "entry_or_default", since = "1.28.0")]
2504    pub fn or_default(self) -> &'a mut V {
2505        match self {
2506            Occupied(entry) => entry.into_mut(),
2507            Vacant(entry) => entry.insert(Default::default()),
2508        }
2509    }
2510}
2511
2512impl<'a, K, V> OccupiedEntry<'a, K, V> {
2513    /// Gets a reference to the key in the entry.
2514    ///
2515    /// # Examples
2516    ///
2517    /// ```
2518    /// use std::collections::HashMap;
2519    ///
2520    /// let mut map: HashMap<&str, u32> = HashMap::new();
2521    /// map.entry("poneyland").or_insert(12);
2522    /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2523    /// ```
2524    #[inline]
2525    #[stable(feature = "map_entry_keys", since = "1.10.0")]
2526    pub fn key(&self) -> &K {
2527        self.base.key()
2528    }
2529
2530    /// Take the ownership of the key and value from the map.
2531    ///
2532    /// # Examples
2533    ///
2534    /// ```
2535    /// use std::collections::HashMap;
2536    /// use std::collections::hash_map::Entry;
2537    ///
2538    /// let mut map: HashMap<&str, u32> = HashMap::new();
2539    /// map.entry("poneyland").or_insert(12);
2540    ///
2541    /// if let Entry::Occupied(o) = map.entry("poneyland") {
2542    ///     // We delete the entry from the map.
2543    ///     o.remove_entry();
2544    /// }
2545    ///
2546    /// assert_eq!(map.contains_key("poneyland"), false);
2547    /// ```
2548    #[inline]
2549    #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2550    pub fn remove_entry(self) -> (K, V) {
2551        self.base.remove_entry()
2552    }
2553
2554    /// Gets a reference to the value in the entry.
2555    ///
2556    /// # Examples
2557    ///
2558    /// ```
2559    /// use std::collections::HashMap;
2560    /// use std::collections::hash_map::Entry;
2561    ///
2562    /// let mut map: HashMap<&str, u32> = HashMap::new();
2563    /// map.entry("poneyland").or_insert(12);
2564    ///
2565    /// if let Entry::Occupied(o) = map.entry("poneyland") {
2566    ///     assert_eq!(o.get(), &12);
2567    /// }
2568    /// ```
2569    #[inline]
2570    #[stable(feature = "rust1", since = "1.0.0")]
2571    pub fn get(&self) -> &V {
2572        self.base.get()
2573    }
2574
2575    /// Gets a mutable reference to the value in the entry.
2576    ///
2577    /// If you need a reference to the `OccupiedEntry` which may outlive the
2578    /// destruction of the `Entry` value, see [`into_mut`].
2579    ///
2580    /// [`into_mut`]: Self::into_mut
2581    ///
2582    /// # Examples
2583    ///
2584    /// ```
2585    /// use std::collections::HashMap;
2586    /// use std::collections::hash_map::Entry;
2587    ///
2588    /// let mut map: HashMap<&str, u32> = HashMap::new();
2589    /// map.entry("poneyland").or_insert(12);
2590    ///
2591    /// assert_eq!(map["poneyland"], 12);
2592    /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2593    ///     *o.get_mut() += 10;
2594    ///     assert_eq!(*o.get(), 22);
2595    ///
2596    ///     // We can use the same Entry multiple times.
2597    ///     *o.get_mut() += 2;
2598    /// }
2599    ///
2600    /// assert_eq!(map["poneyland"], 24);
2601    /// ```
2602    #[inline]
2603    #[stable(feature = "rust1", since = "1.0.0")]
2604    pub fn get_mut(&mut self) -> &mut V {
2605        self.base.get_mut()
2606    }
2607
2608    /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2609    /// with a lifetime bound to the map itself.
2610    ///
2611    /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2612    ///
2613    /// [`get_mut`]: Self::get_mut
2614    ///
2615    /// # Examples
2616    ///
2617    /// ```
2618    /// use std::collections::HashMap;
2619    /// use std::collections::hash_map::Entry;
2620    ///
2621    /// let mut map: HashMap<&str, u32> = HashMap::new();
2622    /// map.entry("poneyland").or_insert(12);
2623    ///
2624    /// assert_eq!(map["poneyland"], 12);
2625    /// if let Entry::Occupied(o) = map.entry("poneyland") {
2626    ///     *o.into_mut() += 10;
2627    /// }
2628    ///
2629    /// assert_eq!(map["poneyland"], 22);
2630    /// ```
2631    #[inline]
2632    #[stable(feature = "rust1", since = "1.0.0")]
2633    pub fn into_mut(self) -> &'a mut V {
2634        self.base.into_mut()
2635    }
2636
2637    /// Sets the value of the entry, and returns the entry's old value.
2638    ///
2639    /// # Examples
2640    ///
2641    /// ```
2642    /// use std::collections::HashMap;
2643    /// use std::collections::hash_map::Entry;
2644    ///
2645    /// let mut map: HashMap<&str, u32> = HashMap::new();
2646    /// map.entry("poneyland").or_insert(12);
2647    ///
2648    /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2649    ///     assert_eq!(o.insert(15), 12);
2650    /// }
2651    ///
2652    /// assert_eq!(map["poneyland"], 15);
2653    /// ```
2654    #[inline]
2655    #[stable(feature = "rust1", since = "1.0.0")]
2656    pub fn insert(&mut self, value: V) -> V {
2657        self.base.insert(value)
2658    }
2659
2660    /// Takes the value out of the entry, and returns it.
2661    ///
2662    /// # Examples
2663    ///
2664    /// ```
2665    /// use std::collections::HashMap;
2666    /// use std::collections::hash_map::Entry;
2667    ///
2668    /// let mut map: HashMap<&str, u32> = HashMap::new();
2669    /// map.entry("poneyland").or_insert(12);
2670    ///
2671    /// if let Entry::Occupied(o) = map.entry("poneyland") {
2672    ///     assert_eq!(o.remove(), 12);
2673    /// }
2674    ///
2675    /// assert_eq!(map.contains_key("poneyland"), false);
2676    /// ```
2677    #[inline]
2678    #[stable(feature = "rust1", since = "1.0.0")]
2679    pub fn remove(self) -> V {
2680        self.base.remove()
2681    }
2682}
2683
2684impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2685    /// Gets a reference to the key that would be used when inserting a value
2686    /// through the `VacantEntry`.
2687    ///
2688    /// # Examples
2689    ///
2690    /// ```
2691    /// use std::collections::HashMap;
2692    ///
2693    /// let mut map: HashMap<&str, u32> = HashMap::new();
2694    /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2695    /// ```
2696    #[inline]
2697    #[stable(feature = "map_entry_keys", since = "1.10.0")]
2698    pub fn key(&self) -> &K {
2699        self.base.key()
2700    }
2701
2702    /// Take ownership of the key.
2703    ///
2704    /// # Examples
2705    ///
2706    /// ```
2707    /// use std::collections::HashMap;
2708    /// use std::collections::hash_map::Entry;
2709    ///
2710    /// let mut map: HashMap<&str, u32> = HashMap::new();
2711    ///
2712    /// if let Entry::Vacant(v) = map.entry("poneyland") {
2713    ///     v.into_key();
2714    /// }
2715    /// ```
2716    #[inline]
2717    #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2718    pub fn into_key(self) -> K {
2719        self.base.into_key()
2720    }
2721
2722    /// Sets the value of the entry with the `VacantEntry`'s key,
2723    /// and returns a mutable reference to it.
2724    ///
2725    /// # Examples
2726    ///
2727    /// ```
2728    /// use std::collections::HashMap;
2729    /// use std::collections::hash_map::Entry;
2730    ///
2731    /// let mut map: HashMap<&str, u32> = HashMap::new();
2732    ///
2733    /// if let Entry::Vacant(o) = map.entry("poneyland") {
2734    ///     o.insert(37);
2735    /// }
2736    /// assert_eq!(map["poneyland"], 37);
2737    /// ```
2738    #[inline]
2739    #[stable(feature = "rust1", since = "1.0.0")]
2740    pub fn insert(self, value: V) -> &'a mut V {
2741        self.base.insert(value)
2742    }
2743
2744    /// Sets the value of the entry with the `VacantEntry`'s key,
2745    /// and returns an `OccupiedEntry`.
2746    ///
2747    /// # Examples
2748    ///
2749    /// ```
2750    /// use std::collections::HashMap;
2751    /// use std::collections::hash_map::Entry;
2752    ///
2753    /// let mut map: HashMap<&str, u32> = HashMap::new();
2754    ///
2755    /// if let Entry::Vacant(o) = map.entry("poneyland") {
2756    ///     o.insert_entry(37);
2757    /// }
2758    /// assert_eq!(map["poneyland"], 37);
2759    /// ```
2760    #[inline]
2761    #[stable(feature = "entry_insert", since = "1.83.0")]
2762    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2763        let base = self.base.insert_entry(value);
2764        OccupiedEntry { base }
2765    }
2766}
2767
2768#[stable(feature = "rust1", since = "1.0.0")]
2769impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2770where
2771    K: Eq + Hash,
2772    S: BuildHasher + Default,
2773{
2774    /// Constructs a `HashMap<K, V>` from an iterator of key-value pairs.
2775    ///
2776    /// If the iterator produces any pairs with equal keys,
2777    /// all but one of the corresponding values will be dropped.
2778    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2779        let mut map = HashMap::with_hasher(Default::default());
2780        map.extend(iter);
2781        map
2782    }
2783}
2784
2785/// Inserts all new key-values from the iterator and replaces values with existing
2786/// keys with new values returned from the iterator.
2787#[stable(feature = "rust1", since = "1.0.0")]
2788impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2789where
2790    K: Eq + Hash,
2791    S: BuildHasher,
2792{
2793    #[inline]
2794    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2795        self.base.extend(iter)
2796    }
2797
2798    #[inline]
2799    fn extend_one(&mut self, (k, v): (K, V)) {
2800        self.base.insert(k, v);
2801    }
2802
2803    #[inline]
2804    fn extend_reserve(&mut self, additional: usize) {
2805        self.base.extend_reserve(additional);
2806    }
2807}
2808
2809#[stable(feature = "hash_extend_copy", since = "1.4.0")]
2810impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2811where
2812    K: Eq + Hash + Copy,
2813    V: Copy,
2814    S: BuildHasher,
2815{
2816    #[inline]
2817    fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2818        self.base.extend(iter)
2819    }
2820
2821    #[inline]
2822    fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2823        self.base.insert(k, v);
2824    }
2825
2826    #[inline]
2827    fn extend_reserve(&mut self, additional: usize) {
2828        Extend::<(K, V)>::extend_reserve(self, additional)
2829    }
2830}
2831
2832#[inline]
2833fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2834    match raw {
2835        base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2836        base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2837    }
2838}
2839
2840#[inline]
2841pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
2842    match err {
2843        hashbrown::TryReserveError::CapacityOverflow => {
2844            TryReserveErrorKind::CapacityOverflow.into()
2845        }
2846        hashbrown::TryReserveError::AllocError { layout } => {
2847            TryReserveErrorKind::AllocError { layout, non_exhaustive: () }.into()
2848        }
2849    }
2850}
2851
2852#[allow(dead_code)]
2853fn assert_covariance() {
2854    fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2855        v
2856    }
2857    fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2858        v
2859    }
2860    fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2861        v
2862    }
2863    fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2864        v
2865    }
2866    fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2867        v
2868    }
2869    fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2870        v
2871    }
2872    fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2873        v
2874    }
2875    fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2876        v
2877    }
2878    fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2879        v
2880    }
2881    fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2882        v
2883    }
2884    fn drain<'new>(
2885        d: Drain<'static, &'static str, &'static str>,
2886    ) -> Drain<'new, &'new str, &'new str> {
2887        d
2888    }
2889}