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