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