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