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();
169 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
170 /// We must also derive [`PartialEq`].
172 /// [`RefCell`]: crate::cell::RefCell
173 /// [`Cell`]: crate::cell::Cell
174 /// [`default`]: Default::default
175 /// [`with_hasher`]: Self::with_hasher
176 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
179 /// use std::collections::HashMap;
181 /// #[derive(Hash, Eq, PartialEq, Debug)]
188 /// /// Creates a new Viking.
189 /// fn new(name: &str, country: &str) -> Viking {
190 /// Viking { name: name.to_string(), country: country.to_string() }
194 /// // Use a HashMap to store the vikings' health points.
195 /// let vikings = HashMap::from([
196 /// (Viking::new("Einar", "Norway"), 25),
197 /// (Viking::new("Olaf", "Denmark"), 24),
198 /// (Viking::new("Harald", "Iceland"), 12),
201 /// // Use derived implementation to print the status of the vikings.
202 /// for (viking, health) in &vikings {
203 /// println!("{viking:?} has {health} hp");
207 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]
208 #[stable(feature = "rust1", since = "1.0.0")]
209 #[rustc_insignificant_dtor]
210 pub struct HashMap<K, V, S = RandomState> {
211 base: base::HashMap<K, V, S>,
214 impl<K, V> HashMap<K, V, RandomState> {
215 /// Creates an empty `HashMap`.
217 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
218 /// is first inserted into.
223 /// use std::collections::HashMap;
224 /// let mut map: HashMap<&str, i32> = HashMap::new();
228 #[stable(feature = "rust1", since = "1.0.0")]
229 pub fn new() -> HashMap<K, V, RandomState> {
233 /// Creates an empty `HashMap` with the specified capacity.
235 /// The hash map will be able to hold at least `capacity` elements without
236 /// reallocating. If `capacity` is 0, the hash map will not allocate.
241 /// use std::collections::HashMap;
242 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
248 HashMap::with_capacity_and_hasher(capacity, Default::default())
252 impl<K, V, S> HashMap<K, V, S> {
253 /// Creates an empty `HashMap` which will use the given hash builder to hash
256 /// The created map has the default initial capacity.
258 /// Warning: `hash_builder` is normally randomly generated, and
259 /// is designed to allow HashMaps to be resistant to attacks that
260 /// cause many collisions and very poor performance. Setting it
261 /// manually using this function can expose a DoS attack vector.
263 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
264 /// the HashMap to be useful, see its documentation for details.
269 /// use std::collections::HashMap;
270 /// use std::collections::hash_map::RandomState;
272 /// let s = RandomState::new();
273 /// let mut map = HashMap::with_hasher(s);
274 /// map.insert(1, 2);
277 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
278 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
279 HashMap { base: base::HashMap::with_hasher(hash_builder) }
282 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
283 /// to hash the keys.
285 /// The hash map will be able to hold at least `capacity` elements without
286 /// reallocating. If `capacity` is 0, the hash map will not allocate.
288 /// Warning: `hash_builder` is normally randomly generated, and
289 /// is designed to allow HashMaps to be resistant to attacks that
290 /// cause many collisions and very poor performance. Setting it
291 /// manually using this function can expose a DoS attack vector.
293 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
294 /// the HashMap to be useful, see its documentation for details.
299 /// use std::collections::HashMap;
300 /// use std::collections::hash_map::RandomState;
302 /// let s = RandomState::new();
303 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
304 /// map.insert(1, 2);
307 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
308 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
309 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
312 /// Returns the number of elements the map can hold without reallocating.
314 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
315 /// more, but is guaranteed to be able to hold at least this many.
320 /// use std::collections::HashMap;
321 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
322 /// assert!(map.capacity() >= 100);
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn capacity(&self) -> usize {
330 /// An iterator visiting all keys in arbitrary order.
331 /// The iterator element type is `&'a K`.
336 /// use std::collections::HashMap;
338 /// let map = HashMap::from([
344 /// for key in map.keys() {
345 /// println!("{key}");
351 /// In the current implementation, iterating over keys takes O(capacity) time
352 /// instead of O(len) because it internally visits empty buckets too.
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn keys(&self) -> Keys<'_, K, V> {
355 Keys { inner: self.iter() }
358 /// Creates a consuming iterator visiting all the keys in arbitrary order.
359 /// The map cannot be used after calling this.
360 /// The iterator element type is `K`.
365 /// use std::collections::HashMap;
367 /// let map = HashMap::from([
373 /// let mut vec: Vec<&str> = map.into_keys().collect();
374 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
375 /// // keys must be sorted to test them against a sorted array.
376 /// vec.sort_unstable();
377 /// assert_eq!(vec, ["a", "b", "c"]);
382 /// In the current implementation, iterating over keys takes O(capacity) time
383 /// instead of O(len) because it internally visits empty buckets too.
385 #[rustc_lint_query_instability]
386 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
387 pub fn into_keys(self) -> IntoKeys<K, V> {
388 IntoKeys { inner: self.into_iter() }
391 /// An iterator visiting all values in arbitrary order.
392 /// The iterator element type is `&'a V`.
397 /// use std::collections::HashMap;
399 /// let map = HashMap::from([
405 /// for val in map.values() {
406 /// println!("{val}");
412 /// In the current implementation, iterating over values takes O(capacity) time
413 /// instead of O(len) because it internally visits empty buckets too.
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn values(&self) -> Values<'_, K, V> {
416 Values { inner: self.iter() }
419 /// An iterator visiting all values mutably in arbitrary order.
420 /// The iterator element type is `&'a mut V`.
425 /// use std::collections::HashMap;
427 /// let mut map = HashMap::from([
433 /// for val in map.values_mut() {
434 /// *val = *val + 10;
437 /// for val in map.values() {
438 /// println!("{val}");
444 /// In the current implementation, iterating over values takes O(capacity) time
445 /// instead of O(len) because it internally visits empty buckets too.
446 #[stable(feature = "map_values_mut", since = "1.10.0")]
447 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
448 ValuesMut { inner: self.iter_mut() }
451 /// Creates a consuming iterator visiting all the values in arbitrary order.
452 /// The map cannot be used after calling this.
453 /// The iterator element type is `V`.
458 /// use std::collections::HashMap;
460 /// let map = HashMap::from([
466 /// let mut vec: Vec<i32> = map.into_values().collect();
467 /// // The `IntoValues` iterator produces values in arbitrary order, so
468 /// // the values must be sorted to test them against a sorted array.
469 /// vec.sort_unstable();
470 /// assert_eq!(vec, [1, 2, 3]);
475 /// In the current implementation, iterating over values takes O(capacity) time
476 /// instead of O(len) because it internally visits empty buckets too.
478 #[rustc_lint_query_instability]
479 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
480 pub fn into_values(self) -> IntoValues<K, V> {
481 IntoValues { inner: self.into_iter() }
484 /// An iterator visiting all key-value pairs in arbitrary order.
485 /// The iterator element type is `(&'a K, &'a V)`.
490 /// use std::collections::HashMap;
492 /// let map = HashMap::from([
498 /// for (key, val) in map.iter() {
499 /// println!("key: {key} val: {val}");
505 /// In the current implementation, iterating over map takes O(capacity) time
506 /// instead of O(len) because it internally visits empty buckets too.
507 #[rustc_lint_query_instability]
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn iter(&self) -> Iter<'_, K, V> {
510 Iter { base: self.base.iter() }
513 /// An iterator visiting all key-value pairs in arbitrary order,
514 /// with mutable references to the values.
515 /// The iterator element type is `(&'a K, &'a mut V)`.
520 /// use std::collections::HashMap;
522 /// let mut map = HashMap::from([
528 /// // Update all values
529 /// for (_, val) in map.iter_mut() {
533 /// for (key, val) in &map {
534 /// println!("key: {key} val: {val}");
540 /// In the current implementation, iterating over map takes O(capacity) time
541 /// instead of O(len) because it internally visits empty buckets too.
542 #[rustc_lint_query_instability]
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
545 IterMut { base: self.base.iter_mut() }
548 /// Returns the number of elements in the map.
553 /// use std::collections::HashMap;
555 /// let mut a = HashMap::new();
556 /// assert_eq!(a.len(), 0);
557 /// a.insert(1, "a");
558 /// assert_eq!(a.len(), 1);
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn len(&self) -> usize {
565 /// Returns `true` if the map contains no elements.
570 /// use std::collections::HashMap;
572 /// let mut a = HashMap::new();
573 /// assert!(a.is_empty());
574 /// a.insert(1, "a");
575 /// assert!(!a.is_empty());
578 #[stable(feature = "rust1", since = "1.0.0")]
579 pub fn is_empty(&self) -> bool {
583 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
584 /// allocated memory for reuse.
586 /// If the returned iterator is dropped before being fully consumed, it
587 /// drops the remaining key-value pairs. The returned iterator keeps a
588 /// mutable borrow on the vector to optimize its implementation.
593 /// use std::collections::HashMap;
595 /// let mut a = HashMap::new();
596 /// a.insert(1, "a");
597 /// a.insert(2, "b");
599 /// for (k, v) in a.drain().take(1) {
600 /// assert!(k == 1 || k == 2);
601 /// assert!(v == "a" || v == "b");
604 /// assert!(a.is_empty());
607 #[rustc_lint_query_instability]
608 #[stable(feature = "drain", since = "1.6.0")]
609 pub fn drain(&mut self) -> Drain<'_, K, V> {
610 Drain { base: self.base.drain() }
613 /// Creates an iterator which uses a closure to determine if an element should be removed.
615 /// If the closure returns true, the element is removed from the map and yielded.
616 /// If the closure returns false, or panics, the element remains in the map and will not be
619 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
620 /// whether you choose to keep or remove it.
622 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
623 /// elements will still be subjected to the closure and removed and dropped if it returns true.
625 /// It is unspecified how many more elements will be subjected to the closure
626 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
627 /// or if the `DrainFilter` value is leaked.
631 /// Splitting a map into even and odd keys, reusing the original map:
634 /// #![feature(hash_drain_filter)]
635 /// use std::collections::HashMap;
637 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
638 /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
640 /// let mut evens = drained.keys().copied().collect::<Vec<_>>();
641 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
645 /// assert_eq!(evens, vec![0, 2, 4, 6]);
646 /// assert_eq!(odds, vec![1, 3, 5, 7]);
649 #[rustc_lint_query_instability]
650 #[unstable(feature = "hash_drain_filter", issue = "59618")]
651 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
653 F: FnMut(&K, &mut V) -> bool,
655 DrainFilter { base: self.base.drain_filter(pred) }
658 /// Retains only the elements specified by the predicate.
660 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
661 /// The elements are visited in unsorted (and unspecified) order.
666 /// use std::collections::HashMap;
668 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
669 /// map.retain(|&k, _| k % 2 == 0);
670 /// assert_eq!(map.len(), 4);
675 /// In the current implementation, this operation takes O(capacity) time
676 /// instead of O(len) because it internally visits empty buckets too.
678 #[rustc_lint_query_instability]
679 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
680 pub fn retain<F>(&mut self, f: F)
682 F: FnMut(&K, &mut V) -> bool,
687 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
693 /// use std::collections::HashMap;
695 /// let mut a = HashMap::new();
696 /// a.insert(1, "a");
698 /// assert!(a.is_empty());
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn clear(&mut self) {
706 /// Returns a reference to the map's [`BuildHasher`].
711 /// use std::collections::HashMap;
712 /// use std::collections::hash_map::RandomState;
714 /// let hasher = RandomState::new();
715 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
716 /// let hasher: &RandomState = map.hasher();
719 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
720 pub fn hasher(&self) -> &S {
725 impl<K, V, S> HashMap<K, V, S>
730 /// Reserves capacity for at least `additional` more elements to be inserted
731 /// in the `HashMap`. The collection may reserve more space to avoid
732 /// frequent reallocations.
736 /// Panics if the new allocation size overflows [`usize`].
741 /// use std::collections::HashMap;
742 /// let mut map: HashMap<&str, i32> = HashMap::new();
746 #[stable(feature = "rust1", since = "1.0.0")]
747 pub fn reserve(&mut self, additional: usize) {
748 self.base.reserve(additional)
751 /// Tries to reserve capacity for at least `additional` more elements to be inserted
752 /// in the given `HashMap<K, V>`. The collection may reserve more space to avoid
753 /// frequent reallocations.
757 /// If the capacity overflows, or the allocator reports a failure, then an error
763 /// use std::collections::HashMap;
765 /// let mut map: HashMap<&str, isize> = HashMap::new();
766 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
769 #[stable(feature = "try_reserve", since = "1.57.0")]
770 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
771 self.base.try_reserve(additional).map_err(map_try_reserve_error)
774 /// Shrinks the capacity of the map as much as possible. It will drop
775 /// down as much as possible while maintaining the internal rules
776 /// and possibly leaving some space in accordance with the resize policy.
781 /// use std::collections::HashMap;
783 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
784 /// map.insert(1, 2);
785 /// map.insert(3, 4);
786 /// assert!(map.capacity() >= 100);
787 /// map.shrink_to_fit();
788 /// assert!(map.capacity() >= 2);
791 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn shrink_to_fit(&mut self) {
793 self.base.shrink_to_fit();
796 /// Shrinks the capacity of the map with a lower limit. It will drop
797 /// down no lower than the supplied limit while maintaining the internal rules
798 /// and possibly leaving some space in accordance with the resize policy.
800 /// If the current capacity is less than the lower limit, this is a no-op.
805 /// use std::collections::HashMap;
807 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
808 /// map.insert(1, 2);
809 /// map.insert(3, 4);
810 /// assert!(map.capacity() >= 100);
811 /// map.shrink_to(10);
812 /// assert!(map.capacity() >= 10);
813 /// map.shrink_to(0);
814 /// assert!(map.capacity() >= 2);
817 #[stable(feature = "shrink_to", since = "1.56.0")]
818 pub fn shrink_to(&mut self, min_capacity: usize) {
819 self.base.shrink_to(min_capacity);
822 /// Gets the given key's corresponding entry in the map for in-place manipulation.
827 /// use std::collections::HashMap;
829 /// let mut letters = HashMap::new();
831 /// for ch in "a short treatise on fungi".chars() {
832 /// let counter = letters.entry(ch).or_insert(0);
836 /// assert_eq!(letters[&'s'], 2);
837 /// assert_eq!(letters[&'t'], 3);
838 /// assert_eq!(letters[&'u'], 1);
839 /// assert_eq!(letters.get(&'y'), None);
842 #[stable(feature = "rust1", since = "1.0.0")]
843 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
844 map_entry(self.base.rustc_entry(key))
847 /// Returns a reference to the value corresponding to the key.
849 /// The key may be any borrowed form of the map's key type, but
850 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
856 /// use std::collections::HashMap;
858 /// let mut map = HashMap::new();
859 /// map.insert(1, "a");
860 /// assert_eq!(map.get(&1), Some(&"a"));
861 /// assert_eq!(map.get(&2), None);
863 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
873 /// Returns the key-value pair corresponding to the supplied key.
875 /// The supplied key may be any borrowed form of the map's key type, but
876 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
882 /// use std::collections::HashMap;
884 /// let mut map = HashMap::new();
885 /// map.insert(1, "a");
886 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
887 /// assert_eq!(map.get_key_value(&2), None);
890 #[stable(feature = "map_get_key_value", since = "1.40.0")]
891 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
896 self.base.get_key_value(k)
899 /// Attempts to get mutable references to `N` values in the map at once.
901 /// Returns an array of length `N` with the results of each query. For soundness, at most one
902 /// mutable reference will be returned to any value. `None` will be returned if any of the
903 /// keys are duplicates or missing.
908 /// #![feature(map_many_mut)]
909 /// use std::collections::HashMap;
911 /// let mut libraries = HashMap::new();
912 /// libraries.insert("Bodleian Library".to_string(), 1602);
913 /// libraries.insert("Athenæum".to_string(), 1807);
914 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
915 /// libraries.insert("Library of Congress".to_string(), 1800);
917 /// let got = libraries.get_many_mut([
919 /// "Library of Congress",
929 /// // Missing keys result in None
930 /// let got = libraries.get_many_mut([
932 /// "New York Public Library",
934 /// assert_eq!(got, None);
936 /// // Duplicate keys result in None
937 /// let got = libraries.get_many_mut([
941 /// assert_eq!(got, None);
944 #[unstable(feature = "map_many_mut", issue = "97601")]
945 pub fn get_many_mut<Q: ?Sized, const N: usize>(&mut self, ks: [&Q; N]) -> Option<[&'_ mut V; N]>
950 self.base.get_many_mut(ks)
953 /// Attempts to get mutable references to `N` values in the map at once, without validating that
954 /// the values are unique.
956 /// Returns an array of length `N` with the results of each query. `None` will be returned if
957 /// any of the keys are missing.
959 /// For a safe alternative see [`get_many_mut`](Self::get_many_mut).
963 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
964 /// references are not used.
966 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
971 /// #![feature(map_many_mut)]
972 /// use std::collections::HashMap;
974 /// let mut libraries = HashMap::new();
975 /// libraries.insert("Bodleian Library".to_string(), 1602);
976 /// libraries.insert("Athenæum".to_string(), 1807);
977 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
978 /// libraries.insert("Library of Congress".to_string(), 1800);
980 /// let got = libraries.get_many_mut([
982 /// "Library of Congress",
992 /// // Missing keys result in None
993 /// let got = libraries.get_many_mut([
995 /// "New York Public Library",
997 /// assert_eq!(got, None);
1000 #[unstable(feature = "map_many_mut", issue = "97601")]
1001 pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>(
1004 ) -> Option<[&'_ mut V; N]>
1009 self.base.get_many_unchecked_mut(ks)
1012 /// Returns `true` if the map contains a value for the specified key.
1014 /// The key may be any borrowed form of the map's key type, but
1015 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1021 /// use std::collections::HashMap;
1023 /// let mut map = HashMap::new();
1024 /// map.insert(1, "a");
1025 /// assert_eq!(map.contains_key(&1), true);
1026 /// assert_eq!(map.contains_key(&2), false);
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1035 self.base.contains_key(k)
1038 /// Returns a mutable reference to the value corresponding to the key.
1040 /// The key may be any borrowed form of the map's key type, but
1041 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1047 /// use std::collections::HashMap;
1049 /// let mut map = HashMap::new();
1050 /// map.insert(1, "a");
1051 /// if let Some(x) = map.get_mut(&1) {
1054 /// assert_eq!(map[&1], "b");
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1063 self.base.get_mut(k)
1066 /// Inserts a key-value pair into the map.
1068 /// If the map did not have this key present, [`None`] is returned.
1070 /// If the map did have this key present, the value is updated, and the old
1071 /// value is returned. The key is not updated, though; this matters for
1072 /// types that can be `==` without being identical. See the [module-level
1073 /// documentation] for more.
1075 /// [module-level documentation]: crate::collections#insert-and-complex-keys
1080 /// use std::collections::HashMap;
1082 /// let mut map = HashMap::new();
1083 /// assert_eq!(map.insert(37, "a"), None);
1084 /// assert_eq!(map.is_empty(), false);
1086 /// map.insert(37, "b");
1087 /// assert_eq!(map.insert(37, "c"), Some("b"));
1088 /// assert_eq!(map[&37], "c");
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1093 self.base.insert(k, v)
1096 /// Tries to insert a key-value pair into the map, and returns
1097 /// a mutable reference to the value in the entry.
1099 /// If the map already had this key present, nothing is updated, and
1100 /// an error containing the occupied entry and the value is returned.
1107 /// #![feature(map_try_insert)]
1109 /// use std::collections::HashMap;
1111 /// let mut map = HashMap::new();
1112 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1114 /// let err = map.try_insert(37, "b").unwrap_err();
1115 /// assert_eq!(err.entry.key(), &37);
1116 /// assert_eq!(err.entry.get(), &"a");
1117 /// assert_eq!(err.value, "b");
1119 #[unstable(feature = "map_try_insert", issue = "82766")]
1120 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>> {
1121 match self.entry(key) {
1122 Occupied(entry) => Err(OccupiedError { entry, value }),
1123 Vacant(entry) => Ok(entry.insert(value)),
1127 /// Removes a key from the map, returning the value at the key if the key
1128 /// was previously in the map.
1130 /// The key may be any borrowed form of the map's key type, but
1131 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1137 /// use std::collections::HashMap;
1139 /// let mut map = HashMap::new();
1140 /// map.insert(1, "a");
1141 /// assert_eq!(map.remove(&1), Some("a"));
1142 /// assert_eq!(map.remove(&1), None);
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1154 /// Removes a key from the map, returning the stored key and value if the
1155 /// key was previously in the map.
1157 /// The key may be any borrowed form of the map's key type, but
1158 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1164 /// use std::collections::HashMap;
1167 /// let mut map = HashMap::new();
1168 /// map.insert(1, "a");
1169 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1170 /// assert_eq!(map.remove(&1), None);
1174 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1175 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1180 self.base.remove_entry(k)
1184 impl<K, V, S> HashMap<K, V, S>
1188 /// Creates a raw entry builder for the HashMap.
1190 /// Raw entries provide the lowest level of control for searching and
1191 /// manipulating a map. They must be manually initialized with a hash and
1192 /// then manually searched. After this, insertions into a vacant entry
1193 /// still require an owned key to be provided.
1195 /// Raw entries are useful for such exotic situations as:
1197 /// * Hash memoization
1198 /// * Deferring the creation of an owned key until it is known to be required
1199 /// * Using a search key that doesn't work with the Borrow trait
1200 /// * Using custom comparison logic without newtype wrappers
1202 /// Because raw entries provide much more low-level control, it's much easier
1203 /// to put the HashMap into an inconsistent state which, while memory-safe,
1204 /// will cause the map to produce seemingly random results. Higher-level and
1205 /// more foolproof APIs like `entry` should be preferred when possible.
1207 /// In particular, the hash used to initialized the raw entry must still be
1208 /// consistent with the hash of the key that is ultimately stored in the entry.
1209 /// This is because implementations of HashMap may need to recompute hashes
1210 /// when resizing, at which point only the keys are available.
1212 /// Raw entries give mutable access to the keys. This must not be used
1213 /// to modify how the key would compare or hash, as the map will not re-evaluate
1214 /// where the key should go, meaning the keys may become "lost" if their
1215 /// location does not reflect their state. For instance, if you change a key
1216 /// so that the map now contains keys which compare equal, search may start
1217 /// acting erratically, with two keys randomly masking each other. Implementations
1218 /// are free to assume this doesn't happen (within the limits of memory-safety).
1220 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1221 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
1222 RawEntryBuilderMut { map: self }
1225 /// Creates a raw immutable entry builder for the HashMap.
1227 /// Raw entries provide the lowest level of control for searching and
1228 /// manipulating a map. They must be manually initialized with a hash and
1229 /// then manually searched.
1231 /// This is useful for
1232 /// * Hash memoization
1233 /// * Using a search key that doesn't work with the Borrow trait
1234 /// * Using custom comparison logic without newtype wrappers
1236 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1237 /// `get` should be preferred.
1239 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1241 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1242 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
1243 RawEntryBuilder { map: self }
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl<K, V, S> Clone for HashMap<K, V, S>
1255 fn clone(&self) -> Self {
1256 Self { base: self.base.clone() }
1260 fn clone_from(&mut self, other: &Self) {
1261 self.base.clone_from(&other.base);
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 impl<K, V, S> PartialEq for HashMap<K, V, S>
1272 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1273 if self.len() != other.len() {
1277 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<K, V, S> Eq for HashMap<K, V, S>
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 impl<K, V, S> Debug for HashMap<K, V, S>
1296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1297 f.debug_map().entries(self.iter()).finish()
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<K, V, S> Default for HashMap<K, V, S>
1306 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1308 fn default() -> HashMap<K, V, S> {
1309 HashMap::with_hasher(Default::default())
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1316 K: Eq + Hash + Borrow<Q>,
1322 /// Returns a reference to the value corresponding to the supplied key.
1326 /// Panics if the key is not present in the `HashMap`.
1328 fn index(&self, key: &Q) -> &V {
1329 self.get(key).expect("no entry found for key")
1333 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1334 // Note: as what is currently the most convenient built-in way to construct
1335 // a HashMap, a simple usage of this function must not *require* the user
1336 // to provide a type annotation in order to infer the third type parameter
1337 // (the hasher parameter, conventionally "S").
1338 // To that end, this impl is defined using RandomState as the concrete
1339 // type of S, rather than being generic over `S: BuildHasher + Default`.
1340 // It is expected that users who want to specify a hasher will manually use
1341 // `with_capacity_and_hasher`.
1342 // If type parameter defaults worked on impls, and if type parameter
1343 // defaults could be mixed with const generics, then perhaps
1344 // this could be generalized.
1345 // See also the equivalent impl on HashSet.
1346 impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
1353 /// use std::collections::HashMap;
1355 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1356 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1357 /// assert_eq!(map1, map2);
1359 fn from(arr: [(K, V); N]) -> Self {
1360 Self::from_iter(arr)
1364 /// An iterator over the entries of a `HashMap`.
1366 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1367 /// documentation for more.
1369 /// [`iter`]: HashMap::iter
1374 /// use std::collections::HashMap;
1376 /// let map = HashMap::from([
1379 /// let iter = map.iter();
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 pub struct Iter<'a, K: 'a, V: 'a> {
1383 base: base::Iter<'a, K, V>,
1386 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 impl<K, V> Clone for Iter<'_, K, V> {
1390 fn clone(&self) -> Self {
1391 Iter { base: self.base.clone() }
1395 #[stable(feature = "std_debug", since = "1.16.0")]
1396 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1398 f.debug_list().entries(self.clone()).finish()
1402 /// A mutable iterator over the entries of a `HashMap`.
1404 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1405 /// documentation for more.
1407 /// [`iter_mut`]: HashMap::iter_mut
1412 /// use std::collections::HashMap;
1414 /// let mut map = HashMap::from([
1417 /// let iter = map.iter_mut();
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 pub struct IterMut<'a, K: 'a, V: 'a> {
1421 base: base::IterMut<'a, K, V>,
1424 impl<'a, K, V> IterMut<'a, K, V> {
1425 /// Returns an iterator of references over the remaining items.
1427 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1428 Iter { base: self.base.rustc_iter() }
1432 /// An owning iterator over the entries of a `HashMap`.
1434 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1435 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1437 /// [`into_iter`]: IntoIterator::into_iter
1438 /// [`IntoIterator`]: crate::iter::IntoIterator
1443 /// use std::collections::HashMap;
1445 /// let map = HashMap::from([
1448 /// let iter = map.into_iter();
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 pub struct IntoIter<K, V> {
1452 base: base::IntoIter<K, V>,
1455 impl<K, V> IntoIter<K, V> {
1456 /// Returns an iterator of references over the remaining items.
1458 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1459 Iter { base: self.base.rustc_iter() }
1463 /// An iterator over the keys of a `HashMap`.
1465 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1466 /// documentation for more.
1468 /// [`keys`]: HashMap::keys
1473 /// use std::collections::HashMap;
1475 /// let map = HashMap::from([
1478 /// let iter_keys = map.keys();
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub struct Keys<'a, K: 'a, V: 'a> {
1482 inner: Iter<'a, K, V>,
1485 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 impl<K, V> Clone for Keys<'_, K, V> {
1489 fn clone(&self) -> Self {
1490 Keys { inner: self.inner.clone() }
1494 #[stable(feature = "std_debug", since = "1.16.0")]
1495 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1497 f.debug_list().entries(self.clone()).finish()
1501 /// An iterator over the values of a `HashMap`.
1503 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1504 /// documentation for more.
1506 /// [`values`]: HashMap::values
1511 /// use std::collections::HashMap;
1513 /// let map = HashMap::from([
1516 /// let iter_values = map.values();
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 pub struct Values<'a, K: 'a, V: 'a> {
1520 inner: Iter<'a, K, V>,
1523 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl<K, V> Clone for Values<'_, K, V> {
1527 fn clone(&self) -> Self {
1528 Values { inner: self.inner.clone() }
1532 #[stable(feature = "std_debug", since = "1.16.0")]
1533 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1535 f.debug_list().entries(self.clone()).finish()
1539 /// A draining iterator over the entries of a `HashMap`.
1541 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1542 /// documentation for more.
1544 /// [`drain`]: HashMap::drain
1549 /// use std::collections::HashMap;
1551 /// let mut map = HashMap::from([
1554 /// let iter = map.drain();
1556 #[stable(feature = "drain", since = "1.6.0")]
1557 pub struct Drain<'a, K: 'a, V: 'a> {
1558 base: base::Drain<'a, K, V>,
1561 impl<'a, K, V> Drain<'a, K, V> {
1562 /// Returns an iterator of references over the remaining items.
1564 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1565 Iter { base: self.base.rustc_iter() }
1569 /// A draining, filtering iterator over the entries of a `HashMap`.
1571 /// This `struct` is created by the [`drain_filter`] method on [`HashMap`].
1573 /// [`drain_filter`]: HashMap::drain_filter
1578 /// #![feature(hash_drain_filter)]
1580 /// use std::collections::HashMap;
1582 /// let mut map = HashMap::from([
1585 /// let iter = map.drain_filter(|_k, v| *v % 2 == 0);
1587 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1588 pub struct DrainFilter<'a, K, V, F>
1590 F: FnMut(&K, &mut V) -> bool,
1592 base: base::DrainFilter<'a, K, V, F>,
1595 /// A mutable iterator over the values of a `HashMap`.
1597 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1598 /// documentation for more.
1600 /// [`values_mut`]: HashMap::values_mut
1605 /// use std::collections::HashMap;
1607 /// let mut map = HashMap::from([
1610 /// let iter_values = map.values_mut();
1612 #[stable(feature = "map_values_mut", since = "1.10.0")]
1613 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1614 inner: IterMut<'a, K, V>,
1617 /// An owning iterator over the keys of a `HashMap`.
1619 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1620 /// See its documentation for more.
1622 /// [`into_keys`]: HashMap::into_keys
1627 /// use std::collections::HashMap;
1629 /// let map = HashMap::from([
1632 /// let iter_keys = map.into_keys();
1634 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1635 pub struct IntoKeys<K, V> {
1636 inner: IntoIter<K, V>,
1639 /// An owning iterator over the values of a `HashMap`.
1641 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1642 /// See its documentation for more.
1644 /// [`into_values`]: HashMap::into_values
1649 /// use std::collections::HashMap;
1651 /// let map = HashMap::from([
1654 /// let iter_keys = map.into_values();
1656 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1657 pub struct IntoValues<K, V> {
1658 inner: IntoIter<K, V>,
1661 /// A builder for computing where in a HashMap a key-value pair would be stored.
1663 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1664 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1665 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1666 map: &'a mut HashMap<K, V, S>,
1669 /// A view into a single entry in a map, which may either be vacant or occupied.
1671 /// This is a lower-level version of [`Entry`].
1673 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1674 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1676 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1677 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1678 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1679 /// An occupied entry.
1680 Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1682 Vacant(RawVacantEntryMut<'a, K, V, S>),
1685 /// A view into an occupied entry in a `HashMap`.
1686 /// It is part of the [`RawEntryMut`] enum.
1687 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1688 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1689 base: base::RawOccupiedEntryMut<'a, K, V, S>,
1692 /// A view into a vacant entry in a `HashMap`.
1693 /// It is part of the [`RawEntryMut`] enum.
1694 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1695 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1696 base: base::RawVacantEntryMut<'a, K, V, S>,
1699 /// A builder for computing where in a HashMap a key-value pair would be stored.
1701 /// See the [`HashMap::raw_entry`] docs for usage examples.
1702 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1703 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1704 map: &'a HashMap<K, V, S>,
1707 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1711 /// Creates a `RawEntryMut` from the given key.
1713 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1714 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1719 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1722 /// Creates a `RawEntryMut` from the given key and its hash.
1724 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1725 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1730 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1733 /// Creates a `RawEntryMut` from the given hash.
1735 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1736 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1738 for<'b> F: FnMut(&'b K) -> bool,
1740 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1744 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1748 /// Access an entry by key.
1750 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1751 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1756 self.map.base.raw_entry().from_key(k)
1759 /// Access an entry by a key and its hash.
1761 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1762 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1767 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1770 /// Access an entry by hash.
1772 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1773 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1775 F: FnMut(&K) -> bool,
1777 self.map.base.raw_entry().from_hash(hash, is_match)
1781 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1782 /// Ensures a value is in the entry by inserting the default if empty, and returns
1783 /// mutable references to the key and value in the entry.
1788 /// #![feature(hash_raw_entry)]
1789 /// use std::collections::HashMap;
1791 /// let mut map: HashMap<&str, u32> = HashMap::new();
1793 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1794 /// assert_eq!(map["poneyland"], 3);
1796 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1797 /// assert_eq!(map["poneyland"], 6);
1800 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1801 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1807 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1808 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1812 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1813 /// and returns mutable references to the key and value in the entry.
1818 /// #![feature(hash_raw_entry)]
1819 /// use std::collections::HashMap;
1821 /// let mut map: HashMap<&str, String> = HashMap::new();
1823 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1824 /// ("poneyland", "hoho".to_string())
1827 /// assert_eq!(map["poneyland"], "hoho".to_string());
1830 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1831 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1833 F: FnOnce() -> (K, V),
1838 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1839 RawEntryMut::Vacant(entry) => {
1840 let (k, v) = default();
1846 /// Provides in-place mutable access to an occupied entry before any
1847 /// potential inserts into the map.
1852 /// #![feature(hash_raw_entry)]
1853 /// use std::collections::HashMap;
1855 /// let mut map: HashMap<&str, u32> = HashMap::new();
1857 /// map.raw_entry_mut()
1858 /// .from_key("poneyland")
1859 /// .and_modify(|_k, v| { *v += 1 })
1860 /// .or_insert("poneyland", 42);
1861 /// assert_eq!(map["poneyland"], 42);
1863 /// map.raw_entry_mut()
1864 /// .from_key("poneyland")
1865 /// .and_modify(|_k, v| { *v += 1 })
1866 /// .or_insert("poneyland", 0);
1867 /// assert_eq!(map["poneyland"], 43);
1870 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1871 pub fn and_modify<F>(self, f: F) -> Self
1873 F: FnOnce(&mut K, &mut V),
1876 RawEntryMut::Occupied(mut entry) => {
1878 let (k, v) = entry.get_key_value_mut();
1881 RawEntryMut::Occupied(entry)
1883 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1888 impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1889 /// Gets a reference to the key in the entry.
1892 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1893 pub fn key(&self) -> &K {
1897 /// Gets a mutable reference to the key in the entry.
1900 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1901 pub fn key_mut(&mut self) -> &mut K {
1905 /// Converts the entry into a mutable reference to the key in the entry
1906 /// with a lifetime bound to the map itself.
1908 #[must_use = "`self` will be dropped if the result is not used"]
1909 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1910 pub fn into_key(self) -> &'a mut K {
1911 self.base.into_key()
1914 /// Gets a reference to the value in the entry.
1917 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1918 pub fn get(&self) -> &V {
1922 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
1923 /// with a lifetime bound to the map itself.
1925 #[must_use = "`self` will be dropped if the result is not used"]
1926 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1927 pub fn into_mut(self) -> &'a mut V {
1928 self.base.into_mut()
1931 /// Gets a mutable reference to the value in the entry.
1934 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1935 pub fn get_mut(&mut self) -> &mut V {
1939 /// Gets a reference to the key and value in the entry.
1942 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1943 pub fn get_key_value(&mut self) -> (&K, &V) {
1944 self.base.get_key_value()
1947 /// Gets a mutable reference to the key and value in the entry.
1949 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1950 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1951 self.base.get_key_value_mut()
1954 /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry
1955 /// with a lifetime bound to the map itself.
1957 #[must_use = "`self` will be dropped if the result is not used"]
1958 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1959 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1960 self.base.into_key_value()
1963 /// Sets the value of the entry, and returns the entry's old value.
1965 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1966 pub fn insert(&mut self, value: V) -> V {
1967 self.base.insert(value)
1970 /// Sets the value of the entry, and returns the entry's old value.
1972 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1973 pub fn insert_key(&mut self, key: K) -> K {
1974 self.base.insert_key(key)
1977 /// Takes the value out of the entry, and returns it.
1979 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1980 pub fn remove(self) -> V {
1984 /// Take the ownership of the key and value from the map.
1986 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1987 pub fn remove_entry(self) -> (K, V) {
1988 self.base.remove_entry()
1992 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1993 /// Sets the value of the entry with the `VacantEntry`'s key,
1994 /// and returns a mutable reference to it.
1996 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1997 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2002 self.base.insert(key, value)
2005 /// Sets the value of the entry with the VacantEntry's key,
2006 /// and returns a mutable reference to it.
2008 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2009 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
2014 self.base.insert_hashed_nocheck(hash, key, value)
2018 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2019 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
2020 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2021 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
2025 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2026 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
2027 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2029 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
2030 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
2035 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2036 impl<K: Debug, V: Debug, S> Debug for RawOccupiedEntryMut<'_, K, V, S> {
2037 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2038 f.debug_struct("RawOccupiedEntryMut")
2039 .field("key", self.key())
2040 .field("value", self.get())
2041 .finish_non_exhaustive()
2045 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2046 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
2047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2048 f.debug_struct("RawVacantEntryMut").finish_non_exhaustive()
2052 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2053 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
2054 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2055 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
2059 /// A view into a single entry in a map, which may either be vacant or occupied.
2061 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2063 /// [`entry`]: HashMap::entry
2064 #[stable(feature = "rust1", since = "1.0.0")]
2065 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
2066 pub enum Entry<'a, K: 'a, V: 'a> {
2067 /// An occupied entry.
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
2076 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2077 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
2078 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2080 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2081 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2086 /// A view into an occupied entry in a `HashMap`.
2087 /// It is part of the [`Entry`] enum.
2088 #[stable(feature = "rust1", since = "1.0.0")]
2089 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2090 base: base::RustcOccupiedEntry<'a, K, V>,
2093 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2094 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
2095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2096 f.debug_struct("OccupiedEntry")
2097 .field("key", self.key())
2098 .field("value", self.get())
2099 .finish_non_exhaustive()
2103 /// A view into a vacant entry in a `HashMap`.
2104 /// It is part of the [`Entry`] enum.
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 pub struct VacantEntry<'a, K: 'a, V: 'a> {
2107 base: base::RustcVacantEntry<'a, K, V>,
2110 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2111 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
2112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2113 f.debug_tuple("VacantEntry").field(self.key()).finish()
2117 /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
2119 /// Contains the occupied entry, and the value that was not inserted.
2120 #[unstable(feature = "map_try_insert", issue = "82766")]
2121 pub struct OccupiedError<'a, K: 'a, V: 'a> {
2122 /// The entry in the map that was already occupied.
2123 pub entry: OccupiedEntry<'a, K, V>,
2124 /// The value which was not inserted, because the entry was already occupied.
2128 #[unstable(feature = "map_try_insert", issue = "82766")]
2129 impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V> {
2130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2131 f.debug_struct("OccupiedError")
2132 .field("key", self.entry.key())
2133 .field("old_value", self.entry.get())
2134 .field("new_value", &self.value)
2135 .finish_non_exhaustive()
2139 #[unstable(feature = "map_try_insert", issue = "82766")]
2140 impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> {
2141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2144 "failed to insert {:?}, key {:?} already exists with value {:?}",
2152 #[stable(feature = "rust1", since = "1.0.0")]
2153 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
2154 type Item = (&'a K, &'a V);
2155 type IntoIter = Iter<'a, K, V>;
2158 #[rustc_lint_query_instability]
2159 fn into_iter(self) -> Iter<'a, K, V> {
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
2166 type Item = (&'a K, &'a mut V);
2167 type IntoIter = IterMut<'a, K, V>;
2170 #[rustc_lint_query_instability]
2171 fn into_iter(self) -> IterMut<'a, K, V> {
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
2179 type IntoIter = IntoIter<K, V>;
2181 /// Creates a consuming iterator, that is, one that moves each key-value
2182 /// pair out of the map in arbitrary order. The map cannot be used after
2188 /// use std::collections::HashMap;
2190 /// let map = HashMap::from([
2196 /// // Not possible with .iter()
2197 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2200 #[rustc_lint_query_instability]
2201 fn into_iter(self) -> IntoIter<K, V> {
2202 IntoIter { base: self.base.into_iter() }
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2208 type Item = (&'a K, &'a V);
2211 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2215 fn size_hint(&self) -> (usize, Option<usize>) {
2216 self.base.size_hint()
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
2222 fn len(&self) -> usize {
2227 #[stable(feature = "fused", since = "1.26.0")]
2228 impl<K, V> FusedIterator for Iter<'_, K, V> {}
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2232 type Item = (&'a K, &'a mut V);
2235 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2239 fn size_hint(&self) -> (usize, Option<usize>) {
2240 self.base.size_hint()
2243 #[stable(feature = "rust1", since = "1.0.0")]
2244 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2246 fn len(&self) -> usize {
2250 #[stable(feature = "fused", since = "1.26.0")]
2251 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2253 #[stable(feature = "std_debug", since = "1.16.0")]
2254 impl<K, V> fmt::Debug for IterMut<'_, K, V>
2259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2260 f.debug_list().entries(self.iter()).finish()
2264 #[stable(feature = "rust1", since = "1.0.0")]
2265 impl<K, V> Iterator for IntoIter<K, V> {
2269 fn next(&mut self) -> Option<(K, V)> {
2273 fn size_hint(&self) -> (usize, Option<usize>) {
2274 self.base.size_hint()
2277 #[stable(feature = "rust1", since = "1.0.0")]
2278 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2280 fn len(&self) -> usize {
2284 #[stable(feature = "fused", since = "1.26.0")]
2285 impl<K, V> FusedIterator for IntoIter<K, V> {}
2287 #[stable(feature = "std_debug", since = "1.16.0")]
2288 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2290 f.debug_list().entries(self.iter()).finish()
2294 #[stable(feature = "rust1", since = "1.0.0")]
2295 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2299 fn next(&mut self) -> Option<&'a K> {
2300 self.inner.next().map(|(k, _)| k)
2303 fn size_hint(&self) -> (usize, Option<usize>) {
2304 self.inner.size_hint()
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2310 fn len(&self) -> usize {
2314 #[stable(feature = "fused", since = "1.26.0")]
2315 impl<K, V> FusedIterator for Keys<'_, K, V> {}
2317 #[stable(feature = "rust1", since = "1.0.0")]
2318 impl<'a, K, V> Iterator for Values<'a, K, V> {
2322 fn next(&mut self) -> Option<&'a V> {
2323 self.inner.next().map(|(_, v)| v)
2326 fn size_hint(&self) -> (usize, Option<usize>) {
2327 self.inner.size_hint()
2330 #[stable(feature = "rust1", since = "1.0.0")]
2331 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2333 fn len(&self) -> usize {
2337 #[stable(feature = "fused", since = "1.26.0")]
2338 impl<K, V> FusedIterator for Values<'_, K, V> {}
2340 #[stable(feature = "map_values_mut", since = "1.10.0")]
2341 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2342 type Item = &'a mut V;
2345 fn next(&mut self) -> Option<&'a mut V> {
2346 self.inner.next().map(|(_, v)| v)
2349 fn size_hint(&self) -> (usize, Option<usize>) {
2350 self.inner.size_hint()
2353 #[stable(feature = "map_values_mut", since = "1.10.0")]
2354 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2356 fn len(&self) -> usize {
2360 #[stable(feature = "fused", since = "1.26.0")]
2361 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2363 #[stable(feature = "std_debug", since = "1.16.0")]
2364 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2366 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2370 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2371 impl<K, V> Iterator for IntoKeys<K, V> {
2375 fn next(&mut self) -> Option<K> {
2376 self.inner.next().map(|(k, _)| k)
2379 fn size_hint(&self) -> (usize, Option<usize>) {
2380 self.inner.size_hint()
2383 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2384 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2386 fn len(&self) -> usize {
2390 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2391 impl<K, V> FusedIterator for IntoKeys<K, V> {}
2393 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2394 impl<K: Debug, V> fmt::Debug for IntoKeys<K, V> {
2395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2396 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2400 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2401 impl<K, V> Iterator for IntoValues<K, V> {
2405 fn next(&mut self) -> Option<V> {
2406 self.inner.next().map(|(_, v)| v)
2409 fn size_hint(&self) -> (usize, Option<usize>) {
2410 self.inner.size_hint()
2413 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2414 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2416 fn len(&self) -> usize {
2420 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2421 impl<K, V> FusedIterator for IntoValues<K, V> {}
2423 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2424 impl<K, V: Debug> fmt::Debug for IntoValues<K, V> {
2425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2426 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2430 #[stable(feature = "drain", since = "1.6.0")]
2431 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2435 fn next(&mut self) -> Option<(K, V)> {
2439 fn size_hint(&self) -> (usize, Option<usize>) {
2440 self.base.size_hint()
2443 #[stable(feature = "drain", since = "1.6.0")]
2444 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2446 fn len(&self) -> usize {
2450 #[stable(feature = "fused", since = "1.26.0")]
2451 impl<K, V> FusedIterator for Drain<'_, K, V> {}
2453 #[stable(feature = "std_debug", since = "1.16.0")]
2454 impl<K, V> fmt::Debug for Drain<'_, K, V>
2459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2460 f.debug_list().entries(self.iter()).finish()
2464 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2465 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
2467 F: FnMut(&K, &mut V) -> bool,
2472 fn next(&mut self) -> Option<(K, V)> {
2476 fn size_hint(&self) -> (usize, Option<usize>) {
2477 self.base.size_hint()
2481 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2482 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2484 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2485 impl<'a, K, V, F> fmt::Debug for DrainFilter<'a, K, V, F>
2487 F: FnMut(&K, &mut V) -> bool,
2489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2490 f.debug_struct("DrainFilter").finish_non_exhaustive()
2494 impl<'a, K, V> Entry<'a, K, V> {
2495 /// Ensures a value is in the entry by inserting the default if empty, and returns
2496 /// a mutable reference to the value in the entry.
2501 /// use std::collections::HashMap;
2503 /// let mut map: HashMap<&str, u32> = HashMap::new();
2505 /// map.entry("poneyland").or_insert(3);
2506 /// assert_eq!(map["poneyland"], 3);
2508 /// *map.entry("poneyland").or_insert(10) *= 2;
2509 /// assert_eq!(map["poneyland"], 6);
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 pub fn or_insert(self, default: V) -> &'a mut V {
2515 Occupied(entry) => entry.into_mut(),
2516 Vacant(entry) => entry.insert(default),
2520 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2521 /// and returns a mutable reference to the value in the entry.
2526 /// use std::collections::HashMap;
2528 /// let mut map: HashMap<&str, String> = HashMap::new();
2529 /// let s = "hoho".to_string();
2531 /// map.entry("poneyland").or_insert_with(|| s);
2533 /// assert_eq!(map["poneyland"], "hoho".to_string());
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2539 Occupied(entry) => entry.into_mut(),
2540 Vacant(entry) => entry.insert(default()),
2544 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2545 /// This method allows for generating key-derived values for insertion by providing the default
2546 /// function a reference to the key that was moved during the `.entry(key)` method call.
2548 /// The reference to the moved key is provided so that cloning or copying the key is
2549 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2554 /// use std::collections::HashMap;
2556 /// let mut map: HashMap<&str, usize> = HashMap::new();
2558 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2560 /// assert_eq!(map["poneyland"], 9);
2563 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2564 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2566 Occupied(entry) => entry.into_mut(),
2568 let value = default(entry.key());
2574 /// Returns a reference to this entry's key.
2579 /// use std::collections::HashMap;
2581 /// let mut map: HashMap<&str, u32> = HashMap::new();
2582 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2585 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2586 pub fn key(&self) -> &K {
2588 Occupied(ref entry) => entry.key(),
2589 Vacant(ref entry) => entry.key(),
2593 /// Provides in-place mutable access to an occupied entry before any
2594 /// potential inserts into the map.
2599 /// use std::collections::HashMap;
2601 /// let mut map: HashMap<&str, u32> = HashMap::new();
2603 /// map.entry("poneyland")
2604 /// .and_modify(|e| { *e += 1 })
2606 /// assert_eq!(map["poneyland"], 42);
2608 /// map.entry("poneyland")
2609 /// .and_modify(|e| { *e += 1 })
2611 /// assert_eq!(map["poneyland"], 43);
2614 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2615 pub fn and_modify<F>(self, f: F) -> Self
2620 Occupied(mut entry) => {
2624 Vacant(entry) => Vacant(entry),
2628 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2633 /// #![feature(entry_insert)]
2634 /// use std::collections::HashMap;
2636 /// let mut map: HashMap<&str, String> = HashMap::new();
2637 /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2639 /// assert_eq!(entry.key(), &"poneyland");
2642 #[unstable(feature = "entry_insert", issue = "65225")]
2643 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2645 Occupied(mut entry) => {
2646 entry.insert(value);
2649 Vacant(entry) => entry.insert_entry(value),
2654 impl<'a, K, V: Default> Entry<'a, K, V> {
2655 /// Ensures a value is in the entry by inserting the default value if empty,
2656 /// and returns a mutable reference to the value in the entry.
2662 /// use std::collections::HashMap;
2664 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2665 /// map.entry("poneyland").or_default();
2667 /// assert_eq!(map["poneyland"], None);
2671 #[stable(feature = "entry_or_default", since = "1.28.0")]
2672 pub fn or_default(self) -> &'a mut V {
2674 Occupied(entry) => entry.into_mut(),
2675 Vacant(entry) => entry.insert(Default::default()),
2680 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2681 /// Gets a reference to the key in the entry.
2686 /// use std::collections::HashMap;
2688 /// let mut map: HashMap<&str, u32> = HashMap::new();
2689 /// map.entry("poneyland").or_insert(12);
2690 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2693 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2694 pub fn key(&self) -> &K {
2698 /// Take the ownership of the key and value from the map.
2703 /// use std::collections::HashMap;
2704 /// use std::collections::hash_map::Entry;
2706 /// let mut map: HashMap<&str, u32> = HashMap::new();
2707 /// map.entry("poneyland").or_insert(12);
2709 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2710 /// // We delete the entry from the map.
2711 /// o.remove_entry();
2714 /// assert_eq!(map.contains_key("poneyland"), false);
2717 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2718 pub fn remove_entry(self) -> (K, V) {
2719 self.base.remove_entry()
2722 /// Gets a reference to the value in the entry.
2727 /// use std::collections::HashMap;
2728 /// use std::collections::hash_map::Entry;
2730 /// let mut map: HashMap<&str, u32> = HashMap::new();
2731 /// map.entry("poneyland").or_insert(12);
2733 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2734 /// assert_eq!(o.get(), &12);
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 pub fn get(&self) -> &V {
2743 /// Gets a mutable reference to the value in the entry.
2745 /// If you need a reference to the `OccupiedEntry` which may outlive the
2746 /// destruction of the `Entry` value, see [`into_mut`].
2748 /// [`into_mut`]: Self::into_mut
2753 /// use std::collections::HashMap;
2754 /// use std::collections::hash_map::Entry;
2756 /// let mut map: HashMap<&str, u32> = HashMap::new();
2757 /// map.entry("poneyland").or_insert(12);
2759 /// assert_eq!(map["poneyland"], 12);
2760 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2761 /// *o.get_mut() += 10;
2762 /// assert_eq!(*o.get(), 22);
2764 /// // We can use the same Entry multiple times.
2765 /// *o.get_mut() += 2;
2768 /// assert_eq!(map["poneyland"], 24);
2771 #[stable(feature = "rust1", since = "1.0.0")]
2772 pub fn get_mut(&mut self) -> &mut V {
2776 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2777 /// with a lifetime bound to the map itself.
2779 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2781 /// [`get_mut`]: Self::get_mut
2786 /// use std::collections::HashMap;
2787 /// use std::collections::hash_map::Entry;
2789 /// let mut map: HashMap<&str, u32> = HashMap::new();
2790 /// map.entry("poneyland").or_insert(12);
2792 /// assert_eq!(map["poneyland"], 12);
2793 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2794 /// *o.into_mut() += 10;
2797 /// assert_eq!(map["poneyland"], 22);
2800 #[stable(feature = "rust1", since = "1.0.0")]
2801 pub fn into_mut(self) -> &'a mut V {
2802 self.base.into_mut()
2805 /// Sets the value of the entry, and returns the entry's old value.
2810 /// use std::collections::HashMap;
2811 /// use std::collections::hash_map::Entry;
2813 /// let mut map: HashMap<&str, u32> = HashMap::new();
2814 /// map.entry("poneyland").or_insert(12);
2816 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2817 /// assert_eq!(o.insert(15), 12);
2820 /// assert_eq!(map["poneyland"], 15);
2823 #[stable(feature = "rust1", since = "1.0.0")]
2824 pub fn insert(&mut self, value: V) -> V {
2825 self.base.insert(value)
2828 /// Takes the value out of the entry, and returns it.
2833 /// use std::collections::HashMap;
2834 /// use std::collections::hash_map::Entry;
2836 /// let mut map: HashMap<&str, u32> = HashMap::new();
2837 /// map.entry("poneyland").or_insert(12);
2839 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2840 /// assert_eq!(o.remove(), 12);
2843 /// assert_eq!(map.contains_key("poneyland"), false);
2846 #[stable(feature = "rust1", since = "1.0.0")]
2847 pub fn remove(self) -> V {
2851 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2852 /// the key used to create this entry.
2857 /// #![feature(map_entry_replace)]
2858 /// use std::collections::hash_map::{Entry, HashMap};
2859 /// use std::rc::Rc;
2861 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2862 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2864 /// let my_key = Rc::new("Stringthing".to_string());
2866 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2867 /// // Also replace the key with a handle to our other key.
2868 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2873 #[unstable(feature = "map_entry_replace", issue = "44286")]
2874 pub fn replace_entry(self, value: V) -> (K, V) {
2875 self.base.replace_entry(value)
2878 /// Replaces the key in the hash map with the key used to create this entry.
2883 /// #![feature(map_entry_replace)]
2884 /// use std::collections::hash_map::{Entry, HashMap};
2885 /// use std::rc::Rc;
2887 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2888 /// let known_strings: Vec<Rc<String>> = Vec::new();
2890 /// // Initialise known strings, run program, etc.
2892 /// reclaim_memory(&mut map, &known_strings);
2894 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2895 /// for s in known_strings {
2896 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2897 /// // Replaces the entry's key with our version of it in `known_strings`.
2898 /// entry.replace_key();
2904 #[unstable(feature = "map_entry_replace", issue = "44286")]
2905 pub fn replace_key(self) -> K {
2906 self.base.replace_key()
2910 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2911 /// Gets a reference to the key that would be used when inserting a value
2912 /// through the `VacantEntry`.
2917 /// use std::collections::HashMap;
2919 /// let mut map: HashMap<&str, u32> = HashMap::new();
2920 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2923 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2924 pub fn key(&self) -> &K {
2928 /// Take ownership of the key.
2933 /// use std::collections::HashMap;
2934 /// use std::collections::hash_map::Entry;
2936 /// let mut map: HashMap<&str, u32> = HashMap::new();
2938 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2943 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2944 pub fn into_key(self) -> K {
2945 self.base.into_key()
2948 /// Sets the value of the entry with the `VacantEntry`'s key,
2949 /// and returns a mutable reference to it.
2954 /// use std::collections::HashMap;
2955 /// use std::collections::hash_map::Entry;
2957 /// let mut map: HashMap<&str, u32> = HashMap::new();
2959 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2962 /// assert_eq!(map["poneyland"], 37);
2965 #[stable(feature = "rust1", since = "1.0.0")]
2966 pub fn insert(self, value: V) -> &'a mut V {
2967 self.base.insert(value)
2970 /// Sets the value of the entry with the `VacantEntry`'s key,
2971 /// and returns an `OccupiedEntry`.
2976 /// #![feature(entry_insert)]
2977 /// use std::collections::HashMap;
2978 /// use std::collections::hash_map::Entry;
2980 /// let mut map: HashMap<&str, u32> = HashMap::new();
2982 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2983 /// o.insert_entry(37);
2985 /// assert_eq!(map["poneyland"], 37);
2988 #[unstable(feature = "entry_insert", issue = "65225")]
2989 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2990 let base = self.base.insert_entry(value);
2991 OccupiedEntry { base }
2995 #[stable(feature = "rust1", since = "1.0.0")]
2996 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2999 S: BuildHasher + Default,
3001 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3002 let mut map = HashMap::with_hasher(Default::default());
3008 /// Inserts all new key-values from the iterator and replaces values with existing
3009 /// keys with new values returned from the iterator.
3010 #[stable(feature = "rust1", since = "1.0.0")]
3011 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3017 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3018 self.base.extend(iter)
3022 fn extend_one(&mut self, (k, v): (K, V)) {
3023 self.base.insert(k, v);
3027 fn extend_reserve(&mut self, additional: usize) {
3028 self.base.extend_reserve(additional);
3032 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3033 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3035 K: Eq + Hash + Copy,
3040 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3041 self.base.extend(iter)
3045 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
3046 self.base.insert(k, v);
3050 fn extend_reserve(&mut self, additional: usize) {
3051 Extend::<(K, V)>::extend_reserve(self, additional)
3055 /// `RandomState` is the default state for [`HashMap`] types.
3057 /// A particular instance `RandomState` will create the same instances of
3058 /// [`Hasher`], but the hashers created by two different `RandomState`
3059 /// instances are unlikely to produce the same result for the same values.
3064 /// use std::collections::HashMap;
3065 /// use std::collections::hash_map::RandomState;
3067 /// let s = RandomState::new();
3068 /// let mut map = HashMap::with_hasher(s);
3069 /// map.insert(1, 2);
3072 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3073 pub struct RandomState {
3079 /// Constructs a new `RandomState` that is initialized with random keys.
3084 /// use std::collections::hash_map::RandomState;
3086 /// let s = RandomState::new();
3089 #[allow(deprecated)]
3092 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3093 pub fn new() -> RandomState {
3094 // Historically this function did not cache keys from the OS and instead
3095 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3096 // was discovered, however, that because we re-seed the thread-local RNG
3097 // from the OS periodically that this can cause excessive slowdown when
3098 // many hash maps are created on a thread. To solve this performance
3099 // trap we cache the first set of randomly generated keys per-thread.
3101 // Later in #36481 it was discovered that exposing a deterministic
3102 // iteration order allows a form of DOS attack. To counter that we
3103 // increment one of the seeds on every RandomState creation, giving
3104 // every corresponding HashMap a different iteration order.
3105 thread_local!(static KEYS: Cell<(u64, u64)> = {
3106 Cell::new(sys::hashmap_random_keys())
3110 let (k0, k1) = keys.get();
3111 keys.set((k0.wrapping_add(1), k1));
3112 RandomState { k0, k1 }
3117 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3118 impl BuildHasher for RandomState {
3119 type Hasher = DefaultHasher;
3121 #[allow(deprecated)]
3122 fn build_hasher(&self) -> DefaultHasher {
3123 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
3127 /// The default [`Hasher`] used by [`RandomState`].
3129 /// The internal algorithm is not specified, and so it and its hashes should
3130 /// not be relied upon over releases.
3131 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3132 #[allow(deprecated)]
3133 #[derive(Clone, Debug)]
3134 pub struct DefaultHasher(SipHasher13);
3136 impl DefaultHasher {
3137 /// Creates a new `DefaultHasher`.
3139 /// This hasher is not guaranteed to be the same as all other
3140 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3141 /// instances created through `new` or `default`.
3142 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3144 #[allow(deprecated)]
3146 pub fn new() -> DefaultHasher {
3147 DefaultHasher(SipHasher13::new_with_keys(0, 0))
3151 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3152 impl Default for DefaultHasher {
3153 /// Creates a new `DefaultHasher` using [`new`].
3154 /// See its documentation for more.
3156 /// [`new`]: DefaultHasher::new
3158 fn default() -> DefaultHasher {
3159 DefaultHasher::new()
3163 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3164 impl Hasher for DefaultHasher {
3165 // The underlying `SipHasher13` doesn't override the other
3166 // `write_*` methods, so it's ok not to forward them here.
3169 fn write(&mut self, msg: &[u8]) {
3174 fn write_str(&mut self, s: &str) {
3175 self.0.write_str(s);
3179 fn finish(&self) -> u64 {
3184 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3185 impl Default for RandomState {
3186 /// Constructs a new `RandomState`.
3188 fn default() -> RandomState {
3193 #[stable(feature = "std_debug", since = "1.16.0")]
3194 impl fmt::Debug for RandomState {
3195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3196 f.debug_struct("RandomState").finish_non_exhaustive()
3201 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
3203 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
3204 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
3209 pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
3211 hashbrown::TryReserveError::CapacityOverflow => {
3212 TryReserveErrorKind::CapacityOverflow.into()
3214 hashbrown::TryReserveError::AllocError { layout } => {
3215 TryReserveErrorKind::AllocError { layout, non_exhaustive: () }.into()
3221 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
3222 raw: base::RawEntryMut<'a, K, V, S>,
3223 ) -> RawEntryMut<'a, K, V, S> {
3225 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
3226 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
3231 fn assert_covariance() {
3232 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3235 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3238 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3241 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3244 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3247 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3250 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3253 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3256 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3259 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3263 d: Drain<'static, &'static str, &'static str>,
3264 ) -> Drain<'new, &'new str, &'new str> {