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