]> git.lizzy.rs Git - rust.git/blob - library/std/src/collections/hash/map.rs
Merge commit '3d0b0e66afdfaa519d8855b338b35b4605775945' into clippyup
[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_try_reserve_error)
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     /// Creates a consuming iterator visiting all the keys in arbitrary order.
877     /// The map cannot be used after calling this.
878     /// The iterator element type is `K`.
879     ///
880     /// # Examples
881     ///
882     /// ```
883     /// #![feature(map_into_keys_values)]
884     /// use std::collections::HashMap;
885     ///
886     /// let mut map = HashMap::new();
887     /// map.insert("a", 1);
888     /// map.insert("b", 2);
889     /// map.insert("c", 3);
890     ///
891     /// let vec: Vec<&str> = map.into_keys().collect();
892     /// ```
893     #[inline]
894     #[unstable(feature = "map_into_keys_values", issue = "75294")]
895     pub fn into_keys(self) -> IntoKeys<K, V> {
896         IntoKeys { inner: self.into_iter() }
897     }
898
899     /// Creates a consuming iterator visiting all the values in arbitrary order.
900     /// The map cannot be used after calling this.
901     /// The iterator element type is `V`.
902     ///
903     /// # Examples
904     ///
905     /// ```
906     /// #![feature(map_into_keys_values)]
907     /// use std::collections::HashMap;
908     ///
909     /// let mut map = HashMap::new();
910     /// map.insert("a", 1);
911     /// map.insert("b", 2);
912     /// map.insert("c", 3);
913     ///
914     /// let vec: Vec<i32> = map.into_values().collect();
915     /// ```
916     #[inline]
917     #[unstable(feature = "map_into_keys_values", issue = "75294")]
918     pub fn into_values(self) -> IntoValues<K, V> {
919         IntoValues { inner: self.into_iter() }
920     }
921 }
922
923 impl<K, V, S> HashMap<K, V, S>
924 where
925     S: BuildHasher,
926 {
927     /// Creates a raw entry builder for the HashMap.
928     ///
929     /// Raw entries provide the lowest level of control for searching and
930     /// manipulating a map. They must be manually initialized with a hash and
931     /// then manually searched. After this, insertions into a vacant entry
932     /// still require an owned key to be provided.
933     ///
934     /// Raw entries are useful for such exotic situations as:
935     ///
936     /// * Hash memoization
937     /// * Deferring the creation of an owned key until it is known to be required
938     /// * Using a search key that doesn't work with the Borrow trait
939     /// * Using custom comparison logic without newtype wrappers
940     ///
941     /// Because raw entries provide much more low-level control, it's much easier
942     /// to put the HashMap into an inconsistent state which, while memory-safe,
943     /// will cause the map to produce seemingly random results. Higher-level and
944     /// more foolproof APIs like `entry` should be preferred when possible.
945     ///
946     /// In particular, the hash used to initialized the raw entry must still be
947     /// consistent with the hash of the key that is ultimately stored in the entry.
948     /// This is because implementations of HashMap may need to recompute hashes
949     /// when resizing, at which point only the keys are available.
950     ///
951     /// Raw entries give mutable access to the keys. This must not be used
952     /// to modify how the key would compare or hash, as the map will not re-evaluate
953     /// where the key should go, meaning the keys may become "lost" if their
954     /// location does not reflect their state. For instance, if you change a key
955     /// so that the map now contains keys which compare equal, search may start
956     /// acting erratically, with two keys randomly masking each other. Implementations
957     /// are free to assume this doesn't happen (within the limits of memory-safety).
958     #[inline]
959     #[unstable(feature = "hash_raw_entry", issue = "56167")]
960     pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
961         RawEntryBuilderMut { map: self }
962     }
963
964     /// Creates a raw immutable entry builder for the HashMap.
965     ///
966     /// Raw entries provide the lowest level of control for searching and
967     /// manipulating a map. They must be manually initialized with a hash and
968     /// then manually searched.
969     ///
970     /// This is useful for
971     /// * Hash memoization
972     /// * Using a search key that doesn't work with the Borrow trait
973     /// * Using custom comparison logic without newtype wrappers
974     ///
975     /// Unless you are in such a situation, higher-level and more foolproof APIs like
976     /// `get` should be preferred.
977     ///
978     /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
979     #[inline]
980     #[unstable(feature = "hash_raw_entry", issue = "56167")]
981     pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
982         RawEntryBuilder { map: self }
983     }
984 }
985
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<K, V, S> PartialEq for HashMap<K, V, S>
988 where
989     K: Eq + Hash,
990     V: PartialEq,
991     S: BuildHasher,
992 {
993     fn eq(&self, other: &HashMap<K, V, S>) -> bool {
994         if self.len() != other.len() {
995             return false;
996         }
997
998         self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
999     }
1000 }
1001
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<K, V, S> Eq for HashMap<K, V, S>
1004 where
1005     K: Eq + Hash,
1006     V: Eq,
1007     S: BuildHasher,
1008 {
1009 }
1010
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<K, V, S> Debug for HashMap<K, V, S>
1013 where
1014     K: Debug,
1015     V: Debug,
1016 {
1017     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018         f.debug_map().entries(self.iter()).finish()
1019     }
1020 }
1021
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<K, V, S> Default for HashMap<K, V, S>
1024 where
1025     S: Default,
1026 {
1027     /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1028     #[inline]
1029     fn default() -> HashMap<K, V, S> {
1030         HashMap::with_hasher(Default::default())
1031     }
1032 }
1033
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1036 where
1037     K: Eq + Hash + Borrow<Q>,
1038     Q: Eq + Hash,
1039     S: BuildHasher,
1040 {
1041     type Output = V;
1042
1043     /// Returns a reference to the value corresponding to the supplied key.
1044     ///
1045     /// # Panics
1046     ///
1047     /// Panics if the key is not present in the `HashMap`.
1048     #[inline]
1049     fn index(&self, key: &Q) -> &V {
1050         self.get(key).expect("no entry found for key")
1051     }
1052 }
1053
1054 /// An iterator over the entries of a `HashMap`.
1055 ///
1056 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1057 /// documentation for more.
1058 ///
1059 /// [`iter`]: HashMap::iter
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub struct Iter<'a, K: 'a, V: 'a> {
1062     base: base::Iter<'a, K, V>,
1063 }
1064
1065 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<K, V> Clone for Iter<'_, K, V> {
1068     #[inline]
1069     fn clone(&self) -> Self {
1070         Iter { base: self.base.clone() }
1071     }
1072 }
1073
1074 #[stable(feature = "std_debug", since = "1.16.0")]
1075 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1076     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1077         f.debug_list().entries(self.clone()).finish()
1078     }
1079 }
1080
1081 /// A mutable iterator over the entries of a `HashMap`.
1082 ///
1083 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1084 /// documentation for more.
1085 ///
1086 /// [`iter_mut`]: HashMap::iter_mut
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub struct IterMut<'a, K: 'a, V: 'a> {
1089     base: base::IterMut<'a, K, V>,
1090 }
1091
1092 impl<'a, K, V> IterMut<'a, K, V> {
1093     /// Returns a iterator of references over the remaining items.
1094     #[inline]
1095     pub(super) fn iter(&self) -> Iter<'_, K, V> {
1096         Iter { base: self.base.rustc_iter() }
1097     }
1098 }
1099
1100 /// An owning iterator over the entries of a `HashMap`.
1101 ///
1102 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1103 /// (provided by the `IntoIterator` trait). See its documentation for more.
1104 ///
1105 /// [`into_iter`]: IntoIterator::into_iter
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub struct IntoIter<K, V> {
1108     base: base::IntoIter<K, V>,
1109 }
1110
1111 impl<K, V> IntoIter<K, V> {
1112     /// Returns a iterator of references over the remaining items.
1113     #[inline]
1114     pub(super) fn iter(&self) -> Iter<'_, K, V> {
1115         Iter { base: self.base.rustc_iter() }
1116     }
1117 }
1118
1119 /// An iterator over the keys of a `HashMap`.
1120 ///
1121 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1122 /// documentation for more.
1123 ///
1124 /// [`keys`]: HashMap::keys
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub struct Keys<'a, K: 'a, V: 'a> {
1127     inner: Iter<'a, K, V>,
1128 }
1129
1130 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<K, V> Clone for Keys<'_, K, V> {
1133     #[inline]
1134     fn clone(&self) -> Self {
1135         Keys { inner: self.inner.clone() }
1136     }
1137 }
1138
1139 #[stable(feature = "std_debug", since = "1.16.0")]
1140 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1141     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1142         f.debug_list().entries(self.clone()).finish()
1143     }
1144 }
1145
1146 /// An iterator over the values of a `HashMap`.
1147 ///
1148 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1149 /// documentation for more.
1150 ///
1151 /// [`values`]: HashMap::values
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub struct Values<'a, K: 'a, V: 'a> {
1154     inner: Iter<'a, K, V>,
1155 }
1156
1157 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<K, V> Clone for Values<'_, K, V> {
1160     #[inline]
1161     fn clone(&self) -> Self {
1162         Values { inner: self.inner.clone() }
1163     }
1164 }
1165
1166 #[stable(feature = "std_debug", since = "1.16.0")]
1167 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1168     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1169         f.debug_list().entries(self.clone()).finish()
1170     }
1171 }
1172
1173 /// A draining iterator over the entries of a `HashMap`.
1174 ///
1175 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1176 /// documentation for more.
1177 ///
1178 /// [`drain`]: HashMap::drain
1179 #[stable(feature = "drain", since = "1.6.0")]
1180 pub struct Drain<'a, K: 'a, V: 'a> {
1181     base: base::Drain<'a, K, V>,
1182 }
1183
1184 impl<'a, K, V> Drain<'a, K, V> {
1185     /// Returns a iterator of references over the remaining items.
1186     #[inline]
1187     pub(super) fn iter(&self) -> Iter<'_, K, V> {
1188         Iter { base: self.base.rustc_iter() }
1189     }
1190 }
1191
1192 /// A mutable iterator over the values of a `HashMap`.
1193 ///
1194 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1195 /// documentation for more.
1196 ///
1197 /// [`values_mut`]: HashMap::values_mut
1198 #[stable(feature = "map_values_mut", since = "1.10.0")]
1199 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1200     inner: IterMut<'a, K, V>,
1201 }
1202
1203 /// An owning iterator over the keys of a `HashMap`.
1204 ///
1205 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1206 /// See its documentation for more.
1207 ///
1208 /// [`into_keys`]: HashMap::into_keys
1209 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1210 pub struct IntoKeys<K, V> {
1211     inner: IntoIter<K, V>,
1212 }
1213
1214 /// An owning iterator over the values of a `HashMap`.
1215 ///
1216 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1217 /// See its documentation for more.
1218 ///
1219 /// [`into_values`]: HashMap::into_values
1220 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1221 pub struct IntoValues<K, V> {
1222     inner: IntoIter<K, V>,
1223 }
1224
1225 /// A builder for computing where in a HashMap a key-value pair would be stored.
1226 ///
1227 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1228 ///
1229 /// [`HashMap::raw_entry_mut`]: HashMap::raw_entry_mut
1230
1231 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1232 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1233     map: &'a mut HashMap<K, V, S>,
1234 }
1235
1236 /// A view into a single entry in a map, which may either be vacant or occupied.
1237 ///
1238 /// This is a lower-level version of [`Entry`].
1239 ///
1240 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1241 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1242 ///
1243 /// [`Entry`]: enum.Entry.html
1244 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1245 /// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html
1246 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1247 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1248     /// An occupied entry.
1249     Occupied(RawOccupiedEntryMut<'a, K, V>),
1250     /// A vacant entry.
1251     Vacant(RawVacantEntryMut<'a, K, V, S>),
1252 }
1253
1254 /// A view into an occupied entry in a `HashMap`.
1255 /// It is part of the [`RawEntryMut`] enum.
1256 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1257 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1258     base: base::RawOccupiedEntryMut<'a, K, V>,
1259 }
1260
1261 /// A view into a vacant entry in a `HashMap`.
1262 /// It is part of the [`RawEntryMut`] enum.
1263 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1264 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1265     base: base::RawVacantEntryMut<'a, K, V, S>,
1266 }
1267
1268 /// A builder for computing where in a HashMap a key-value pair would be stored.
1269 ///
1270 /// See the [`HashMap::raw_entry`] docs for usage examples.
1271 ///
1272 /// [`HashMap::raw_entry`]: HashMap::raw_entry
1273 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1274 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1275     map: &'a HashMap<K, V, S>,
1276 }
1277
1278 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1279 where
1280     S: BuildHasher,
1281 {
1282     /// Creates a `RawEntryMut` from the given key.
1283     #[inline]
1284     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1285     pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1286     where
1287         K: Borrow<Q>,
1288         Q: Hash + Eq,
1289     {
1290         map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1291     }
1292
1293     /// Creates a `RawEntryMut` from the given key and its hash.
1294     #[inline]
1295     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1296     pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1297     where
1298         K: Borrow<Q>,
1299         Q: Eq,
1300     {
1301         map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1302     }
1303
1304     /// Creates a `RawEntryMut` from the given hash.
1305     #[inline]
1306     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1307     pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1308     where
1309         for<'b> F: FnMut(&'b K) -> bool,
1310     {
1311         map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1312     }
1313 }
1314
1315 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1316 where
1317     S: BuildHasher,
1318 {
1319     /// Access an entry by key.
1320     #[inline]
1321     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1322     pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1323     where
1324         K: Borrow<Q>,
1325         Q: Hash + Eq,
1326     {
1327         self.map.base.raw_entry().from_key(k)
1328     }
1329
1330     /// Access an entry by a key and its hash.
1331     #[inline]
1332     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1333     pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1334     where
1335         K: Borrow<Q>,
1336         Q: Hash + Eq,
1337     {
1338         self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1339     }
1340
1341     /// Access an entry by hash.
1342     #[inline]
1343     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1344     pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1345     where
1346         F: FnMut(&K) -> bool,
1347     {
1348         self.map.base.raw_entry().from_hash(hash, is_match)
1349     }
1350 }
1351
1352 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1353     /// Ensures a value is in the entry by inserting the default if empty, and returns
1354     /// mutable references to the key and value in the entry.
1355     ///
1356     /// # Examples
1357     ///
1358     /// ```
1359     /// #![feature(hash_raw_entry)]
1360     /// use std::collections::HashMap;
1361     ///
1362     /// let mut map: HashMap<&str, u32> = HashMap::new();
1363     ///
1364     /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1365     /// assert_eq!(map["poneyland"], 3);
1366     ///
1367     /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1368     /// assert_eq!(map["poneyland"], 6);
1369     /// ```
1370     #[inline]
1371     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1372     pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1373     where
1374         K: Hash,
1375         S: BuildHasher,
1376     {
1377         match self {
1378             RawEntryMut::Occupied(entry) => entry.into_key_value(),
1379             RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1380         }
1381     }
1382
1383     /// Ensures a value is in the entry by inserting the result of the default function if empty,
1384     /// and returns mutable references to the key and value in the entry.
1385     ///
1386     /// # Examples
1387     ///
1388     /// ```
1389     /// #![feature(hash_raw_entry)]
1390     /// use std::collections::HashMap;
1391     ///
1392     /// let mut map: HashMap<&str, String> = HashMap::new();
1393     ///
1394     /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1395     ///     ("poneyland", "hoho".to_string())
1396     /// });
1397     ///
1398     /// assert_eq!(map["poneyland"], "hoho".to_string());
1399     /// ```
1400     #[inline]
1401     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1402     pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1403     where
1404         F: FnOnce() -> (K, V),
1405         K: Hash,
1406         S: BuildHasher,
1407     {
1408         match self {
1409             RawEntryMut::Occupied(entry) => entry.into_key_value(),
1410             RawEntryMut::Vacant(entry) => {
1411                 let (k, v) = default();
1412                 entry.insert(k, v)
1413             }
1414         }
1415     }
1416
1417     /// Provides in-place mutable access to an occupied entry before any
1418     /// potential inserts into the map.
1419     ///
1420     /// # Examples
1421     ///
1422     /// ```
1423     /// #![feature(hash_raw_entry)]
1424     /// use std::collections::HashMap;
1425     ///
1426     /// let mut map: HashMap<&str, u32> = HashMap::new();
1427     ///
1428     /// map.raw_entry_mut()
1429     ///    .from_key("poneyland")
1430     ///    .and_modify(|_k, v| { *v += 1 })
1431     ///    .or_insert("poneyland", 42);
1432     /// assert_eq!(map["poneyland"], 42);
1433     ///
1434     /// map.raw_entry_mut()
1435     ///    .from_key("poneyland")
1436     ///    .and_modify(|_k, v| { *v += 1 })
1437     ///    .or_insert("poneyland", 0);
1438     /// assert_eq!(map["poneyland"], 43);
1439     /// ```
1440     #[inline]
1441     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1442     pub fn and_modify<F>(self, f: F) -> Self
1443     where
1444         F: FnOnce(&mut K, &mut V),
1445     {
1446         match self {
1447             RawEntryMut::Occupied(mut entry) => {
1448                 {
1449                     let (k, v) = entry.get_key_value_mut();
1450                     f(k, v);
1451                 }
1452                 RawEntryMut::Occupied(entry)
1453             }
1454             RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1455         }
1456     }
1457 }
1458
1459 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
1460     /// Gets a reference to the key in the entry.
1461     #[inline]
1462     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1463     pub fn key(&self) -> &K {
1464         self.base.key()
1465     }
1466
1467     /// Gets a mutable reference to the key in the entry.
1468     #[inline]
1469     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1470     pub fn key_mut(&mut self) -> &mut K {
1471         self.base.key_mut()
1472     }
1473
1474     /// Converts the entry into a mutable reference to the key in the entry
1475     /// with a lifetime bound to the map itself.
1476     #[inline]
1477     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1478     pub fn into_key(self) -> &'a mut K {
1479         self.base.into_key()
1480     }
1481
1482     /// Gets a reference to the value in the entry.
1483     #[inline]
1484     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1485     pub fn get(&self) -> &V {
1486         self.base.get()
1487     }
1488
1489     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1490     /// with a lifetime bound to the map itself.
1491     #[inline]
1492     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1493     pub fn into_mut(self) -> &'a mut V {
1494         self.base.into_mut()
1495     }
1496
1497     /// Gets a mutable reference to the value in the entry.
1498     #[inline]
1499     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1500     pub fn get_mut(&mut self) -> &mut V {
1501         self.base.get_mut()
1502     }
1503
1504     /// Gets a reference to the key and value in the entry.
1505     #[inline]
1506     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1507     pub fn get_key_value(&mut self) -> (&K, &V) {
1508         self.base.get_key_value()
1509     }
1510
1511     /// Gets a mutable reference to the key and value in the entry.
1512     #[inline]
1513     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1514     pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1515         self.base.get_key_value_mut()
1516     }
1517
1518     /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
1519     /// with a lifetime bound to the map itself.
1520     #[inline]
1521     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1522     pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1523         self.base.into_key_value()
1524     }
1525
1526     /// Sets the value of the entry, and returns the entry's old value.
1527     #[inline]
1528     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1529     pub fn insert(&mut self, value: V) -> V {
1530         self.base.insert(value)
1531     }
1532
1533     /// Sets the value of the entry, and returns the entry's old value.
1534     #[inline]
1535     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1536     pub fn insert_key(&mut self, key: K) -> K {
1537         self.base.insert_key(key)
1538     }
1539
1540     /// Takes the value out of the entry, and returns it.
1541     #[inline]
1542     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1543     pub fn remove(self) -> V {
1544         self.base.remove()
1545     }
1546
1547     /// Take the ownership of the key and value from the map.
1548     #[inline]
1549     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1550     pub fn remove_entry(self) -> (K, V) {
1551         self.base.remove_entry()
1552     }
1553 }
1554
1555 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1556     /// Sets the value of the entry with the VacantEntry's key,
1557     /// and returns a mutable reference to it.
1558     #[inline]
1559     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1560     pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1561     where
1562         K: Hash,
1563         S: BuildHasher,
1564     {
1565         self.base.insert(key, value)
1566     }
1567
1568     /// Sets the value of the entry with the VacantEntry's key,
1569     /// and returns a mutable reference to it.
1570     #[inline]
1571     #[unstable(feature = "hash_raw_entry", issue = "56167")]
1572     pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1573     where
1574         K: Hash,
1575         S: BuildHasher,
1576     {
1577         self.base.insert_hashed_nocheck(hash, key, value)
1578     }
1579 }
1580
1581 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1582 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1583     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1584         f.debug_struct("RawEntryBuilder").finish()
1585     }
1586 }
1587
1588 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1589 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1590     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1591         match *self {
1592             RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1593             RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1594         }
1595     }
1596 }
1597
1598 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1599 impl<K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'_, K, V> {
1600     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1601         f.debug_struct("RawOccupiedEntryMut")
1602             .field("key", self.key())
1603             .field("value", self.get())
1604             .finish()
1605     }
1606 }
1607
1608 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1609 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1610     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1611         f.debug_struct("RawVacantEntryMut").finish()
1612     }
1613 }
1614
1615 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1616 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1617     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1618         f.debug_struct("RawEntryBuilder").finish()
1619     }
1620 }
1621
1622 /// A view into a single entry in a map, which may either be vacant or occupied.
1623 ///
1624 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1625 ///
1626 /// [`entry`]: HashMap::entry
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 pub enum Entry<'a, K: 'a, V: 'a> {
1629     /// An occupied entry.
1630     #[stable(feature = "rust1", since = "1.0.0")]
1631     Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1632
1633     /// A vacant entry.
1634     #[stable(feature = "rust1", since = "1.0.0")]
1635     Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1636 }
1637
1638 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1639 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1640     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1641         match *self {
1642             Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1643             Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1644         }
1645     }
1646 }
1647
1648 /// A view into an occupied entry in a `HashMap`.
1649 /// It is part of the [`Entry`] enum.
1650 ///
1651 /// [`Entry`]: enum.Entry.html
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1654     base: base::RustcOccupiedEntry<'a, K, V>,
1655 }
1656
1657 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1658 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1659     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1660         f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
1661     }
1662 }
1663
1664 /// A view into a vacant entry in a `HashMap`.
1665 /// It is part of the [`Entry`] enum.
1666 ///
1667 /// [`Entry`]: enum.Entry.html
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1670     base: base::RustcVacantEntry<'a, K, V>,
1671 }
1672
1673 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1674 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1675     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1676         f.debug_tuple("VacantEntry").field(self.key()).finish()
1677     }
1678 }
1679
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1682     type Item = (&'a K, &'a V);
1683     type IntoIter = Iter<'a, K, V>;
1684
1685     #[inline]
1686     fn into_iter(self) -> Iter<'a, K, V> {
1687         self.iter()
1688     }
1689 }
1690
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1693     type Item = (&'a K, &'a mut V);
1694     type IntoIter = IterMut<'a, K, V>;
1695
1696     #[inline]
1697     fn into_iter(self) -> IterMut<'a, K, V> {
1698         self.iter_mut()
1699     }
1700 }
1701
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1704     type Item = (K, V);
1705     type IntoIter = IntoIter<K, V>;
1706
1707     /// Creates a consuming iterator, that is, one that moves each key-value
1708     /// pair out of the map in arbitrary order. The map cannot be used after
1709     /// calling this.
1710     ///
1711     /// # Examples
1712     ///
1713     /// ```
1714     /// use std::collections::HashMap;
1715     ///
1716     /// let mut map = HashMap::new();
1717     /// map.insert("a", 1);
1718     /// map.insert("b", 2);
1719     /// map.insert("c", 3);
1720     ///
1721     /// // Not possible with .iter()
1722     /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1723     /// ```
1724     #[inline]
1725     fn into_iter(self) -> IntoIter<K, V> {
1726         IntoIter { base: self.base.into_iter() }
1727     }
1728 }
1729
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1732     type Item = (&'a K, &'a V);
1733
1734     #[inline]
1735     fn next(&mut self) -> Option<(&'a K, &'a V)> {
1736         self.base.next()
1737     }
1738     #[inline]
1739     fn size_hint(&self) -> (usize, Option<usize>) {
1740         self.base.size_hint()
1741     }
1742 }
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1745     #[inline]
1746     fn len(&self) -> usize {
1747         self.base.len()
1748     }
1749 }
1750
1751 #[stable(feature = "fused", since = "1.26.0")]
1752 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1753
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1756     type Item = (&'a K, &'a mut V);
1757
1758     #[inline]
1759     fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1760         self.base.next()
1761     }
1762     #[inline]
1763     fn size_hint(&self) -> (usize, Option<usize>) {
1764         self.base.size_hint()
1765     }
1766 }
1767 #[stable(feature = "rust1", since = "1.0.0")]
1768 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1769     #[inline]
1770     fn len(&self) -> usize {
1771         self.base.len()
1772     }
1773 }
1774 #[stable(feature = "fused", since = "1.26.0")]
1775 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1776
1777 #[stable(feature = "std_debug", since = "1.16.0")]
1778 impl<K, V> fmt::Debug for IterMut<'_, K, V>
1779 where
1780     K: fmt::Debug,
1781     V: fmt::Debug,
1782 {
1783     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1784         f.debug_list().entries(self.iter()).finish()
1785     }
1786 }
1787
1788 #[stable(feature = "rust1", since = "1.0.0")]
1789 impl<K, V> Iterator for IntoIter<K, V> {
1790     type Item = (K, V);
1791
1792     #[inline]
1793     fn next(&mut self) -> Option<(K, V)> {
1794         self.base.next()
1795     }
1796     #[inline]
1797     fn size_hint(&self) -> (usize, Option<usize>) {
1798         self.base.size_hint()
1799     }
1800 }
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1803     #[inline]
1804     fn len(&self) -> usize {
1805         self.base.len()
1806     }
1807 }
1808 #[stable(feature = "fused", since = "1.26.0")]
1809 impl<K, V> FusedIterator for IntoIter<K, V> {}
1810
1811 #[stable(feature = "std_debug", since = "1.16.0")]
1812 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1813     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1814         f.debug_list().entries(self.iter()).finish()
1815     }
1816 }
1817
1818 #[stable(feature = "rust1", since = "1.0.0")]
1819 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1820     type Item = &'a K;
1821
1822     #[inline]
1823     fn next(&mut self) -> Option<&'a K> {
1824         self.inner.next().map(|(k, _)| k)
1825     }
1826     #[inline]
1827     fn size_hint(&self) -> (usize, Option<usize>) {
1828         self.inner.size_hint()
1829     }
1830 }
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1833     #[inline]
1834     fn len(&self) -> usize {
1835         self.inner.len()
1836     }
1837 }
1838 #[stable(feature = "fused", since = "1.26.0")]
1839 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1840
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 impl<'a, K, V> Iterator for Values<'a, K, V> {
1843     type Item = &'a V;
1844
1845     #[inline]
1846     fn next(&mut self) -> Option<&'a V> {
1847         self.inner.next().map(|(_, v)| v)
1848     }
1849     #[inline]
1850     fn size_hint(&self) -> (usize, Option<usize>) {
1851         self.inner.size_hint()
1852     }
1853 }
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1856     #[inline]
1857     fn len(&self) -> usize {
1858         self.inner.len()
1859     }
1860 }
1861 #[stable(feature = "fused", since = "1.26.0")]
1862 impl<K, V> FusedIterator for Values<'_, K, V> {}
1863
1864 #[stable(feature = "map_values_mut", since = "1.10.0")]
1865 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1866     type Item = &'a mut V;
1867
1868     #[inline]
1869     fn next(&mut self) -> Option<&'a mut V> {
1870         self.inner.next().map(|(_, v)| v)
1871     }
1872     #[inline]
1873     fn size_hint(&self) -> (usize, Option<usize>) {
1874         self.inner.size_hint()
1875     }
1876 }
1877 #[stable(feature = "map_values_mut", since = "1.10.0")]
1878 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1879     #[inline]
1880     fn len(&self) -> usize {
1881         self.inner.len()
1882     }
1883 }
1884 #[stable(feature = "fused", since = "1.26.0")]
1885 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1886
1887 #[stable(feature = "std_debug", since = "1.16.0")]
1888 impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1889 where
1890     K: fmt::Debug,
1891     V: fmt::Debug,
1892 {
1893     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894         f.debug_list().entries(self.inner.iter()).finish()
1895     }
1896 }
1897
1898 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1899 impl<K, V> Iterator for IntoKeys<K, V> {
1900     type Item = K;
1901
1902     #[inline]
1903     fn next(&mut self) -> Option<K> {
1904         self.inner.next().map(|(k, _)| k)
1905     }
1906     #[inline]
1907     fn size_hint(&self) -> (usize, Option<usize>) {
1908         self.inner.size_hint()
1909     }
1910 }
1911 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1912 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1913     #[inline]
1914     fn len(&self) -> usize {
1915         self.inner.len()
1916     }
1917 }
1918 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1919 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1920
1921 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1922 impl<K: Debug, V: Debug> fmt::Debug for IntoKeys<K, V> {
1923     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1924         f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
1925     }
1926 }
1927
1928 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1929 impl<K, V> Iterator for IntoValues<K, V> {
1930     type Item = V;
1931
1932     #[inline]
1933     fn next(&mut self) -> Option<V> {
1934         self.inner.next().map(|(_, v)| v)
1935     }
1936     #[inline]
1937     fn size_hint(&self) -> (usize, Option<usize>) {
1938         self.inner.size_hint()
1939     }
1940 }
1941 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1942 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1943     #[inline]
1944     fn len(&self) -> usize {
1945         self.inner.len()
1946     }
1947 }
1948 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1949 impl<K, V> FusedIterator for IntoValues<K, V> {}
1950
1951 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1952 impl<K: Debug, V: Debug> fmt::Debug for IntoValues<K, V> {
1953     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1954         f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
1955     }
1956 }
1957
1958 #[stable(feature = "drain", since = "1.6.0")]
1959 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1960     type Item = (K, V);
1961
1962     #[inline]
1963     fn next(&mut self) -> Option<(K, V)> {
1964         self.base.next()
1965     }
1966     #[inline]
1967     fn size_hint(&self) -> (usize, Option<usize>) {
1968         self.base.size_hint()
1969     }
1970 }
1971 #[stable(feature = "drain", since = "1.6.0")]
1972 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
1973     #[inline]
1974     fn len(&self) -> usize {
1975         self.base.len()
1976     }
1977 }
1978 #[stable(feature = "fused", since = "1.26.0")]
1979 impl<K, V> FusedIterator for Drain<'_, K, V> {}
1980
1981 #[stable(feature = "std_debug", since = "1.16.0")]
1982 impl<K, V> fmt::Debug for Drain<'_, K, V>
1983 where
1984     K: fmt::Debug,
1985     V: fmt::Debug,
1986 {
1987     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1988         f.debug_list().entries(self.iter()).finish()
1989     }
1990 }
1991
1992 impl<'a, K, V> Entry<'a, K, V> {
1993     #[stable(feature = "rust1", since = "1.0.0")]
1994     /// Ensures a value is in the entry by inserting the default if empty, and returns
1995     /// a mutable reference to the value in the entry.
1996     ///
1997     /// # Examples
1998     ///
1999     /// ```
2000     /// use std::collections::HashMap;
2001     ///
2002     /// let mut map: HashMap<&str, u32> = HashMap::new();
2003     ///
2004     /// map.entry("poneyland").or_insert(3);
2005     /// assert_eq!(map["poneyland"], 3);
2006     ///
2007     /// *map.entry("poneyland").or_insert(10) *= 2;
2008     /// assert_eq!(map["poneyland"], 6);
2009     /// ```
2010     #[inline]
2011     pub fn or_insert(self, default: V) -> &'a mut V {
2012         match self {
2013             Occupied(entry) => entry.into_mut(),
2014             Vacant(entry) => entry.insert(default),
2015         }
2016     }
2017
2018     #[stable(feature = "rust1", since = "1.0.0")]
2019     /// Ensures a value is in the entry by inserting the result of the default function if empty,
2020     /// and returns a mutable reference to the value in the entry.
2021     ///
2022     /// # Examples
2023     ///
2024     /// ```
2025     /// use std::collections::HashMap;
2026     ///
2027     /// let mut map: HashMap<&str, String> = HashMap::new();
2028     /// let s = "hoho".to_string();
2029     ///
2030     /// map.entry("poneyland").or_insert_with(|| s);
2031     ///
2032     /// assert_eq!(map["poneyland"], "hoho".to_string());
2033     /// ```
2034     #[inline]
2035     pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2036         match self {
2037             Occupied(entry) => entry.into_mut(),
2038             Vacant(entry) => entry.insert(default()),
2039         }
2040     }
2041
2042     #[unstable(feature = "or_insert_with_key", issue = "71024")]
2043     /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2044     /// which takes the key as its argument, and returns a mutable reference to the value in the
2045     /// entry.
2046     ///
2047     /// # Examples
2048     ///
2049     /// ```
2050     /// #![feature(or_insert_with_key)]
2051     /// use std::collections::HashMap;
2052     ///
2053     /// let mut map: HashMap<&str, usize> = HashMap::new();
2054     ///
2055     /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2056     ///
2057     /// assert_eq!(map["poneyland"], 9);
2058     /// ```
2059     #[inline]
2060     pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2061         match self {
2062             Occupied(entry) => entry.into_mut(),
2063             Vacant(entry) => {
2064                 let value = default(entry.key());
2065                 entry.insert(value)
2066             }
2067         }
2068     }
2069
2070     /// Returns a reference to this entry's key.
2071     ///
2072     /// # Examples
2073     ///
2074     /// ```
2075     /// use std::collections::HashMap;
2076     ///
2077     /// let mut map: HashMap<&str, u32> = HashMap::new();
2078     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2079     /// ```
2080     #[inline]
2081     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2082     pub fn key(&self) -> &K {
2083         match *self {
2084             Occupied(ref entry) => entry.key(),
2085             Vacant(ref entry) => entry.key(),
2086         }
2087     }
2088
2089     /// Provides in-place mutable access to an occupied entry before any
2090     /// potential inserts into the map.
2091     ///
2092     /// # Examples
2093     ///
2094     /// ```
2095     /// use std::collections::HashMap;
2096     ///
2097     /// let mut map: HashMap<&str, u32> = HashMap::new();
2098     ///
2099     /// map.entry("poneyland")
2100     ///    .and_modify(|e| { *e += 1 })
2101     ///    .or_insert(42);
2102     /// assert_eq!(map["poneyland"], 42);
2103     ///
2104     /// map.entry("poneyland")
2105     ///    .and_modify(|e| { *e += 1 })
2106     ///    .or_insert(42);
2107     /// assert_eq!(map["poneyland"], 43);
2108     /// ```
2109     #[inline]
2110     #[stable(feature = "entry_and_modify", since = "1.26.0")]
2111     pub fn and_modify<F>(self, f: F) -> Self
2112     where
2113         F: FnOnce(&mut V),
2114     {
2115         match self {
2116             Occupied(mut entry) => {
2117                 f(entry.get_mut());
2118                 Occupied(entry)
2119             }
2120             Vacant(entry) => Vacant(entry),
2121         }
2122     }
2123
2124     /// Sets the value of the entry, and returns an OccupiedEntry.
2125     ///
2126     /// # Examples
2127     ///
2128     /// ```
2129     /// #![feature(entry_insert)]
2130     /// use std::collections::HashMap;
2131     ///
2132     /// let mut map: HashMap<&str, String> = HashMap::new();
2133     /// let entry = map.entry("poneyland").insert("hoho".to_string());
2134     ///
2135     /// assert_eq!(entry.key(), &"poneyland");
2136     /// ```
2137     #[inline]
2138     #[unstable(feature = "entry_insert", issue = "65225")]
2139     pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
2140         match self {
2141             Occupied(mut entry) => {
2142                 entry.insert(value);
2143                 entry
2144             }
2145             Vacant(entry) => entry.insert_entry(value),
2146         }
2147     }
2148 }
2149
2150 impl<'a, K, V: Default> Entry<'a, K, V> {
2151     #[stable(feature = "entry_or_default", since = "1.28.0")]
2152     /// Ensures a value is in the entry by inserting the default value if empty,
2153     /// and returns a mutable reference to the value in the entry.
2154     ///
2155     /// # Examples
2156     ///
2157     /// ```
2158     /// # fn main() {
2159     /// use std::collections::HashMap;
2160     ///
2161     /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2162     /// map.entry("poneyland").or_default();
2163     ///
2164     /// assert_eq!(map["poneyland"], None);
2165     /// # }
2166     /// ```
2167     #[inline]
2168     pub fn or_default(self) -> &'a mut V {
2169         match self {
2170             Occupied(entry) => entry.into_mut(),
2171             Vacant(entry) => entry.insert(Default::default()),
2172         }
2173     }
2174 }
2175
2176 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2177     /// Gets a reference to the key in the entry.
2178     ///
2179     /// # Examples
2180     ///
2181     /// ```
2182     /// use std::collections::HashMap;
2183     ///
2184     /// let mut map: HashMap<&str, u32> = HashMap::new();
2185     /// map.entry("poneyland").or_insert(12);
2186     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2187     /// ```
2188     #[inline]
2189     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2190     pub fn key(&self) -> &K {
2191         self.base.key()
2192     }
2193
2194     /// Take the ownership of the key and value from the map.
2195     ///
2196     /// # Examples
2197     ///
2198     /// ```
2199     /// use std::collections::HashMap;
2200     /// use std::collections::hash_map::Entry;
2201     ///
2202     /// let mut map: HashMap<&str, u32> = HashMap::new();
2203     /// map.entry("poneyland").or_insert(12);
2204     ///
2205     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2206     ///     // We delete the entry from the map.
2207     ///     o.remove_entry();
2208     /// }
2209     ///
2210     /// assert_eq!(map.contains_key("poneyland"), false);
2211     /// ```
2212     #[inline]
2213     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2214     pub fn remove_entry(self) -> (K, V) {
2215         self.base.remove_entry()
2216     }
2217
2218     /// Gets a reference to the value in the entry.
2219     ///
2220     /// # Examples
2221     ///
2222     /// ```
2223     /// use std::collections::HashMap;
2224     /// use std::collections::hash_map::Entry;
2225     ///
2226     /// let mut map: HashMap<&str, u32> = HashMap::new();
2227     /// map.entry("poneyland").or_insert(12);
2228     ///
2229     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2230     ///     assert_eq!(o.get(), &12);
2231     /// }
2232     /// ```
2233     #[inline]
2234     #[stable(feature = "rust1", since = "1.0.0")]
2235     pub fn get(&self) -> &V {
2236         self.base.get()
2237     }
2238
2239     /// Gets a mutable reference to the value in the entry.
2240     ///
2241     /// If you need a reference to the `OccupiedEntry` which may outlive the
2242     /// destruction of the `Entry` value, see [`into_mut`].
2243     ///
2244     /// [`into_mut`]: Self::into_mut
2245     ///
2246     /// # Examples
2247     ///
2248     /// ```
2249     /// use std::collections::HashMap;
2250     /// use std::collections::hash_map::Entry;
2251     ///
2252     /// let mut map: HashMap<&str, u32> = HashMap::new();
2253     /// map.entry("poneyland").or_insert(12);
2254     ///
2255     /// assert_eq!(map["poneyland"], 12);
2256     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2257     ///     *o.get_mut() += 10;
2258     ///     assert_eq!(*o.get(), 22);
2259     ///
2260     ///     // We can use the same Entry multiple times.
2261     ///     *o.get_mut() += 2;
2262     /// }
2263     ///
2264     /// assert_eq!(map["poneyland"], 24);
2265     /// ```
2266     #[inline]
2267     #[stable(feature = "rust1", since = "1.0.0")]
2268     pub fn get_mut(&mut self) -> &mut V {
2269         self.base.get_mut()
2270     }
2271
2272     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2273     /// with a lifetime bound to the map itself.
2274     ///
2275     /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2276     ///
2277     /// [`get_mut`]: Self::get_mut
2278     ///
2279     /// # Examples
2280     ///
2281     /// ```
2282     /// use std::collections::HashMap;
2283     /// use std::collections::hash_map::Entry;
2284     ///
2285     /// let mut map: HashMap<&str, u32> = HashMap::new();
2286     /// map.entry("poneyland").or_insert(12);
2287     ///
2288     /// assert_eq!(map["poneyland"], 12);
2289     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2290     ///     *o.into_mut() += 10;
2291     /// }
2292     ///
2293     /// assert_eq!(map["poneyland"], 22);
2294     /// ```
2295     #[inline]
2296     #[stable(feature = "rust1", since = "1.0.0")]
2297     pub fn into_mut(self) -> &'a mut V {
2298         self.base.into_mut()
2299     }
2300
2301     /// Sets the value of the entry, and returns the entry's old value.
2302     ///
2303     /// # Examples
2304     ///
2305     /// ```
2306     /// use std::collections::HashMap;
2307     /// use std::collections::hash_map::Entry;
2308     ///
2309     /// let mut map: HashMap<&str, u32> = HashMap::new();
2310     /// map.entry("poneyland").or_insert(12);
2311     ///
2312     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2313     ///     assert_eq!(o.insert(15), 12);
2314     /// }
2315     ///
2316     /// assert_eq!(map["poneyland"], 15);
2317     /// ```
2318     #[inline]
2319     #[stable(feature = "rust1", since = "1.0.0")]
2320     pub fn insert(&mut self, value: V) -> V {
2321         self.base.insert(value)
2322     }
2323
2324     /// Takes the value out of the entry, and returns it.
2325     ///
2326     /// # Examples
2327     ///
2328     /// ```
2329     /// use std::collections::HashMap;
2330     /// use std::collections::hash_map::Entry;
2331     ///
2332     /// let mut map: HashMap<&str, u32> = HashMap::new();
2333     /// map.entry("poneyland").or_insert(12);
2334     ///
2335     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2336     ///     assert_eq!(o.remove(), 12);
2337     /// }
2338     ///
2339     /// assert_eq!(map.contains_key("poneyland"), false);
2340     /// ```
2341     #[inline]
2342     #[stable(feature = "rust1", since = "1.0.0")]
2343     pub fn remove(self) -> V {
2344         self.base.remove()
2345     }
2346
2347     /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2348     /// the key used to create this entry.
2349     ///
2350     /// # Examples
2351     ///
2352     /// ```
2353     /// #![feature(map_entry_replace)]
2354     /// use std::collections::hash_map::{Entry, HashMap};
2355     /// use std::rc::Rc;
2356     ///
2357     /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2358     /// map.insert(Rc::new("Stringthing".to_string()), 15);
2359     ///
2360     /// let my_key = Rc::new("Stringthing".to_string());
2361     ///
2362     /// if let Entry::Occupied(entry) = map.entry(my_key) {
2363     ///     // Also replace the key with a handle to our other key.
2364     ///     let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2365     /// }
2366     ///
2367     /// ```
2368     #[inline]
2369     #[unstable(feature = "map_entry_replace", issue = "44286")]
2370     pub fn replace_entry(self, value: V) -> (K, V) {
2371         self.base.replace_entry(value)
2372     }
2373
2374     /// Replaces the key in the hash map with the key used to create this entry.
2375     ///
2376     /// # Examples
2377     ///
2378     /// ```
2379     /// #![feature(map_entry_replace)]
2380     /// use std::collections::hash_map::{Entry, HashMap};
2381     /// use std::rc::Rc;
2382     ///
2383     /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2384     /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2385     ///
2386     /// // Initialise known strings, run program, etc.
2387     ///
2388     /// reclaim_memory(&mut map, &known_strings);
2389     ///
2390     /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2391     ///     for s in known_strings {
2392     ///         if let Entry::Occupied(entry) = map.entry(s.clone()) {
2393     ///             // Replaces the entry's key with our version of it in `known_strings`.
2394     ///             entry.replace_key();
2395     ///         }
2396     ///     }
2397     /// }
2398     /// ```
2399     #[inline]
2400     #[unstable(feature = "map_entry_replace", issue = "44286")]
2401     pub fn replace_key(self) -> K {
2402         self.base.replace_key()
2403     }
2404 }
2405
2406 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2407     /// Gets a reference to the key that would be used when inserting a value
2408     /// through the `VacantEntry`.
2409     ///
2410     /// # Examples
2411     ///
2412     /// ```
2413     /// use std::collections::HashMap;
2414     ///
2415     /// let mut map: HashMap<&str, u32> = HashMap::new();
2416     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2417     /// ```
2418     #[inline]
2419     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2420     pub fn key(&self) -> &K {
2421         self.base.key()
2422     }
2423
2424     /// Take ownership of the key.
2425     ///
2426     /// # Examples
2427     ///
2428     /// ```
2429     /// use std::collections::HashMap;
2430     /// use std::collections::hash_map::Entry;
2431     ///
2432     /// let mut map: HashMap<&str, u32> = HashMap::new();
2433     ///
2434     /// if let Entry::Vacant(v) = map.entry("poneyland") {
2435     ///     v.into_key();
2436     /// }
2437     /// ```
2438     #[inline]
2439     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2440     pub fn into_key(self) -> K {
2441         self.base.into_key()
2442     }
2443
2444     /// Sets the value of the entry with the VacantEntry's key,
2445     /// and returns a mutable reference to it.
2446     ///
2447     /// # Examples
2448     ///
2449     /// ```
2450     /// use std::collections::HashMap;
2451     /// use std::collections::hash_map::Entry;
2452     ///
2453     /// let mut map: HashMap<&str, u32> = HashMap::new();
2454     ///
2455     /// if let Entry::Vacant(o) = map.entry("poneyland") {
2456     ///     o.insert(37);
2457     /// }
2458     /// assert_eq!(map["poneyland"], 37);
2459     /// ```
2460     #[inline]
2461     #[stable(feature = "rust1", since = "1.0.0")]
2462     pub fn insert(self, value: V) -> &'a mut V {
2463         self.base.insert(value)
2464     }
2465
2466     /// Sets the value of the entry with the VacantEntry's key,
2467     /// and returns an OccupiedEntry.
2468     ///
2469     /// # Examples
2470     ///
2471     /// ```
2472     /// use std::collections::HashMap;
2473     /// use std::collections::hash_map::Entry;
2474     ///
2475     /// let mut map: HashMap<&str, u32> = HashMap::new();
2476     ///
2477     /// if let Entry::Vacant(o) = map.entry("poneyland") {
2478     ///     o.insert(37);
2479     /// }
2480     /// assert_eq!(map["poneyland"], 37);
2481     /// ```
2482     #[inline]
2483     fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2484         let base = self.base.insert_entry(value);
2485         OccupiedEntry { base }
2486     }
2487 }
2488
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2491 where
2492     K: Eq + Hash,
2493     S: BuildHasher + Default,
2494 {
2495     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2496         let mut map = HashMap::with_hasher(Default::default());
2497         map.extend(iter);
2498         map
2499     }
2500 }
2501
2502 /// Inserts all new key-values from the iterator and replaces values with existing
2503 /// keys with new values returned from the iterator.
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2506 where
2507     K: Eq + Hash,
2508     S: BuildHasher,
2509 {
2510     #[inline]
2511     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2512         self.base.extend(iter)
2513     }
2514
2515     #[inline]
2516     fn extend_one(&mut self, (k, v): (K, V)) {
2517         self.base.insert(k, v);
2518     }
2519
2520     #[inline]
2521     fn extend_reserve(&mut self, additional: usize) {
2522         // self.base.extend_reserve(additional);
2523         // FIXME: hashbrown should implement this method.
2524         // But until then, use the same reservation logic:
2525
2526         // Reserve the entire hint lower bound if the map is empty.
2527         // Otherwise reserve half the hint (rounded up), so the map
2528         // will only resize twice in the worst case.
2529         let reserve = if self.is_empty() { additional } else { (additional + 1) / 2 };
2530         self.base.reserve(reserve);
2531     }
2532 }
2533
2534 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2535 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2536 where
2537     K: Eq + Hash + Copy,
2538     V: Copy,
2539     S: BuildHasher,
2540 {
2541     #[inline]
2542     fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2543         self.base.extend(iter)
2544     }
2545
2546     #[inline]
2547     fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2548         self.base.insert(k, v);
2549     }
2550
2551     #[inline]
2552     fn extend_reserve(&mut self, additional: usize) {
2553         Extend::<(K, V)>::extend_reserve(self, additional)
2554     }
2555 }
2556
2557 /// `RandomState` is the default state for [`HashMap`] types.
2558 ///
2559 /// A particular instance `RandomState` will create the same instances of
2560 /// [`Hasher`], but the hashers created by two different `RandomState`
2561 /// instances are unlikely to produce the same result for the same values.
2562 ///
2563 /// # Examples
2564 ///
2565 /// ```
2566 /// use std::collections::HashMap;
2567 /// use std::collections::hash_map::RandomState;
2568 ///
2569 /// let s = RandomState::new();
2570 /// let mut map = HashMap::with_hasher(s);
2571 /// map.insert(1, 2);
2572 /// ```
2573 #[derive(Clone)]
2574 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2575 pub struct RandomState {
2576     k0: u64,
2577     k1: u64,
2578 }
2579
2580 impl RandomState {
2581     /// Constructs a new `RandomState` that is initialized with random keys.
2582     ///
2583     /// # Examples
2584     ///
2585     /// ```
2586     /// use std::collections::hash_map::RandomState;
2587     ///
2588     /// let s = RandomState::new();
2589     /// ```
2590     #[inline]
2591     #[allow(deprecated)]
2592     // rand
2593     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2594     pub fn new() -> RandomState {
2595         // Historically this function did not cache keys from the OS and instead
2596         // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2597         // was discovered, however, that because we re-seed the thread-local RNG
2598         // from the OS periodically that this can cause excessive slowdown when
2599         // many hash maps are created on a thread. To solve this performance
2600         // trap we cache the first set of randomly generated keys per-thread.
2601         //
2602         // Later in #36481 it was discovered that exposing a deterministic
2603         // iteration order allows a form of DOS attack. To counter that we
2604         // increment one of the seeds on every RandomState creation, giving
2605         // every corresponding HashMap a different iteration order.
2606         thread_local!(static KEYS: Cell<(u64, u64)> = {
2607             Cell::new(sys::hashmap_random_keys())
2608         });
2609
2610         KEYS.with(|keys| {
2611             let (k0, k1) = keys.get();
2612             keys.set((k0.wrapping_add(1), k1));
2613             RandomState { k0, k1 }
2614         })
2615     }
2616 }
2617
2618 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2619 impl BuildHasher for RandomState {
2620     type Hasher = DefaultHasher;
2621     #[inline]
2622     #[allow(deprecated)]
2623     fn build_hasher(&self) -> DefaultHasher {
2624         DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2625     }
2626 }
2627
2628 /// The default [`Hasher`] used by [`RandomState`].
2629 ///
2630 /// The internal algorithm is not specified, and so it and its hashes should
2631 /// not be relied upon over releases.
2632 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2633 #[allow(deprecated)]
2634 #[derive(Clone, Debug)]
2635 pub struct DefaultHasher(SipHasher13);
2636
2637 impl DefaultHasher {
2638     /// Creates a new `DefaultHasher`.
2639     ///
2640     /// This hasher is not guaranteed to be the same as all other
2641     /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2642     /// instances created through `new` or `default`.
2643     #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2644     #[allow(deprecated)]
2645     pub fn new() -> DefaultHasher {
2646         DefaultHasher(SipHasher13::new_with_keys(0, 0))
2647     }
2648 }
2649
2650 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2651 impl Default for DefaultHasher {
2652     // FIXME: here should link `new` to [DefaultHasher::new], but it occurs intra-doc link
2653     // resolution failure when re-exporting libstd items. When #56922 fixed,
2654     // link `new` to [DefaultHasher::new] again.
2655     /// Creates a new `DefaultHasher` using `new`.
2656     /// See its documentation for more.
2657     fn default() -> DefaultHasher {
2658         DefaultHasher::new()
2659     }
2660 }
2661
2662 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2663 impl Hasher for DefaultHasher {
2664     #[inline]
2665     fn write(&mut self, msg: &[u8]) {
2666         self.0.write(msg)
2667     }
2668
2669     #[inline]
2670     fn finish(&self) -> u64 {
2671         self.0.finish()
2672     }
2673 }
2674
2675 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2676 impl Default for RandomState {
2677     /// Constructs a new `RandomState`.
2678     #[inline]
2679     fn default() -> RandomState {
2680         RandomState::new()
2681     }
2682 }
2683
2684 #[stable(feature = "std_debug", since = "1.16.0")]
2685 impl fmt::Debug for RandomState {
2686     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2687         f.pad("RandomState { .. }")
2688     }
2689 }
2690
2691 #[inline]
2692 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2693     match raw {
2694         base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2695         base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2696     }
2697 }
2698
2699 #[inline]
2700 fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
2701     match err {
2702         hashbrown::TryReserveError::CapacityOverflow => TryReserveError::CapacityOverflow,
2703         hashbrown::TryReserveError::AllocError { layout } => {
2704             TryReserveError::AllocError { layout, non_exhaustive: () }
2705         }
2706     }
2707 }
2708
2709 #[inline]
2710 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
2711     raw: base::RawEntryMut<'a, K, V, S>,
2712 ) -> RawEntryMut<'a, K, V, S> {
2713     match raw {
2714         base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
2715         base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
2716     }
2717 }
2718
2719 #[allow(dead_code)]
2720 fn assert_covariance() {
2721     fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2722         v
2723     }
2724     fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2725         v
2726     }
2727     fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2728         v
2729     }
2730     fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2731         v
2732     }
2733     fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2734         v
2735     }
2736     fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2737         v
2738     }
2739     fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2740         v
2741     }
2742     fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2743         v
2744     }
2745     fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2746         v
2747     }
2748     fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2749         v
2750     }
2751     fn drain<'new>(
2752         d: Drain<'static, &'static str, &'static str>,
2753     ) -> Drain<'new, &'new str, &'new str> {
2754         d
2755     }
2756 }
2757
2758 #[cfg(test)]
2759 mod test_map {
2760     use super::Entry::{Occupied, Vacant};
2761     use super::HashMap;
2762     use super::RandomState;
2763     use crate::cell::RefCell;
2764     use rand::{thread_rng, Rng};
2765     use realstd::collections::TryReserveError::*;
2766
2767     // https://github.com/rust-lang/rust/issues/62301
2768     fn _assert_hashmap_is_unwind_safe() {
2769         fn assert_unwind_safe<T: crate::panic::UnwindSafe>() {}
2770         assert_unwind_safe::<HashMap<(), crate::cell::UnsafeCell<()>>>();
2771     }
2772
2773     #[test]
2774     fn test_zero_capacities() {
2775         type HM = HashMap<i32, i32>;
2776
2777         let m = HM::new();
2778         assert_eq!(m.capacity(), 0);
2779
2780         let m = HM::default();
2781         assert_eq!(m.capacity(), 0);
2782
2783         let m = HM::with_hasher(RandomState::new());
2784         assert_eq!(m.capacity(), 0);
2785
2786         let m = HM::with_capacity(0);
2787         assert_eq!(m.capacity(), 0);
2788
2789         let m = HM::with_capacity_and_hasher(0, RandomState::new());
2790         assert_eq!(m.capacity(), 0);
2791
2792         let mut m = HM::new();
2793         m.insert(1, 1);
2794         m.insert(2, 2);
2795         m.remove(&1);
2796         m.remove(&2);
2797         m.shrink_to_fit();
2798         assert_eq!(m.capacity(), 0);
2799
2800         let mut m = HM::new();
2801         m.reserve(0);
2802         assert_eq!(m.capacity(), 0);
2803     }
2804
2805     #[test]
2806     fn test_create_capacity_zero() {
2807         let mut m = HashMap::with_capacity(0);
2808
2809         assert!(m.insert(1, 1).is_none());
2810
2811         assert!(m.contains_key(&1));
2812         assert!(!m.contains_key(&0));
2813     }
2814
2815     #[test]
2816     fn test_insert() {
2817         let mut m = HashMap::new();
2818         assert_eq!(m.len(), 0);
2819         assert!(m.insert(1, 2).is_none());
2820         assert_eq!(m.len(), 1);
2821         assert!(m.insert(2, 4).is_none());
2822         assert_eq!(m.len(), 2);
2823         assert_eq!(*m.get(&1).unwrap(), 2);
2824         assert_eq!(*m.get(&2).unwrap(), 4);
2825     }
2826
2827     #[test]
2828     fn test_clone() {
2829         let mut m = HashMap::new();
2830         assert_eq!(m.len(), 0);
2831         assert!(m.insert(1, 2).is_none());
2832         assert_eq!(m.len(), 1);
2833         assert!(m.insert(2, 4).is_none());
2834         assert_eq!(m.len(), 2);
2835         let m2 = m.clone();
2836         assert_eq!(*m2.get(&1).unwrap(), 2);
2837         assert_eq!(*m2.get(&2).unwrap(), 4);
2838         assert_eq!(m2.len(), 2);
2839     }
2840
2841     thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
2842
2843     #[derive(Hash, PartialEq, Eq)]
2844     struct Droppable {
2845         k: usize,
2846     }
2847
2848     impl Droppable {
2849         fn new(k: usize) -> Droppable {
2850             DROP_VECTOR.with(|slot| {
2851                 slot.borrow_mut()[k] += 1;
2852             });
2853
2854             Droppable { k }
2855         }
2856     }
2857
2858     impl Drop for Droppable {
2859         fn drop(&mut self) {
2860             DROP_VECTOR.with(|slot| {
2861                 slot.borrow_mut()[self.k] -= 1;
2862             });
2863         }
2864     }
2865
2866     impl Clone for Droppable {
2867         fn clone(&self) -> Droppable {
2868             Droppable::new(self.k)
2869         }
2870     }
2871
2872     #[test]
2873     fn test_drops() {
2874         DROP_VECTOR.with(|slot| {
2875             *slot.borrow_mut() = vec![0; 200];
2876         });
2877
2878         {
2879             let mut m = HashMap::new();
2880
2881             DROP_VECTOR.with(|v| {
2882                 for i in 0..200 {
2883                     assert_eq!(v.borrow()[i], 0);
2884                 }
2885             });
2886
2887             for i in 0..100 {
2888                 let d1 = Droppable::new(i);
2889                 let d2 = Droppable::new(i + 100);
2890                 m.insert(d1, d2);
2891             }
2892
2893             DROP_VECTOR.with(|v| {
2894                 for i in 0..200 {
2895                     assert_eq!(v.borrow()[i], 1);
2896                 }
2897             });
2898
2899             for i in 0..50 {
2900                 let k = Droppable::new(i);
2901                 let v = m.remove(&k);
2902
2903                 assert!(v.is_some());
2904
2905                 DROP_VECTOR.with(|v| {
2906                     assert_eq!(v.borrow()[i], 1);
2907                     assert_eq!(v.borrow()[i + 100], 1);
2908                 });
2909             }
2910
2911             DROP_VECTOR.with(|v| {
2912                 for i in 0..50 {
2913                     assert_eq!(v.borrow()[i], 0);
2914                     assert_eq!(v.borrow()[i + 100], 0);
2915                 }
2916
2917                 for i in 50..100 {
2918                     assert_eq!(v.borrow()[i], 1);
2919                     assert_eq!(v.borrow()[i + 100], 1);
2920                 }
2921             });
2922         }
2923
2924         DROP_VECTOR.with(|v| {
2925             for i in 0..200 {
2926                 assert_eq!(v.borrow()[i], 0);
2927             }
2928         });
2929     }
2930
2931     #[test]
2932     fn test_into_iter_drops() {
2933         DROP_VECTOR.with(|v| {
2934             *v.borrow_mut() = vec![0; 200];
2935         });
2936
2937         let hm = {
2938             let mut hm = HashMap::new();
2939
2940             DROP_VECTOR.with(|v| {
2941                 for i in 0..200 {
2942                     assert_eq!(v.borrow()[i], 0);
2943                 }
2944             });
2945
2946             for i in 0..100 {
2947                 let d1 = Droppable::new(i);
2948                 let d2 = Droppable::new(i + 100);
2949                 hm.insert(d1, d2);
2950             }
2951
2952             DROP_VECTOR.with(|v| {
2953                 for i in 0..200 {
2954                     assert_eq!(v.borrow()[i], 1);
2955                 }
2956             });
2957
2958             hm
2959         };
2960
2961         // By the way, ensure that cloning doesn't screw up the dropping.
2962         drop(hm.clone());
2963
2964         {
2965             let mut half = hm.into_iter().take(50);
2966
2967             DROP_VECTOR.with(|v| {
2968                 for i in 0..200 {
2969                     assert_eq!(v.borrow()[i], 1);
2970                 }
2971             });
2972
2973             for _ in half.by_ref() {}
2974
2975             DROP_VECTOR.with(|v| {
2976                 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
2977
2978                 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
2979
2980                 assert_eq!(nk, 50);
2981                 assert_eq!(nv, 50);
2982             });
2983         };
2984
2985         DROP_VECTOR.with(|v| {
2986             for i in 0..200 {
2987                 assert_eq!(v.borrow()[i], 0);
2988             }
2989         });
2990     }
2991
2992     #[test]
2993     fn test_empty_remove() {
2994         let mut m: HashMap<i32, bool> = HashMap::new();
2995         assert_eq!(m.remove(&0), None);
2996     }
2997
2998     #[test]
2999     fn test_empty_entry() {
3000         let mut m: HashMap<i32, bool> = HashMap::new();
3001         match m.entry(0) {
3002             Occupied(_) => panic!(),
3003             Vacant(_) => {}
3004         }
3005         assert!(*m.entry(0).or_insert(true));
3006         assert_eq!(m.len(), 1);
3007     }
3008
3009     #[test]
3010     fn test_empty_iter() {
3011         let mut m: HashMap<i32, bool> = HashMap::new();
3012         assert_eq!(m.drain().next(), None);
3013         assert_eq!(m.keys().next(), None);
3014         assert_eq!(m.values().next(), None);
3015         assert_eq!(m.values_mut().next(), None);
3016         assert_eq!(m.iter().next(), None);
3017         assert_eq!(m.iter_mut().next(), None);
3018         assert_eq!(m.len(), 0);
3019         assert!(m.is_empty());
3020         assert_eq!(m.into_iter().next(), None);
3021     }
3022
3023     #[test]
3024     fn test_lots_of_insertions() {
3025         let mut m = HashMap::new();
3026
3027         // Try this a few times to make sure we never screw up the hashmap's
3028         // internal state.
3029         for _ in 0..10 {
3030             assert!(m.is_empty());
3031
3032             for i in 1..1001 {
3033                 assert!(m.insert(i, i).is_none());
3034
3035                 for j in 1..=i {
3036                     let r = m.get(&j);
3037                     assert_eq!(r, Some(&j));
3038                 }
3039
3040                 for j in i + 1..1001 {
3041                     let r = m.get(&j);
3042                     assert_eq!(r, None);
3043                 }
3044             }
3045
3046             for i in 1001..2001 {
3047                 assert!(!m.contains_key(&i));
3048             }
3049
3050             // remove forwards
3051             for i in 1..1001 {
3052                 assert!(m.remove(&i).is_some());
3053
3054                 for j in 1..=i {
3055                     assert!(!m.contains_key(&j));
3056                 }
3057
3058                 for j in i + 1..1001 {
3059                     assert!(m.contains_key(&j));
3060                 }
3061             }
3062
3063             for i in 1..1001 {
3064                 assert!(!m.contains_key(&i));
3065             }
3066
3067             for i in 1..1001 {
3068                 assert!(m.insert(i, i).is_none());
3069             }
3070
3071             // remove backwards
3072             for i in (1..1001).rev() {
3073                 assert!(m.remove(&i).is_some());
3074
3075                 for j in i..1001 {
3076                     assert!(!m.contains_key(&j));
3077                 }
3078
3079                 for j in 1..i {
3080                     assert!(m.contains_key(&j));
3081                 }
3082             }
3083         }
3084     }
3085
3086     #[test]
3087     fn test_find_mut() {
3088         let mut m = HashMap::new();
3089         assert!(m.insert(1, 12).is_none());
3090         assert!(m.insert(2, 8).is_none());
3091         assert!(m.insert(5, 14).is_none());
3092         let new = 100;
3093         match m.get_mut(&5) {
3094             None => panic!(),
3095             Some(x) => *x = new,
3096         }
3097         assert_eq!(m.get(&5), Some(&new));
3098     }
3099
3100     #[test]
3101     fn test_insert_overwrite() {
3102         let mut m = HashMap::new();
3103         assert!(m.insert(1, 2).is_none());
3104         assert_eq!(*m.get(&1).unwrap(), 2);
3105         assert!(!m.insert(1, 3).is_none());
3106         assert_eq!(*m.get(&1).unwrap(), 3);
3107     }
3108
3109     #[test]
3110     fn test_insert_conflicts() {
3111         let mut m = HashMap::with_capacity(4);
3112         assert!(m.insert(1, 2).is_none());
3113         assert!(m.insert(5, 3).is_none());
3114         assert!(m.insert(9, 4).is_none());
3115         assert_eq!(*m.get(&9).unwrap(), 4);
3116         assert_eq!(*m.get(&5).unwrap(), 3);
3117         assert_eq!(*m.get(&1).unwrap(), 2);
3118     }
3119
3120     #[test]
3121     fn test_conflict_remove() {
3122         let mut m = HashMap::with_capacity(4);
3123         assert!(m.insert(1, 2).is_none());
3124         assert_eq!(*m.get(&1).unwrap(), 2);
3125         assert!(m.insert(5, 3).is_none());
3126         assert_eq!(*m.get(&1).unwrap(), 2);
3127         assert_eq!(*m.get(&5).unwrap(), 3);
3128         assert!(m.insert(9, 4).is_none());
3129         assert_eq!(*m.get(&1).unwrap(), 2);
3130         assert_eq!(*m.get(&5).unwrap(), 3);
3131         assert_eq!(*m.get(&9).unwrap(), 4);
3132         assert!(m.remove(&1).is_some());
3133         assert_eq!(*m.get(&9).unwrap(), 4);
3134         assert_eq!(*m.get(&5).unwrap(), 3);
3135     }
3136
3137     #[test]
3138     fn test_is_empty() {
3139         let mut m = HashMap::with_capacity(4);
3140         assert!(m.insert(1, 2).is_none());
3141         assert!(!m.is_empty());
3142         assert!(m.remove(&1).is_some());
3143         assert!(m.is_empty());
3144     }
3145
3146     #[test]
3147     fn test_remove() {
3148         let mut m = HashMap::new();
3149         m.insert(1, 2);
3150         assert_eq!(m.remove(&1), Some(2));
3151         assert_eq!(m.remove(&1), None);
3152     }
3153
3154     #[test]
3155     fn test_remove_entry() {
3156         let mut m = HashMap::new();
3157         m.insert(1, 2);
3158         assert_eq!(m.remove_entry(&1), Some((1, 2)));
3159         assert_eq!(m.remove(&1), None);
3160     }
3161
3162     #[test]
3163     fn test_iterate() {
3164         let mut m = HashMap::with_capacity(4);
3165         for i in 0..32 {
3166             assert!(m.insert(i, i * 2).is_none());
3167         }
3168         assert_eq!(m.len(), 32);
3169
3170         let mut observed: u32 = 0;
3171
3172         for (k, v) in &m {
3173             assert_eq!(*v, *k * 2);
3174             observed |= 1 << *k;
3175         }
3176         assert_eq!(observed, 0xFFFF_FFFF);
3177     }
3178
3179     #[test]
3180     fn test_keys() {
3181         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3182         let map: HashMap<_, _> = vec.into_iter().collect();
3183         let keys: Vec<_> = map.keys().cloned().collect();
3184         assert_eq!(keys.len(), 3);
3185         assert!(keys.contains(&1));
3186         assert!(keys.contains(&2));
3187         assert!(keys.contains(&3));
3188     }
3189
3190     #[test]
3191     fn test_values() {
3192         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3193         let map: HashMap<_, _> = vec.into_iter().collect();
3194         let values: Vec<_> = map.values().cloned().collect();
3195         assert_eq!(values.len(), 3);
3196         assert!(values.contains(&'a'));
3197         assert!(values.contains(&'b'));
3198         assert!(values.contains(&'c'));
3199     }
3200
3201     #[test]
3202     fn test_values_mut() {
3203         let vec = vec![(1, 1), (2, 2), (3, 3)];
3204         let mut map: HashMap<_, _> = vec.into_iter().collect();
3205         for value in map.values_mut() {
3206             *value = (*value) * 2
3207         }
3208         let values: Vec<_> = map.values().cloned().collect();
3209         assert_eq!(values.len(), 3);
3210         assert!(values.contains(&2));
3211         assert!(values.contains(&4));
3212         assert!(values.contains(&6));
3213     }
3214
3215     #[test]
3216     fn test_into_keys() {
3217         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3218         let map: HashMap<_, _> = vec.into_iter().collect();
3219         let keys: Vec<_> = map.into_keys().collect();
3220
3221         assert_eq!(keys.len(), 3);
3222         assert!(keys.contains(&1));
3223         assert!(keys.contains(&2));
3224         assert!(keys.contains(&3));
3225     }
3226
3227     #[test]
3228     fn test_into_values() {
3229         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3230         let map: HashMap<_, _> = vec.into_iter().collect();
3231         let values: Vec<_> = map.into_values().collect();
3232
3233         assert_eq!(values.len(), 3);
3234         assert!(values.contains(&'a'));
3235         assert!(values.contains(&'b'));
3236         assert!(values.contains(&'c'));
3237     }
3238
3239     #[test]
3240     fn test_find() {
3241         let mut m = HashMap::new();
3242         assert!(m.get(&1).is_none());
3243         m.insert(1, 2);
3244         match m.get(&1) {
3245             None => panic!(),
3246             Some(v) => assert_eq!(*v, 2),
3247         }
3248     }
3249
3250     #[test]
3251     fn test_eq() {
3252         let mut m1 = HashMap::new();
3253         m1.insert(1, 2);
3254         m1.insert(2, 3);
3255         m1.insert(3, 4);
3256
3257         let mut m2 = HashMap::new();
3258         m2.insert(1, 2);
3259         m2.insert(2, 3);
3260
3261         assert!(m1 != m2);
3262
3263         m2.insert(3, 4);
3264
3265         assert_eq!(m1, m2);
3266     }
3267
3268     #[test]
3269     fn test_show() {
3270         let mut map = HashMap::new();
3271         let empty: HashMap<i32, i32> = HashMap::new();
3272
3273         map.insert(1, 2);
3274         map.insert(3, 4);
3275
3276         let map_str = format!("{:?}", map);
3277
3278         assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
3279         assert_eq!(format!("{:?}", empty), "{}");
3280     }
3281
3282     #[test]
3283     fn test_reserve_shrink_to_fit() {
3284         let mut m = HashMap::new();
3285         m.insert(0, 0);
3286         m.remove(&0);
3287         assert!(m.capacity() >= m.len());
3288         for i in 0..128 {
3289             m.insert(i, i);
3290         }
3291         m.reserve(256);
3292
3293         let usable_cap = m.capacity();
3294         for i in 128..(128 + 256) {
3295             m.insert(i, i);
3296             assert_eq!(m.capacity(), usable_cap);
3297         }
3298
3299         for i in 100..(128 + 256) {
3300             assert_eq!(m.remove(&i), Some(i));
3301         }
3302         m.shrink_to_fit();
3303
3304         assert_eq!(m.len(), 100);
3305         assert!(!m.is_empty());
3306         assert!(m.capacity() >= m.len());
3307
3308         for i in 0..100 {
3309             assert_eq!(m.remove(&i), Some(i));
3310         }
3311         m.shrink_to_fit();
3312         m.insert(0, 0);
3313
3314         assert_eq!(m.len(), 1);
3315         assert!(m.capacity() >= m.len());
3316         assert_eq!(m.remove(&0), Some(0));
3317     }
3318
3319     #[test]
3320     fn test_from_iter() {
3321         let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3322
3323         let map: HashMap<_, _> = xs.iter().cloned().collect();
3324
3325         for &(k, v) in &xs {
3326             assert_eq!(map.get(&k), Some(&v));
3327         }
3328
3329         assert_eq!(map.iter().len(), xs.len() - 1);
3330     }
3331
3332     #[test]
3333     fn test_size_hint() {
3334         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3335
3336         let map: HashMap<_, _> = xs.iter().cloned().collect();
3337
3338         let mut iter = map.iter();
3339
3340         for _ in iter.by_ref().take(3) {}
3341
3342         assert_eq!(iter.size_hint(), (3, Some(3)));
3343     }
3344
3345     #[test]
3346     fn test_iter_len() {
3347         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3348
3349         let map: HashMap<_, _> = xs.iter().cloned().collect();
3350
3351         let mut iter = map.iter();
3352
3353         for _ in iter.by_ref().take(3) {}
3354
3355         assert_eq!(iter.len(), 3);
3356     }
3357
3358     #[test]
3359     fn test_mut_size_hint() {
3360         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3361
3362         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3363
3364         let mut iter = map.iter_mut();
3365
3366         for _ in iter.by_ref().take(3) {}
3367
3368         assert_eq!(iter.size_hint(), (3, Some(3)));
3369     }
3370
3371     #[test]
3372     fn test_iter_mut_len() {
3373         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3374
3375         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3376
3377         let mut iter = map.iter_mut();
3378
3379         for _ in iter.by_ref().take(3) {}
3380
3381         assert_eq!(iter.len(), 3);
3382     }
3383
3384     #[test]
3385     fn test_index() {
3386         let mut map = HashMap::new();
3387
3388         map.insert(1, 2);
3389         map.insert(2, 1);
3390         map.insert(3, 4);
3391
3392         assert_eq!(map[&2], 1);
3393     }
3394
3395     #[test]
3396     #[should_panic]
3397     fn test_index_nonexistent() {
3398         let mut map = HashMap::new();
3399
3400         map.insert(1, 2);
3401         map.insert(2, 1);
3402         map.insert(3, 4);
3403
3404         map[&4];
3405     }
3406
3407     #[test]
3408     fn test_entry() {
3409         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3410
3411         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3412
3413         // Existing key (insert)
3414         match map.entry(1) {
3415             Vacant(_) => unreachable!(),
3416             Occupied(mut view) => {
3417                 assert_eq!(view.get(), &10);
3418                 assert_eq!(view.insert(100), 10);
3419             }
3420         }
3421         assert_eq!(map.get(&1).unwrap(), &100);
3422         assert_eq!(map.len(), 6);
3423
3424         // Existing key (update)
3425         match map.entry(2) {
3426             Vacant(_) => unreachable!(),
3427             Occupied(mut view) => {
3428                 let v = view.get_mut();
3429                 let new_v = (*v) * 10;
3430                 *v = new_v;
3431             }
3432         }
3433         assert_eq!(map.get(&2).unwrap(), &200);
3434         assert_eq!(map.len(), 6);
3435
3436         // Existing key (take)
3437         match map.entry(3) {
3438             Vacant(_) => unreachable!(),
3439             Occupied(view) => {
3440                 assert_eq!(view.remove(), 30);
3441             }
3442         }
3443         assert_eq!(map.get(&3), None);
3444         assert_eq!(map.len(), 5);
3445
3446         // Inexistent key (insert)
3447         match map.entry(10) {
3448             Occupied(_) => unreachable!(),
3449             Vacant(view) => {
3450                 assert_eq!(*view.insert(1000), 1000);
3451             }
3452         }
3453         assert_eq!(map.get(&10).unwrap(), &1000);
3454         assert_eq!(map.len(), 6);
3455     }
3456
3457     #[test]
3458     fn test_entry_take_doesnt_corrupt() {
3459         #![allow(deprecated)] //rand
3460         // Test for #19292
3461         fn check(m: &HashMap<i32, ()>) {
3462             for k in m.keys() {
3463                 assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
3464             }
3465         }
3466
3467         let mut m = HashMap::new();
3468         let mut rng = thread_rng();
3469
3470         // Populate the map with some items.
3471         for _ in 0..50 {
3472             let x = rng.gen_range(-10, 10);
3473             m.insert(x, ());
3474         }
3475
3476         for _ in 0..1000 {
3477             let x = rng.gen_range(-10, 10);
3478             match m.entry(x) {
3479                 Vacant(_) => {}
3480                 Occupied(e) => {
3481                     e.remove();
3482                 }
3483             }
3484
3485             check(&m);
3486         }
3487     }
3488
3489     #[test]
3490     fn test_extend_ref() {
3491         let mut a = HashMap::new();
3492         a.insert(1, "one");
3493         let mut b = HashMap::new();
3494         b.insert(2, "two");
3495         b.insert(3, "three");
3496
3497         a.extend(&b);
3498
3499         assert_eq!(a.len(), 3);
3500         assert_eq!(a[&1], "one");
3501         assert_eq!(a[&2], "two");
3502         assert_eq!(a[&3], "three");
3503     }
3504
3505     #[test]
3506     fn test_capacity_not_less_than_len() {
3507         let mut a = HashMap::new();
3508         let mut item = 0;
3509
3510         for _ in 0..116 {
3511             a.insert(item, 0);
3512             item += 1;
3513         }
3514
3515         assert!(a.capacity() > a.len());
3516
3517         let free = a.capacity() - a.len();
3518         for _ in 0..free {
3519             a.insert(item, 0);
3520             item += 1;
3521         }
3522
3523         assert_eq!(a.len(), a.capacity());
3524
3525         // Insert at capacity should cause allocation.
3526         a.insert(item, 0);
3527         assert!(a.capacity() > a.len());
3528     }
3529
3530     #[test]
3531     fn test_occupied_entry_key() {
3532         let mut a = HashMap::new();
3533         let key = "hello there";
3534         let value = "value goes here";
3535         assert!(a.is_empty());
3536         a.insert(key.clone(), value.clone());
3537         assert_eq!(a.len(), 1);
3538         assert_eq!(a[key], value);
3539
3540         match a.entry(key.clone()) {
3541             Vacant(_) => panic!(),
3542             Occupied(e) => assert_eq!(key, *e.key()),
3543         }
3544         assert_eq!(a.len(), 1);
3545         assert_eq!(a[key], value);
3546     }
3547
3548     #[test]
3549     fn test_vacant_entry_key() {
3550         let mut a = HashMap::new();
3551         let key = "hello there";
3552         let value = "value goes here";
3553
3554         assert!(a.is_empty());
3555         match a.entry(key.clone()) {
3556             Occupied(_) => panic!(),
3557             Vacant(e) => {
3558                 assert_eq!(key, *e.key());
3559                 e.insert(value.clone());
3560             }
3561         }
3562         assert_eq!(a.len(), 1);
3563         assert_eq!(a[key], value);
3564     }
3565
3566     #[test]
3567     fn test_retain() {
3568         let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
3569
3570         map.retain(|&k, _| k % 2 == 0);
3571         assert_eq!(map.len(), 50);
3572         assert_eq!(map[&2], 20);
3573         assert_eq!(map[&4], 40);
3574         assert_eq!(map[&6], 60);
3575     }
3576
3577     #[test]
3578     fn test_try_reserve() {
3579         let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
3580
3581         const MAX_USIZE: usize = usize::MAX;
3582
3583         if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
3584         } else {
3585             panic!("usize::MAX should trigger an overflow!");
3586         }
3587
3588         if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE / 8) {
3589         } else {
3590             panic!("usize::MAX / 8 should trigger an OOM!")
3591         }
3592     }
3593
3594     #[test]
3595     fn test_raw_entry() {
3596         use super::RawEntryMut::{Occupied, Vacant};
3597
3598         let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3599
3600         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3601
3602         let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
3603             use core::hash::{BuildHasher, Hash, Hasher};
3604
3605             let mut hasher = map.hasher().build_hasher();
3606             k.hash(&mut hasher);
3607             hasher.finish()
3608         };
3609
3610         // Existing key (insert)
3611         match map.raw_entry_mut().from_key(&1) {
3612             Vacant(_) => unreachable!(),
3613             Occupied(mut view) => {
3614                 assert_eq!(view.get(), &10);
3615                 assert_eq!(view.insert(100), 10);
3616             }
3617         }
3618         let hash1 = compute_hash(&map, 1);
3619         assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
3620         assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
3621         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
3622         assert_eq!(map.len(), 6);
3623
3624         // Existing key (update)
3625         match map.raw_entry_mut().from_key(&2) {
3626             Vacant(_) => unreachable!(),
3627             Occupied(mut view) => {
3628                 let v = view.get_mut();
3629                 let new_v = (*v) * 10;
3630                 *v = new_v;
3631             }
3632         }
3633         let hash2 = compute_hash(&map, 2);
3634         assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
3635         assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
3636         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
3637         assert_eq!(map.len(), 6);
3638
3639         // Existing key (take)
3640         let hash3 = compute_hash(&map, 3);
3641         match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
3642             Vacant(_) => unreachable!(),
3643             Occupied(view) => {
3644                 assert_eq!(view.remove_entry(), (3, 30));
3645             }
3646         }
3647         assert_eq!(map.raw_entry().from_key(&3), None);
3648         assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
3649         assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
3650         assert_eq!(map.len(), 5);
3651
3652         // Nonexistent key (insert)
3653         match map.raw_entry_mut().from_key(&10) {
3654             Occupied(_) => unreachable!(),
3655             Vacant(view) => {
3656                 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
3657             }
3658         }
3659         assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
3660         assert_eq!(map.len(), 6);
3661
3662         // Ensure all lookup methods produce equivalent results.
3663         for k in 0..12 {
3664             let hash = compute_hash(&map, k);
3665             let v = map.get(&k).cloned();
3666             let kv = v.as_ref().map(|v| (&k, v));
3667
3668             assert_eq!(map.raw_entry().from_key(&k), kv);
3669             assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
3670             assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
3671
3672             match map.raw_entry_mut().from_key(&k) {
3673                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3674                 Vacant(_) => assert_eq!(v, None),
3675             }
3676             match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
3677                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3678                 Vacant(_) => assert_eq!(v, None),
3679             }
3680             match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
3681                 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3682                 Vacant(_) => assert_eq!(v, None),
3683             }
3684         }
3685     }
3686 }