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