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