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