6 use hashbrown::hash_map as base;
8 use crate::borrow::Borrow;
10 use crate::collections::TryReserveError;
11 use crate::collections::TryReserveErrorKind;
12 use crate::fmt::{self, Debug};
14 use crate::hash::{BuildHasher, Hash, Hasher, SipHasher13};
15 use crate::iter::FusedIterator;
16 use crate::ops::Index;
19 /// A [hash map] implemented with quadratic probing and SIMD lookup.
21 /// By default, `HashMap` uses a hashing algorithm selected to provide
22 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
23 /// reasonable best-effort is made to generate this seed from a high quality,
24 /// secure source of randomness provided by the host without blocking the
25 /// program. Because of this, the randomness of the seed depends on the output
26 /// quality of the system's random number generator when the seed is created.
27 /// In particular, seeds generated when the system's entropy pool is abnormally
28 /// low such as during system boot may be of a lower quality.
30 /// The default hashing algorithm is currently SipHash 1-3, though this is
31 /// subject to change at any point in the future. While its performance is very
32 /// competitive for medium sized keys, other hashing algorithms will outperform
33 /// it for small keys such as integers as well as large keys such as long
34 /// strings, though those algorithms will typically *not* protect against
35 /// attacks such as HashDoS.
37 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
38 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods.
39 /// There are many alternative [hashing algorithms available on crates.io].
41 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
42 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
43 /// If you implement these yourself, it is important that the following
47 /// k1 == k2 -> hash(k1) == hash(k2)
50 /// In other words, if two keys are equal, their hashes must be equal.
52 /// It is a logic error for a key to be modified in such a way that the key's
53 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
54 /// the [`Eq`] trait, changes while it is in the map. This is normally only
55 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56 /// The behavior resulting from such a logic error is not specified, but will
57 /// be encapsulated to the `HashMap` that observed the logic error and not
58 /// result in undefined behavior. This could include panics, incorrect results,
59 /// aborts, memory leaks, and non-termination.
61 /// The hash table implementation is a Rust port of Google's [SwissTable].
62 /// The original C++ version of SwissTable can be found [here], and this
63 /// [CppCon talk] gives an overview of how the algorithm works.
65 /// [hash map]: crate::collections#use-a-hashmap-when
66 /// [hashing algorithms available on crates.io]: https://crates.io/keywords/hasher
67 /// [SwissTable]: https://abseil.io/blog/20180927-swisstables
68 /// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
69 /// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
74 /// use std::collections::HashMap;
76 /// // Type inference lets us omit an explicit type signature (which
77 /// // would be `HashMap<String, String>` in this example).
78 /// let mut book_reviews = HashMap::new();
80 /// // Review some books.
81 /// book_reviews.insert(
82 /// "Adventures of Huckleberry Finn".to_string(),
83 /// "My favorite book.".to_string(),
85 /// book_reviews.insert(
86 /// "Grimms' Fairy Tales".to_string(),
87 /// "Masterpiece.".to_string(),
89 /// book_reviews.insert(
90 /// "Pride and Prejudice".to_string(),
91 /// "Very enjoyable.".to_string(),
93 /// book_reviews.insert(
94 /// "The Adventures of Sherlock Holmes".to_string(),
95 /// "Eye lyked it alot.".to_string(),
98 /// // Check for a specific one.
99 /// // When collections store owned values (String), they can still be
100 /// // queried using references (&str).
101 /// if !book_reviews.contains_key("Les Misérables") {
102 /// println!("We've got {} reviews, but Les Misérables ain't one.",
103 /// book_reviews.len());
106 /// // oops, this review has a lot of spelling mistakes, let's delete it.
107 /// book_reviews.remove("The Adventures of Sherlock Holmes");
109 /// // Look up the values associated with some keys.
110 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
111 /// for &book in &to_find {
112 /// match book_reviews.get(book) {
113 /// Some(review) => println!("{book}: {review}"),
114 /// None => println!("{book} is unreviewed.")
118 /// // Look up the value for a key (will panic if the key is not found).
119 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
121 /// // Iterate over everything.
122 /// for (book, review) in &book_reviews {
123 /// println!("{book}: \"{review}\"");
127 /// A `HashMap` with a known list of items can be initialized from an array:
130 /// use std::collections::HashMap;
132 /// let solar_distance = HashMap::from([
133 /// ("Mercury", 0.4),
140 /// `HashMap` implements an [`Entry` API](#method.entry), which allows
141 /// for complex methods of getting, setting, updating and removing keys and
145 /// use std::collections::HashMap;
147 /// // type inference lets us omit an explicit type signature (which
148 /// // would be `HashMap<&str, u8>` in this example).
149 /// let mut player_stats = HashMap::new();
151 /// fn random_stat_buff() -> u8 {
152 /// // could actually return some random value here - let's just return
153 /// // some fixed value for now
157 /// // insert a key only if it doesn't already exist
158 /// player_stats.entry("health").or_insert(100);
160 /// // insert a key using a function that provides a new value only if it
161 /// // doesn't already exist
162 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
164 /// // update a key, guarding against the key possibly not being set
165 /// let stat = player_stats.entry("attack").or_insert(100);
166 /// *stat += random_stat_buff();
168 /// // modify an entry before an insert with in-place mutation
169 /// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
172 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
173 /// We must also derive [`PartialEq`].
175 /// [`RefCell`]: crate::cell::RefCell
176 /// [`Cell`]: crate::cell::Cell
177 /// [`default`]: Default::default
178 /// [`with_hasher`]: Self::with_hasher
179 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
182 /// use std::collections::HashMap;
184 /// #[derive(Hash, Eq, PartialEq, Debug)]
191 /// /// Creates a new Viking.
192 /// fn new(name: &str, country: &str) -> Viking {
193 /// Viking { name: name.to_string(), country: country.to_string() }
197 /// // Use a HashMap to store the vikings' health points.
198 /// let vikings = HashMap::from([
199 /// (Viking::new("Einar", "Norway"), 25),
200 /// (Viking::new("Olaf", "Denmark"), 24),
201 /// (Viking::new("Harald", "Iceland"), 12),
204 /// // Use derived implementation to print the status of the vikings.
205 /// for (viking, health) in &vikings {
206 /// println!("{viking:?} has {health} hp");
210 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[rustc_insignificant_dtor]
213 pub struct HashMap<K, V, S = RandomState> {
214 base: base::HashMap<K, V, S>,
217 impl<K, V> HashMap<K, V, RandomState> {
218 /// Creates an empty `HashMap`.
220 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
221 /// is first inserted into.
226 /// use std::collections::HashMap;
227 /// let mut map: HashMap<&str, i32> = HashMap::new();
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn new() -> HashMap<K, V, RandomState> {
236 /// Creates an empty `HashMap` with the specified capacity.
238 /// The hash map will be able to hold at least `capacity` elements without
239 /// reallocating. If `capacity` is 0, the hash map will not allocate.
244 /// use std::collections::HashMap;
245 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
251 HashMap::with_capacity_and_hasher(capacity, Default::default())
255 impl<K, V, S> HashMap<K, V, S> {
256 /// Creates an empty `HashMap` which will use the given hash builder to hash
259 /// The created map has the default initial capacity.
261 /// Warning: `hash_builder` is normally randomly generated, and
262 /// is designed to allow HashMaps to be resistant to attacks that
263 /// cause many collisions and very poor performance. Setting it
264 /// manually using this function can expose a DoS attack vector.
266 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
267 /// the HashMap to be useful, see its documentation for details.
272 /// use std::collections::HashMap;
273 /// use std::collections::hash_map::RandomState;
275 /// let s = RandomState::new();
276 /// let mut map = HashMap::with_hasher(s);
277 /// map.insert(1, 2);
280 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
281 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
282 HashMap { base: base::HashMap::with_hasher(hash_builder) }
285 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
286 /// to hash the keys.
288 /// The hash map will be able to hold at least `capacity` elements without
289 /// reallocating. If `capacity` is 0, the hash map will not allocate.
291 /// Warning: `hash_builder` is normally randomly generated, and
292 /// is designed to allow HashMaps to be resistant to attacks that
293 /// cause many collisions and very poor performance. Setting it
294 /// manually using this function can expose a DoS attack vector.
296 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
297 /// the HashMap to be useful, see its documentation for details.
302 /// use std::collections::HashMap;
303 /// use std::collections::hash_map::RandomState;
305 /// let s = RandomState::new();
306 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
307 /// map.insert(1, 2);
310 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
311 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
312 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
315 /// Returns the number of elements the map can hold without reallocating.
317 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
318 /// more, but is guaranteed to be able to hold at least this many.
323 /// use std::collections::HashMap;
324 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
325 /// assert!(map.capacity() >= 100);
328 #[stable(feature = "rust1", since = "1.0.0")]
329 pub fn capacity(&self) -> usize {
333 /// An iterator visiting all keys in arbitrary order.
334 /// The iterator element type is `&'a K`.
339 /// use std::collections::HashMap;
341 /// let map = HashMap::from([
347 /// for key in map.keys() {
348 /// println!("{key}");
354 /// In the current implementation, iterating over keys takes O(capacity) time
355 /// instead of O(len) because it internally visits empty buckets too.
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn keys(&self) -> Keys<'_, K, V> {
358 Keys { inner: self.iter() }
361 /// Creates a consuming iterator visiting all the keys in arbitrary order.
362 /// The map cannot be used after calling this.
363 /// The iterator element type is `K`.
368 /// use std::collections::HashMap;
370 /// let map = HashMap::from([
376 /// let mut vec: Vec<&str> = map.into_keys().collect();
377 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
378 /// // keys must be sorted to test them against a sorted array.
379 /// vec.sort_unstable();
380 /// assert_eq!(vec, ["a", "b", "c"]);
385 /// In the current implementation, iterating over keys takes O(capacity) time
386 /// instead of O(len) because it internally visits empty buckets too.
388 #[rustc_lint_query_instability]
389 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
390 pub fn into_keys(self) -> IntoKeys<K, V> {
391 IntoKeys { inner: self.into_iter() }
394 /// An iterator visiting all values in arbitrary order.
395 /// The iterator element type is `&'a V`.
400 /// use std::collections::HashMap;
402 /// let map = HashMap::from([
408 /// for val in map.values() {
409 /// println!("{val}");
415 /// In the current implementation, iterating over values takes O(capacity) time
416 /// instead of O(len) because it internally visits empty buckets too.
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub fn values(&self) -> Values<'_, K, V> {
419 Values { inner: self.iter() }
422 /// An iterator visiting all values mutably in arbitrary order.
423 /// The iterator element type is `&'a mut V`.
428 /// use std::collections::HashMap;
430 /// let mut map = HashMap::from([
436 /// for val in map.values_mut() {
437 /// *val = *val + 10;
440 /// for val in map.values() {
441 /// println!("{val}");
447 /// In the current implementation, iterating over values takes O(capacity) time
448 /// instead of O(len) because it internally visits empty buckets too.
449 #[stable(feature = "map_values_mut", since = "1.10.0")]
450 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
451 ValuesMut { inner: self.iter_mut() }
454 /// Creates a consuming iterator visiting all the values in arbitrary order.
455 /// The map cannot be used after calling this.
456 /// The iterator element type is `V`.
461 /// use std::collections::HashMap;
463 /// let map = HashMap::from([
469 /// let mut vec: Vec<i32> = map.into_values().collect();
470 /// // The `IntoValues` iterator produces values in arbitrary order, so
471 /// // the values must be sorted to test them against a sorted array.
472 /// vec.sort_unstable();
473 /// assert_eq!(vec, [1, 2, 3]);
478 /// In the current implementation, iterating over values takes O(capacity) time
479 /// instead of O(len) because it internally visits empty buckets too.
481 #[rustc_lint_query_instability]
482 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
483 pub fn into_values(self) -> IntoValues<K, V> {
484 IntoValues { inner: self.into_iter() }
487 /// An iterator visiting all key-value pairs in arbitrary order.
488 /// The iterator element type is `(&'a K, &'a V)`.
493 /// use std::collections::HashMap;
495 /// let map = HashMap::from([
501 /// for (key, val) in map.iter() {
502 /// println!("key: {key} val: {val}");
508 /// In the current implementation, iterating over map takes O(capacity) time
509 /// instead of O(len) because it internally visits empty buckets too.
510 #[rustc_lint_query_instability]
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn iter(&self) -> Iter<'_, K, V> {
513 Iter { base: self.base.iter() }
516 /// An iterator visiting all key-value pairs in arbitrary order,
517 /// with mutable references to the values.
518 /// The iterator element type is `(&'a K, &'a mut V)`.
523 /// use std::collections::HashMap;
525 /// let mut map = HashMap::from([
531 /// // Update all values
532 /// for (_, val) in map.iter_mut() {
536 /// for (key, val) in &map {
537 /// println!("key: {key} val: {val}");
543 /// In the current implementation, iterating over map takes O(capacity) time
544 /// instead of O(len) because it internally visits empty buckets too.
545 #[rustc_lint_query_instability]
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
548 IterMut { base: self.base.iter_mut() }
551 /// Returns the number of elements in the map.
556 /// use std::collections::HashMap;
558 /// let mut a = HashMap::new();
559 /// assert_eq!(a.len(), 0);
560 /// a.insert(1, "a");
561 /// assert_eq!(a.len(), 1);
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn len(&self) -> usize {
568 /// Returns `true` if the map contains no elements.
573 /// use std::collections::HashMap;
575 /// let mut a = HashMap::new();
576 /// assert!(a.is_empty());
577 /// a.insert(1, "a");
578 /// assert!(!a.is_empty());
581 #[stable(feature = "rust1", since = "1.0.0")]
582 pub fn is_empty(&self) -> bool {
586 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
587 /// allocated memory for reuse.
589 /// If the returned iterator is dropped before being fully consumed, it
590 /// drops the remaining key-value pairs. The returned iterator keeps a
591 /// mutable borrow on the vector to optimize its implementation.
596 /// use std::collections::HashMap;
598 /// let mut a = HashMap::new();
599 /// a.insert(1, "a");
600 /// a.insert(2, "b");
602 /// for (k, v) in a.drain().take(1) {
603 /// assert!(k == 1 || k == 2);
604 /// assert!(v == "a" || v == "b");
607 /// assert!(a.is_empty());
610 #[rustc_lint_query_instability]
611 #[stable(feature = "drain", since = "1.6.0")]
612 pub fn drain(&mut self) -> Drain<'_, K, V> {
613 Drain { base: self.base.drain() }
616 /// Creates an iterator which uses a closure to determine if an element should be removed.
618 /// If the closure returns true, the element is removed from the map and yielded.
619 /// If the closure returns false, or panics, the element remains in the map and will not be
622 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
623 /// whether you choose to keep or remove it.
625 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
626 /// elements will still be subjected to the closure and removed and dropped if it returns true.
628 /// It is unspecified how many more elements will be subjected to the closure
629 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
630 /// or if the `DrainFilter` value is leaked.
634 /// Splitting a map into even and odd keys, reusing the original map:
637 /// #![feature(hash_drain_filter)]
638 /// use std::collections::HashMap;
640 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
641 /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
643 /// let mut evens = drained.keys().copied().collect::<Vec<_>>();
644 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
648 /// assert_eq!(evens, vec![0, 2, 4, 6]);
649 /// assert_eq!(odds, vec![1, 3, 5, 7]);
652 #[rustc_lint_query_instability]
653 #[unstable(feature = "hash_drain_filter", issue = "59618")]
654 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
656 F: FnMut(&K, &mut V) -> bool,
658 DrainFilter { base: self.base.drain_filter(pred) }
661 /// Retains only the elements specified by the predicate.
663 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
664 /// The elements are visited in unsorted (and unspecified) order.
669 /// use std::collections::HashMap;
671 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
672 /// map.retain(|&k, _| k % 2 == 0);
673 /// assert_eq!(map.len(), 4);
678 /// In the current implementation, this operation takes O(capacity) time
679 /// instead of O(len) because it internally visits empty buckets too.
681 #[rustc_lint_query_instability]
682 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
683 pub fn retain<F>(&mut self, f: F)
685 F: FnMut(&K, &mut V) -> bool,
690 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
696 /// use std::collections::HashMap;
698 /// let mut a = HashMap::new();
699 /// a.insert(1, "a");
701 /// assert!(a.is_empty());
704 #[stable(feature = "rust1", since = "1.0.0")]
705 pub fn clear(&mut self) {
709 /// Returns a reference to the map's [`BuildHasher`].
714 /// use std::collections::HashMap;
715 /// use std::collections::hash_map::RandomState;
717 /// let hasher = RandomState::new();
718 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
719 /// let hasher: &RandomState = map.hasher();
722 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
723 pub fn hasher(&self) -> &S {
728 impl<K, V, S> HashMap<K, V, S>
733 /// Reserves capacity for at least `additional` more elements to be inserted
734 /// in the `HashMap`. The collection may reserve more space to avoid
735 /// frequent reallocations.
739 /// Panics if the new allocation size overflows [`usize`].
744 /// use std::collections::HashMap;
745 /// let mut map: HashMap<&str, i32> = HashMap::new();
749 #[stable(feature = "rust1", since = "1.0.0")]
750 pub fn reserve(&mut self, additional: usize) {
751 self.base.reserve(additional)
754 /// Tries to reserve capacity for at least `additional` more elements to be inserted
755 /// in the given `HashMap<K, V>`. The collection may reserve more space to avoid
756 /// frequent reallocations.
760 /// If the capacity overflows, or the allocator reports a failure, then an error
766 /// use std::collections::HashMap;
768 /// let mut map: HashMap<&str, isize> = HashMap::new();
769 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
772 #[stable(feature = "try_reserve", since = "1.57.0")]
773 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
774 self.base.try_reserve(additional).map_err(map_try_reserve_error)
777 /// Shrinks the capacity of the map as much as possible. It will drop
778 /// down as much as possible while maintaining the internal rules
779 /// and possibly leaving some space in accordance with the resize policy.
784 /// use std::collections::HashMap;
786 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
787 /// map.insert(1, 2);
788 /// map.insert(3, 4);
789 /// assert!(map.capacity() >= 100);
790 /// map.shrink_to_fit();
791 /// assert!(map.capacity() >= 2);
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn shrink_to_fit(&mut self) {
796 self.base.shrink_to_fit();
799 /// Shrinks the capacity of the map with a lower limit. It will drop
800 /// down no lower than the supplied limit while maintaining the internal rules
801 /// and possibly leaving some space in accordance with the resize policy.
803 /// If the current capacity is less than the lower limit, this is a no-op.
808 /// use std::collections::HashMap;
810 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
811 /// map.insert(1, 2);
812 /// map.insert(3, 4);
813 /// assert!(map.capacity() >= 100);
814 /// map.shrink_to(10);
815 /// assert!(map.capacity() >= 10);
816 /// map.shrink_to(0);
817 /// assert!(map.capacity() >= 2);
820 #[stable(feature = "shrink_to", since = "1.56.0")]
821 pub fn shrink_to(&mut self, min_capacity: usize) {
822 self.base.shrink_to(min_capacity);
825 /// Gets the given key's corresponding entry in the map for in-place manipulation.
830 /// use std::collections::HashMap;
832 /// let mut letters = HashMap::new();
834 /// for ch in "a short treatise on fungi".chars() {
835 /// letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
838 /// assert_eq!(letters[&'s'], 2);
839 /// assert_eq!(letters[&'t'], 3);
840 /// assert_eq!(letters[&'u'], 1);
841 /// assert_eq!(letters.get(&'y'), None);
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
846 map_entry(self.base.rustc_entry(key))
849 /// Returns a reference to the value corresponding to the key.
851 /// The key may be any borrowed form of the map's key type, but
852 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
858 /// use std::collections::HashMap;
860 /// let mut map = HashMap::new();
861 /// map.insert(1, "a");
862 /// assert_eq!(map.get(&1), Some(&"a"));
863 /// assert_eq!(map.get(&2), None);
865 #[stable(feature = "rust1", since = "1.0.0")]
867 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
875 /// Returns the key-value pair corresponding to the supplied key.
877 /// The supplied key may be any borrowed form of the map's key type, but
878 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
884 /// use std::collections::HashMap;
886 /// let mut map = HashMap::new();
887 /// map.insert(1, "a");
888 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
889 /// assert_eq!(map.get_key_value(&2), None);
892 #[stable(feature = "map_get_key_value", since = "1.40.0")]
893 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
898 self.base.get_key_value(k)
901 /// Attempts to get mutable references to `N` values in the map at once.
903 /// Returns an array of length `N` with the results of each query. For soundness, at most one
904 /// mutable reference will be returned to any value. `None` will be returned if any of the
905 /// keys are duplicates or missing.
910 /// #![feature(map_many_mut)]
911 /// use std::collections::HashMap;
913 /// let mut libraries = HashMap::new();
914 /// libraries.insert("Bodleian Library".to_string(), 1602);
915 /// libraries.insert("Athenæum".to_string(), 1807);
916 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
917 /// libraries.insert("Library of Congress".to_string(), 1800);
919 /// let got = libraries.get_many_mut([
921 /// "Library of Congress",
931 /// // Missing keys result in None
932 /// let got = libraries.get_many_mut([
934 /// "New York Public Library",
936 /// assert_eq!(got, None);
938 /// // Duplicate keys result in None
939 /// let got = libraries.get_many_mut([
943 /// assert_eq!(got, None);
946 #[unstable(feature = "map_many_mut", issue = "97601")]
947 pub fn get_many_mut<Q: ?Sized, const N: usize>(&mut self, ks: [&Q; N]) -> Option<[&'_ mut V; N]>
952 self.base.get_many_mut(ks)
955 /// Attempts to get mutable references to `N` values in the map at once, without validating that
956 /// the values are unique.
958 /// Returns an array of length `N` with the results of each query. `None` will be returned if
959 /// any of the keys are missing.
961 /// For a safe alternative see [`get_many_mut`](Self::get_many_mut).
965 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
966 /// references are not used.
968 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
973 /// #![feature(map_many_mut)]
974 /// use std::collections::HashMap;
976 /// let mut libraries = HashMap::new();
977 /// libraries.insert("Bodleian Library".to_string(), 1602);
978 /// libraries.insert("Athenæum".to_string(), 1807);
979 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
980 /// libraries.insert("Library of Congress".to_string(), 1800);
982 /// let got = libraries.get_many_mut([
984 /// "Library of Congress",
994 /// // Missing keys result in None
995 /// let got = libraries.get_many_mut([
997 /// "New York Public Library",
999 /// assert_eq!(got, None);
1002 #[unstable(feature = "map_many_mut", issue = "97601")]
1003 pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>(
1006 ) -> Option<[&'_ mut V; N]>
1011 self.base.get_many_unchecked_mut(ks)
1014 /// Returns `true` if the map contains a value for the specified key.
1016 /// The key may be any borrowed form of the map's key type, but
1017 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1023 /// use std::collections::HashMap;
1025 /// let mut map = HashMap::new();
1026 /// map.insert(1, "a");
1027 /// assert_eq!(map.contains_key(&1), true);
1028 /// assert_eq!(map.contains_key(&2), false);
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1037 self.base.contains_key(k)
1040 /// Returns a mutable reference to the value corresponding to the key.
1042 /// The key may be any borrowed form of the map's key type, but
1043 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1049 /// use std::collections::HashMap;
1051 /// let mut map = HashMap::new();
1052 /// map.insert(1, "a");
1053 /// if let Some(x) = map.get_mut(&1) {
1056 /// assert_eq!(map[&1], "b");
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1065 self.base.get_mut(k)
1068 /// Inserts a key-value pair into the map.
1070 /// If the map did not have this key present, [`None`] is returned.
1072 /// If the map did have this key present, the value is updated, and the old
1073 /// value is returned. The key is not updated, though; this matters for
1074 /// types that can be `==` without being identical. See the [module-level
1075 /// documentation] for more.
1077 /// [module-level documentation]: crate::collections#insert-and-complex-keys
1082 /// use std::collections::HashMap;
1084 /// let mut map = HashMap::new();
1085 /// assert_eq!(map.insert(37, "a"), None);
1086 /// assert_eq!(map.is_empty(), false);
1088 /// map.insert(37, "b");
1089 /// assert_eq!(map.insert(37, "c"), Some("b"));
1090 /// assert_eq!(map[&37], "c");
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1095 self.base.insert(k, v)
1098 /// Tries to insert a key-value pair into the map, and returns
1099 /// a mutable reference to the value in the entry.
1101 /// If the map already had this key present, nothing is updated, and
1102 /// an error containing the occupied entry and the value is returned.
1109 /// #![feature(map_try_insert)]
1111 /// use std::collections::HashMap;
1113 /// let mut map = HashMap::new();
1114 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1116 /// let err = map.try_insert(37, "b").unwrap_err();
1117 /// assert_eq!(err.entry.key(), &37);
1118 /// assert_eq!(err.entry.get(), &"a");
1119 /// assert_eq!(err.value, "b");
1121 #[unstable(feature = "map_try_insert", issue = "82766")]
1122 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>> {
1123 match self.entry(key) {
1124 Occupied(entry) => Err(OccupiedError { entry, value }),
1125 Vacant(entry) => Ok(entry.insert(value)),
1129 /// Removes a key from the map, returning the value at the key if the key
1130 /// was previously in the map.
1132 /// The key may be any borrowed form of the map's key type, but
1133 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1139 /// use std::collections::HashMap;
1141 /// let mut map = HashMap::new();
1142 /// map.insert(1, "a");
1143 /// assert_eq!(map.remove(&1), Some("a"));
1144 /// assert_eq!(map.remove(&1), None);
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1156 /// Removes a key from the map, returning the stored key and value if the
1157 /// key was previously in the map.
1159 /// The key may be any borrowed form of the map's key type, but
1160 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1166 /// use std::collections::HashMap;
1169 /// let mut map = HashMap::new();
1170 /// map.insert(1, "a");
1171 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1172 /// assert_eq!(map.remove(&1), None);
1176 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1177 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1182 self.base.remove_entry(k)
1186 impl<K, V, S> HashMap<K, V, S>
1190 /// Creates a raw entry builder for the HashMap.
1192 /// Raw entries provide the lowest level of control for searching and
1193 /// manipulating a map. They must be manually initialized with a hash and
1194 /// then manually searched. After this, insertions into a vacant entry
1195 /// still require an owned key to be provided.
1197 /// Raw entries are useful for such exotic situations as:
1199 /// * Hash memoization
1200 /// * Deferring the creation of an owned key until it is known to be required
1201 /// * Using a search key that doesn't work with the Borrow trait
1202 /// * Using custom comparison logic without newtype wrappers
1204 /// Because raw entries provide much more low-level control, it's much easier
1205 /// to put the HashMap into an inconsistent state which, while memory-safe,
1206 /// will cause the map to produce seemingly random results. Higher-level and
1207 /// more foolproof APIs like `entry` should be preferred when possible.
1209 /// In particular, the hash used to initialized the raw entry must still be
1210 /// consistent with the hash of the key that is ultimately stored in the entry.
1211 /// This is because implementations of HashMap may need to recompute hashes
1212 /// when resizing, at which point only the keys are available.
1214 /// Raw entries give mutable access to the keys. This must not be used
1215 /// to modify how the key would compare or hash, as the map will not re-evaluate
1216 /// where the key should go, meaning the keys may become "lost" if their
1217 /// location does not reflect their state. For instance, if you change a key
1218 /// so that the map now contains keys which compare equal, search may start
1219 /// acting erratically, with two keys randomly masking each other. Implementations
1220 /// are free to assume this doesn't happen (within the limits of memory-safety).
1222 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1223 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
1224 RawEntryBuilderMut { map: self }
1227 /// Creates a raw immutable entry builder for the HashMap.
1229 /// Raw entries provide the lowest level of control for searching and
1230 /// manipulating a map. They must be manually initialized with a hash and
1231 /// then manually searched.
1233 /// This is useful for
1234 /// * Hash memoization
1235 /// * Using a search key that doesn't work with the Borrow trait
1236 /// * Using custom comparison logic without newtype wrappers
1238 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1239 /// `get` should be preferred.
1241 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1243 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1244 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
1245 RawEntryBuilder { map: self }
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<K, V, S> Clone for HashMap<K, V, S>
1257 fn clone(&self) -> Self {
1258 Self { base: self.base.clone() }
1262 fn clone_from(&mut self, other: &Self) {
1263 self.base.clone_from(&other.base);
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 impl<K, V, S> PartialEq for HashMap<K, V, S>
1274 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1275 if self.len() != other.len() {
1279 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 impl<K, V, S> Eq for HashMap<K, V, S>
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<K, V, S> Debug for HashMap<K, V, S>
1298 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1299 f.debug_map().entries(self.iter()).finish()
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<K, V, S> Default for HashMap<K, V, S>
1308 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1310 fn default() -> HashMap<K, V, S> {
1311 HashMap::with_hasher(Default::default())
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1318 K: Eq + Hash + Borrow<Q>,
1324 /// Returns a reference to the value corresponding to the supplied key.
1328 /// Panics if the key is not present in the `HashMap`.
1330 fn index(&self, key: &Q) -> &V {
1331 self.get(key).expect("no entry found for key")
1335 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1336 // Note: as what is currently the most convenient built-in way to construct
1337 // a HashMap, a simple usage of this function must not *require* the user
1338 // to provide a type annotation in order to infer the third type parameter
1339 // (the hasher parameter, conventionally "S").
1340 // To that end, this impl is defined using RandomState as the concrete
1341 // type of S, rather than being generic over `S: BuildHasher + Default`.
1342 // It is expected that users who want to specify a hasher will manually use
1343 // `with_capacity_and_hasher`.
1344 // If type parameter defaults worked on impls, and if type parameter
1345 // defaults could be mixed with const generics, then perhaps
1346 // this could be generalized.
1347 // See also the equivalent impl on HashSet.
1348 impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
1355 /// use std::collections::HashMap;
1357 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1358 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1359 /// assert_eq!(map1, map2);
1361 fn from(arr: [(K, V); N]) -> Self {
1362 Self::from_iter(arr)
1366 /// An iterator over the entries of a `HashMap`.
1368 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1369 /// documentation for more.
1371 /// [`iter`]: HashMap::iter
1376 /// use std::collections::HashMap;
1378 /// let map = HashMap::from([
1381 /// let iter = map.iter();
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 pub struct Iter<'a, K: 'a, V: 'a> {
1385 base: base::Iter<'a, K, V>,
1388 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<K, V> Clone for Iter<'_, K, V> {
1392 fn clone(&self) -> Self {
1393 Iter { base: self.base.clone() }
1397 #[stable(feature = "std_debug", since = "1.16.0")]
1398 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1400 f.debug_list().entries(self.clone()).finish()
1404 /// A mutable iterator over the entries of a `HashMap`.
1406 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1407 /// documentation for more.
1409 /// [`iter_mut`]: HashMap::iter_mut
1414 /// use std::collections::HashMap;
1416 /// let mut map = HashMap::from([
1419 /// let iter = map.iter_mut();
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub struct IterMut<'a, K: 'a, V: 'a> {
1423 base: base::IterMut<'a, K, V>,
1426 impl<'a, K, V> IterMut<'a, K, V> {
1427 /// Returns an iterator of references over the remaining items.
1429 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1430 Iter { base: self.base.rustc_iter() }
1434 /// An owning iterator over the entries of a `HashMap`.
1436 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1437 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1439 /// [`into_iter`]: IntoIterator::into_iter
1440 /// [`IntoIterator`]: crate::iter::IntoIterator
1445 /// use std::collections::HashMap;
1447 /// let map = HashMap::from([
1450 /// let iter = map.into_iter();
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 pub struct IntoIter<K, V> {
1454 base: base::IntoIter<K, V>,
1457 impl<K, V> IntoIter<K, V> {
1458 /// Returns an iterator of references over the remaining items.
1460 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1461 Iter { base: self.base.rustc_iter() }
1465 /// An iterator over the keys of a `HashMap`.
1467 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1468 /// documentation for more.
1470 /// [`keys`]: HashMap::keys
1475 /// use std::collections::HashMap;
1477 /// let map = HashMap::from([
1480 /// let iter_keys = map.keys();
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 pub struct Keys<'a, K: 'a, V: 'a> {
1484 inner: Iter<'a, K, V>,
1487 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<K, V> Clone for Keys<'_, K, V> {
1491 fn clone(&self) -> Self {
1492 Keys { inner: self.inner.clone() }
1496 #[stable(feature = "std_debug", since = "1.16.0")]
1497 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1499 f.debug_list().entries(self.clone()).finish()
1503 /// An iterator over the values of a `HashMap`.
1505 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1506 /// documentation for more.
1508 /// [`values`]: HashMap::values
1513 /// use std::collections::HashMap;
1515 /// let map = HashMap::from([
1518 /// let iter_values = map.values();
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 pub struct Values<'a, K: 'a, V: 'a> {
1522 inner: Iter<'a, K, V>,
1525 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<K, V> Clone for Values<'_, K, V> {
1529 fn clone(&self) -> Self {
1530 Values { inner: self.inner.clone() }
1534 #[stable(feature = "std_debug", since = "1.16.0")]
1535 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1536 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1537 f.debug_list().entries(self.clone()).finish()
1541 /// A draining iterator over the entries of a `HashMap`.
1543 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1544 /// documentation for more.
1546 /// [`drain`]: HashMap::drain
1551 /// use std::collections::HashMap;
1553 /// let mut map = HashMap::from([
1556 /// let iter = map.drain();
1558 #[stable(feature = "drain", since = "1.6.0")]
1559 pub struct Drain<'a, K: 'a, V: 'a> {
1560 base: base::Drain<'a, K, V>,
1563 impl<'a, K, V> Drain<'a, K, V> {
1564 /// Returns an iterator of references over the remaining items.
1566 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1567 Iter { base: self.base.rustc_iter() }
1571 /// A draining, filtering iterator over the entries of a `HashMap`.
1573 /// This `struct` is created by the [`drain_filter`] method on [`HashMap`].
1575 /// [`drain_filter`]: HashMap::drain_filter
1580 /// #![feature(hash_drain_filter)]
1582 /// use std::collections::HashMap;
1584 /// let mut map = HashMap::from([
1587 /// let iter = map.drain_filter(|_k, v| *v % 2 == 0);
1589 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1590 pub struct DrainFilter<'a, K, V, F>
1592 F: FnMut(&K, &mut V) -> bool,
1594 base: base::DrainFilter<'a, K, V, F>,
1597 /// A mutable iterator over the values of a `HashMap`.
1599 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1600 /// documentation for more.
1602 /// [`values_mut`]: HashMap::values_mut
1607 /// use std::collections::HashMap;
1609 /// let mut map = HashMap::from([
1612 /// let iter_values = map.values_mut();
1614 #[stable(feature = "map_values_mut", since = "1.10.0")]
1615 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1616 inner: IterMut<'a, K, V>,
1619 /// An owning iterator over the keys of a `HashMap`.
1621 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1622 /// See its documentation for more.
1624 /// [`into_keys`]: HashMap::into_keys
1629 /// use std::collections::HashMap;
1631 /// let map = HashMap::from([
1634 /// let iter_keys = map.into_keys();
1636 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1637 pub struct IntoKeys<K, V> {
1638 inner: IntoIter<K, V>,
1641 /// An owning iterator over the values of a `HashMap`.
1643 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1644 /// See its documentation for more.
1646 /// [`into_values`]: HashMap::into_values
1651 /// use std::collections::HashMap;
1653 /// let map = HashMap::from([
1656 /// let iter_keys = map.into_values();
1658 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1659 pub struct IntoValues<K, V> {
1660 inner: IntoIter<K, V>,
1663 /// A builder for computing where in a HashMap a key-value pair would be stored.
1665 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1666 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1667 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1668 map: &'a mut HashMap<K, V, S>,
1671 /// A view into a single entry in a map, which may either be vacant or occupied.
1673 /// This is a lower-level version of [`Entry`].
1675 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1676 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1678 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1679 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1680 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1681 /// An occupied entry.
1682 Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1684 Vacant(RawVacantEntryMut<'a, K, V, S>),
1687 /// A view into an occupied entry in a `HashMap`.
1688 /// It is part of the [`RawEntryMut`] enum.
1689 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1690 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1691 base: base::RawOccupiedEntryMut<'a, K, V, S>,
1694 /// A view into a vacant entry in a `HashMap`.
1695 /// It is part of the [`RawEntryMut`] enum.
1696 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1697 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1698 base: base::RawVacantEntryMut<'a, K, V, S>,
1701 /// A builder for computing where in a HashMap a key-value pair would be stored.
1703 /// See the [`HashMap::raw_entry`] docs for usage examples.
1704 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1705 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1706 map: &'a HashMap<K, V, S>,
1709 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1713 /// Creates a `RawEntryMut` from the given key.
1715 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1716 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1721 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1724 /// Creates a `RawEntryMut` from the given key and its hash.
1726 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1727 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1732 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1735 /// Creates a `RawEntryMut` from the given hash.
1737 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1738 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1740 for<'b> F: FnMut(&'b K) -> bool,
1742 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1746 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1750 /// Access an entry by key.
1752 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1753 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1758 self.map.base.raw_entry().from_key(k)
1761 /// Access an entry by a key and its hash.
1763 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1764 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1769 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1772 /// Access an entry by hash.
1774 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1775 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1777 F: FnMut(&K) -> bool,
1779 self.map.base.raw_entry().from_hash(hash, is_match)
1783 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1784 /// Ensures a value is in the entry by inserting the default if empty, and returns
1785 /// mutable references to the key and value in the entry.
1790 /// #![feature(hash_raw_entry)]
1791 /// use std::collections::HashMap;
1793 /// let mut map: HashMap<&str, u32> = HashMap::new();
1795 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1796 /// assert_eq!(map["poneyland"], 3);
1798 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1799 /// assert_eq!(map["poneyland"], 6);
1802 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1803 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1809 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1810 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1814 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1815 /// and returns mutable references to the key and value in the entry.
1820 /// #![feature(hash_raw_entry)]
1821 /// use std::collections::HashMap;
1823 /// let mut map: HashMap<&str, String> = HashMap::new();
1825 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1826 /// ("poneyland", "hoho".to_string())
1829 /// assert_eq!(map["poneyland"], "hoho".to_string());
1832 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1833 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1835 F: FnOnce() -> (K, V),
1840 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1841 RawEntryMut::Vacant(entry) => {
1842 let (k, v) = default();
1848 /// Provides in-place mutable access to an occupied entry before any
1849 /// potential inserts into the map.
1854 /// #![feature(hash_raw_entry)]
1855 /// use std::collections::HashMap;
1857 /// let mut map: HashMap<&str, u32> = HashMap::new();
1859 /// map.raw_entry_mut()
1860 /// .from_key("poneyland")
1861 /// .and_modify(|_k, v| { *v += 1 })
1862 /// .or_insert("poneyland", 42);
1863 /// assert_eq!(map["poneyland"], 42);
1865 /// map.raw_entry_mut()
1866 /// .from_key("poneyland")
1867 /// .and_modify(|_k, v| { *v += 1 })
1868 /// .or_insert("poneyland", 0);
1869 /// assert_eq!(map["poneyland"], 43);
1872 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1873 pub fn and_modify<F>(self, f: F) -> Self
1875 F: FnOnce(&mut K, &mut V),
1878 RawEntryMut::Occupied(mut entry) => {
1880 let (k, v) = entry.get_key_value_mut();
1883 RawEntryMut::Occupied(entry)
1885 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1890 impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1891 /// Gets a reference to the key in the entry.
1894 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1895 pub fn key(&self) -> &K {
1899 /// Gets a mutable reference to the key in the entry.
1902 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1903 pub fn key_mut(&mut self) -> &mut K {
1907 /// Converts the entry into a mutable reference to the key in the entry
1908 /// with a lifetime bound to the map itself.
1910 #[must_use = "`self` will be dropped if the result is not used"]
1911 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1912 pub fn into_key(self) -> &'a mut K {
1913 self.base.into_key()
1916 /// Gets a reference to the value in the entry.
1919 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1920 pub fn get(&self) -> &V {
1924 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
1925 /// with a lifetime bound to the map itself.
1927 #[must_use = "`self` will be dropped if the result is not used"]
1928 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1929 pub fn into_mut(self) -> &'a mut V {
1930 self.base.into_mut()
1933 /// Gets a mutable reference to the value in the entry.
1936 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1937 pub fn get_mut(&mut self) -> &mut V {
1941 /// Gets a reference to the key and value in the entry.
1944 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1945 pub fn get_key_value(&mut self) -> (&K, &V) {
1946 self.base.get_key_value()
1949 /// Gets a mutable reference to the key and value in the entry.
1951 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1952 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1953 self.base.get_key_value_mut()
1956 /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry
1957 /// with a lifetime bound to the map itself.
1959 #[must_use = "`self` will be dropped if the result is not used"]
1960 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1961 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1962 self.base.into_key_value()
1965 /// Sets the value of the entry, and returns the entry's old value.
1967 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1968 pub fn insert(&mut self, value: V) -> V {
1969 self.base.insert(value)
1972 /// Sets the value of the entry, and returns the entry's old value.
1974 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1975 pub fn insert_key(&mut self, key: K) -> K {
1976 self.base.insert_key(key)
1979 /// Takes the value out of the entry, and returns it.
1981 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1982 pub fn remove(self) -> V {
1986 /// Take the ownership of the key and value from the map.
1988 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1989 pub fn remove_entry(self) -> (K, V) {
1990 self.base.remove_entry()
1994 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1995 /// Sets the value of the entry with the `VacantEntry`'s key,
1996 /// and returns a mutable reference to it.
1998 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1999 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2004 self.base.insert(key, value)
2007 /// Sets the value of the entry with the VacantEntry's key,
2008 /// and returns a mutable reference to it.
2010 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2011 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
2016 self.base.insert_hashed_nocheck(hash, key, value)
2020 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2021 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
2022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2023 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
2027 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2028 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
2029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2031 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
2032 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
2037 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2038 impl<K: Debug, V: Debug, S> Debug for RawOccupiedEntryMut<'_, K, V, S> {
2039 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2040 f.debug_struct("RawOccupiedEntryMut")
2041 .field("key", self.key())
2042 .field("value", self.get())
2043 .finish_non_exhaustive()
2047 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2048 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
2049 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2050 f.debug_struct("RawVacantEntryMut").finish_non_exhaustive()
2054 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2055 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
2056 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2057 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
2061 /// A view into a single entry in a map, which may either be vacant or occupied.
2063 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2065 /// [`entry`]: HashMap::entry
2066 #[stable(feature = "rust1", since = "1.0.0")]
2067 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
2068 pub enum Entry<'a, K: 'a, V: 'a> {
2069 /// An occupied entry.
2070 #[stable(feature = "rust1", since = "1.0.0")]
2071 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
2078 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2079 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
2080 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2082 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2083 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2088 /// A view into an occupied entry in a `HashMap`.
2089 /// It is part of the [`Entry`] enum.
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2092 base: base::RustcOccupiedEntry<'a, K, V>,
2095 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2096 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
2097 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2098 f.debug_struct("OccupiedEntry")
2099 .field("key", self.key())
2100 .field("value", self.get())
2101 .finish_non_exhaustive()
2105 /// A view into a vacant entry in a `HashMap`.
2106 /// It is part of the [`Entry`] enum.
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2109 base: base::RustcVacantEntry<'a, K, V>,
2112 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2113 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
2114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2115 f.debug_tuple("VacantEntry").field(self.key()).finish()
2119 /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
2121 /// Contains the occupied entry, and the value that was not inserted.
2122 #[unstable(feature = "map_try_insert", issue = "82766")]
2123 pub struct OccupiedError<'a, K: 'a, V: 'a> {
2124 /// The entry in the map that was already occupied.
2125 pub entry: OccupiedEntry<'a, K, V>,
2126 /// The value which was not inserted, because the entry was already occupied.
2130 #[unstable(feature = "map_try_insert", issue = "82766")]
2131 impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V> {
2132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2133 f.debug_struct("OccupiedError")
2134 .field("key", self.entry.key())
2135 .field("old_value", self.entry.get())
2136 .field("new_value", &self.value)
2137 .finish_non_exhaustive()
2141 #[unstable(feature = "map_try_insert", issue = "82766")]
2142 impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> {
2143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2146 "failed to insert {:?}, key {:?} already exists with value {:?}",
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
2156 type Item = (&'a K, &'a V);
2157 type IntoIter = Iter<'a, K, V>;
2160 #[rustc_lint_query_instability]
2161 fn into_iter(self) -> Iter<'a, K, V> {
2166 #[stable(feature = "rust1", since = "1.0.0")]
2167 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
2168 type Item = (&'a K, &'a mut V);
2169 type IntoIter = IterMut<'a, K, V>;
2172 #[rustc_lint_query_instability]
2173 fn into_iter(self) -> IterMut<'a, K, V> {
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
2181 type IntoIter = IntoIter<K, V>;
2183 /// Creates a consuming iterator, that is, one that moves each key-value
2184 /// pair out of the map in arbitrary order. The map cannot be used after
2190 /// use std::collections::HashMap;
2192 /// let map = HashMap::from([
2198 /// // Not possible with .iter()
2199 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2202 #[rustc_lint_query_instability]
2203 fn into_iter(self) -> IntoIter<K, V> {
2204 IntoIter { base: self.base.into_iter() }
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2210 type Item = (&'a K, &'a V);
2213 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2217 fn size_hint(&self) -> (usize, Option<usize>) {
2218 self.base.size_hint()
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
2224 fn len(&self) -> usize {
2229 #[stable(feature = "fused", since = "1.26.0")]
2230 impl<K, V> FusedIterator for Iter<'_, K, V> {}
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2234 type Item = (&'a K, &'a mut V);
2237 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2241 fn size_hint(&self) -> (usize, Option<usize>) {
2242 self.base.size_hint()
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2248 fn len(&self) -> usize {
2252 #[stable(feature = "fused", since = "1.26.0")]
2253 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2255 #[stable(feature = "std_debug", since = "1.16.0")]
2256 impl<K, V> fmt::Debug for IterMut<'_, K, V>
2261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2262 f.debug_list().entries(self.iter()).finish()
2266 #[stable(feature = "rust1", since = "1.0.0")]
2267 impl<K, V> Iterator for IntoIter<K, V> {
2271 fn next(&mut self) -> Option<(K, V)> {
2275 fn size_hint(&self) -> (usize, Option<usize>) {
2276 self.base.size_hint()
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2282 fn len(&self) -> usize {
2286 #[stable(feature = "fused", since = "1.26.0")]
2287 impl<K, V> FusedIterator for IntoIter<K, V> {}
2289 #[stable(feature = "std_debug", since = "1.16.0")]
2290 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2292 f.debug_list().entries(self.iter()).finish()
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2301 fn next(&mut self) -> Option<&'a K> {
2302 self.inner.next().map(|(k, _)| k)
2305 fn size_hint(&self) -> (usize, Option<usize>) {
2306 self.inner.size_hint()
2309 #[stable(feature = "rust1", since = "1.0.0")]
2310 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2312 fn len(&self) -> usize {
2316 #[stable(feature = "fused", since = "1.26.0")]
2317 impl<K, V> FusedIterator for Keys<'_, K, V> {}
2319 #[stable(feature = "rust1", since = "1.0.0")]
2320 impl<'a, K, V> Iterator for Values<'a, K, V> {
2324 fn next(&mut self) -> Option<&'a V> {
2325 self.inner.next().map(|(_, v)| v)
2328 fn size_hint(&self) -> (usize, Option<usize>) {
2329 self.inner.size_hint()
2332 #[stable(feature = "rust1", since = "1.0.0")]
2333 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2335 fn len(&self) -> usize {
2339 #[stable(feature = "fused", since = "1.26.0")]
2340 impl<K, V> FusedIterator for Values<'_, K, V> {}
2342 #[stable(feature = "map_values_mut", since = "1.10.0")]
2343 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2344 type Item = &'a mut V;
2347 fn next(&mut self) -> Option<&'a mut V> {
2348 self.inner.next().map(|(_, v)| v)
2351 fn size_hint(&self) -> (usize, Option<usize>) {
2352 self.inner.size_hint()
2355 #[stable(feature = "map_values_mut", since = "1.10.0")]
2356 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2358 fn len(&self) -> usize {
2362 #[stable(feature = "fused", since = "1.26.0")]
2363 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2365 #[stable(feature = "std_debug", since = "1.16.0")]
2366 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2368 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2372 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2373 impl<K, V> Iterator for IntoKeys<K, V> {
2377 fn next(&mut self) -> Option<K> {
2378 self.inner.next().map(|(k, _)| k)
2381 fn size_hint(&self) -> (usize, Option<usize>) {
2382 self.inner.size_hint()
2385 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2386 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2388 fn len(&self) -> usize {
2392 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2393 impl<K, V> FusedIterator for IntoKeys<K, V> {}
2395 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2396 impl<K: Debug, V> fmt::Debug for IntoKeys<K, V> {
2397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2398 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2402 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2403 impl<K, V> Iterator for IntoValues<K, V> {
2407 fn next(&mut self) -> Option<V> {
2408 self.inner.next().map(|(_, v)| v)
2411 fn size_hint(&self) -> (usize, Option<usize>) {
2412 self.inner.size_hint()
2415 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2416 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2418 fn len(&self) -> usize {
2422 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2423 impl<K, V> FusedIterator for IntoValues<K, V> {}
2425 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2426 impl<K, V: Debug> fmt::Debug for IntoValues<K, V> {
2427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2428 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2432 #[stable(feature = "drain", since = "1.6.0")]
2433 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2437 fn next(&mut self) -> Option<(K, V)> {
2441 fn size_hint(&self) -> (usize, Option<usize>) {
2442 self.base.size_hint()
2445 #[stable(feature = "drain", since = "1.6.0")]
2446 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2448 fn len(&self) -> usize {
2452 #[stable(feature = "fused", since = "1.26.0")]
2453 impl<K, V> FusedIterator for Drain<'_, K, V> {}
2455 #[stable(feature = "std_debug", since = "1.16.0")]
2456 impl<K, V> fmt::Debug for Drain<'_, K, V>
2461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2462 f.debug_list().entries(self.iter()).finish()
2466 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2467 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
2469 F: FnMut(&K, &mut V) -> bool,
2474 fn next(&mut self) -> Option<(K, V)> {
2478 fn size_hint(&self) -> (usize, Option<usize>) {
2479 self.base.size_hint()
2483 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2484 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2486 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2487 impl<'a, K, V, F> fmt::Debug for DrainFilter<'a, K, V, F>
2489 F: FnMut(&K, &mut V) -> bool,
2491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2492 f.debug_struct("DrainFilter").finish_non_exhaustive()
2496 impl<'a, K, V> Entry<'a, K, V> {
2497 /// Ensures a value is in the entry by inserting the default if empty, and returns
2498 /// a mutable reference to the value in the entry.
2503 /// use std::collections::HashMap;
2505 /// let mut map: HashMap<&str, u32> = HashMap::new();
2507 /// map.entry("poneyland").or_insert(3);
2508 /// assert_eq!(map["poneyland"], 3);
2510 /// *map.entry("poneyland").or_insert(10) *= 2;
2511 /// assert_eq!(map["poneyland"], 6);
2514 #[stable(feature = "rust1", since = "1.0.0")]
2515 pub fn or_insert(self, default: V) -> &'a mut V {
2517 Occupied(entry) => entry.into_mut(),
2518 Vacant(entry) => entry.insert(default),
2522 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2523 /// and returns a mutable reference to the value in the entry.
2528 /// use std::collections::HashMap;
2530 /// let mut map: HashMap<&str, String> = HashMap::new();
2531 /// let s = "hoho".to_string();
2533 /// map.entry("poneyland").or_insert_with(|| s);
2535 /// assert_eq!(map["poneyland"], "hoho".to_string());
2538 #[stable(feature = "rust1", since = "1.0.0")]
2539 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2541 Occupied(entry) => entry.into_mut(),
2542 Vacant(entry) => entry.insert(default()),
2546 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2547 /// This method allows for generating key-derived values for insertion by providing the default
2548 /// function a reference to the key that was moved during the `.entry(key)` method call.
2550 /// The reference to the moved key is provided so that cloning or copying the key is
2551 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2556 /// use std::collections::HashMap;
2558 /// let mut map: HashMap<&str, usize> = HashMap::new();
2560 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2562 /// assert_eq!(map["poneyland"], 9);
2565 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2566 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2568 Occupied(entry) => entry.into_mut(),
2570 let value = default(entry.key());
2576 /// Returns a reference to this entry's key.
2581 /// use std::collections::HashMap;
2583 /// let mut map: HashMap<&str, u32> = HashMap::new();
2584 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2587 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2588 pub fn key(&self) -> &K {
2590 Occupied(ref entry) => entry.key(),
2591 Vacant(ref entry) => entry.key(),
2595 /// Provides in-place mutable access to an occupied entry before any
2596 /// potential inserts into the map.
2601 /// use std::collections::HashMap;
2603 /// let mut map: HashMap<&str, u32> = HashMap::new();
2605 /// map.entry("poneyland")
2606 /// .and_modify(|e| { *e += 1 })
2608 /// assert_eq!(map["poneyland"], 42);
2610 /// map.entry("poneyland")
2611 /// .and_modify(|e| { *e += 1 })
2613 /// assert_eq!(map["poneyland"], 43);
2616 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2617 pub fn and_modify<F>(self, f: F) -> Self
2622 Occupied(mut entry) => {
2626 Vacant(entry) => Vacant(entry),
2630 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2635 /// #![feature(entry_insert)]
2636 /// use std::collections::HashMap;
2638 /// let mut map: HashMap<&str, String> = HashMap::new();
2639 /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2641 /// assert_eq!(entry.key(), &"poneyland");
2644 #[unstable(feature = "entry_insert", issue = "65225")]
2645 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2647 Occupied(mut entry) => {
2648 entry.insert(value);
2651 Vacant(entry) => entry.insert_entry(value),
2656 impl<'a, K, V: Default> Entry<'a, K, V> {
2657 /// Ensures a value is in the entry by inserting the default value if empty,
2658 /// and returns a mutable reference to the value in the entry.
2664 /// use std::collections::HashMap;
2666 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2667 /// map.entry("poneyland").or_default();
2669 /// assert_eq!(map["poneyland"], None);
2673 #[stable(feature = "entry_or_default", since = "1.28.0")]
2674 pub fn or_default(self) -> &'a mut V {
2676 Occupied(entry) => entry.into_mut(),
2677 Vacant(entry) => entry.insert(Default::default()),
2682 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2683 /// Gets a reference to the key in the entry.
2688 /// use std::collections::HashMap;
2690 /// let mut map: HashMap<&str, u32> = HashMap::new();
2691 /// map.entry("poneyland").or_insert(12);
2692 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2695 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2696 pub fn key(&self) -> &K {
2700 /// Take the ownership of the key and value from the map.
2705 /// use std::collections::HashMap;
2706 /// use std::collections::hash_map::Entry;
2708 /// let mut map: HashMap<&str, u32> = HashMap::new();
2709 /// map.entry("poneyland").or_insert(12);
2711 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2712 /// // We delete the entry from the map.
2713 /// o.remove_entry();
2716 /// assert_eq!(map.contains_key("poneyland"), false);
2719 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2720 pub fn remove_entry(self) -> (K, V) {
2721 self.base.remove_entry()
2724 /// Gets a reference to the value in the entry.
2729 /// use std::collections::HashMap;
2730 /// use std::collections::hash_map::Entry;
2732 /// let mut map: HashMap<&str, u32> = HashMap::new();
2733 /// map.entry("poneyland").or_insert(12);
2735 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2736 /// assert_eq!(o.get(), &12);
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 pub fn get(&self) -> &V {
2745 /// Gets a mutable reference to the value in the entry.
2747 /// If you need a reference to the `OccupiedEntry` which may outlive the
2748 /// destruction of the `Entry` value, see [`into_mut`].
2750 /// [`into_mut`]: Self::into_mut
2755 /// use std::collections::HashMap;
2756 /// use std::collections::hash_map::Entry;
2758 /// let mut map: HashMap<&str, u32> = HashMap::new();
2759 /// map.entry("poneyland").or_insert(12);
2761 /// assert_eq!(map["poneyland"], 12);
2762 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2763 /// *o.get_mut() += 10;
2764 /// assert_eq!(*o.get(), 22);
2766 /// // We can use the same Entry multiple times.
2767 /// *o.get_mut() += 2;
2770 /// assert_eq!(map["poneyland"], 24);
2773 #[stable(feature = "rust1", since = "1.0.0")]
2774 pub fn get_mut(&mut self) -> &mut V {
2778 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2779 /// with a lifetime bound to the map itself.
2781 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2783 /// [`get_mut`]: Self::get_mut
2788 /// use std::collections::HashMap;
2789 /// use std::collections::hash_map::Entry;
2791 /// let mut map: HashMap<&str, u32> = HashMap::new();
2792 /// map.entry("poneyland").or_insert(12);
2794 /// assert_eq!(map["poneyland"], 12);
2795 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2796 /// *o.into_mut() += 10;
2799 /// assert_eq!(map["poneyland"], 22);
2802 #[stable(feature = "rust1", since = "1.0.0")]
2803 pub fn into_mut(self) -> &'a mut V {
2804 self.base.into_mut()
2807 /// Sets the value of the entry, and returns the entry's old value.
2812 /// use std::collections::HashMap;
2813 /// use std::collections::hash_map::Entry;
2815 /// let mut map: HashMap<&str, u32> = HashMap::new();
2816 /// map.entry("poneyland").or_insert(12);
2818 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2819 /// assert_eq!(o.insert(15), 12);
2822 /// assert_eq!(map["poneyland"], 15);
2825 #[stable(feature = "rust1", since = "1.0.0")]
2826 pub fn insert(&mut self, value: V) -> V {
2827 self.base.insert(value)
2830 /// Takes the value out of the entry, and returns it.
2835 /// use std::collections::HashMap;
2836 /// use std::collections::hash_map::Entry;
2838 /// let mut map: HashMap<&str, u32> = HashMap::new();
2839 /// map.entry("poneyland").or_insert(12);
2841 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2842 /// assert_eq!(o.remove(), 12);
2845 /// assert_eq!(map.contains_key("poneyland"), false);
2848 #[stable(feature = "rust1", since = "1.0.0")]
2849 pub fn remove(self) -> V {
2853 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2854 /// the key used to create this entry.
2859 /// #![feature(map_entry_replace)]
2860 /// use std::collections::hash_map::{Entry, HashMap};
2861 /// use std::rc::Rc;
2863 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2864 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2866 /// let my_key = Rc::new("Stringthing".to_string());
2868 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2869 /// // Also replace the key with a handle to our other key.
2870 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2875 #[unstable(feature = "map_entry_replace", issue = "44286")]
2876 pub fn replace_entry(self, value: V) -> (K, V) {
2877 self.base.replace_entry(value)
2880 /// Replaces the key in the hash map with the key used to create this entry.
2885 /// #![feature(map_entry_replace)]
2886 /// use std::collections::hash_map::{Entry, HashMap};
2887 /// use std::rc::Rc;
2889 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2890 /// let known_strings: Vec<Rc<String>> = Vec::new();
2892 /// // Initialise known strings, run program, etc.
2894 /// reclaim_memory(&mut map, &known_strings);
2896 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2897 /// for s in known_strings {
2898 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2899 /// // Replaces the entry's key with our version of it in `known_strings`.
2900 /// entry.replace_key();
2906 #[unstable(feature = "map_entry_replace", issue = "44286")]
2907 pub fn replace_key(self) -> K {
2908 self.base.replace_key()
2912 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2913 /// Gets a reference to the key that would be used when inserting a value
2914 /// through the `VacantEntry`.
2919 /// use std::collections::HashMap;
2921 /// let mut map: HashMap<&str, u32> = HashMap::new();
2922 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2925 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2926 pub fn key(&self) -> &K {
2930 /// Take ownership of the key.
2935 /// use std::collections::HashMap;
2936 /// use std::collections::hash_map::Entry;
2938 /// let mut map: HashMap<&str, u32> = HashMap::new();
2940 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2945 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2946 pub fn into_key(self) -> K {
2947 self.base.into_key()
2950 /// Sets the value of the entry with the `VacantEntry`'s key,
2951 /// and returns a mutable reference to it.
2956 /// use std::collections::HashMap;
2957 /// use std::collections::hash_map::Entry;
2959 /// let mut map: HashMap<&str, u32> = HashMap::new();
2961 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2964 /// assert_eq!(map["poneyland"], 37);
2967 #[stable(feature = "rust1", since = "1.0.0")]
2968 pub fn insert(self, value: V) -> &'a mut V {
2969 self.base.insert(value)
2972 /// Sets the value of the entry with the `VacantEntry`'s key,
2973 /// and returns an `OccupiedEntry`.
2978 /// #![feature(entry_insert)]
2979 /// use std::collections::HashMap;
2980 /// use std::collections::hash_map::Entry;
2982 /// let mut map: HashMap<&str, u32> = HashMap::new();
2984 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2985 /// o.insert_entry(37);
2987 /// assert_eq!(map["poneyland"], 37);
2990 #[unstable(feature = "entry_insert", issue = "65225")]
2991 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2992 let base = self.base.insert_entry(value);
2993 OccupiedEntry { base }
2997 #[stable(feature = "rust1", since = "1.0.0")]
2998 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3001 S: BuildHasher + Default,
3003 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3004 let mut map = HashMap::with_hasher(Default::default());
3010 /// Inserts all new key-values from the iterator and replaces values with existing
3011 /// keys with new values returned from the iterator.
3012 #[stable(feature = "rust1", since = "1.0.0")]
3013 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3019 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3020 self.base.extend(iter)
3024 fn extend_one(&mut self, (k, v): (K, V)) {
3025 self.base.insert(k, v);
3029 fn extend_reserve(&mut self, additional: usize) {
3030 self.base.extend_reserve(additional);
3034 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3035 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3037 K: Eq + Hash + Copy,
3042 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3043 self.base.extend(iter)
3047 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
3048 self.base.insert(k, v);
3052 fn extend_reserve(&mut self, additional: usize) {
3053 Extend::<(K, V)>::extend_reserve(self, additional)
3057 /// `RandomState` is the default state for [`HashMap`] types.
3059 /// A particular instance `RandomState` will create the same instances of
3060 /// [`Hasher`], but the hashers created by two different `RandomState`
3061 /// instances are unlikely to produce the same result for the same values.
3066 /// use std::collections::HashMap;
3067 /// use std::collections::hash_map::RandomState;
3069 /// let s = RandomState::new();
3070 /// let mut map = HashMap::with_hasher(s);
3071 /// map.insert(1, 2);
3074 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3075 pub struct RandomState {
3081 /// Constructs a new `RandomState` that is initialized with random keys.
3086 /// use std::collections::hash_map::RandomState;
3088 /// let s = RandomState::new();
3091 #[allow(deprecated)]
3094 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3095 pub fn new() -> RandomState {
3096 // Historically this function did not cache keys from the OS and instead
3097 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3098 // was discovered, however, that because we re-seed the thread-local RNG
3099 // from the OS periodically that this can cause excessive slowdown when
3100 // many hash maps are created on a thread. To solve this performance
3101 // trap we cache the first set of randomly generated keys per-thread.
3103 // Later in #36481 it was discovered that exposing a deterministic
3104 // iteration order allows a form of DOS attack. To counter that we
3105 // increment one of the seeds on every RandomState creation, giving
3106 // every corresponding HashMap a different iteration order.
3107 thread_local!(static KEYS: Cell<(u64, u64)> = {
3108 Cell::new(sys::hashmap_random_keys())
3112 let (k0, k1) = keys.get();
3113 keys.set((k0.wrapping_add(1), k1));
3114 RandomState { k0, k1 }
3119 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3120 impl BuildHasher for RandomState {
3121 type Hasher = DefaultHasher;
3123 #[allow(deprecated)]
3124 fn build_hasher(&self) -> DefaultHasher {
3125 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3129 /// The default [`Hasher`] used by [`RandomState`].
3131 /// The internal algorithm is not specified, and so it and its hashes should
3132 /// not be relied upon over releases.
3133 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3134 #[allow(deprecated)]
3135 #[derive(Clone, Debug)]
3136 pub struct DefaultHasher(SipHasher13);
3138 impl DefaultHasher {
3139 /// Creates a new `DefaultHasher`.
3141 /// This hasher is not guaranteed to be the same as all other
3142 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3143 /// instances created through `new` or `default`.
3144 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3146 #[allow(deprecated)]
3148 pub fn new() -> DefaultHasher {
3149 DefaultHasher(SipHasher13::new_with_keys(0, 0))
3153 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3154 impl Default for DefaultHasher {
3155 /// Creates a new `DefaultHasher` using [`new`].
3156 /// See its documentation for more.
3158 /// [`new`]: DefaultHasher::new
3160 fn default() -> DefaultHasher {
3161 DefaultHasher::new()
3165 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3166 impl Hasher for DefaultHasher {
3167 // The underlying `SipHasher13` doesn't override the other
3168 // `write_*` methods, so it's ok not to forward them here.
3171 fn write(&mut self, msg: &[u8]) {
3176 fn write_str(&mut self, s: &str) {
3177 self.0.write_str(s);
3181 fn finish(&self) -> u64 {
3186 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3187 impl Default for RandomState {
3188 /// Constructs a new `RandomState`.
3190 fn default() -> RandomState {
3195 #[stable(feature = "std_debug", since = "1.16.0")]
3196 impl fmt::Debug for RandomState {
3197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3198 f.debug_struct("RandomState").finish_non_exhaustive()
3203 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
3205 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
3206 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
3211 pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
3213 hashbrown::TryReserveError::CapacityOverflow => {
3214 TryReserveErrorKind::CapacityOverflow.into()
3216 hashbrown::TryReserveError::AllocError { layout } => {
3217 TryReserveErrorKind::AllocError { layout, non_exhaustive: () }.into()
3223 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
3224 raw: base::RawEntryMut<'a, K, V, S>,
3225 ) -> RawEntryMut<'a, K, V, S> {
3227 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
3228 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
3233 fn assert_covariance() {
3234 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3237 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3240 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3243 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3246 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3249 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3252 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3255 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3258 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3261 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3265 d: Drain<'static, &'static str, &'static str>,
3266 ) -> Drain<'new, &'new str, &'new str> {