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