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::{FromIterator, 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 /// not result in undefined behavior. This could include panics, incorrect results,
58 /// aborts, memory leaks, and non-termination.
60 /// The hash table implementation is a Rust port of Google's [SwissTable].
61 /// The original C++ version of SwissTable can be found [here], and this
62 /// [CppCon talk] gives an overview of how the algorithm works.
64 /// [hash map]: crate::collections#use-a-hashmap-when
65 /// [hashing algorithms available on crates.io]: https://crates.io/keywords/hasher
66 /// [SwissTable]: https://abseil.io/blog/20180927-swisstables
67 /// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
68 /// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
73 /// use std::collections::HashMap;
75 /// // Type inference lets us omit an explicit type signature (which
76 /// // would be `HashMap<String, String>` in this example).
77 /// let mut book_reviews = HashMap::new();
79 /// // Review some books.
80 /// book_reviews.insert(
81 /// "Adventures of Huckleberry Finn".to_string(),
82 /// "My favorite book.".to_string(),
84 /// book_reviews.insert(
85 /// "Grimms' Fairy Tales".to_string(),
86 /// "Masterpiece.".to_string(),
88 /// book_reviews.insert(
89 /// "Pride and Prejudice".to_string(),
90 /// "Very enjoyable.".to_string(),
92 /// book_reviews.insert(
93 /// "The Adventures of Sherlock Holmes".to_string(),
94 /// "Eye lyked it alot.".to_string(),
97 /// // Check for a specific one.
98 /// // When collections store owned values (String), they can still be
99 /// // queried using references (&str).
100 /// if !book_reviews.contains_key("Les Misérables") {
101 /// println!("We've got {} reviews, but Les Misérables ain't one.",
102 /// book_reviews.len());
105 /// // oops, this review has a lot of spelling mistakes, let's delete it.
106 /// book_reviews.remove("The Adventures of Sherlock Holmes");
108 /// // Look up the values associated with some keys.
109 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
110 /// for &book in &to_find {
111 /// match book_reviews.get(book) {
112 /// Some(review) => println!("{}: {}", book, review),
113 /// None => println!("{} is unreviewed.", book)
117 /// // Look up the value for a key (will panic if the key is not found).
118 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
120 /// // Iterate over everything.
121 /// for (book, review) in &book_reviews {
122 /// println!("{}: \"{}\"", book, review);
126 /// A `HashMap` with a known list of items can be initialized from an array:
129 /// use std::collections::HashMap;
131 /// let solar_distance = HashMap::from([
132 /// ("Mercury", 0.4),
139 /// `HashMap` implements an [`Entry API`](#method.entry), which allows
140 /// for complex methods of getting, setting, updating and removing keys and
144 /// use std::collections::HashMap;
146 /// // type inference lets us omit an explicit type signature (which
147 /// // would be `HashMap<&str, u8>` in this example).
148 /// let mut player_stats = HashMap::new();
150 /// fn random_stat_buff() -> u8 {
151 /// // could actually return some random value here - let's just return
152 /// // some fixed value for now
156 /// // insert a key only if it doesn't already exist
157 /// player_stats.entry("health").or_insert(100);
159 /// // insert a key using a function that provides a new value only if it
160 /// // doesn't already exist
161 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
163 /// // update a key, guarding against the key possibly not being set
164 /// let stat = player_stats.entry("attack").or_insert(100);
165 /// *stat += random_stat_buff();
168 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
169 /// We must also derive [`PartialEq`].
171 /// [`RefCell`]: crate::cell::RefCell
172 /// [`Cell`]: crate::cell::Cell
173 /// [`default`]: Default::default
174 /// [`with_hasher`]: Self::with_hasher
175 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
178 /// use std::collections::HashMap;
180 /// #[derive(Hash, Eq, PartialEq, Debug)]
187 /// /// Creates a new Viking.
188 /// fn new(name: &str, country: &str) -> Viking {
189 /// Viking { name: name.to_string(), country: country.to_string() }
193 /// // Use a HashMap to store the vikings' health points.
194 /// let vikings = HashMap::from([
195 /// (Viking::new("Einar", "Norway"), 25),
196 /// (Viking::new("Olaf", "Denmark"), 24),
197 /// (Viking::new("Harald", "Iceland"), 12),
200 /// // Use derived implementation to print the status of the vikings.
201 /// for (viking, health) in &vikings {
202 /// println!("{:?} has {} hp", viking, health);
206 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]
207 #[stable(feature = "rust1", since = "1.0.0")]
208 #[rustc_insignificant_dtor]
209 pub struct HashMap<K, V, S = RandomState> {
210 base: base::HashMap<K, V, S>,
213 impl<K, V> HashMap<K, V, RandomState> {
214 /// Creates an empty `HashMap`.
216 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
217 /// is first inserted into.
222 /// use std::collections::HashMap;
223 /// let mut map: HashMap<&str, i32> = HashMap::new();
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn new() -> HashMap<K, V, RandomState> {
232 /// Creates an empty `HashMap` with the specified capacity.
234 /// The hash map will be able to hold at least `capacity` elements without
235 /// reallocating. If `capacity` is 0, the hash map will not allocate.
240 /// use std::collections::HashMap;
241 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
247 HashMap::with_capacity_and_hasher(capacity, Default::default())
251 impl<K, V, S> HashMap<K, V, S> {
252 /// Creates an empty `HashMap` which will use the given hash builder to hash
255 /// The created map has the default initial capacity.
257 /// Warning: `hash_builder` is normally randomly generated, and
258 /// is designed to allow HashMaps to be resistant to attacks that
259 /// cause many collisions and very poor performance. Setting it
260 /// manually using this function can expose a DoS attack vector.
262 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
263 /// the HashMap to be useful, see its documentation for details.
268 /// use std::collections::HashMap;
269 /// use std::collections::hash_map::RandomState;
271 /// let s = RandomState::new();
272 /// let mut map = HashMap::with_hasher(s);
273 /// map.insert(1, 2);
276 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
277 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
278 HashMap { base: base::HashMap::with_hasher(hash_builder) }
281 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
282 /// to hash the keys.
284 /// The hash map will be able to hold at least `capacity` elements without
285 /// reallocating. If `capacity` is 0, the hash map will not allocate.
287 /// Warning: `hash_builder` is normally randomly generated, and
288 /// is designed to allow HashMaps to be resistant to attacks that
289 /// cause many collisions and very poor performance. Setting it
290 /// manually using this function can expose a DoS attack vector.
292 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
293 /// the HashMap to be useful, see its documentation for details.
298 /// use std::collections::HashMap;
299 /// use std::collections::hash_map::RandomState;
301 /// let s = RandomState::new();
302 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
303 /// map.insert(1, 2);
306 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
307 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
308 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
311 /// Returns the number of elements the map can hold without reallocating.
313 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
314 /// more, but is guaranteed to be able to hold at least this many.
319 /// use std::collections::HashMap;
320 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
321 /// assert!(map.capacity() >= 100);
324 #[stable(feature = "rust1", since = "1.0.0")]
325 pub fn capacity(&self) -> usize {
329 /// An iterator visiting all keys in arbitrary order.
330 /// The iterator element type is `&'a K`.
335 /// use std::collections::HashMap;
337 /// let map = HashMap::from([
343 /// for key in map.keys() {
344 /// println!("{}", key);
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn keys(&self) -> Keys<'_, K, V> {
349 Keys { inner: self.iter() }
352 /// Creates a consuming iterator visiting all the keys in arbitrary order.
353 /// The map cannot be used after calling this.
354 /// The iterator element type is `K`.
359 /// use std::collections::HashMap;
361 /// let map = HashMap::from([
367 /// let mut vec: Vec<&str> = map.into_keys().collect();
368 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
369 /// // keys must be sorted to test them against a sorted array.
370 /// vec.sort_unstable();
371 /// assert_eq!(vec, ["a", "b", "c"]);
374 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
375 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
376 pub fn into_keys(self) -> IntoKeys<K, V> {
377 IntoKeys { inner: self.into_iter() }
380 /// An iterator visiting all values in arbitrary order.
381 /// The iterator element type is `&'a V`.
386 /// use std::collections::HashMap;
388 /// let map = HashMap::from([
394 /// for val in map.values() {
395 /// println!("{}", val);
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn values(&self) -> Values<'_, K, V> {
400 Values { inner: self.iter() }
403 /// An iterator visiting all values mutably in arbitrary order.
404 /// The iterator element type is `&'a mut V`.
409 /// use std::collections::HashMap;
411 /// let mut map = HashMap::from([
417 /// for val in map.values_mut() {
418 /// *val = *val + 10;
421 /// for val in map.values() {
422 /// println!("{}", val);
425 #[stable(feature = "map_values_mut", since = "1.10.0")]
426 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
427 ValuesMut { inner: self.iter_mut() }
430 /// Creates a consuming iterator visiting all the values in arbitrary order.
431 /// The map cannot be used after calling this.
432 /// The iterator element type is `V`.
437 /// use std::collections::HashMap;
439 /// let map = HashMap::from([
445 /// let mut vec: Vec<i32> = map.into_values().collect();
446 /// // The `IntoValues` iterator produces values in arbitrary order, so
447 /// // the values must be sorted to test them against a sorted array.
448 /// vec.sort_unstable();
449 /// assert_eq!(vec, [1, 2, 3]);
452 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
453 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
454 pub fn into_values(self) -> IntoValues<K, V> {
455 IntoValues { inner: self.into_iter() }
458 /// An iterator visiting all key-value pairs in arbitrary order.
459 /// The iterator element type is `(&'a K, &'a V)`.
464 /// use std::collections::HashMap;
466 /// let map = HashMap::from([
472 /// for (key, val) in map.iter() {
473 /// println!("key: {} val: {}", key, val);
476 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn iter(&self) -> Iter<'_, K, V> {
479 Iter { base: self.base.iter() }
482 /// An iterator visiting all key-value pairs in arbitrary order,
483 /// with mutable references to the values.
484 /// The iterator element type is `(&'a K, &'a mut V)`.
489 /// use std::collections::HashMap;
491 /// let mut map = HashMap::from([
497 /// // Update all values
498 /// for (_, val) in map.iter_mut() {
502 /// for (key, val) in &map {
503 /// println!("key: {} val: {}", key, val);
506 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
509 IterMut { base: self.base.iter_mut() }
512 /// Returns the number of elements in the map.
517 /// use std::collections::HashMap;
519 /// let mut a = HashMap::new();
520 /// assert_eq!(a.len(), 0);
521 /// a.insert(1, "a");
522 /// assert_eq!(a.len(), 1);
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn len(&self) -> usize {
529 /// Returns `true` if the map contains no elements.
534 /// use std::collections::HashMap;
536 /// let mut a = HashMap::new();
537 /// assert!(a.is_empty());
538 /// a.insert(1, "a");
539 /// assert!(!a.is_empty());
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn is_empty(&self) -> bool {
547 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
548 /// allocated memory for reuse.
550 /// If the returned iterator is dropped before being fully consumed, it
551 /// drops the remaining key-value pairs. The returned iterator keeps a
552 /// mutable borrow on the vector to optimize its implementation.
557 /// use std::collections::HashMap;
559 /// let mut a = HashMap::new();
560 /// a.insert(1, "a");
561 /// a.insert(2, "b");
563 /// for (k, v) in a.drain().take(1) {
564 /// assert!(k == 1 || k == 2);
565 /// assert!(v == "a" || v == "b");
568 /// assert!(a.is_empty());
571 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
572 #[stable(feature = "drain", since = "1.6.0")]
573 pub fn drain(&mut self) -> Drain<'_, K, V> {
574 Drain { base: self.base.drain() }
577 /// Creates an iterator which uses a closure to determine if an element should be removed.
579 /// If the closure returns true, the element is removed from the map and yielded.
580 /// If the closure returns false, or panics, the element remains in the map and will not be
583 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
584 /// whether you choose to keep or remove it.
586 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
587 /// elements will still be subjected to the closure and removed and dropped if it returns true.
589 /// It is unspecified how many more elements will be subjected to the closure
590 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
591 /// or if the `DrainFilter` value is leaked.
595 /// Splitting a map into even and odd keys, reusing the original map:
598 /// #![feature(hash_drain_filter)]
599 /// use std::collections::HashMap;
601 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
602 /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
604 /// let mut evens = drained.keys().copied().collect::<Vec<_>>();
605 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
609 /// assert_eq!(evens, vec![0, 2, 4, 6]);
610 /// assert_eq!(odds, vec![1, 3, 5, 7]);
613 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
614 #[unstable(feature = "hash_drain_filter", issue = "59618")]
615 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
617 F: FnMut(&K, &mut V) -> bool,
619 DrainFilter { base: self.base.drain_filter(pred) }
622 /// Retains only the elements specified by the predicate.
624 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
625 /// The elements are visited in unsorted (and unspecified) order.
630 /// use std::collections::HashMap;
632 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
633 /// map.retain(|&k, _| k % 2 == 0);
634 /// assert_eq!(map.len(), 4);
637 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
638 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
639 pub fn retain<F>(&mut self, f: F)
641 F: FnMut(&K, &mut V) -> bool,
646 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
652 /// use std::collections::HashMap;
654 /// let mut a = HashMap::new();
655 /// a.insert(1, "a");
657 /// assert!(a.is_empty());
660 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn clear(&mut self) {
665 /// Returns a reference to the map's [`BuildHasher`].
670 /// use std::collections::HashMap;
671 /// use std::collections::hash_map::RandomState;
673 /// let hasher = RandomState::new();
674 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
675 /// let hasher: &RandomState = map.hasher();
678 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
679 pub fn hasher(&self) -> &S {
684 impl<K, V, S> HashMap<K, V, S>
689 /// Reserves capacity for at least `additional` more elements to be inserted
690 /// in the `HashMap`. The collection may reserve more space to avoid
691 /// frequent reallocations.
695 /// Panics if the new allocation size overflows [`usize`].
700 /// use std::collections::HashMap;
701 /// let mut map: HashMap<&str, i32> = HashMap::new();
705 #[stable(feature = "rust1", since = "1.0.0")]
706 pub fn reserve(&mut self, additional: usize) {
707 self.base.reserve(additional)
710 /// Tries to reserve capacity for at least `additional` more elements to be inserted
711 /// in the given `HashMap<K, V>`. The collection may reserve more space to avoid
712 /// frequent reallocations.
716 /// If the capacity overflows, or the allocator reports a failure, then an error
722 /// use std::collections::HashMap;
724 /// let mut map: HashMap<&str, isize> = HashMap::new();
725 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
728 #[stable(feature = "try_reserve", since = "1.57.0")]
729 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
730 self.base.try_reserve(additional).map_err(map_try_reserve_error)
733 /// Shrinks the capacity of the map as much as possible. It will drop
734 /// down as much as possible while maintaining the internal rules
735 /// and possibly leaving some space in accordance with the resize policy.
740 /// use std::collections::HashMap;
742 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
743 /// map.insert(1, 2);
744 /// map.insert(3, 4);
745 /// assert!(map.capacity() >= 100);
746 /// map.shrink_to_fit();
747 /// assert!(map.capacity() >= 2);
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn shrink_to_fit(&mut self) {
752 self.base.shrink_to_fit();
755 /// Shrinks the capacity of the map with a lower limit. It will drop
756 /// down no lower than the supplied limit while maintaining the internal rules
757 /// and possibly leaving some space in accordance with the resize policy.
759 /// If the current capacity is less than the lower limit, this is a no-op.
764 /// use std::collections::HashMap;
766 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
767 /// map.insert(1, 2);
768 /// map.insert(3, 4);
769 /// assert!(map.capacity() >= 100);
770 /// map.shrink_to(10);
771 /// assert!(map.capacity() >= 10);
772 /// map.shrink_to(0);
773 /// assert!(map.capacity() >= 2);
776 #[stable(feature = "shrink_to", since = "1.56.0")]
777 pub fn shrink_to(&mut self, min_capacity: usize) {
778 self.base.shrink_to(min_capacity);
781 /// Gets the given key's corresponding entry in the map for in-place manipulation.
786 /// use std::collections::HashMap;
788 /// let mut letters = HashMap::new();
790 /// for ch in "a short treatise on fungi".chars() {
791 /// let counter = letters.entry(ch).or_insert(0);
795 /// assert_eq!(letters[&'s'], 2);
796 /// assert_eq!(letters[&'t'], 3);
797 /// assert_eq!(letters[&'u'], 1);
798 /// assert_eq!(letters.get(&'y'), None);
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
803 map_entry(self.base.rustc_entry(key))
806 /// Returns a reference to the value corresponding to the key.
808 /// The key may be any borrowed form of the map's key type, but
809 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
815 /// use std::collections::HashMap;
817 /// let mut map = HashMap::new();
818 /// map.insert(1, "a");
819 /// assert_eq!(map.get(&1), Some(&"a"));
820 /// assert_eq!(map.get(&2), None);
822 #[stable(feature = "rust1", since = "1.0.0")]
824 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
832 /// Returns the key-value pair corresponding to the supplied key.
834 /// The supplied key may be any borrowed form of the map's key type, but
835 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
841 /// use std::collections::HashMap;
843 /// let mut map = HashMap::new();
844 /// map.insert(1, "a");
845 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
846 /// assert_eq!(map.get_key_value(&2), None);
849 #[stable(feature = "map_get_key_value", since = "1.40.0")]
850 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
855 self.base.get_key_value(k)
858 /// Returns `true` if the map contains a value for the specified key.
860 /// The key may be any borrowed form of the map's key type, but
861 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
867 /// use std::collections::HashMap;
869 /// let mut map = HashMap::new();
870 /// map.insert(1, "a");
871 /// assert_eq!(map.contains_key(&1), true);
872 /// assert_eq!(map.contains_key(&2), false);
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
881 self.base.contains_key(k)
884 /// Returns a mutable reference to the value corresponding to the key.
886 /// The key may be any borrowed form of the map's key type, but
887 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
893 /// use std::collections::HashMap;
895 /// let mut map = HashMap::new();
896 /// map.insert(1, "a");
897 /// if let Some(x) = map.get_mut(&1) {
900 /// assert_eq!(map[&1], "b");
903 #[stable(feature = "rust1", since = "1.0.0")]
904 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
912 /// Inserts a key-value pair into the map.
914 /// If the map did not have this key present, [`None`] is returned.
916 /// If the map did have this key present, the value is updated, and the old
917 /// value is returned. The key is not updated, though; this matters for
918 /// types that can be `==` without being identical. See the [module-level
919 /// documentation] for more.
921 /// [module-level documentation]: crate::collections#insert-and-complex-keys
926 /// use std::collections::HashMap;
928 /// let mut map = HashMap::new();
929 /// assert_eq!(map.insert(37, "a"), None);
930 /// assert_eq!(map.is_empty(), false);
932 /// map.insert(37, "b");
933 /// assert_eq!(map.insert(37, "c"), Some("b"));
934 /// assert_eq!(map[&37], "c");
937 #[stable(feature = "rust1", since = "1.0.0")]
938 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
939 self.base.insert(k, v)
942 /// Tries to insert a key-value pair into the map, and returns
943 /// a mutable reference to the value in the entry.
945 /// If the map already had this key present, nothing is updated, and
946 /// an error containing the occupied entry and the value is returned.
953 /// #![feature(map_try_insert)]
955 /// use std::collections::HashMap;
957 /// let mut map = HashMap::new();
958 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
960 /// let err = map.try_insert(37, "b").unwrap_err();
961 /// assert_eq!(err.entry.key(), &37);
962 /// assert_eq!(err.entry.get(), &"a");
963 /// assert_eq!(err.value, "b");
965 #[unstable(feature = "map_try_insert", issue = "82766")]
966 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>> {
967 match self.entry(key) {
968 Occupied(entry) => Err(OccupiedError { entry, value }),
969 Vacant(entry) => Ok(entry.insert(value)),
973 /// Removes a key from the map, returning the value at the key if the key
974 /// was previously in the map.
976 /// The key may be any borrowed form of the map's key type, but
977 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
983 /// use std::collections::HashMap;
985 /// let mut map = HashMap::new();
986 /// map.insert(1, "a");
987 /// assert_eq!(map.remove(&1), Some("a"));
988 /// assert_eq!(map.remove(&1), None);
991 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1000 /// Removes a key from the map, returning the stored key and value if the
1001 /// key was previously in the map.
1003 /// The key may be any borrowed form of the map's key type, but
1004 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1010 /// use std::collections::HashMap;
1013 /// let mut map = HashMap::new();
1014 /// map.insert(1, "a");
1015 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1016 /// assert_eq!(map.remove(&1), None);
1020 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1021 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1026 self.base.remove_entry(k)
1030 impl<K, V, S> HashMap<K, V, S>
1034 /// Creates a raw entry builder for the HashMap.
1036 /// Raw entries provide the lowest level of control for searching and
1037 /// manipulating a map. They must be manually initialized with a hash and
1038 /// then manually searched. After this, insertions into a vacant entry
1039 /// still require an owned key to be provided.
1041 /// Raw entries are useful for such exotic situations as:
1043 /// * Hash memoization
1044 /// * Deferring the creation of an owned key until it is known to be required
1045 /// * Using a search key that doesn't work with the Borrow trait
1046 /// * Using custom comparison logic without newtype wrappers
1048 /// Because raw entries provide much more low-level control, it's much easier
1049 /// to put the HashMap into an inconsistent state which, while memory-safe,
1050 /// will cause the map to produce seemingly random results. Higher-level and
1051 /// more foolproof APIs like `entry` should be preferred when possible.
1053 /// In particular, the hash used to initialized the raw entry must still be
1054 /// consistent with the hash of the key that is ultimately stored in the entry.
1055 /// This is because implementations of HashMap may need to recompute hashes
1056 /// when resizing, at which point only the keys are available.
1058 /// Raw entries give mutable access to the keys. This must not be used
1059 /// to modify how the key would compare or hash, as the map will not re-evaluate
1060 /// where the key should go, meaning the keys may become "lost" if their
1061 /// location does not reflect their state. For instance, if you change a key
1062 /// so that the map now contains keys which compare equal, search may start
1063 /// acting erratically, with two keys randomly masking each other. Implementations
1064 /// are free to assume this doesn't happen (within the limits of memory-safety).
1066 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1067 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
1068 RawEntryBuilderMut { map: self }
1071 /// Creates a raw immutable entry builder for the HashMap.
1073 /// Raw entries provide the lowest level of control for searching and
1074 /// manipulating a map. They must be manually initialized with a hash and
1075 /// then manually searched.
1077 /// This is useful for
1078 /// * Hash memoization
1079 /// * Using a search key that doesn't work with the Borrow trait
1080 /// * Using custom comparison logic without newtype wrappers
1082 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1083 /// `get` should be preferred.
1085 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1087 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1088 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
1089 RawEntryBuilder { map: self }
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 impl<K, V, S> Clone for HashMap<K, V, S>
1101 fn clone(&self) -> Self {
1102 Self { base: self.base.clone() }
1106 fn clone_from(&mut self, other: &Self) {
1107 self.base.clone_from(&other.base);
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<K, V, S> PartialEq for HashMap<K, V, S>
1118 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1119 if self.len() != other.len() {
1123 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl<K, V, S> Eq for HashMap<K, V, S>
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<K, V, S> Debug for HashMap<K, V, S>
1142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143 f.debug_map().entries(self.iter()).finish()
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<K, V, S> Default for HashMap<K, V, S>
1152 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1154 fn default() -> HashMap<K, V, S> {
1155 HashMap::with_hasher(Default::default())
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1162 K: Eq + Hash + Borrow<Q>,
1168 /// Returns a reference to the value corresponding to the supplied key.
1172 /// Panics if the key is not present in the `HashMap`.
1174 fn index(&self, key: &Q) -> &V {
1175 self.get(key).expect("no entry found for key")
1179 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1180 // Note: as what is currently the most convenient built-in way to construct
1181 // a HashMap, a simple usage of this function must not *require* the user
1182 // to provide a type annotation in order to infer the third type parameter
1183 // (the hasher parameter, conventionally "S").
1184 // To that end, this impl is defined using RandomState as the concrete
1185 // type of S, rather than being generic over `S: BuildHasher + Default`.
1186 // It is expected that users who want to specify a hasher will manually use
1187 // `with_capacity_and_hasher`.
1188 // If type parameter defaults worked on impls, and if type parameter
1189 // defaults could be mixed with const generics, then perhaps
1190 // this could be generalized.
1191 // See also the equivalent impl on HashSet.
1192 impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
1199 /// use std::collections::HashMap;
1201 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1202 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1203 /// assert_eq!(map1, map2);
1205 fn from(arr: [(K, V); N]) -> Self {
1206 Self::from_iter(arr)
1210 /// An iterator over the entries of a `HashMap`.
1212 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1213 /// documentation for more.
1215 /// [`iter`]: HashMap::iter
1220 /// use std::collections::HashMap;
1222 /// let map = HashMap::from([
1225 /// let iter = map.iter();
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 pub struct Iter<'a, K: 'a, V: 'a> {
1229 base: base::Iter<'a, K, V>,
1232 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl<K, V> Clone for Iter<'_, K, V> {
1236 fn clone(&self) -> Self {
1237 Iter { base: self.base.clone() }
1241 #[stable(feature = "std_debug", since = "1.16.0")]
1242 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1244 f.debug_list().entries(self.clone()).finish()
1248 /// A mutable iterator over the entries of a `HashMap`.
1250 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1251 /// documentation for more.
1253 /// [`iter_mut`]: HashMap::iter_mut
1258 /// use std::collections::HashMap;
1260 /// let mut map = HashMap::from([
1263 /// let iter = map.iter_mut();
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 pub struct IterMut<'a, K: 'a, V: 'a> {
1267 base: base::IterMut<'a, K, V>,
1270 impl<'a, K, V> IterMut<'a, K, V> {
1271 /// Returns an iterator of references over the remaining items.
1273 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1274 Iter { base: self.base.rustc_iter() }
1278 /// An owning iterator over the entries of a `HashMap`.
1280 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1281 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1283 /// [`into_iter`]: IntoIterator::into_iter
1284 /// [`IntoIterator`]: crate::iter::IntoIterator
1289 /// use std::collections::HashMap;
1291 /// let map = HashMap::from([
1294 /// let iter = map.into_iter();
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 pub struct IntoIter<K, V> {
1298 base: base::IntoIter<K, V>,
1301 impl<K, V> IntoIter<K, V> {
1302 /// Returns an iterator of references over the remaining items.
1304 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1305 Iter { base: self.base.rustc_iter() }
1309 /// An iterator over the keys of a `HashMap`.
1311 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1312 /// documentation for more.
1314 /// [`keys`]: HashMap::keys
1319 /// use std::collections::HashMap;
1321 /// let map = HashMap::from([
1324 /// let iter_keys = map.keys();
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 pub struct Keys<'a, K: 'a, V: 'a> {
1328 inner: Iter<'a, K, V>,
1331 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl<K, V> Clone for Keys<'_, K, V> {
1335 fn clone(&self) -> Self {
1336 Keys { inner: self.inner.clone() }
1340 #[stable(feature = "std_debug", since = "1.16.0")]
1341 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343 f.debug_list().entries(self.clone()).finish()
1347 /// An iterator over the values of a `HashMap`.
1349 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1350 /// documentation for more.
1352 /// [`values`]: HashMap::values
1357 /// use std::collections::HashMap;
1359 /// let map = HashMap::from([
1362 /// let iter_values = map.values();
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub struct Values<'a, K: 'a, V: 'a> {
1366 inner: Iter<'a, K, V>,
1369 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<K, V> Clone for Values<'_, K, V> {
1373 fn clone(&self) -> Self {
1374 Values { inner: self.inner.clone() }
1378 #[stable(feature = "std_debug", since = "1.16.0")]
1379 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1381 f.debug_list().entries(self.clone()).finish()
1385 /// A draining iterator over the entries of a `HashMap`.
1387 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1388 /// documentation for more.
1390 /// [`drain`]: HashMap::drain
1395 /// use std::collections::HashMap;
1397 /// let mut map = HashMap::from([
1400 /// let iter = map.drain();
1402 #[stable(feature = "drain", since = "1.6.0")]
1403 pub struct Drain<'a, K: 'a, V: 'a> {
1404 base: base::Drain<'a, K, V>,
1407 impl<'a, K, V> Drain<'a, K, V> {
1408 /// Returns an iterator of references over the remaining items.
1410 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1411 Iter { base: self.base.rustc_iter() }
1415 /// A draining, filtering iterator over the entries of a `HashMap`.
1417 /// This `struct` is created by the [`drain_filter`] method on [`HashMap`].
1419 /// [`drain_filter`]: HashMap::drain_filter
1424 /// #![feature(hash_drain_filter)]
1426 /// use std::collections::HashMap;
1428 /// let mut map = HashMap::from([
1431 /// let iter = map.drain_filter(|_k, v| *v % 2 == 0);
1433 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1434 pub struct DrainFilter<'a, K, V, F>
1436 F: FnMut(&K, &mut V) -> bool,
1438 base: base::DrainFilter<'a, K, V, F>,
1441 /// A mutable iterator over the values of a `HashMap`.
1443 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1444 /// documentation for more.
1446 /// [`values_mut`]: HashMap::values_mut
1451 /// use std::collections::HashMap;
1453 /// let mut map = HashMap::from([
1456 /// let iter_values = map.values_mut();
1458 #[stable(feature = "map_values_mut", since = "1.10.0")]
1459 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1460 inner: IterMut<'a, K, V>,
1463 /// An owning iterator over the keys of a `HashMap`.
1465 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1466 /// See its documentation for more.
1468 /// [`into_keys`]: HashMap::into_keys
1473 /// use std::collections::HashMap;
1475 /// let map = HashMap::from([
1478 /// let iter_keys = map.into_keys();
1480 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1481 pub struct IntoKeys<K, V> {
1482 inner: IntoIter<K, V>,
1485 /// An owning iterator over the values of a `HashMap`.
1487 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1488 /// See its documentation for more.
1490 /// [`into_values`]: HashMap::into_values
1495 /// use std::collections::HashMap;
1497 /// let map = HashMap::from([
1500 /// let iter_keys = map.into_values();
1502 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1503 pub struct IntoValues<K, V> {
1504 inner: IntoIter<K, V>,
1507 /// A builder for computing where in a HashMap a key-value pair would be stored.
1509 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1510 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1511 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1512 map: &'a mut HashMap<K, V, S>,
1515 /// A view into a single entry in a map, which may either be vacant or occupied.
1517 /// This is a lower-level version of [`Entry`].
1519 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1520 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1522 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1523 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1524 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1525 /// An occupied entry.
1526 Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1528 Vacant(RawVacantEntryMut<'a, K, V, S>),
1531 /// A view into an occupied entry in a `HashMap`.
1532 /// It is part of the [`RawEntryMut`] enum.
1533 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1534 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1535 base: base::RawOccupiedEntryMut<'a, K, V, S>,
1538 /// A view into a vacant entry in a `HashMap`.
1539 /// It is part of the [`RawEntryMut`] enum.
1540 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1541 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1542 base: base::RawVacantEntryMut<'a, K, V, S>,
1545 /// A builder for computing where in a HashMap a key-value pair would be stored.
1547 /// See the [`HashMap::raw_entry`] docs for usage examples.
1548 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1549 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1550 map: &'a HashMap<K, V, S>,
1553 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1557 /// Creates a `RawEntryMut` from the given key.
1559 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1560 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1565 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1568 /// Creates a `RawEntryMut` from the given key and its hash.
1570 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1571 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1576 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1579 /// Creates a `RawEntryMut` from the given hash.
1581 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1582 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1584 for<'b> F: FnMut(&'b K) -> bool,
1586 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1590 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1594 /// Access an entry by key.
1596 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1597 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1602 self.map.base.raw_entry().from_key(k)
1605 /// Access an entry by a key and its hash.
1607 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1608 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1613 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1616 /// Access an entry by hash.
1618 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1619 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1621 F: FnMut(&K) -> bool,
1623 self.map.base.raw_entry().from_hash(hash, is_match)
1627 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1628 /// Ensures a value is in the entry by inserting the default if empty, and returns
1629 /// mutable references to the key and value in the entry.
1634 /// #![feature(hash_raw_entry)]
1635 /// use std::collections::HashMap;
1637 /// let mut map: HashMap<&str, u32> = HashMap::new();
1639 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1640 /// assert_eq!(map["poneyland"], 3);
1642 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1643 /// assert_eq!(map["poneyland"], 6);
1646 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1647 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1653 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1654 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1658 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1659 /// and returns mutable references to the key and value in the entry.
1664 /// #![feature(hash_raw_entry)]
1665 /// use std::collections::HashMap;
1667 /// let mut map: HashMap<&str, String> = HashMap::new();
1669 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1670 /// ("poneyland", "hoho".to_string())
1673 /// assert_eq!(map["poneyland"], "hoho".to_string());
1676 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1677 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1679 F: FnOnce() -> (K, V),
1684 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1685 RawEntryMut::Vacant(entry) => {
1686 let (k, v) = default();
1692 /// Provides in-place mutable access to an occupied entry before any
1693 /// potential inserts into the map.
1698 /// #![feature(hash_raw_entry)]
1699 /// use std::collections::HashMap;
1701 /// let mut map: HashMap<&str, u32> = HashMap::new();
1703 /// map.raw_entry_mut()
1704 /// .from_key("poneyland")
1705 /// .and_modify(|_k, v| { *v += 1 })
1706 /// .or_insert("poneyland", 42);
1707 /// assert_eq!(map["poneyland"], 42);
1709 /// map.raw_entry_mut()
1710 /// .from_key("poneyland")
1711 /// .and_modify(|_k, v| { *v += 1 })
1712 /// .or_insert("poneyland", 0);
1713 /// assert_eq!(map["poneyland"], 43);
1716 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1717 pub fn and_modify<F>(self, f: F) -> Self
1719 F: FnOnce(&mut K, &mut V),
1722 RawEntryMut::Occupied(mut entry) => {
1724 let (k, v) = entry.get_key_value_mut();
1727 RawEntryMut::Occupied(entry)
1729 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1734 impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1735 /// Gets a reference to the key in the entry.
1738 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1739 pub fn key(&self) -> &K {
1743 /// Gets a mutable reference to the key in the entry.
1746 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1747 pub fn key_mut(&mut self) -> &mut K {
1751 /// Converts the entry into a mutable reference to the key in the entry
1752 /// with a lifetime bound to the map itself.
1754 #[must_use = "`self` will be dropped if the result is not used"]
1755 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1756 pub fn into_key(self) -> &'a mut K {
1757 self.base.into_key()
1760 /// Gets a reference to the value in the entry.
1763 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1764 pub fn get(&self) -> &V {
1768 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
1769 /// with a lifetime bound to the map itself.
1771 #[must_use = "`self` will be dropped if the result is not used"]
1772 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1773 pub fn into_mut(self) -> &'a mut V {
1774 self.base.into_mut()
1777 /// Gets a mutable reference to the value in the entry.
1780 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1781 pub fn get_mut(&mut self) -> &mut V {
1785 /// Gets a reference to the key and value in the entry.
1788 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1789 pub fn get_key_value(&mut self) -> (&K, &V) {
1790 self.base.get_key_value()
1793 /// Gets a mutable reference to the key and value in the entry.
1795 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1796 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1797 self.base.get_key_value_mut()
1800 /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry
1801 /// with a lifetime bound to the map itself.
1803 #[must_use = "`self` will be dropped if the result is not used"]
1804 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1805 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1806 self.base.into_key_value()
1809 /// Sets the value of the entry, and returns the entry's old value.
1811 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1812 pub fn insert(&mut self, value: V) -> V {
1813 self.base.insert(value)
1816 /// Sets the value of the entry, and returns the entry's old value.
1818 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1819 pub fn insert_key(&mut self, key: K) -> K {
1820 self.base.insert_key(key)
1823 /// Takes the value out of the entry, and returns it.
1825 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1826 pub fn remove(self) -> V {
1830 /// Take the ownership of the key and value from the map.
1832 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1833 pub fn remove_entry(self) -> (K, V) {
1834 self.base.remove_entry()
1838 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1839 /// Sets the value of the entry with the `VacantEntry`'s key,
1840 /// and returns a mutable reference to it.
1842 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1843 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1848 self.base.insert(key, value)
1851 /// Sets the value of the entry with the VacantEntry's key,
1852 /// and returns a mutable reference to it.
1854 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1855 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1860 self.base.insert_hashed_nocheck(hash, key, value)
1864 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1865 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1867 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
1871 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1872 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1873 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1876 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1881 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1882 impl<K: Debug, V: Debug, S> Debug for RawOccupiedEntryMut<'_, K, V, S> {
1883 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1884 f.debug_struct("RawOccupiedEntryMut")
1885 .field("key", self.key())
1886 .field("value", self.get())
1887 .finish_non_exhaustive()
1891 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1892 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894 f.debug_struct("RawVacantEntryMut").finish_non_exhaustive()
1898 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1899 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1901 f.debug_struct("RawEntryBuilder").finish_non_exhaustive()
1905 /// A view into a single entry in a map, which may either be vacant or occupied.
1907 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1909 /// [`entry`]: HashMap::entry
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
1912 pub enum Entry<'a, K: 'a, V: 'a> {
1913 /// An occupied entry.
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1922 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1923 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1924 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1926 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1927 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1932 /// A view into an occupied entry in a `HashMap`.
1933 /// It is part of the [`Entry`] enum.
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1936 base: base::RustcOccupiedEntry<'a, K, V>,
1939 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1940 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1942 f.debug_struct("OccupiedEntry")
1943 .field("key", self.key())
1944 .field("value", self.get())
1945 .finish_non_exhaustive()
1949 /// A view into a vacant entry in a `HashMap`.
1950 /// It is part of the [`Entry`] enum.
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1953 base: base::RustcVacantEntry<'a, K, V>,
1956 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1957 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1958 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1959 f.debug_tuple("VacantEntry").field(self.key()).finish()
1963 /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1965 /// Contains the occupied entry, and the value that was not inserted.
1966 #[unstable(feature = "map_try_insert", issue = "82766")]
1967 pub struct OccupiedError<'a, K: 'a, V: 'a> {
1968 /// The entry in the map that was already occupied.
1969 pub entry: OccupiedEntry<'a, K, V>,
1970 /// The value which was not inserted, because the entry was already occupied.
1974 #[unstable(feature = "map_try_insert", issue = "82766")]
1975 impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V> {
1976 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977 f.debug_struct("OccupiedError")
1978 .field("key", self.entry.key())
1979 .field("old_value", self.entry.get())
1980 .field("new_value", &self.value)
1981 .finish_non_exhaustive()
1985 #[unstable(feature = "map_try_insert", issue = "82766")]
1986 impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> {
1987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1990 "failed to insert {:?}, key {:?} already exists with value {:?}",
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
2000 type Item = (&'a K, &'a V);
2001 type IntoIter = Iter<'a, K, V>;
2004 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
2005 fn into_iter(self) -> Iter<'a, K, V> {
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
2012 type Item = (&'a K, &'a mut V);
2013 type IntoIter = IterMut<'a, K, V>;
2016 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
2017 fn into_iter(self) -> IterMut<'a, K, V> {
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
2025 type IntoIter = IntoIter<K, V>;
2027 /// Creates a consuming iterator, that is, one that moves each key-value
2028 /// pair out of the map in arbitrary order. The map cannot be used after
2034 /// use std::collections::HashMap;
2036 /// let map = HashMap::from([
2042 /// // Not possible with .iter()
2043 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2046 #[cfg_attr(not(bootstrap), rustc_lint_query_instability)]
2047 fn into_iter(self) -> IntoIter<K, V> {
2048 IntoIter { base: self.base.into_iter() }
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 impl<'a, K, V> Iterator for Iter<'a, K, V> {
2054 type Item = (&'a K, &'a V);
2057 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2061 fn size_hint(&self) -> (usize, Option<usize>) {
2062 self.base.size_hint()
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
2068 fn len(&self) -> usize {
2073 #[stable(feature = "fused", since = "1.26.0")]
2074 impl<K, V> FusedIterator for Iter<'_, K, V> {}
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2078 type Item = (&'a K, &'a mut V);
2081 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2085 fn size_hint(&self) -> (usize, Option<usize>) {
2086 self.base.size_hint()
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2092 fn len(&self) -> usize {
2096 #[stable(feature = "fused", since = "1.26.0")]
2097 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2099 #[stable(feature = "std_debug", since = "1.16.0")]
2100 impl<K, V> fmt::Debug for IterMut<'_, K, V>
2105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2106 f.debug_list().entries(self.iter()).finish()
2110 #[stable(feature = "rust1", since = "1.0.0")]
2111 impl<K, V> Iterator for IntoIter<K, V> {
2115 fn next(&mut self) -> Option<(K, V)> {
2119 fn size_hint(&self) -> (usize, Option<usize>) {
2120 self.base.size_hint()
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2126 fn len(&self) -> usize {
2130 #[stable(feature = "fused", since = "1.26.0")]
2131 impl<K, V> FusedIterator for IntoIter<K, V> {}
2133 #[stable(feature = "std_debug", since = "1.16.0")]
2134 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2136 f.debug_list().entries(self.iter()).finish()
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2145 fn next(&mut self) -> Option<&'a K> {
2146 self.inner.next().map(|(k, _)| k)
2149 fn size_hint(&self) -> (usize, Option<usize>) {
2150 self.inner.size_hint()
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2156 fn len(&self) -> usize {
2160 #[stable(feature = "fused", since = "1.26.0")]
2161 impl<K, V> FusedIterator for Keys<'_, K, V> {}
2163 #[stable(feature = "rust1", since = "1.0.0")]
2164 impl<'a, K, V> Iterator for Values<'a, K, V> {
2168 fn next(&mut self) -> Option<&'a V> {
2169 self.inner.next().map(|(_, v)| v)
2172 fn size_hint(&self) -> (usize, Option<usize>) {
2173 self.inner.size_hint()
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2179 fn len(&self) -> usize {
2183 #[stable(feature = "fused", since = "1.26.0")]
2184 impl<K, V> FusedIterator for Values<'_, K, V> {}
2186 #[stable(feature = "map_values_mut", since = "1.10.0")]
2187 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2188 type Item = &'a mut V;
2191 fn next(&mut self) -> Option<&'a mut V> {
2192 self.inner.next().map(|(_, v)| v)
2195 fn size_hint(&self) -> (usize, Option<usize>) {
2196 self.inner.size_hint()
2199 #[stable(feature = "map_values_mut", since = "1.10.0")]
2200 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2202 fn len(&self) -> usize {
2206 #[stable(feature = "fused", since = "1.26.0")]
2207 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2209 #[stable(feature = "std_debug", since = "1.16.0")]
2210 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2212 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2216 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2217 impl<K, V> Iterator for IntoKeys<K, V> {
2221 fn next(&mut self) -> Option<K> {
2222 self.inner.next().map(|(k, _)| k)
2225 fn size_hint(&self) -> (usize, Option<usize>) {
2226 self.inner.size_hint()
2229 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2230 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2232 fn len(&self) -> usize {
2236 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2237 impl<K, V> FusedIterator for IntoKeys<K, V> {}
2239 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2240 impl<K: Debug, V> fmt::Debug for IntoKeys<K, V> {
2241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2242 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2246 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2247 impl<K, V> Iterator for IntoValues<K, V> {
2251 fn next(&mut self) -> Option<V> {
2252 self.inner.next().map(|(_, v)| v)
2255 fn size_hint(&self) -> (usize, Option<usize>) {
2256 self.inner.size_hint()
2259 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2260 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2262 fn len(&self) -> usize {
2266 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2267 impl<K, V> FusedIterator for IntoValues<K, V> {}
2269 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2270 impl<K, V: Debug> fmt::Debug for IntoValues<K, V> {
2271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2272 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2276 #[stable(feature = "drain", since = "1.6.0")]
2277 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2281 fn next(&mut self) -> Option<(K, V)> {
2285 fn size_hint(&self) -> (usize, Option<usize>) {
2286 self.base.size_hint()
2289 #[stable(feature = "drain", since = "1.6.0")]
2290 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2292 fn len(&self) -> usize {
2296 #[stable(feature = "fused", since = "1.26.0")]
2297 impl<K, V> FusedIterator for Drain<'_, K, V> {}
2299 #[stable(feature = "std_debug", since = "1.16.0")]
2300 impl<K, V> fmt::Debug for Drain<'_, K, V>
2305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2306 f.debug_list().entries(self.iter()).finish()
2310 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2311 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
2313 F: FnMut(&K, &mut V) -> bool,
2318 fn next(&mut self) -> Option<(K, V)> {
2322 fn size_hint(&self) -> (usize, Option<usize>) {
2323 self.base.size_hint()
2327 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2328 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2330 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2331 impl<'a, K, V, F> fmt::Debug for DrainFilter<'a, K, V, F>
2333 F: FnMut(&K, &mut V) -> bool,
2335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2336 f.debug_struct("DrainFilter").finish_non_exhaustive()
2340 impl<'a, K, V> Entry<'a, K, V> {
2341 /// Ensures a value is in the entry by inserting the default if empty, and returns
2342 /// a mutable reference to the value in the entry.
2347 /// use std::collections::HashMap;
2349 /// let mut map: HashMap<&str, u32> = HashMap::new();
2351 /// map.entry("poneyland").or_insert(3);
2352 /// assert_eq!(map["poneyland"], 3);
2354 /// *map.entry("poneyland").or_insert(10) *= 2;
2355 /// assert_eq!(map["poneyland"], 6);
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 pub fn or_insert(self, default: V) -> &'a mut V {
2361 Occupied(entry) => entry.into_mut(),
2362 Vacant(entry) => entry.insert(default),
2366 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2367 /// and returns a mutable reference to the value in the entry.
2372 /// use std::collections::HashMap;
2374 /// let mut map: HashMap<&str, String> = HashMap::new();
2375 /// let s = "hoho".to_string();
2377 /// map.entry("poneyland").or_insert_with(|| s);
2379 /// assert_eq!(map["poneyland"], "hoho".to_string());
2382 #[stable(feature = "rust1", since = "1.0.0")]
2383 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2385 Occupied(entry) => entry.into_mut(),
2386 Vacant(entry) => entry.insert(default()),
2390 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2391 /// This method allows for generating key-derived values for insertion by providing the default
2392 /// function a reference to the key that was moved during the `.entry(key)` method call.
2394 /// The reference to the moved key is provided so that cloning or copying the key is
2395 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2400 /// use std::collections::HashMap;
2402 /// let mut map: HashMap<&str, usize> = HashMap::new();
2404 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2406 /// assert_eq!(map["poneyland"], 9);
2409 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2410 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2412 Occupied(entry) => entry.into_mut(),
2414 let value = default(entry.key());
2420 /// Returns a reference to this entry's key.
2425 /// use std::collections::HashMap;
2427 /// let mut map: HashMap<&str, u32> = HashMap::new();
2428 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2431 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2432 pub fn key(&self) -> &K {
2434 Occupied(ref entry) => entry.key(),
2435 Vacant(ref entry) => entry.key(),
2439 /// Provides in-place mutable access to an occupied entry before any
2440 /// potential inserts into the map.
2445 /// use std::collections::HashMap;
2447 /// let mut map: HashMap<&str, u32> = HashMap::new();
2449 /// map.entry("poneyland")
2450 /// .and_modify(|e| { *e += 1 })
2452 /// assert_eq!(map["poneyland"], 42);
2454 /// map.entry("poneyland")
2455 /// .and_modify(|e| { *e += 1 })
2457 /// assert_eq!(map["poneyland"], 43);
2460 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2461 pub fn and_modify<F>(self, f: F) -> Self
2466 Occupied(mut entry) => {
2470 Vacant(entry) => Vacant(entry),
2474 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2479 /// #![feature(entry_insert)]
2480 /// use std::collections::HashMap;
2482 /// let mut map: HashMap<&str, String> = HashMap::new();
2483 /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2485 /// assert_eq!(entry.key(), &"poneyland");
2488 #[unstable(feature = "entry_insert", issue = "65225")]
2489 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2491 Occupied(mut entry) => {
2492 entry.insert(value);
2495 Vacant(entry) => entry.insert_entry(value),
2500 impl<'a, K, V: Default> Entry<'a, K, V> {
2501 /// Ensures a value is in the entry by inserting the default value if empty,
2502 /// and returns a mutable reference to the value in the entry.
2508 /// use std::collections::HashMap;
2510 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2511 /// map.entry("poneyland").or_default();
2513 /// assert_eq!(map["poneyland"], None);
2517 #[stable(feature = "entry_or_default", since = "1.28.0")]
2518 pub fn or_default(self) -> &'a mut V {
2520 Occupied(entry) => entry.into_mut(),
2521 Vacant(entry) => entry.insert(Default::default()),
2526 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2527 /// Gets a reference to the key in the entry.
2532 /// use std::collections::HashMap;
2534 /// let mut map: HashMap<&str, u32> = HashMap::new();
2535 /// map.entry("poneyland").or_insert(12);
2536 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2539 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2540 pub fn key(&self) -> &K {
2544 /// Take the ownership of the key and value from the map.
2549 /// use std::collections::HashMap;
2550 /// use std::collections::hash_map::Entry;
2552 /// let mut map: HashMap<&str, u32> = HashMap::new();
2553 /// map.entry("poneyland").or_insert(12);
2555 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2556 /// // We delete the entry from the map.
2557 /// o.remove_entry();
2560 /// assert_eq!(map.contains_key("poneyland"), false);
2563 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2564 pub fn remove_entry(self) -> (K, V) {
2565 self.base.remove_entry()
2568 /// Gets a reference to the value in the entry.
2573 /// use std::collections::HashMap;
2574 /// use std::collections::hash_map::Entry;
2576 /// let mut map: HashMap<&str, u32> = HashMap::new();
2577 /// map.entry("poneyland").or_insert(12);
2579 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2580 /// assert_eq!(o.get(), &12);
2584 #[stable(feature = "rust1", since = "1.0.0")]
2585 pub fn get(&self) -> &V {
2589 /// Gets a mutable reference to the value in the entry.
2591 /// If you need a reference to the `OccupiedEntry` which may outlive the
2592 /// destruction of the `Entry` value, see [`into_mut`].
2594 /// [`into_mut`]: Self::into_mut
2599 /// use std::collections::HashMap;
2600 /// use std::collections::hash_map::Entry;
2602 /// let mut map: HashMap<&str, u32> = HashMap::new();
2603 /// map.entry("poneyland").or_insert(12);
2605 /// assert_eq!(map["poneyland"], 12);
2606 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2607 /// *o.get_mut() += 10;
2608 /// assert_eq!(*o.get(), 22);
2610 /// // We can use the same Entry multiple times.
2611 /// *o.get_mut() += 2;
2614 /// assert_eq!(map["poneyland"], 24);
2617 #[stable(feature = "rust1", since = "1.0.0")]
2618 pub fn get_mut(&mut self) -> &mut V {
2622 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2623 /// with a lifetime bound to the map itself.
2625 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2627 /// [`get_mut`]: Self::get_mut
2632 /// use std::collections::HashMap;
2633 /// use std::collections::hash_map::Entry;
2635 /// let mut map: HashMap<&str, u32> = HashMap::new();
2636 /// map.entry("poneyland").or_insert(12);
2638 /// assert_eq!(map["poneyland"], 12);
2639 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2640 /// *o.into_mut() += 10;
2643 /// assert_eq!(map["poneyland"], 22);
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 pub fn into_mut(self) -> &'a mut V {
2648 self.base.into_mut()
2651 /// Sets the value of the entry, and returns the entry's old value.
2656 /// use std::collections::HashMap;
2657 /// use std::collections::hash_map::Entry;
2659 /// let mut map: HashMap<&str, u32> = HashMap::new();
2660 /// map.entry("poneyland").or_insert(12);
2662 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2663 /// assert_eq!(o.insert(15), 12);
2666 /// assert_eq!(map["poneyland"], 15);
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 pub fn insert(&mut self, value: V) -> V {
2671 self.base.insert(value)
2674 /// Takes the value out of the entry, and returns it.
2679 /// use std::collections::HashMap;
2680 /// use std::collections::hash_map::Entry;
2682 /// let mut map: HashMap<&str, u32> = HashMap::new();
2683 /// map.entry("poneyland").or_insert(12);
2685 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2686 /// assert_eq!(o.remove(), 12);
2689 /// assert_eq!(map.contains_key("poneyland"), false);
2692 #[stable(feature = "rust1", since = "1.0.0")]
2693 pub fn remove(self) -> V {
2697 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2698 /// the key used to create this entry.
2703 /// #![feature(map_entry_replace)]
2704 /// use std::collections::hash_map::{Entry, HashMap};
2705 /// use std::rc::Rc;
2707 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2708 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2710 /// let my_key = Rc::new("Stringthing".to_string());
2712 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2713 /// // Also replace the key with a handle to our other key.
2714 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2719 #[unstable(feature = "map_entry_replace", issue = "44286")]
2720 pub fn replace_entry(self, value: V) -> (K, V) {
2721 self.base.replace_entry(value)
2724 /// Replaces the key in the hash map with the key used to create this entry.
2729 /// #![feature(map_entry_replace)]
2730 /// use std::collections::hash_map::{Entry, HashMap};
2731 /// use std::rc::Rc;
2733 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2734 /// let known_strings: Vec<Rc<String>> = Vec::new();
2736 /// // Initialise known strings, run program, etc.
2738 /// reclaim_memory(&mut map, &known_strings);
2740 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2741 /// for s in known_strings {
2742 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2743 /// // Replaces the entry's key with our version of it in `known_strings`.
2744 /// entry.replace_key();
2750 #[unstable(feature = "map_entry_replace", issue = "44286")]
2751 pub fn replace_key(self) -> K {
2752 self.base.replace_key()
2756 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2757 /// Gets a reference to the key that would be used when inserting a value
2758 /// through the `VacantEntry`.
2763 /// use std::collections::HashMap;
2765 /// let mut map: HashMap<&str, u32> = HashMap::new();
2766 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2769 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2770 pub fn key(&self) -> &K {
2774 /// Take ownership of the key.
2779 /// use std::collections::HashMap;
2780 /// use std::collections::hash_map::Entry;
2782 /// let mut map: HashMap<&str, u32> = HashMap::new();
2784 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2789 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2790 pub fn into_key(self) -> K {
2791 self.base.into_key()
2794 /// Sets the value of the entry with the `VacantEntry`'s key,
2795 /// and returns a mutable reference to it.
2800 /// use std::collections::HashMap;
2801 /// use std::collections::hash_map::Entry;
2803 /// let mut map: HashMap<&str, u32> = HashMap::new();
2805 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2808 /// assert_eq!(map["poneyland"], 37);
2811 #[stable(feature = "rust1", since = "1.0.0")]
2812 pub fn insert(self, value: V) -> &'a mut V {
2813 self.base.insert(value)
2816 /// Sets the value of the entry with the `VacantEntry`'s key,
2817 /// and returns an `OccupiedEntry`.
2822 /// #![feature(entry_insert)]
2823 /// use std::collections::HashMap;
2824 /// use std::collections::hash_map::Entry;
2826 /// let mut map: HashMap<&str, u32> = HashMap::new();
2828 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2829 /// o.insert_entry(37);
2831 /// assert_eq!(map["poneyland"], 37);
2834 #[unstable(feature = "entry_insert", issue = "65225")]
2835 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2836 let base = self.base.insert_entry(value);
2837 OccupiedEntry { base }
2841 #[stable(feature = "rust1", since = "1.0.0")]
2842 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2845 S: BuildHasher + Default,
2847 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2848 let mut map = HashMap::with_hasher(Default::default());
2854 /// Inserts all new key-values from the iterator and replaces values with existing
2855 /// keys with new values returned from the iterator.
2856 #[stable(feature = "rust1", since = "1.0.0")]
2857 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2863 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2864 self.base.extend(iter)
2868 fn extend_one(&mut self, (k, v): (K, V)) {
2869 self.base.insert(k, v);
2873 fn extend_reserve(&mut self, additional: usize) {
2874 self.base.extend_reserve(additional);
2878 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2879 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2881 K: Eq + Hash + Copy,
2886 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2887 self.base.extend(iter)
2891 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2892 self.base.insert(k, v);
2896 fn extend_reserve(&mut self, additional: usize) {
2897 Extend::<(K, V)>::extend_reserve(self, additional)
2901 /// `RandomState` is the default state for [`HashMap`] types.
2903 /// A particular instance `RandomState` will create the same instances of
2904 /// [`Hasher`], but the hashers created by two different `RandomState`
2905 /// instances are unlikely to produce the same result for the same values.
2910 /// use std::collections::HashMap;
2911 /// use std::collections::hash_map::RandomState;
2913 /// let s = RandomState::new();
2914 /// let mut map = HashMap::with_hasher(s);
2915 /// map.insert(1, 2);
2918 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2919 pub struct RandomState {
2925 /// Constructs a new `RandomState` that is initialized with random keys.
2930 /// use std::collections::hash_map::RandomState;
2932 /// let s = RandomState::new();
2935 #[allow(deprecated)]
2938 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2939 pub fn new() -> RandomState {
2940 // Historically this function did not cache keys from the OS and instead
2941 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2942 // was discovered, however, that because we re-seed the thread-local RNG
2943 // from the OS periodically that this can cause excessive slowdown when
2944 // many hash maps are created on a thread. To solve this performance
2945 // trap we cache the first set of randomly generated keys per-thread.
2947 // Later in #36481 it was discovered that exposing a deterministic
2948 // iteration order allows a form of DOS attack. To counter that we
2949 // increment one of the seeds on every RandomState creation, giving
2950 // every corresponding HashMap a different iteration order.
2951 thread_local!(static KEYS: Cell<(u64, u64)> = {
2952 Cell::new(sys::hashmap_random_keys())
2956 let (k0, k1) = keys.get();
2957 keys.set((k0.wrapping_add(1), k1));
2958 RandomState { k0, k1 }
2963 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2964 impl BuildHasher for RandomState {
2965 type Hasher = DefaultHasher;
2967 #[allow(deprecated)]
2968 fn build_hasher(&self) -> DefaultHasher {
2969 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2973 /// The default [`Hasher`] used by [`RandomState`].
2975 /// The internal algorithm is not specified, and so it and its hashes should
2976 /// not be relied upon over releases.
2977 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2978 #[allow(deprecated)]
2979 #[derive(Clone, Debug)]
2980 pub struct DefaultHasher(SipHasher13);
2982 impl DefaultHasher {
2983 /// Creates a new `DefaultHasher`.
2985 /// This hasher is not guaranteed to be the same as all other
2986 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2987 /// instances created through `new` or `default`.
2988 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2989 #[allow(deprecated)]
2991 pub fn new() -> DefaultHasher {
2992 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2996 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2997 impl Default for DefaultHasher {
2998 /// Creates a new `DefaultHasher` using [`new`].
2999 /// See its documentation for more.
3001 /// [`new`]: DefaultHasher::new
3002 fn default() -> DefaultHasher {
3003 DefaultHasher::new()
3007 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3008 impl Hasher for DefaultHasher {
3010 fn write(&mut self, msg: &[u8]) {
3015 fn finish(&self) -> u64 {
3020 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3021 impl Default for RandomState {
3022 /// Constructs a new `RandomState`.
3024 fn default() -> RandomState {
3029 #[stable(feature = "std_debug", since = "1.16.0")]
3030 impl fmt::Debug for RandomState {
3031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3032 f.debug_struct("RandomState").finish_non_exhaustive()
3037 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
3039 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
3040 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
3045 pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
3047 hashbrown::TryReserveError::CapacityOverflow => {
3048 TryReserveErrorKind::CapacityOverflow.into()
3050 hashbrown::TryReserveError::AllocError { layout } => {
3051 TryReserveErrorKind::AllocError { layout, non_exhaustive: () }.into()
3057 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
3058 raw: base::RawEntryMut<'a, K, V, S>,
3059 ) -> RawEntryMut<'a, K, V, S> {
3061 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
3062 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
3067 fn assert_covariance() {
3068 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3071 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3074 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3077 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3080 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3083 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3086 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3089 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3092 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3095 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3099 d: Drain<'static, &'static str, &'static str>,
3100 ) -> Drain<'new, &'new str, &'new str> {