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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy