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