1 // ignore-tidy-filelength
5 use hashbrown::hash_map as base;
7 use crate::borrow::Borrow;
9 use crate::collections::TryReserveError;
10 use crate::fmt::{self, Debug};
12 use crate::hash::{BuildHasher, Hash, Hasher, SipHasher13};
13 use crate::iter::{FromIterator, FusedIterator};
14 use crate::ops::Index;
17 /// A hash map implemented with quadratic probing and SIMD lookup.
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.
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.
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.
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
45 /// k1 == k2 -> hash(k1) == hash(k2)
48 /// In other words, if two keys are equal, their hashes must be equal.
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.
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.
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
66 /// use std::collections::HashMap;
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();
72 /// // Review some books.
73 /// book_reviews.insert(
74 /// "Adventures of Huckleberry Finn".to_string(),
75 /// "My favorite book.".to_string(),
77 /// book_reviews.insert(
78 /// "Grimms' Fairy Tales".to_string(),
79 /// "Masterpiece.".to_string(),
81 /// book_reviews.insert(
82 /// "Pride and Prejudice".to_string(),
83 /// "Very enjoyable.".to_string(),
85 /// book_reviews.insert(
86 /// "The Adventures of Sherlock Holmes".to_string(),
87 /// "Eye lyked it alot.".to_string(),
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());
98 /// // oops, this review has a lot of spelling mistakes, let's delete it.
99 /// book_reviews.remove("The Adventures of Sherlock Holmes");
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)
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"]);
113 /// // Iterate over everything.
114 /// for (book, review) in &book_reviews {
115 /// println!("{}: \"{}\"", book, review);
119 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
120 /// for more complex methods of getting, setting, updating and removing keys and
124 /// use std::collections::HashMap;
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();
130 /// fn random_stat_buff() -> u8 {
131 /// // could actually return some random value here - let's just return
132 /// // some fixed value for now
136 /// // insert a key only if it doesn't already exist
137 /// player_stats.entry("health").or_insert(100);
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);
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();
148 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
149 /// We must also derive [`PartialEq`].
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
159 /// use std::collections::HashMap;
161 /// #[derive(Hash, Eq, PartialEq, Debug)]
168 /// /// Creates a new Viking.
169 /// fn new(name: &str, country: &str) -> Viking {
170 /// Viking { name: name.to_string(), country: country.to_string() }
174 /// // Use a HashMap to store the vikings' health points.
175 /// let mut vikings = HashMap::new();
177 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
178 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
179 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
181 /// // Use derived implementation to print the status of the vikings.
182 /// for (viking, health) in &vikings {
183 /// println!("{:?} has {} hp", viking, health);
187 /// A `HashMap` with fixed list of elements can be initialized from an array:
190 /// use std::collections::HashMap;
192 /// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
193 /// .iter().cloned().collect();
194 /// // use the values stored in map
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>,
204 impl<K, V> HashMap<K, V, RandomState> {
205 /// Creates an empty `HashMap`.
207 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
208 /// is first inserted into.
213 /// use std::collections::HashMap;
214 /// let mut map: HashMap<&str, i32> = HashMap::new();
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn new() -> HashMap<K, V, RandomState> {
222 /// Creates an empty `HashMap` with the specified capacity.
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.
230 /// use std::collections::HashMap;
231 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
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())
240 impl<K, V, S> HashMap<K, V, S> {
241 /// Creates an empty `HashMap` which will use the given hash builder to hash
244 /// The created map has the default initial capacity.
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.
251 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
252 /// the HashMap to be useful, see its documentation for details.
257 /// use std::collections::HashMap;
258 /// use std::collections::hash_map::RandomState;
260 /// let s = RandomState::new();
261 /// let mut map = HashMap::with_hasher(s);
262 /// map.insert(1, 2);
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) }
270 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
271 /// to hash the keys.
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.
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.
281 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
282 /// the HashMap to be useful, see its documentation for details.
287 /// use std::collections::HashMap;
288 /// use std::collections::hash_map::RandomState;
290 /// let s = RandomState::new();
291 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
292 /// map.insert(1, 2);
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) }
300 /// Returns the number of elements the map can hold without reallocating.
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.
308 /// use std::collections::HashMap;
309 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
310 /// assert!(map.capacity() >= 100);
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn capacity(&self) -> usize {
318 /// An iterator visiting all keys in arbitrary order.
319 /// The iterator element type is `&'a K`.
324 /// use std::collections::HashMap;
326 /// let mut map = HashMap::new();
327 /// map.insert("a", 1);
328 /// map.insert("b", 2);
329 /// map.insert("c", 3);
331 /// for key in map.keys() {
332 /// println!("{}", key);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn keys(&self) -> Keys<'_, K, V> {
337 Keys { inner: self.iter() }
340 /// An iterator visiting all values in arbitrary order.
341 /// The iterator element type is `&'a V`.
346 /// use std::collections::HashMap;
348 /// let mut map = HashMap::new();
349 /// map.insert("a", 1);
350 /// map.insert("b", 2);
351 /// map.insert("c", 3);
353 /// for val in map.values() {
354 /// println!("{}", val);
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn values(&self) -> Values<'_, K, V> {
359 Values { inner: self.iter() }
362 /// An iterator visiting all values mutably in arbitrary order.
363 /// The iterator element type is `&'a mut V`.
368 /// use std::collections::HashMap;
370 /// let mut map = HashMap::new();
372 /// map.insert("a", 1);
373 /// map.insert("b", 2);
374 /// map.insert("c", 3);
376 /// for val in map.values_mut() {
377 /// *val = *val + 10;
380 /// for val in map.values() {
381 /// println!("{}", val);
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() }
389 /// An iterator visiting all key-value pairs in arbitrary order.
390 /// The iterator element type is `(&'a K, &'a V)`.
395 /// use std::collections::HashMap;
397 /// let mut map = HashMap::new();
398 /// map.insert("a", 1);
399 /// map.insert("b", 2);
400 /// map.insert("c", 3);
402 /// for (key, val) in map.iter() {
403 /// println!("key: {} val: {}", key, val);
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn iter(&self) -> Iter<'_, K, V> {
408 Iter { base: self.base.iter() }
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)`.
418 /// use std::collections::HashMap;
420 /// let mut map = HashMap::new();
421 /// map.insert("a", 1);
422 /// map.insert("b", 2);
423 /// map.insert("c", 3);
425 /// // Update all values
426 /// for (_, val) in map.iter_mut() {
430 /// for (key, val) in &map {
431 /// println!("key: {} val: {}", key, val);
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() }
439 /// Returns the number of elements in the map.
444 /// use std::collections::HashMap;
446 /// let mut a = HashMap::new();
447 /// assert_eq!(a.len(), 0);
448 /// a.insert(1, "a");
449 /// assert_eq!(a.len(), 1);
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn len(&self) -> usize {
456 /// Returns `true` if the map contains no elements.
461 /// use std::collections::HashMap;
463 /// let mut a = HashMap::new();
464 /// assert!(a.is_empty());
465 /// a.insert(1, "a");
466 /// assert!(!a.is_empty());
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn is_empty(&self) -> bool {
474 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
475 /// allocated memory for reuse.
480 /// use std::collections::HashMap;
482 /// let mut a = HashMap::new();
483 /// a.insert(1, "a");
484 /// a.insert(2, "b");
486 /// for (k, v) in a.drain().take(1) {
487 /// assert!(k == 1 || k == 2);
488 /// assert!(v == "a" || v == "b");
491 /// assert!(a.is_empty());
494 #[stable(feature = "drain", since = "1.6.0")]
495 pub fn drain(&mut self) -> Drain<'_, K, V> {
496 Drain { base: self.base.drain() }
499 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
505 /// use std::collections::HashMap;
507 /// let mut a = HashMap::new();
508 /// a.insert(1, "a");
510 /// assert!(a.is_empty());
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn clear(&mut self) {
518 /// Returns a reference to the map's [`BuildHasher`].
523 /// use std::collections::HashMap;
524 /// use std::collections::hash_map::RandomState;
526 /// let hasher = RandomState::new();
527 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
528 /// let hasher: &RandomState = map.hasher();
531 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
532 pub fn hasher(&self) -> &S {
537 impl<K, V, S> HashMap<K, V, S>
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.
548 /// Panics if the new allocation size overflows [`usize`].
553 /// use std::collections::HashMap;
554 /// let mut map: HashMap<&str, i32> = HashMap::new();
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn reserve(&mut self, additional: usize) {
560 self.base.reserve(additional)
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.
569 /// If the capacity overflows, or the allocator reports a failure, then an error
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?");
581 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
582 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
583 self.base.try_reserve(additional).map_err(map_collection_alloc_err)
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.
593 /// use std::collections::HashMap;
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);
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn shrink_to_fit(&mut self) {
605 self.base.shrink_to_fit();
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.
612 /// Panics if the current capacity is smaller than the supplied
613 /// minimum capacity.
618 /// #![feature(shrink_to)]
619 /// use std::collections::HashMap;
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);
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);
637 /// Gets the given key's corresponding entry in the map for in-place manipulation.
642 /// use std::collections::HashMap;
644 /// let mut letters = HashMap::new();
646 /// for ch in "a short treatise on fungi".chars() {
647 /// let counter = letters.entry(ch).or_insert(0);
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);
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))
662 /// Returns a reference to the value corresponding to the key.
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
671 /// use std::collections::HashMap;
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);
678 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
688 /// Returns the key-value pair corresponding to the supplied key.
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
697 /// use std::collections::HashMap;
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);
704 #[stable(feature = "map_get_key_value", since = "1.40.0")]
706 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
711 self.base.get_key_value(k)
714 /// Returns `true` if the map contains a value for the specified key.
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
723 /// use std::collections::HashMap;
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);
730 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
737 self.base.contains_key(k)
740 /// Returns a mutable reference to the value corresponding to the key.
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
749 /// use std::collections::HashMap;
751 /// let mut map = HashMap::new();
752 /// map.insert(1, "a");
753 /// if let Some(x) = map.get_mut(&1) {
756 /// assert_eq!(map[&1], "b");
758 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
768 /// Inserts a key-value pair into the map.
770 /// If the map did not have this key present, [`None`] is returned.
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.
777 /// [module-level documentation]: crate::collections#insert-and-complex-keys
782 /// use std::collections::HashMap;
784 /// let mut map = HashMap::new();
785 /// assert_eq!(map.insert(37, "a"), None);
786 /// assert_eq!(map.is_empty(), false);
788 /// map.insert(37, "b");
789 /// assert_eq!(map.insert(37, "c"), Some("b"));
790 /// assert_eq!(map[&37], "c");
792 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
795 self.base.insert(k, v)
798 /// Removes a key from the map, returning the value at the key if the key
799 /// was previously in the map.
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
808 /// use std::collections::HashMap;
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);
815 #[stable(feature = "rust1", since = "1.0.0")]
817 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
825 /// Removes a key from the map, returning the stored key and value if the
826 /// key was previously in the map.
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
835 /// use std::collections::HashMap;
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);
844 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
846 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
851 self.base.remove_entry(k)
854 /// Retains only the elements specified by the predicate.
856 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
861 /// use std::collections::HashMap;
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);
867 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
869 pub fn retain<F>(&mut self, f: F)
871 F: FnMut(&K, &mut V) -> bool,
877 impl<K, V, S> HashMap<K, V, S>
881 /// Creates a raw entry builder for the HashMap.
883 /// Raw entries provide the lowest level of control for searching and
884 /// manipulating a map. They must be manually initialized with a hash and
885 /// then manually searched. After this, insertions into a vacant entry
886 /// still require an owned key to be provided.
888 /// Raw entries are useful for such exotic situations as:
890 /// * Hash memoization
891 /// * Deferring the creation of an owned key until it is known to be required
892 /// * Using a search key that doesn't work with the Borrow trait
893 /// * Using custom comparison logic without newtype wrappers
895 /// Because raw entries provide much more low-level control, it's much easier
896 /// to put the HashMap into an inconsistent state which, while memory-safe,
897 /// will cause the map to produce seemingly random results. Higher-level and
898 /// more foolproof APIs like `entry` should be preferred when possible.
900 /// In particular, the hash used to initialized the raw entry must still be
901 /// consistent with the hash of the key that is ultimately stored in the entry.
902 /// This is because implementations of HashMap may need to recompute hashes
903 /// when resizing, at which point only the keys are available.
905 /// Raw entries give mutable access to the keys. This must not be used
906 /// to modify how the key would compare or hash, as the map will not re-evaluate
907 /// where the key should go, meaning the keys may become "lost" if their
908 /// location does not reflect their state. For instance, if you change a key
909 /// so that the map now contains keys which compare equal, search may start
910 /// acting erratically, with two keys randomly masking each other. Implementations
911 /// are free to assume this doesn't happen (within the limits of memory-safety).
913 #[unstable(feature = "hash_raw_entry", issue = "56167")]
914 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
915 RawEntryBuilderMut { map: self }
918 /// Creates a raw immutable entry builder for the HashMap.
920 /// Raw entries provide the lowest level of control for searching and
921 /// manipulating a map. They must be manually initialized with a hash and
922 /// then manually searched.
924 /// This is useful for
925 /// * Hash memoization
926 /// * Using a search key that doesn't work with the Borrow trait
927 /// * Using custom comparison logic without newtype wrappers
929 /// Unless you are in such a situation, higher-level and more foolproof APIs like
930 /// `get` should be preferred.
932 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
934 #[unstable(feature = "hash_raw_entry", issue = "56167")]
935 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
936 RawEntryBuilder { map: self }
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl<K, V, S> PartialEq for HashMap<K, V, S>
947 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
948 if self.len() != other.len() {
952 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<K, V, S> Eq for HashMap<K, V, S>
965 #[stable(feature = "rust1", since = "1.0.0")]
966 impl<K, V, S> Debug for HashMap<K, V, S>
971 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
972 f.debug_map().entries(self.iter()).finish()
976 #[stable(feature = "rust1", since = "1.0.0")]
977 impl<K, V, S> Default for HashMap<K, V, S>
981 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
983 fn default() -> HashMap<K, V, S> {
984 HashMap::with_hasher(Default::default())
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
991 K: Eq + Hash + Borrow<Q>,
997 /// Returns a reference to the value corresponding to the supplied key.
1001 /// Panics if the key is not present in the `HashMap`.
1003 fn index(&self, key: &Q) -> &V {
1004 self.get(key).expect("no entry found for key")
1008 /// An iterator over the entries of a `HashMap`.
1010 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1011 /// documentation for more.
1013 /// [`iter`]: HashMap::iter
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub struct Iter<'a, K: 'a, V: 'a> {
1016 base: base::Iter<'a, K, V>,
1019 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<K, V> Clone for Iter<'_, K, V> {
1023 fn clone(&self) -> Self {
1024 Iter { base: self.base.clone() }
1028 #[stable(feature = "std_debug", since = "1.16.0")]
1029 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 f.debug_list().entries(self.clone()).finish()
1035 /// A mutable iterator over the entries of a `HashMap`.
1037 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1038 /// documentation for more.
1040 /// [`iter_mut`]: HashMap::iter_mut
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 pub struct IterMut<'a, K: 'a, V: 'a> {
1043 base: base::IterMut<'a, K, V>,
1046 impl<'a, K, V> IterMut<'a, K, V> {
1047 /// Returns a iterator of references over the remaining items.
1049 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1050 Iter { base: self.base.rustc_iter() }
1054 /// An owning iterator over the entries of a `HashMap`.
1056 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1057 /// (provided by the `IntoIterator` trait). See its documentation for more.
1059 /// [`into_iter`]: IntoIterator::into_iter
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub struct IntoIter<K, V> {
1062 base: base::IntoIter<K, V>,
1065 impl<K, V> IntoIter<K, V> {
1066 /// Returns a iterator of references over the remaining items.
1068 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1069 Iter { base: self.base.rustc_iter() }
1073 /// An iterator over the keys of a `HashMap`.
1075 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1076 /// documentation for more.
1078 /// [`keys`]: HashMap::keys
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub struct Keys<'a, K: 'a, V: 'a> {
1081 inner: Iter<'a, K, V>,
1084 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<K, V> Clone for Keys<'_, K, V> {
1088 fn clone(&self) -> Self {
1089 Keys { inner: self.inner.clone() }
1093 #[stable(feature = "std_debug", since = "1.16.0")]
1094 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 f.debug_list().entries(self.clone()).finish()
1100 /// An iterator over the values of a `HashMap`.
1102 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1103 /// documentation for more.
1105 /// [`values`]: HashMap::values
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub struct Values<'a, K: 'a, V: 'a> {
1108 inner: Iter<'a, K, V>,
1111 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 impl<K, V> Clone for Values<'_, K, V> {
1115 fn clone(&self) -> Self {
1116 Values { inner: self.inner.clone() }
1120 #[stable(feature = "std_debug", since = "1.16.0")]
1121 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1123 f.debug_list().entries(self.clone()).finish()
1127 /// A draining iterator over the entries of a `HashMap`.
1129 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1130 /// documentation for more.
1132 /// [`drain`]: HashMap::drain
1133 #[stable(feature = "drain", since = "1.6.0")]
1134 pub struct Drain<'a, K: 'a, V: 'a> {
1135 base: base::Drain<'a, K, V>,
1138 impl<'a, K, V> Drain<'a, K, V> {
1139 /// Returns a iterator of references over the remaining items.
1141 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1142 Iter { base: self.base.rustc_iter() }
1146 /// A mutable iterator over the values of a `HashMap`.
1148 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1149 /// documentation for more.
1151 /// [`values_mut`]: HashMap::values_mut
1152 #[stable(feature = "map_values_mut", since = "1.10.0")]
1153 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1154 inner: IterMut<'a, K, V>,
1157 /// A builder for computing where in a HashMap a key-value pair would be stored.
1159 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1161 /// [`HashMap::raw_entry_mut`]: HashMap::raw_entry_mut
1163 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1164 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1165 map: &'a mut HashMap<K, V, S>,
1168 /// A view into a single entry in a map, which may either be vacant or occupied.
1170 /// This is a lower-level version of [`Entry`].
1172 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1173 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1175 /// [`Entry`]: enum.Entry.html
1176 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1177 /// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html
1178 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1179 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1180 /// An occupied entry.
1181 Occupied(RawOccupiedEntryMut<'a, K, V>),
1183 Vacant(RawVacantEntryMut<'a, K, V, S>),
1186 /// A view into an occupied entry in a `HashMap`.
1187 /// It is part of the [`RawEntryMut`] enum.
1188 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1189 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1190 base: base::RawOccupiedEntryMut<'a, K, V>,
1193 /// A view into a vacant entry in a `HashMap`.
1194 /// It is part of the [`RawEntryMut`] enum.
1195 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1196 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1197 base: base::RawVacantEntryMut<'a, K, V, S>,
1200 /// A builder for computing where in a HashMap a key-value pair would be stored.
1202 /// See the [`HashMap::raw_entry`] docs for usage examples.
1204 /// [`HashMap::raw_entry`]: HashMap::raw_entry
1205 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1206 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1207 map: &'a HashMap<K, V, S>,
1210 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1214 /// Creates a `RawEntryMut` from the given key.
1216 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1217 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1222 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1225 /// Creates a `RawEntryMut` from the given key and its hash.
1227 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1228 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1233 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1236 /// Creates a `RawEntryMut` from the given hash.
1238 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1239 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1241 for<'b> F: FnMut(&'b K) -> bool,
1243 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1247 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1251 /// Access an entry by key.
1253 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1254 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1259 self.map.base.raw_entry().from_key(k)
1262 /// Access an entry by a key and its hash.
1264 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1265 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1270 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1273 /// Access an entry by hash.
1275 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1276 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1278 F: FnMut(&K) -> bool,
1280 self.map.base.raw_entry().from_hash(hash, is_match)
1284 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1285 /// Ensures a value is in the entry by inserting the default if empty, and returns
1286 /// mutable references to the key and value in the entry.
1291 /// #![feature(hash_raw_entry)]
1292 /// use std::collections::HashMap;
1294 /// let mut map: HashMap<&str, u32> = HashMap::new();
1296 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1297 /// assert_eq!(map["poneyland"], 3);
1299 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1300 /// assert_eq!(map["poneyland"], 6);
1303 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1304 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1310 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1311 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1315 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1316 /// and returns mutable references to the key and value in the entry.
1321 /// #![feature(hash_raw_entry)]
1322 /// use std::collections::HashMap;
1324 /// let mut map: HashMap<&str, String> = HashMap::new();
1326 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1327 /// ("poneyland", "hoho".to_string())
1330 /// assert_eq!(map["poneyland"], "hoho".to_string());
1333 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1334 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1336 F: FnOnce() -> (K, V),
1341 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1342 RawEntryMut::Vacant(entry) => {
1343 let (k, v) = default();
1349 /// Provides in-place mutable access to an occupied entry before any
1350 /// potential inserts into the map.
1355 /// #![feature(hash_raw_entry)]
1356 /// use std::collections::HashMap;
1358 /// let mut map: HashMap<&str, u32> = HashMap::new();
1360 /// map.raw_entry_mut()
1361 /// .from_key("poneyland")
1362 /// .and_modify(|_k, v| { *v += 1 })
1363 /// .or_insert("poneyland", 42);
1364 /// assert_eq!(map["poneyland"], 42);
1366 /// map.raw_entry_mut()
1367 /// .from_key("poneyland")
1368 /// .and_modify(|_k, v| { *v += 1 })
1369 /// .or_insert("poneyland", 0);
1370 /// assert_eq!(map["poneyland"], 43);
1373 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1374 pub fn and_modify<F>(self, f: F) -> Self
1376 F: FnOnce(&mut K, &mut V),
1379 RawEntryMut::Occupied(mut entry) => {
1381 let (k, v) = entry.get_key_value_mut();
1384 RawEntryMut::Occupied(entry)
1386 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1391 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
1392 /// Gets a reference to the key in the entry.
1394 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1395 pub fn key(&self) -> &K {
1399 /// Gets a mutable reference to the key in the entry.
1401 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1402 pub fn key_mut(&mut self) -> &mut K {
1406 /// Converts the entry into a mutable reference to the key in the entry
1407 /// with a lifetime bound to the map itself.
1409 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1410 pub fn into_key(self) -> &'a mut K {
1411 self.base.into_key()
1414 /// Gets a reference to the value in the entry.
1416 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1417 pub fn get(&self) -> &V {
1421 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1422 /// with a lifetime bound to the map itself.
1424 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1425 pub fn into_mut(self) -> &'a mut V {
1426 self.base.into_mut()
1429 /// Gets a mutable reference to the value in the entry.
1431 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1432 pub fn get_mut(&mut self) -> &mut V {
1436 /// Gets a reference to the key and value in the entry.
1438 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1439 pub fn get_key_value(&mut self) -> (&K, &V) {
1440 self.base.get_key_value()
1443 /// Gets a mutable reference to the key and value in the entry.
1445 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1446 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1447 self.base.get_key_value_mut()
1450 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
1451 /// with a lifetime bound to the map itself.
1453 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1454 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1455 self.base.into_key_value()
1458 /// Sets the value of the entry, and returns the entry's old value.
1460 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1461 pub fn insert(&mut self, value: V) -> V {
1462 self.base.insert(value)
1465 /// Sets the value of the entry, and returns the entry's old value.
1467 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1468 pub fn insert_key(&mut self, key: K) -> K {
1469 self.base.insert_key(key)
1472 /// Takes the value out of the entry, and returns it.
1474 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1475 pub fn remove(self) -> V {
1479 /// Take the ownership of the key and value from the map.
1481 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1482 pub fn remove_entry(self) -> (K, V) {
1483 self.base.remove_entry()
1487 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1488 /// Sets the value of the entry with the VacantEntry's key,
1489 /// and returns a mutable reference to it.
1491 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1492 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1497 self.base.insert(key, value)
1500 /// Sets the value of the entry with the VacantEntry's key,
1501 /// and returns a mutable reference to it.
1503 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1504 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1509 self.base.insert_hashed_nocheck(hash, key, value)
1513 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1514 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1516 f.debug_struct("RawEntryBuilder").finish()
1520 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1521 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1524 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1525 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1530 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1531 impl<K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'_, K, V> {
1532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533 f.debug_struct("RawOccupiedEntryMut")
1534 .field("key", self.key())
1535 .field("value", self.get())
1540 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1541 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1542 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1543 f.debug_struct("RawVacantEntryMut").finish()
1547 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1548 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1550 f.debug_struct("RawEntryBuilder").finish()
1554 /// A view into a single entry in a map, which may either be vacant or occupied.
1556 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1558 /// [`entry`]: HashMap::entry
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 pub enum Entry<'a, K: 'a, V: 'a> {
1561 /// An occupied entry.
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1570 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1571 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1575 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1580 /// A view into an occupied entry in a `HashMap`.
1581 /// It is part of the [`Entry`] enum.
1583 /// [`Entry`]: enum.Entry.html
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1586 base: base::RustcOccupiedEntry<'a, K, V>,
1589 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1590 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
1596 /// A view into a vacant entry in a `HashMap`.
1597 /// It is part of the [`Entry`] enum.
1599 /// [`Entry`]: enum.Entry.html
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1602 base: base::RustcVacantEntry<'a, K, V>,
1605 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1606 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1608 f.debug_tuple("VacantEntry").field(self.key()).finish()
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1614 type Item = (&'a K, &'a V);
1615 type IntoIter = Iter<'a, K, V>;
1618 fn into_iter(self) -> Iter<'a, K, V> {
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1625 type Item = (&'a K, &'a mut V);
1626 type IntoIter = IterMut<'a, K, V>;
1629 fn into_iter(self) -> IterMut<'a, K, V> {
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1637 type IntoIter = IntoIter<K, V>;
1639 /// Creates a consuming iterator, that is, one that moves each key-value
1640 /// pair out of the map in arbitrary order. The map cannot be used after
1646 /// use std::collections::HashMap;
1648 /// let mut map = HashMap::new();
1649 /// map.insert("a", 1);
1650 /// map.insert("b", 2);
1651 /// map.insert("c", 3);
1653 /// // Not possible with .iter()
1654 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1657 fn into_iter(self) -> IntoIter<K, V> {
1658 IntoIter { base: self.base.into_iter() }
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1664 type Item = (&'a K, &'a V);
1667 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1671 fn size_hint(&self) -> (usize, Option<usize>) {
1672 self.base.size_hint()
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1678 fn len(&self) -> usize {
1683 #[stable(feature = "fused", since = "1.26.0")]
1684 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1688 type Item = (&'a K, &'a mut V);
1691 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1695 fn size_hint(&self) -> (usize, Option<usize>) {
1696 self.base.size_hint()
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1702 fn len(&self) -> usize {
1706 #[stable(feature = "fused", since = "1.26.0")]
1707 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1709 #[stable(feature = "std_debug", since = "1.16.0")]
1710 impl<K, V> fmt::Debug for IterMut<'_, K, V>
1715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1716 f.debug_list().entries(self.iter()).finish()
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 impl<K, V> Iterator for IntoIter<K, V> {
1725 fn next(&mut self) -> Option<(K, V)> {
1729 fn size_hint(&self) -> (usize, Option<usize>) {
1730 self.base.size_hint()
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1736 fn len(&self) -> usize {
1740 #[stable(feature = "fused", since = "1.26.0")]
1741 impl<K, V> FusedIterator for IntoIter<K, V> {}
1743 #[stable(feature = "std_debug", since = "1.16.0")]
1744 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746 f.debug_list().entries(self.iter()).finish()
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1755 fn next(&mut self) -> Option<&'a K> {
1756 self.inner.next().map(|(k, _)| k)
1759 fn size_hint(&self) -> (usize, Option<usize>) {
1760 self.inner.size_hint()
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1766 fn len(&self) -> usize {
1770 #[stable(feature = "fused", since = "1.26.0")]
1771 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 impl<'a, K, V> Iterator for Values<'a, K, V> {
1778 fn next(&mut self) -> Option<&'a V> {
1779 self.inner.next().map(|(_, v)| v)
1782 fn size_hint(&self) -> (usize, Option<usize>) {
1783 self.inner.size_hint()
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1789 fn len(&self) -> usize {
1793 #[stable(feature = "fused", since = "1.26.0")]
1794 impl<K, V> FusedIterator for Values<'_, K, V> {}
1796 #[stable(feature = "map_values_mut", since = "1.10.0")]
1797 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1798 type Item = &'a mut V;
1801 fn next(&mut self) -> Option<&'a mut V> {
1802 self.inner.next().map(|(_, v)| v)
1805 fn size_hint(&self) -> (usize, Option<usize>) {
1806 self.inner.size_hint()
1809 #[stable(feature = "map_values_mut", since = "1.10.0")]
1810 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1812 fn len(&self) -> usize {
1816 #[stable(feature = "fused", since = "1.26.0")]
1817 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1819 #[stable(feature = "std_debug", since = "1.16.0")]
1820 impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1826 f.debug_list().entries(self.inner.iter()).finish()
1830 #[stable(feature = "drain", since = "1.6.0")]
1831 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1835 fn next(&mut self) -> Option<(K, V)> {
1839 fn size_hint(&self) -> (usize, Option<usize>) {
1840 self.base.size_hint()
1843 #[stable(feature = "drain", since = "1.6.0")]
1844 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
1846 fn len(&self) -> usize {
1850 #[stable(feature = "fused", since = "1.26.0")]
1851 impl<K, V> FusedIterator for Drain<'_, K, V> {}
1853 #[stable(feature = "std_debug", since = "1.16.0")]
1854 impl<K, V> fmt::Debug for Drain<'_, K, V>
1859 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1860 f.debug_list().entries(self.iter()).finish()
1864 impl<'a, K, V> Entry<'a, K, V> {
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 /// Ensures a value is in the entry by inserting the default if empty, and returns
1867 /// a mutable reference to the value in the entry.
1872 /// use std::collections::HashMap;
1874 /// let mut map: HashMap<&str, u32> = HashMap::new();
1876 /// map.entry("poneyland").or_insert(3);
1877 /// assert_eq!(map["poneyland"], 3);
1879 /// *map.entry("poneyland").or_insert(10) *= 2;
1880 /// assert_eq!(map["poneyland"], 6);
1883 pub fn or_insert(self, default: V) -> &'a mut V {
1885 Occupied(entry) => entry.into_mut(),
1886 Vacant(entry) => entry.insert(default),
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1892 /// and returns a mutable reference to the value in the entry.
1897 /// use std::collections::HashMap;
1899 /// let mut map: HashMap<&str, String> = HashMap::new();
1900 /// let s = "hoho".to_string();
1902 /// map.entry("poneyland").or_insert_with(|| s);
1904 /// assert_eq!(map["poneyland"], "hoho".to_string());
1907 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1909 Occupied(entry) => entry.into_mut(),
1910 Vacant(entry) => entry.insert(default()),
1914 #[unstable(feature = "or_insert_with_key", issue = "71024")]
1915 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
1916 /// which takes the key as its argument, and returns a mutable reference to the value in the
1922 /// #![feature(or_insert_with_key)]
1923 /// use std::collections::HashMap;
1925 /// let mut map: HashMap<&str, usize> = HashMap::new();
1927 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
1929 /// assert_eq!(map["poneyland"], 9);
1932 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
1934 Occupied(entry) => entry.into_mut(),
1936 let value = default(entry.key());
1942 /// Returns a reference to this entry's key.
1947 /// use std::collections::HashMap;
1949 /// let mut map: HashMap<&str, u32> = HashMap::new();
1950 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1953 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1954 pub fn key(&self) -> &K {
1956 Occupied(ref entry) => entry.key(),
1957 Vacant(ref entry) => entry.key(),
1961 /// Provides in-place mutable access to an occupied entry before any
1962 /// potential inserts into the map.
1967 /// use std::collections::HashMap;
1969 /// let mut map: HashMap<&str, u32> = HashMap::new();
1971 /// map.entry("poneyland")
1972 /// .and_modify(|e| { *e += 1 })
1974 /// assert_eq!(map["poneyland"], 42);
1976 /// map.entry("poneyland")
1977 /// .and_modify(|e| { *e += 1 })
1979 /// assert_eq!(map["poneyland"], 43);
1982 #[stable(feature = "entry_and_modify", since = "1.26.0")]
1983 pub fn and_modify<F>(self, f: F) -> Self
1988 Occupied(mut entry) => {
1992 Vacant(entry) => Vacant(entry),
1996 /// Sets the value of the entry, and returns an OccupiedEntry.
2001 /// #![feature(entry_insert)]
2002 /// use std::collections::HashMap;
2004 /// let mut map: HashMap<&str, String> = HashMap::new();
2005 /// let entry = map.entry("poneyland").insert("hoho".to_string());
2007 /// assert_eq!(entry.key(), &"poneyland");
2010 #[unstable(feature = "entry_insert", issue = "65225")]
2011 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
2013 Occupied(mut entry) => {
2014 entry.insert(value);
2017 Vacant(entry) => entry.insert_entry(value),
2022 impl<'a, K, V: Default> Entry<'a, K, V> {
2023 #[stable(feature = "entry_or_default", since = "1.28.0")]
2024 /// Ensures a value is in the entry by inserting the default value if empty,
2025 /// and returns a mutable reference to the value in the entry.
2031 /// use std::collections::HashMap;
2033 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2034 /// map.entry("poneyland").or_default();
2036 /// assert_eq!(map["poneyland"], None);
2040 pub fn or_default(self) -> &'a mut V {
2042 Occupied(entry) => entry.into_mut(),
2043 Vacant(entry) => entry.insert(Default::default()),
2048 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2049 /// Gets a reference to the key in the entry.
2054 /// use std::collections::HashMap;
2056 /// let mut map: HashMap<&str, u32> = HashMap::new();
2057 /// map.entry("poneyland").or_insert(12);
2058 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2061 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2062 pub fn key(&self) -> &K {
2066 /// Take the ownership of the key and value from the map.
2071 /// use std::collections::HashMap;
2072 /// use std::collections::hash_map::Entry;
2074 /// let mut map: HashMap<&str, u32> = HashMap::new();
2075 /// map.entry("poneyland").or_insert(12);
2077 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2078 /// // We delete the entry from the map.
2079 /// o.remove_entry();
2082 /// assert_eq!(map.contains_key("poneyland"), false);
2085 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2086 pub fn remove_entry(self) -> (K, V) {
2087 self.base.remove_entry()
2090 /// Gets a reference to the value in the entry.
2095 /// use std::collections::HashMap;
2096 /// use std::collections::hash_map::Entry;
2098 /// let mut map: HashMap<&str, u32> = HashMap::new();
2099 /// map.entry("poneyland").or_insert(12);
2101 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2102 /// assert_eq!(o.get(), &12);
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 pub fn get(&self) -> &V {
2111 /// Gets a mutable reference to the value in the entry.
2113 /// If you need a reference to the `OccupiedEntry` which may outlive the
2114 /// destruction of the `Entry` value, see [`into_mut`].
2116 /// [`into_mut`]: Self::into_mut
2121 /// use std::collections::HashMap;
2122 /// use std::collections::hash_map::Entry;
2124 /// let mut map: HashMap<&str, u32> = HashMap::new();
2125 /// map.entry("poneyland").or_insert(12);
2127 /// assert_eq!(map["poneyland"], 12);
2128 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2129 /// *o.get_mut() += 10;
2130 /// assert_eq!(*o.get(), 22);
2132 /// // We can use the same Entry multiple times.
2133 /// *o.get_mut() += 2;
2136 /// assert_eq!(map["poneyland"], 24);
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 pub fn get_mut(&mut self) -> &mut V {
2144 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2145 /// with a lifetime bound to the map itself.
2147 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2149 /// [`get_mut`]: Self::get_mut
2154 /// use std::collections::HashMap;
2155 /// use std::collections::hash_map::Entry;
2157 /// let mut map: HashMap<&str, u32> = HashMap::new();
2158 /// map.entry("poneyland").or_insert(12);
2160 /// assert_eq!(map["poneyland"], 12);
2161 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2162 /// *o.into_mut() += 10;
2165 /// assert_eq!(map["poneyland"], 22);
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 pub fn into_mut(self) -> &'a mut V {
2170 self.base.into_mut()
2173 /// Sets the value of the entry, and returns the entry's old value.
2178 /// use std::collections::HashMap;
2179 /// use std::collections::hash_map::Entry;
2181 /// let mut map: HashMap<&str, u32> = HashMap::new();
2182 /// map.entry("poneyland").or_insert(12);
2184 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2185 /// assert_eq!(o.insert(15), 12);
2188 /// assert_eq!(map["poneyland"], 15);
2191 #[stable(feature = "rust1", since = "1.0.0")]
2192 pub fn insert(&mut self, value: V) -> V {
2193 self.base.insert(value)
2196 /// Takes the value out of the entry, and returns it.
2201 /// use std::collections::HashMap;
2202 /// use std::collections::hash_map::Entry;
2204 /// let mut map: HashMap<&str, u32> = HashMap::new();
2205 /// map.entry("poneyland").or_insert(12);
2207 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2208 /// assert_eq!(o.remove(), 12);
2211 /// assert_eq!(map.contains_key("poneyland"), false);
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 pub fn remove(self) -> V {
2219 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2220 /// the key used to create this entry.
2225 /// #![feature(map_entry_replace)]
2226 /// use std::collections::hash_map::{Entry, HashMap};
2227 /// use std::rc::Rc;
2229 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2230 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2232 /// let my_key = Rc::new("Stringthing".to_string());
2234 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2235 /// // Also replace the key with a handle to our other key.
2236 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2241 #[unstable(feature = "map_entry_replace", issue = "44286")]
2242 pub fn replace_entry(self, value: V) -> (K, V) {
2243 self.base.replace_entry(value)
2246 /// Replaces the key in the hash map with the key used to create this entry.
2251 /// #![feature(map_entry_replace)]
2252 /// use std::collections::hash_map::{Entry, HashMap};
2253 /// use std::rc::Rc;
2255 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2256 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2258 /// // Initialise known strings, run program, etc.
2260 /// reclaim_memory(&mut map, &known_strings);
2262 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2263 /// for s in known_strings {
2264 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2265 /// // Replaces the entry's key with our version of it in `known_strings`.
2266 /// entry.replace_key();
2272 #[unstable(feature = "map_entry_replace", issue = "44286")]
2273 pub fn replace_key(self) -> K {
2274 self.base.replace_key()
2278 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2279 /// Gets a reference to the key that would be used when inserting a value
2280 /// through the `VacantEntry`.
2285 /// use std::collections::HashMap;
2287 /// let mut map: HashMap<&str, u32> = HashMap::new();
2288 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2291 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2292 pub fn key(&self) -> &K {
2296 /// Take ownership of the key.
2301 /// use std::collections::HashMap;
2302 /// use std::collections::hash_map::Entry;
2304 /// let mut map: HashMap<&str, u32> = HashMap::new();
2306 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2311 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2312 pub fn into_key(self) -> K {
2313 self.base.into_key()
2316 /// Sets the value of the entry with the VacantEntry's key,
2317 /// and returns a mutable reference to it.
2322 /// use std::collections::HashMap;
2323 /// use std::collections::hash_map::Entry;
2325 /// let mut map: HashMap<&str, u32> = HashMap::new();
2327 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2330 /// assert_eq!(map["poneyland"], 37);
2333 #[stable(feature = "rust1", since = "1.0.0")]
2334 pub fn insert(self, value: V) -> &'a mut V {
2335 self.base.insert(value)
2338 /// Sets the value of the entry with the VacantEntry's key,
2339 /// and returns an OccupiedEntry.
2344 /// use std::collections::HashMap;
2345 /// use std::collections::hash_map::Entry;
2347 /// let mut map: HashMap<&str, u32> = HashMap::new();
2349 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2352 /// assert_eq!(map["poneyland"], 37);
2355 fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2356 let base = self.base.insert_entry(value);
2357 OccupiedEntry { base }
2361 #[stable(feature = "rust1", since = "1.0.0")]
2362 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2365 S: BuildHasher + Default,
2367 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2368 let mut map = HashMap::with_hasher(Default::default());
2374 /// Inserts all new key-values from the iterator and replaces values with existing
2375 /// keys with new values returned from the iterator.
2376 #[stable(feature = "rust1", since = "1.0.0")]
2377 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2383 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2384 self.base.extend(iter)
2388 fn extend_one(&mut self, (k, v): (K, V)) {
2389 self.base.insert(k, v);
2393 fn extend_reserve(&mut self, additional: usize) {
2394 // self.base.extend_reserve(additional);
2395 // FIXME: hashbrown should implement this method.
2396 // But until then, use the same reservation logic:
2398 // Reserve the entire hint lower bound if the map is empty.
2399 // Otherwise reserve half the hint (rounded up), so the map
2400 // will only resize twice in the worst case.
2401 let reserve = if self.is_empty() { additional } else { (additional + 1) / 2 };
2402 self.base.reserve(reserve);
2406 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2407 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2409 K: Eq + Hash + Copy,
2414 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2415 self.base.extend(iter)
2419 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2420 self.base.insert(k, v);
2424 fn extend_reserve(&mut self, additional: usize) {
2425 Extend::<(K, V)>::extend_reserve(self, additional)
2429 /// `RandomState` is the default state for [`HashMap`] types.
2431 /// A particular instance `RandomState` will create the same instances of
2432 /// [`Hasher`], but the hashers created by two different `RandomState`
2433 /// instances are unlikely to produce the same result for the same values.
2438 /// use std::collections::HashMap;
2439 /// use std::collections::hash_map::RandomState;
2441 /// let s = RandomState::new();
2442 /// let mut map = HashMap::with_hasher(s);
2443 /// map.insert(1, 2);
2446 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2447 pub struct RandomState {
2453 /// Constructs a new `RandomState` that is initialized with random keys.
2458 /// use std::collections::hash_map::RandomState;
2460 /// let s = RandomState::new();
2463 #[allow(deprecated)]
2465 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2466 pub fn new() -> RandomState {
2467 // Historically this function did not cache keys from the OS and instead
2468 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2469 // was discovered, however, that because we re-seed the thread-local RNG
2470 // from the OS periodically that this can cause excessive slowdown when
2471 // many hash maps are created on a thread. To solve this performance
2472 // trap we cache the first set of randomly generated keys per-thread.
2474 // Later in #36481 it was discovered that exposing a deterministic
2475 // iteration order allows a form of DOS attack. To counter that we
2476 // increment one of the seeds on every RandomState creation, giving
2477 // every corresponding HashMap a different iteration order.
2478 thread_local!(static KEYS: Cell<(u64, u64)> = {
2479 Cell::new(sys::hashmap_random_keys())
2483 let (k0, k1) = keys.get();
2484 keys.set((k0.wrapping_add(1), k1));
2485 RandomState { k0, k1 }
2490 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2491 impl BuildHasher for RandomState {
2492 type Hasher = DefaultHasher;
2494 #[allow(deprecated)]
2495 fn build_hasher(&self) -> DefaultHasher {
2496 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2500 /// The default [`Hasher`] used by [`RandomState`].
2502 /// The internal algorithm is not specified, and so it and its hashes should
2503 /// not be relied upon over releases.
2504 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2505 #[allow(deprecated)]
2506 #[derive(Clone, Debug)]
2507 pub struct DefaultHasher(SipHasher13);
2509 impl DefaultHasher {
2510 /// Creates a new `DefaultHasher`.
2512 /// This hasher is not guaranteed to be the same as all other
2513 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2514 /// instances created through `new` or `default`.
2515 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2516 #[allow(deprecated)]
2517 pub fn new() -> DefaultHasher {
2518 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2522 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2523 impl Default for DefaultHasher {
2524 // FIXME: here should link `new` to [DefaultHasher::new], but it occurs intra-doc link
2525 // resolution failure when re-exporting libstd items. When #56922 fixed,
2526 // link `new` to [DefaultHasher::new] again.
2527 /// Creates a new `DefaultHasher` using `new`.
2528 /// See its documentation for more.
2529 fn default() -> DefaultHasher {
2530 DefaultHasher::new()
2534 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2535 impl Hasher for DefaultHasher {
2537 fn write(&mut self, msg: &[u8]) {
2542 fn finish(&self) -> u64 {
2547 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2548 impl Default for RandomState {
2549 /// Constructs a new `RandomState`.
2551 fn default() -> RandomState {
2556 #[stable(feature = "std_debug", since = "1.16.0")]
2557 impl fmt::Debug for RandomState {
2558 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2559 f.pad("RandomState { .. }")
2564 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2566 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2567 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2572 fn map_collection_alloc_err(err: hashbrown::CollectionAllocErr) -> TryReserveError {
2574 hashbrown::CollectionAllocErr::CapacityOverflow => TryReserveError::CapacityOverflow,
2575 hashbrown::CollectionAllocErr::AllocErr { layout } => {
2576 TryReserveError::AllocError { layout, non_exhaustive: () }
2582 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
2583 raw: base::RawEntryMut<'a, K, V, S>,
2584 ) -> RawEntryMut<'a, K, V, S> {
2586 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
2587 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
2592 fn assert_covariance() {
2593 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2596 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2599 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2602 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2605 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2608 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2611 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2614 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2617 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2620 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2624 d: Drain<'static, &'static str, &'static str>,
2625 ) -> Drain<'new, &'new str, &'new str> {
2632 use super::Entry::{Occupied, Vacant};
2634 use super::RandomState;
2635 use crate::cell::RefCell;
2636 use rand::{thread_rng, Rng};
2637 use realstd::collections::TryReserveError::*;
2639 // https://github.com/rust-lang/rust/issues/62301
2640 fn _assert_hashmap_is_unwind_safe() {
2641 fn assert_unwind_safe<T: crate::panic::UnwindSafe>() {}
2642 assert_unwind_safe::<HashMap<(), crate::cell::UnsafeCell<()>>>();
2646 fn test_zero_capacities() {
2647 type HM = HashMap<i32, i32>;
2650 assert_eq!(m.capacity(), 0);
2652 let m = HM::default();
2653 assert_eq!(m.capacity(), 0);
2655 let m = HM::with_hasher(RandomState::new());
2656 assert_eq!(m.capacity(), 0);
2658 let m = HM::with_capacity(0);
2659 assert_eq!(m.capacity(), 0);
2661 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2662 assert_eq!(m.capacity(), 0);
2664 let mut m = HM::new();
2670 assert_eq!(m.capacity(), 0);
2672 let mut m = HM::new();
2674 assert_eq!(m.capacity(), 0);
2678 fn test_create_capacity_zero() {
2679 let mut m = HashMap::with_capacity(0);
2681 assert!(m.insert(1, 1).is_none());
2683 assert!(m.contains_key(&1));
2684 assert!(!m.contains_key(&0));
2689 let mut m = HashMap::new();
2690 assert_eq!(m.len(), 0);
2691 assert!(m.insert(1, 2).is_none());
2692 assert_eq!(m.len(), 1);
2693 assert!(m.insert(2, 4).is_none());
2694 assert_eq!(m.len(), 2);
2695 assert_eq!(*m.get(&1).unwrap(), 2);
2696 assert_eq!(*m.get(&2).unwrap(), 4);
2701 let mut m = HashMap::new();
2702 assert_eq!(m.len(), 0);
2703 assert!(m.insert(1, 2).is_none());
2704 assert_eq!(m.len(), 1);
2705 assert!(m.insert(2, 4).is_none());
2706 assert_eq!(m.len(), 2);
2708 assert_eq!(*m2.get(&1).unwrap(), 2);
2709 assert_eq!(*m2.get(&2).unwrap(), 4);
2710 assert_eq!(m2.len(), 2);
2713 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
2715 #[derive(Hash, PartialEq, Eq)]
2721 fn new(k: usize) -> Droppable {
2722 DROP_VECTOR.with(|slot| {
2723 slot.borrow_mut()[k] += 1;
2730 impl Drop for Droppable {
2731 fn drop(&mut self) {
2732 DROP_VECTOR.with(|slot| {
2733 slot.borrow_mut()[self.k] -= 1;
2738 impl Clone for Droppable {
2739 fn clone(&self) -> Droppable {
2740 Droppable::new(self.k)
2746 DROP_VECTOR.with(|slot| {
2747 *slot.borrow_mut() = vec![0; 200];
2751 let mut m = HashMap::new();
2753 DROP_VECTOR.with(|v| {
2755 assert_eq!(v.borrow()[i], 0);
2760 let d1 = Droppable::new(i);
2761 let d2 = Droppable::new(i + 100);
2765 DROP_VECTOR.with(|v| {
2767 assert_eq!(v.borrow()[i], 1);
2772 let k = Droppable::new(i);
2773 let v = m.remove(&k);
2775 assert!(v.is_some());
2777 DROP_VECTOR.with(|v| {
2778 assert_eq!(v.borrow()[i], 1);
2779 assert_eq!(v.borrow()[i + 100], 1);
2783 DROP_VECTOR.with(|v| {
2785 assert_eq!(v.borrow()[i], 0);
2786 assert_eq!(v.borrow()[i + 100], 0);
2790 assert_eq!(v.borrow()[i], 1);
2791 assert_eq!(v.borrow()[i + 100], 1);
2796 DROP_VECTOR.with(|v| {
2798 assert_eq!(v.borrow()[i], 0);
2804 fn test_into_iter_drops() {
2805 DROP_VECTOR.with(|v| {
2806 *v.borrow_mut() = vec![0; 200];
2810 let mut hm = HashMap::new();
2812 DROP_VECTOR.with(|v| {
2814 assert_eq!(v.borrow()[i], 0);
2819 let d1 = Droppable::new(i);
2820 let d2 = Droppable::new(i + 100);
2824 DROP_VECTOR.with(|v| {
2826 assert_eq!(v.borrow()[i], 1);
2833 // By the way, ensure that cloning doesn't screw up the dropping.
2837 let mut half = hm.into_iter().take(50);
2839 DROP_VECTOR.with(|v| {
2841 assert_eq!(v.borrow()[i], 1);
2845 for _ in half.by_ref() {}
2847 DROP_VECTOR.with(|v| {
2848 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
2850 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
2857 DROP_VECTOR.with(|v| {
2859 assert_eq!(v.borrow()[i], 0);
2865 fn test_empty_remove() {
2866 let mut m: HashMap<i32, bool> = HashMap::new();
2867 assert_eq!(m.remove(&0), None);
2871 fn test_empty_entry() {
2872 let mut m: HashMap<i32, bool> = HashMap::new();
2874 Occupied(_) => panic!(),
2877 assert!(*m.entry(0).or_insert(true));
2878 assert_eq!(m.len(), 1);
2882 fn test_empty_iter() {
2883 let mut m: HashMap<i32, bool> = HashMap::new();
2884 assert_eq!(m.drain().next(), None);
2885 assert_eq!(m.keys().next(), None);
2886 assert_eq!(m.values().next(), None);
2887 assert_eq!(m.values_mut().next(), None);
2888 assert_eq!(m.iter().next(), None);
2889 assert_eq!(m.iter_mut().next(), None);
2890 assert_eq!(m.len(), 0);
2891 assert!(m.is_empty());
2892 assert_eq!(m.into_iter().next(), None);
2896 fn test_lots_of_insertions() {
2897 let mut m = HashMap::new();
2899 // Try this a few times to make sure we never screw up the hashmap's
2902 assert!(m.is_empty());
2905 assert!(m.insert(i, i).is_none());
2909 assert_eq!(r, Some(&j));
2912 for j in i + 1..1001 {
2914 assert_eq!(r, None);
2918 for i in 1001..2001 {
2919 assert!(!m.contains_key(&i));
2924 assert!(m.remove(&i).is_some());
2927 assert!(!m.contains_key(&j));
2930 for j in i + 1..1001 {
2931 assert!(m.contains_key(&j));
2936 assert!(!m.contains_key(&i));
2940 assert!(m.insert(i, i).is_none());
2944 for i in (1..1001).rev() {
2945 assert!(m.remove(&i).is_some());
2948 assert!(!m.contains_key(&j));
2952 assert!(m.contains_key(&j));
2959 fn test_find_mut() {
2960 let mut m = HashMap::new();
2961 assert!(m.insert(1, 12).is_none());
2962 assert!(m.insert(2, 8).is_none());
2963 assert!(m.insert(5, 14).is_none());
2965 match m.get_mut(&5) {
2967 Some(x) => *x = new,
2969 assert_eq!(m.get(&5), Some(&new));
2973 fn test_insert_overwrite() {
2974 let mut m = HashMap::new();
2975 assert!(m.insert(1, 2).is_none());
2976 assert_eq!(*m.get(&1).unwrap(), 2);
2977 assert!(!m.insert(1, 3).is_none());
2978 assert_eq!(*m.get(&1).unwrap(), 3);
2982 fn test_insert_conflicts() {
2983 let mut m = HashMap::with_capacity(4);
2984 assert!(m.insert(1, 2).is_none());
2985 assert!(m.insert(5, 3).is_none());
2986 assert!(m.insert(9, 4).is_none());
2987 assert_eq!(*m.get(&9).unwrap(), 4);
2988 assert_eq!(*m.get(&5).unwrap(), 3);
2989 assert_eq!(*m.get(&1).unwrap(), 2);
2993 fn test_conflict_remove() {
2994 let mut m = HashMap::with_capacity(4);
2995 assert!(m.insert(1, 2).is_none());
2996 assert_eq!(*m.get(&1).unwrap(), 2);
2997 assert!(m.insert(5, 3).is_none());
2998 assert_eq!(*m.get(&1).unwrap(), 2);
2999 assert_eq!(*m.get(&5).unwrap(), 3);
3000 assert!(m.insert(9, 4).is_none());
3001 assert_eq!(*m.get(&1).unwrap(), 2);
3002 assert_eq!(*m.get(&5).unwrap(), 3);
3003 assert_eq!(*m.get(&9).unwrap(), 4);
3004 assert!(m.remove(&1).is_some());
3005 assert_eq!(*m.get(&9).unwrap(), 4);
3006 assert_eq!(*m.get(&5).unwrap(), 3);
3010 fn test_is_empty() {
3011 let mut m = HashMap::with_capacity(4);
3012 assert!(m.insert(1, 2).is_none());
3013 assert!(!m.is_empty());
3014 assert!(m.remove(&1).is_some());
3015 assert!(m.is_empty());
3020 let mut m = HashMap::new();
3022 assert_eq!(m.remove(&1), Some(2));
3023 assert_eq!(m.remove(&1), None);
3027 fn test_remove_entry() {
3028 let mut m = HashMap::new();
3030 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3031 assert_eq!(m.remove(&1), None);
3036 let mut m = HashMap::with_capacity(4);
3038 assert!(m.insert(i, i * 2).is_none());
3040 assert_eq!(m.len(), 32);
3042 let mut observed: u32 = 0;
3045 assert_eq!(*v, *k * 2);
3046 observed |= 1 << *k;
3048 assert_eq!(observed, 0xFFFF_FFFF);
3053 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3054 let map: HashMap<_, _> = vec.into_iter().collect();
3055 let keys: Vec<_> = map.keys().cloned().collect();
3056 assert_eq!(keys.len(), 3);
3057 assert!(keys.contains(&1));
3058 assert!(keys.contains(&2));
3059 assert!(keys.contains(&3));
3064 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3065 let map: HashMap<_, _> = vec.into_iter().collect();
3066 let values: Vec<_> = map.values().cloned().collect();
3067 assert_eq!(values.len(), 3);
3068 assert!(values.contains(&'a'));
3069 assert!(values.contains(&'b'));
3070 assert!(values.contains(&'c'));
3074 fn test_values_mut() {
3075 let vec = vec![(1, 1), (2, 2), (3, 3)];
3076 let mut map: HashMap<_, _> = vec.into_iter().collect();
3077 for value in map.values_mut() {
3078 *value = (*value) * 2
3080 let values: Vec<_> = map.values().cloned().collect();
3081 assert_eq!(values.len(), 3);
3082 assert!(values.contains(&2));
3083 assert!(values.contains(&4));
3084 assert!(values.contains(&6));
3089 let mut m = HashMap::new();
3090 assert!(m.get(&1).is_none());
3094 Some(v) => assert_eq!(*v, 2),
3100 let mut m1 = HashMap::new();
3105 let mut m2 = HashMap::new();
3118 let mut map = HashMap::new();
3119 let empty: HashMap<i32, i32> = HashMap::new();
3124 let map_str = format!("{:?}", map);
3126 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
3127 assert_eq!(format!("{:?}", empty), "{}");
3131 fn test_reserve_shrink_to_fit() {
3132 let mut m = HashMap::new();
3135 assert!(m.capacity() >= m.len());
3141 let usable_cap = m.capacity();
3142 for i in 128..(128 + 256) {
3144 assert_eq!(m.capacity(), usable_cap);
3147 for i in 100..(128 + 256) {
3148 assert_eq!(m.remove(&i), Some(i));
3152 assert_eq!(m.len(), 100);
3153 assert!(!m.is_empty());
3154 assert!(m.capacity() >= m.len());
3157 assert_eq!(m.remove(&i), Some(i));
3162 assert_eq!(m.len(), 1);
3163 assert!(m.capacity() >= m.len());
3164 assert_eq!(m.remove(&0), Some(0));
3168 fn test_from_iter() {
3169 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3171 let map: HashMap<_, _> = xs.iter().cloned().collect();
3173 for &(k, v) in &xs {
3174 assert_eq!(map.get(&k), Some(&v));
3177 assert_eq!(map.iter().len(), xs.len() - 1);
3181 fn test_size_hint() {
3182 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3184 let map: HashMap<_, _> = xs.iter().cloned().collect();
3186 let mut iter = map.iter();
3188 for _ in iter.by_ref().take(3) {}
3190 assert_eq!(iter.size_hint(), (3, Some(3)));
3194 fn test_iter_len() {
3195 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3197 let map: HashMap<_, _> = xs.iter().cloned().collect();
3199 let mut iter = map.iter();
3201 for _ in iter.by_ref().take(3) {}
3203 assert_eq!(iter.len(), 3);
3207 fn test_mut_size_hint() {
3208 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3210 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3212 let mut iter = map.iter_mut();
3214 for _ in iter.by_ref().take(3) {}
3216 assert_eq!(iter.size_hint(), (3, Some(3)));
3220 fn test_iter_mut_len() {
3221 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3223 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3225 let mut iter = map.iter_mut();
3227 for _ in iter.by_ref().take(3) {}
3229 assert_eq!(iter.len(), 3);
3234 let mut map = HashMap::new();
3240 assert_eq!(map[&2], 1);
3245 fn test_index_nonexistent() {
3246 let mut map = HashMap::new();
3257 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3259 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3261 // Existing key (insert)
3262 match map.entry(1) {
3263 Vacant(_) => unreachable!(),
3264 Occupied(mut view) => {
3265 assert_eq!(view.get(), &10);
3266 assert_eq!(view.insert(100), 10);
3269 assert_eq!(map.get(&1).unwrap(), &100);
3270 assert_eq!(map.len(), 6);
3272 // Existing key (update)
3273 match map.entry(2) {
3274 Vacant(_) => unreachable!(),
3275 Occupied(mut view) => {
3276 let v = view.get_mut();
3277 let new_v = (*v) * 10;
3281 assert_eq!(map.get(&2).unwrap(), &200);
3282 assert_eq!(map.len(), 6);
3284 // Existing key (take)
3285 match map.entry(3) {
3286 Vacant(_) => unreachable!(),
3288 assert_eq!(view.remove(), 30);
3291 assert_eq!(map.get(&3), None);
3292 assert_eq!(map.len(), 5);
3294 // Inexistent key (insert)
3295 match map.entry(10) {
3296 Occupied(_) => unreachable!(),
3298 assert_eq!(*view.insert(1000), 1000);
3301 assert_eq!(map.get(&10).unwrap(), &1000);
3302 assert_eq!(map.len(), 6);
3306 fn test_entry_take_doesnt_corrupt() {
3307 #![allow(deprecated)] //rand
3309 fn check(m: &HashMap<i32, ()>) {
3311 assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
3315 let mut m = HashMap::new();
3316 let mut rng = thread_rng();
3318 // Populate the map with some items.
3320 let x = rng.gen_range(-10, 10);
3325 let x = rng.gen_range(-10, 10);
3338 fn test_extend_ref() {
3339 let mut a = HashMap::new();
3341 let mut b = HashMap::new();
3343 b.insert(3, "three");
3347 assert_eq!(a.len(), 3);
3348 assert_eq!(a[&1], "one");
3349 assert_eq!(a[&2], "two");
3350 assert_eq!(a[&3], "three");
3354 fn test_capacity_not_less_than_len() {
3355 let mut a = HashMap::new();
3363 assert!(a.capacity() > a.len());
3365 let free = a.capacity() - a.len();
3371 assert_eq!(a.len(), a.capacity());
3373 // Insert at capacity should cause allocation.
3375 assert!(a.capacity() > a.len());
3379 fn test_occupied_entry_key() {
3380 let mut a = HashMap::new();
3381 let key = "hello there";
3382 let value = "value goes here";
3383 assert!(a.is_empty());
3384 a.insert(key.clone(), value.clone());
3385 assert_eq!(a.len(), 1);
3386 assert_eq!(a[key], value);
3388 match a.entry(key.clone()) {
3389 Vacant(_) => panic!(),
3390 Occupied(e) => assert_eq!(key, *e.key()),
3392 assert_eq!(a.len(), 1);
3393 assert_eq!(a[key], value);
3397 fn test_vacant_entry_key() {
3398 let mut a = HashMap::new();
3399 let key = "hello there";
3400 let value = "value goes here";
3402 assert!(a.is_empty());
3403 match a.entry(key.clone()) {
3404 Occupied(_) => panic!(),
3406 assert_eq!(key, *e.key());
3407 e.insert(value.clone());
3410 assert_eq!(a.len(), 1);
3411 assert_eq!(a[key], value);
3416 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
3418 map.retain(|&k, _| k % 2 == 0);
3419 assert_eq!(map.len(), 50);
3420 assert_eq!(map[&2], 20);
3421 assert_eq!(map[&4], 40);
3422 assert_eq!(map[&6], 60);
3426 fn test_try_reserve() {
3427 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
3429 const MAX_USIZE: usize = usize::MAX;
3431 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
3433 panic!("usize::MAX should trigger an overflow!");
3436 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE / 8) {
3438 panic!("usize::MAX / 8 should trigger an OOM!")
3443 fn test_raw_entry() {
3444 use super::RawEntryMut::{Occupied, Vacant};
3446 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3448 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3450 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
3451 use core::hash::{BuildHasher, Hash, Hasher};
3453 let mut hasher = map.hasher().build_hasher();
3454 k.hash(&mut hasher);
3458 // Existing key (insert)
3459 match map.raw_entry_mut().from_key(&1) {
3460 Vacant(_) => unreachable!(),
3461 Occupied(mut view) => {
3462 assert_eq!(view.get(), &10);
3463 assert_eq!(view.insert(100), 10);
3466 let hash1 = compute_hash(&map, 1);
3467 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
3468 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
3469 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
3470 assert_eq!(map.len(), 6);
3472 // Existing key (update)
3473 match map.raw_entry_mut().from_key(&2) {
3474 Vacant(_) => unreachable!(),
3475 Occupied(mut view) => {
3476 let v = view.get_mut();
3477 let new_v = (*v) * 10;
3481 let hash2 = compute_hash(&map, 2);
3482 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
3483 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
3484 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
3485 assert_eq!(map.len(), 6);
3487 // Existing key (take)
3488 let hash3 = compute_hash(&map, 3);
3489 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
3490 Vacant(_) => unreachable!(),
3492 assert_eq!(view.remove_entry(), (3, 30));
3495 assert_eq!(map.raw_entry().from_key(&3), None);
3496 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
3497 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
3498 assert_eq!(map.len(), 5);
3500 // Nonexistent key (insert)
3501 match map.raw_entry_mut().from_key(&10) {
3502 Occupied(_) => unreachable!(),
3504 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
3507 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
3508 assert_eq!(map.len(), 6);
3510 // Ensure all lookup methods produce equivalent results.
3512 let hash = compute_hash(&map, k);
3513 let v = map.get(&k).cloned();
3514 let kv = v.as_ref().map(|v| (&k, v));
3516 assert_eq!(map.raw_entry().from_key(&k), kv);
3517 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
3518 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
3520 match map.raw_entry_mut().from_key(&k) {
3521 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3522 Vacant(_) => assert_eq!(v, None),
3524 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
3525 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3526 Vacant(_) => assert_eq!(v, None),
3528 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
3529 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3530 Vacant(_) => assert_eq!(v, None),