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::error
::Error
;
13 use crate::fmt
::{self, Debug}
;
15 use crate::hash
::{BuildHasher, Hash, Hasher, SipHasher13}
;
16 use crate::iter
::FusedIterator
;
17 use crate::ops
::Index
;
20 /// A [hash map] implemented with quadratic probing and SIMD lookup.
22 /// By default, `HashMap` uses a hashing algorithm selected to provide
23 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
24 /// reasonable best-effort is made to generate this seed from a high quality,
25 /// secure source of randomness provided by the host without blocking the
26 /// program. Because of this, the randomness of the seed depends on the output
27 /// quality of the system's random number generator when the seed is created.
28 /// In particular, seeds generated when the system's entropy pool is abnormally
29 /// low such as during system boot may be of a lower quality.
31 /// The default hashing algorithm is currently SipHash 1-3, though this is
32 /// subject to change at any point in the future. While its performance is very
33 /// competitive for medium sized keys, other hashing algorithms will outperform
34 /// it for small keys such as integers as well as large keys such as long
35 /// strings, though those algorithms will typically *not* protect against
36 /// attacks such as HashDoS.
38 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
39 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods.
40 /// There are many alternative [hashing algorithms available on crates.io].
42 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
43 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
44 /// If you implement these yourself, it is important that the following
48 /// k1 == k2 -> hash(k1) == hash(k2)
51 /// In other words, if two keys are equal, their hashes must be equal.
53 /// It is a logic error for a key to be modified in such a way that the key's
54 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
55 /// the [`Eq`] trait, changes while it is in the map. This is normally only
56 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
57 /// The behavior resulting from such a logic error is not specified, but will
58 /// be encapsulated to the `HashMap` that observed the logic error and not
59 /// result in undefined behavior. This could include panics, incorrect results,
60 /// aborts, memory leaks, and non-termination.
62 /// The hash table implementation is a Rust port of Google's [SwissTable].
63 /// The original C++ version of SwissTable can be found [here], and this
64 /// [CppCon talk] gives an overview of how the algorithm works.
66 /// [hash map]: crate::collections#use-a-hashmap-when
67 /// [hashing algorithms available on crates.io]: https://crates.io/keywords/hasher
68 /// [SwissTable]: https://abseil.io/blog/20180927-swisstables
69 /// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
70 /// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
75 /// use std::collections::HashMap;
77 /// // Type inference lets us omit an explicit type signature (which
78 /// // would be `HashMap<String, String>` in this example).
79 /// let mut book_reviews = HashMap::new();
81 /// // Review some books.
82 /// book_reviews.insert(
83 /// "Adventures of Huckleberry Finn".to_string(),
84 /// "My favorite book.".to_string(),
86 /// book_reviews.insert(
87 /// "Grimms' Fairy Tales".to_string(),
88 /// "Masterpiece.".to_string(),
90 /// book_reviews.insert(
91 /// "Pride and Prejudice".to_string(),
92 /// "Very enjoyable.".to_string(),
94 /// book_reviews.insert(
95 /// "The Adventures of Sherlock Holmes".to_string(),
96 /// "Eye lyked it alot.".to_string(),
99 /// // Check for a specific one.
100 /// // When collections store owned values (String), they can still be
101 /// // queried using references (&str).
102 /// if !book_reviews.contains_key("Les Misérables") {
103 /// println!("We've got {} reviews, but Les Misérables ain't one.",
104 /// book_reviews.len());
107 /// // oops, this review has a lot of spelling mistakes, let's delete it.
108 /// book_reviews.remove("The Adventures of Sherlock Holmes");
110 /// // Look up the values associated with some keys.
111 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
112 /// for &book in &to_find {
113 /// match book_reviews.get(book) {
114 /// Some(review) => println!("{book}: {review}"),
115 /// None => println!("{book} is unreviewed.")
119 /// // Look up the value for a key (will panic if the key is not found).
120 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
122 /// // Iterate over everything.
123 /// for (book, review) in &book_reviews {
124 /// println!("{book}: \"{review}\"");
128 /// A `HashMap` with a known list of items can be initialized from an array:
131 /// use std::collections::HashMap;
133 /// let solar_distance = HashMap::from([
134 /// ("Mercury", 0.4),
141 /// `HashMap` implements an [`Entry` API](#method.entry), which allows
142 /// for complex methods of getting, setting, updating and removing keys and
146 /// use std::collections::HashMap;
148 /// // type inference lets us omit an explicit type signature (which
149 /// // would be `HashMap<&str, u8>` in this example).
150 /// let mut player_stats = HashMap::new();
152 /// fn random_stat_buff() -> u8 {
153 /// // could actually return some random value here - let's just return
154 /// // some fixed value for now
158 /// // insert a key only if it doesn't already exist
159 /// player_stats.entry("health").or_insert(100);
161 /// // insert a key using a function that provides a new value only if it
162 /// // doesn't already exist
163 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
165 /// // update a key, guarding against the key possibly not being set
166 /// let stat = player_stats.entry("attack").or_insert(100);
167 /// *stat += random_stat_buff();
169 /// // modify an entry before an insert with in-place mutation
170 /// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
173 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
174 /// We must also derive [`PartialEq`].
176 /// [`RefCell`]: crate::cell::RefCell
177 /// [`Cell`]: crate::cell::Cell
178 /// [`default`]: Default::default
179 /// [`with_hasher`]: Self::with_hasher
180 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
183 /// use std::collections::HashMap;
185 /// #[derive(Hash, Eq, PartialEq, Debug)]
192 /// /// Creates a new Viking.
193 /// fn new(name: &str, country: &str) -> Viking {
194 /// Viking { name: name.to_string(), country: country.to_string() }
198 /// // Use a HashMap to store the vikings' health points.
199 /// let vikings = HashMap::from([
200 /// (Viking::new("Einar", "Norway"), 25),
201 /// (Viking::new("Olaf", "Denmark"), 24),
202 /// (Viking::new("Harald", "Iceland"), 12),
205 /// // Use derived implementation to print the status of the vikings.
206 /// for (viking, health) in &vikings {
207 /// println!("{viking:?} has {health} hp");
211 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]
212 #[stable(feature = "rust1", since = "1.0.0")]
213 #[rustc_insignificant_dtor]
214 pub struct HashMap
<K
, V
, S
= RandomState
> {
215 base
: base
::HashMap
<K
, V
, S
>,
218 impl<K
, V
> HashMap
<K
, V
, RandomState
> {
219 /// Creates an empty `HashMap`.
221 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
222 /// is first inserted into.
227 /// use std::collections::HashMap;
228 /// let mut map: HashMap<&str, i32> = HashMap::new();
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn new() -> HashMap
<K
, V
, RandomState
> {
237 /// Creates an empty `HashMap` with at least the specified capacity.
239 /// The hash map will be able to hold at least `capacity` elements without
240 /// reallocating. This method is allowed to allocate for more elements than
241 /// `capacity`. If `capacity` is 0, the hash set will not allocate.
246 /// use std::collections::HashMap;
247 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn with_capacity(capacity
: usize) -> HashMap
<K
, V
, RandomState
> {
253 HashMap
::with_capacity_and_hasher(capacity
, Default
::default())
257 impl<K
, V
, S
> HashMap
<K
, V
, S
> {
258 /// Creates an empty `HashMap` which will use the given hash builder to hash
261 /// The created map has the default initial capacity.
263 /// Warning: `hash_builder` is normally randomly generated, and
264 /// is designed to allow HashMaps to be resistant to attacks that
265 /// cause many collisions and very poor performance. Setting it
266 /// manually using this function can expose a DoS attack vector.
268 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
269 /// the HashMap to be useful, see its documentation for details.
274 /// use std::collections::HashMap;
275 /// use std::collections::hash_map::RandomState;
277 /// let s = RandomState::new();
278 /// let mut map = HashMap::with_hasher(s);
279 /// map.insert(1, 2);
282 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
283 #[rustc_const_unstable(feature = "const_collections_with_hasher", issue = "102575")]
284 pub const fn with_hasher(hash_builder
: S
) -> HashMap
<K
, V
, S
> {
285 HashMap { base: base::HashMap::with_hasher(hash_builder) }
288 /// Creates an empty `HashMap` with at least the specified capacity, using
289 /// `hasher` to hash the keys.
291 /// The hash map will be able to hold at least `capacity` elements without
292 /// reallocating. This method is allowed to allocate for more elements than
293 /// `capacity`. If `capacity` is 0, the hash map will not allocate.
295 /// Warning: `hasher` is normally randomly generated, and
296 /// is designed to allow HashMaps to be resistant to attacks that
297 /// cause many collisions and very poor performance. Setting it
298 /// manually using this function can expose a DoS attack vector.
300 /// The `hasher` passed should implement the [`BuildHasher`] trait for
301 /// the HashMap to be useful, see its documentation for details.
306 /// use std::collections::HashMap;
307 /// use std::collections::hash_map::RandomState;
309 /// let s = RandomState::new();
310 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
311 /// map.insert(1, 2);
314 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
315 pub fn with_capacity_and_hasher(capacity
: usize, hasher
: S
) -> HashMap
<K
, V
, S
> {
316 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hasher) }
319 /// Returns the number of elements the map can hold without reallocating.
321 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
322 /// more, but is guaranteed to be able to hold at least this many.
327 /// use std::collections::HashMap;
328 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
329 /// assert!(map.capacity() >= 100);
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn capacity(&self) -> usize {
337 /// An iterator visiting all keys in arbitrary order.
338 /// The iterator element type is `&'a K`.
343 /// use std::collections::HashMap;
345 /// let map = HashMap::from([
351 /// for key in map.keys() {
352 /// println!("{key}");
358 /// In the current implementation, iterating over keys takes O(capacity) time
359 /// instead of O(len) because it internally visits empty buckets too.
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn keys(&self) -> Keys
<'_
, K
, V
> {
362 Keys { inner: self.iter() }
365 /// Creates a consuming iterator visiting all the keys in arbitrary order.
366 /// The map cannot be used after calling this.
367 /// The iterator element type is `K`.
372 /// use std::collections::HashMap;
374 /// let map = HashMap::from([
380 /// let mut vec: Vec<&str> = map.into_keys().collect();
381 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
382 /// // keys must be sorted to test them against a sorted array.
383 /// vec.sort_unstable();
384 /// assert_eq!(vec, ["a", "b", "c"]);
389 /// In the current implementation, iterating over keys takes O(capacity) time
390 /// instead of O(len) because it internally visits empty buckets too.
392 #[rustc_lint_query_instability]
393 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
394 pub fn into_keys(self) -> IntoKeys
<K
, V
> {
395 IntoKeys { inner: self.into_iter() }
398 /// An iterator visiting all values in arbitrary order.
399 /// The iterator element type is `&'a V`.
404 /// use std::collections::HashMap;
406 /// let map = HashMap::from([
412 /// for val in map.values() {
413 /// println!("{val}");
419 /// In the current implementation, iterating over values takes O(capacity) time
420 /// instead of O(len) because it internally visits empty buckets too.
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn values(&self) -> Values
<'_
, K
, V
> {
423 Values { inner: self.iter() }
426 /// An iterator visiting all values mutably in arbitrary order.
427 /// The iterator element type is `&'a mut V`.
432 /// use std::collections::HashMap;
434 /// let mut map = HashMap::from([
440 /// for val in map.values_mut() {
441 /// *val = *val + 10;
444 /// for val in map.values() {
445 /// println!("{val}");
451 /// In the current implementation, iterating over values takes O(capacity) time
452 /// instead of O(len) because it internally visits empty buckets too.
453 #[stable(feature = "map_values_mut", since = "1.10.0")]
454 pub fn values_mut(&mut self) -> ValuesMut
<'_
, K
, V
> {
455 ValuesMut { inner: self.iter_mut() }
458 /// Creates a consuming iterator visiting all the values in arbitrary order.
459 /// The map cannot be used after calling this.
460 /// The iterator element type is `V`.
465 /// use std::collections::HashMap;
467 /// let map = HashMap::from([
473 /// let mut vec: Vec<i32> = map.into_values().collect();
474 /// // The `IntoValues` iterator produces values in arbitrary order, so
475 /// // the values must be sorted to test them against a sorted array.
476 /// vec.sort_unstable();
477 /// assert_eq!(vec, [1, 2, 3]);
482 /// In the current implementation, iterating over values takes O(capacity) time
483 /// instead of O(len) because it internally visits empty buckets too.
485 #[rustc_lint_query_instability]
486 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
487 pub fn into_values(self) -> IntoValues
<K
, V
> {
488 IntoValues { inner: self.into_iter() }
491 /// An iterator visiting all key-value pairs in arbitrary order.
492 /// The iterator element type is `(&'a K, &'a V)`.
497 /// use std::collections::HashMap;
499 /// let map = HashMap::from([
505 /// for (key, val) in map.iter() {
506 /// println!("key: {key} val: {val}");
512 /// In the current implementation, iterating over map takes O(capacity) time
513 /// instead of O(len) because it internally visits empty buckets too.
514 #[rustc_lint_query_instability]
515 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn iter(&self) -> Iter
<'_
, K
, V
> {
517 Iter { base: self.base.iter() }
520 /// An iterator visiting all key-value pairs in arbitrary order,
521 /// with mutable references to the values.
522 /// The iterator element type is `(&'a K, &'a mut V)`.
527 /// use std::collections::HashMap;
529 /// let mut map = HashMap::from([
535 /// // Update all values
536 /// for (_, val) in map.iter_mut() {
540 /// for (key, val) in &map {
541 /// println!("key: {key} val: {val}");
547 /// In the current implementation, iterating over map takes O(capacity) time
548 /// instead of O(len) because it internally visits empty buckets too.
549 #[rustc_lint_query_instability]
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn iter_mut(&mut self) -> IterMut
<'_
, K
, V
> {
552 IterMut { base: self.base.iter_mut() }
555 /// Returns the number of elements in the map.
560 /// use std::collections::HashMap;
562 /// let mut a = HashMap::new();
563 /// assert_eq!(a.len(), 0);
564 /// a.insert(1, "a");
565 /// assert_eq!(a.len(), 1);
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub fn len(&self) -> usize {
572 /// Returns `true` if the map contains no elements.
577 /// use std::collections::HashMap;
579 /// let mut a = HashMap::new();
580 /// assert!(a.is_empty());
581 /// a.insert(1, "a");
582 /// assert!(!a.is_empty());
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn is_empty(&self) -> bool
{
590 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
591 /// allocated memory for reuse.
593 /// If the returned iterator is dropped before being fully consumed, it
594 /// drops the remaining key-value pairs. The returned iterator keeps a
595 /// mutable borrow on the map to optimize its implementation.
600 /// use std::collections::HashMap;
602 /// let mut a = HashMap::new();
603 /// a.insert(1, "a");
604 /// a.insert(2, "b");
606 /// for (k, v) in a.drain().take(1) {
607 /// assert!(k == 1 || k == 2);
608 /// assert!(v == "a" || v == "b");
611 /// assert!(a.is_empty());
614 #[rustc_lint_query_instability]
615 #[stable(feature = "drain", since = "1.6.0")]
616 pub fn drain(&mut self) -> Drain
<'_
, K
, V
> {
617 Drain { base: self.base.drain() }
620 /// Creates an iterator which uses a closure to determine if an element should be removed.
622 /// If the closure returns true, the element is removed from the map and yielded.
623 /// If the closure returns false, or panics, the element remains in the map and will not be
626 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
627 /// whether you choose to keep or remove it.
629 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
630 /// elements will still be subjected to the closure and removed and dropped if it returns true.
632 /// It is unspecified how many more elements will be subjected to the closure
633 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
634 /// or if the `DrainFilter` value is leaked.
638 /// Splitting a map into even and odd keys, reusing the original map:
641 /// #![feature(hash_drain_filter)]
642 /// use std::collections::HashMap;
644 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
645 /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
647 /// let mut evens = drained.keys().copied().collect::<Vec<_>>();
648 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
652 /// assert_eq!(evens, vec![0, 2, 4, 6]);
653 /// assert_eq!(odds, vec![1, 3, 5, 7]);
656 #[rustc_lint_query_instability]
657 #[unstable(feature = "hash_drain_filter", issue = "59618")]
658 pub fn drain_filter
<F
>(&mut self, pred
: F
) -> DrainFilter
<'_
, K
, V
, F
>
660 F
: FnMut(&K
, &mut V
) -> bool
,
662 DrainFilter { base: self.base.drain_filter(pred) }
665 /// Retains only the elements specified by the predicate.
667 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
668 /// The elements are visited in unsorted (and unspecified) order.
673 /// use std::collections::HashMap;
675 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
676 /// map.retain(|&k, _| k % 2 == 0);
677 /// assert_eq!(map.len(), 4);
682 /// In the current implementation, this operation takes O(capacity) time
683 /// instead of O(len) because it internally visits empty buckets too.
685 #[rustc_lint_query_instability]
686 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
687 pub fn retain
<F
>(&mut self, f
: F
)
689 F
: FnMut(&K
, &mut V
) -> bool
,
694 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
700 /// use std::collections::HashMap;
702 /// let mut a = HashMap::new();
703 /// a.insert(1, "a");
705 /// assert!(a.is_empty());
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn clear(&mut self) {
713 /// Returns a reference to the map's [`BuildHasher`].
718 /// use std::collections::HashMap;
719 /// use std::collections::hash_map::RandomState;
721 /// let hasher = RandomState::new();
722 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
723 /// let hasher: &RandomState = map.hasher();
726 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
727 pub fn hasher(&self) -> &S
{
732 impl<K
, V
, S
> HashMap
<K
, V
, S
>
737 /// Reserves capacity for at least `additional` more elements to be inserted
738 /// in the `HashMap`. The collection may reserve more space to speculatively
739 /// avoid frequent reallocations. After calling `reserve`,
740 /// capacity will be greater than or equal to `self.len() + additional`.
741 /// Does nothing if capacity is already sufficient.
745 /// Panics if the new allocation size overflows [`usize`].
750 /// use std::collections::HashMap;
751 /// let mut map: HashMap<&str, i32> = HashMap::new();
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn reserve(&mut self, additional
: usize) {
757 self.base
.reserve(additional
)
760 /// Tries to reserve capacity for at least `additional` more elements to be inserted
761 /// in the `HashMap`. The collection may reserve more space to speculatively
762 /// avoid frequent reallocations. After calling `try_reserve`,
763 /// capacity will be greater than or equal to `self.len() + additional` if
764 /// it returns `Ok(())`.
765 /// Does nothing if capacity is already sufficient.
769 /// If the capacity overflows, or the allocator reports a failure, then an error
775 /// use std::collections::HashMap;
777 /// let mut map: HashMap<&str, isize> = HashMap::new();
778 /// map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?");
781 #[stable(feature = "try_reserve", since = "1.57.0")]
782 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
783 self.base
.try_reserve(additional
).map_err(map_try_reserve_error
)
786 /// Shrinks the capacity of the map as much as possible. It will drop
787 /// down as much as possible while maintaining the internal rules
788 /// and possibly leaving some space in accordance with the resize policy.
793 /// use std::collections::HashMap;
795 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
796 /// map.insert(1, 2);
797 /// map.insert(3, 4);
798 /// assert!(map.capacity() >= 100);
799 /// map.shrink_to_fit();
800 /// assert!(map.capacity() >= 2);
803 #[stable(feature = "rust1", since = "1.0.0")]
804 pub fn shrink_to_fit(&mut self) {
805 self.base
.shrink_to_fit();
808 /// Shrinks the capacity of the map with a lower limit. It will drop
809 /// down no lower than the supplied limit while maintaining the internal rules
810 /// and possibly leaving some space in accordance with the resize policy.
812 /// If the current capacity is less than the lower limit, this is a no-op.
817 /// use std::collections::HashMap;
819 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
820 /// map.insert(1, 2);
821 /// map.insert(3, 4);
822 /// assert!(map.capacity() >= 100);
823 /// map.shrink_to(10);
824 /// assert!(map.capacity() >= 10);
825 /// map.shrink_to(0);
826 /// assert!(map.capacity() >= 2);
829 #[stable(feature = "shrink_to", since = "1.56.0")]
830 pub fn shrink_to(&mut self, min_capacity
: usize) {
831 self.base
.shrink_to(min_capacity
);
834 /// Gets the given key's corresponding entry in the map for in-place manipulation.
839 /// use std::collections::HashMap;
841 /// let mut letters = HashMap::new();
843 /// for ch in "a short treatise on fungi".chars() {
844 /// letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
847 /// assert_eq!(letters[&'s'], 2);
848 /// assert_eq!(letters[&'t'], 3);
849 /// assert_eq!(letters[&'u'], 1);
850 /// assert_eq!(letters.get(&'y'), None);
853 #[stable(feature = "rust1", since = "1.0.0")]
854 pub fn entry(&mut self, key
: K
) -> Entry
<'_
, K
, V
> {
855 map_entry(self.base
.rustc_entry(key
))
858 /// Returns a reference to the value corresponding to the 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.get(&1), Some(&"a"));
872 /// assert_eq!(map.get(&2), None);
874 #[stable(feature = "rust1", since = "1.0.0")]
876 pub fn get
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<&V
>
884 /// Returns the key-value pair corresponding to the supplied key.
886 /// The supplied 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 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
898 /// assert_eq!(map.get_key_value(&2), None);
901 #[stable(feature = "map_get_key_value", since = "1.40.0")]
902 pub fn get_key_value
<Q
: ?Sized
>(&self, k
: &Q
) -> Option
<(&K
, &V
)>
907 self.base
.get_key_value(k
)
910 /// Attempts to get mutable references to `N` values in the map at once.
912 /// Returns an array of length `N` with the results of each query. For soundness, at most one
913 /// mutable reference will be returned to any value. `None` will be returned if any of the
914 /// keys are duplicates or missing.
919 /// #![feature(map_many_mut)]
920 /// use std::collections::HashMap;
922 /// let mut libraries = HashMap::new();
923 /// libraries.insert("Bodleian Library".to_string(), 1602);
924 /// libraries.insert("Athenæum".to_string(), 1807);
925 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
926 /// libraries.insert("Library of Congress".to_string(), 1800);
928 /// let got = libraries.get_many_mut([
930 /// "Library of Congress",
940 /// // Missing keys result in None
941 /// let got = libraries.get_many_mut([
943 /// "New York Public Library",
945 /// assert_eq!(got, None);
947 /// // Duplicate keys result in None
948 /// let got = libraries.get_many_mut([
952 /// assert_eq!(got, None);
955 #[unstable(feature = "map_many_mut", issue = "97601")]
956 pub fn get_many_mut
<Q
: ?Sized
, const N
: usize>(&mut self, ks
: [&Q
; N
]) -> Option
<[&'_
mut V
; N
]>
961 self.base
.get_many_mut(ks
)
964 /// Attempts to get mutable references to `N` values in the map at once, without validating that
965 /// the values are unique.
967 /// Returns an array of length `N` with the results of each query. `None` will be returned if
968 /// any of the keys are missing.
970 /// For a safe alternative see [`get_many_mut`](Self::get_many_mut).
974 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
975 /// references are not used.
977 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
982 /// #![feature(map_many_mut)]
983 /// use std::collections::HashMap;
985 /// let mut libraries = HashMap::new();
986 /// libraries.insert("Bodleian Library".to_string(), 1602);
987 /// libraries.insert("Athenæum".to_string(), 1807);
988 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
989 /// libraries.insert("Library of Congress".to_string(), 1800);
991 /// let got = libraries.get_many_mut([
993 /// "Library of Congress",
1003 /// // Missing keys result in None
1004 /// let got = libraries.get_many_mut([
1006 /// "New York Public Library",
1008 /// assert_eq!(got, None);
1011 #[unstable(feature = "map_many_mut", issue = "97601")]
1012 pub unsafe fn get_many_unchecked_mut
<Q
: ?Sized
, const N
: usize>(
1015 ) -> Option
<[&'_
mut V
; N
]>
1020 self.base
.get_many_unchecked_mut(ks
)
1023 /// Returns `true` if the map contains a value for the specified key.
1025 /// The key may be any borrowed form of the map's key type, but
1026 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1032 /// use std::collections::HashMap;
1034 /// let mut map = HashMap::new();
1035 /// map.insert(1, "a");
1036 /// assert_eq!(map.contains_key(&1), true);
1037 /// assert_eq!(map.contains_key(&2), false);
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 pub fn contains_key
<Q
: ?Sized
>(&self, k
: &Q
) -> bool
1046 self.base
.contains_key(k
)
1049 /// Returns a mutable reference to the value corresponding to the key.
1051 /// The key may be any borrowed form of the map's key type, but
1052 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1058 /// use std::collections::HashMap;
1060 /// let mut map = HashMap::new();
1061 /// map.insert(1, "a");
1062 /// if let Some(x) = map.get_mut(&1) {
1065 /// assert_eq!(map[&1], "b");
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub fn get_mut
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<&mut V
>
1074 self.base
.get_mut(k
)
1077 /// Inserts a key-value pair into the map.
1079 /// If the map did not have this key present, [`None`] is returned.
1081 /// If the map did have this key present, the value is updated, and the old
1082 /// value is returned. The key is not updated, though; this matters for
1083 /// types that can be `==` without being identical. See the [module-level
1084 /// documentation] for more.
1086 /// [module-level documentation]: crate::collections#insert-and-complex-keys
1091 /// use std::collections::HashMap;
1093 /// let mut map = HashMap::new();
1094 /// assert_eq!(map.insert(37, "a"), None);
1095 /// assert_eq!(map.is_empty(), false);
1097 /// map.insert(37, "b");
1098 /// assert_eq!(map.insert(37, "c"), Some("b"));
1099 /// assert_eq!(map[&37], "c");
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 pub fn insert(&mut self, k
: K
, v
: V
) -> Option
<V
> {
1104 self.base
.insert(k
, v
)
1107 /// Tries to insert a key-value pair into the map, and returns
1108 /// a mutable reference to the value in the entry.
1110 /// If the map already had this key present, nothing is updated, and
1111 /// an error containing the occupied entry and the value is returned.
1118 /// #![feature(map_try_insert)]
1120 /// use std::collections::HashMap;
1122 /// let mut map = HashMap::new();
1123 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1125 /// let err = map.try_insert(37, "b").unwrap_err();
1126 /// assert_eq!(err.entry.key(), &37);
1127 /// assert_eq!(err.entry.get(), &"a");
1128 /// assert_eq!(err.value, "b");
1130 #[unstable(feature = "map_try_insert", issue = "82766")]
1131 pub fn try_insert(&mut self, key
: K
, value
: V
) -> Result
<&mut V
, OccupiedError
<'_
, K
, V
>> {
1132 match self.entry(key
) {
1133 Occupied(entry
) => Err(OccupiedError { entry, value }
),
1134 Vacant(entry
) => Ok(entry
.insert(value
)),
1138 /// Removes a key from the map, returning the value at the key if the key
1139 /// was previously in the map.
1141 /// The key may be any borrowed form of the map's key type, but
1142 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1148 /// use std::collections::HashMap;
1150 /// let mut map = HashMap::new();
1151 /// map.insert(1, "a");
1152 /// assert_eq!(map.remove(&1), Some("a"));
1153 /// assert_eq!(map.remove(&1), None);
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 pub fn remove
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<V
>
1165 /// Removes a key from the map, returning the stored key and value if the
1166 /// key was previously in the map.
1168 /// The key may be any borrowed form of the map's key type, but
1169 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1175 /// use std::collections::HashMap;
1178 /// let mut map = HashMap::new();
1179 /// map.insert(1, "a");
1180 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1181 /// assert_eq!(map.remove(&1), None);
1185 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1186 pub fn remove_entry
<Q
: ?Sized
>(&mut self, k
: &Q
) -> Option
<(K
, V
)>
1191 self.base
.remove_entry(k
)
1195 impl<K
, V
, S
> HashMap
<K
, V
, S
>
1199 /// Creates a raw entry builder for the HashMap.
1201 /// Raw entries provide the lowest level of control for searching and
1202 /// manipulating a map. They must be manually initialized with a hash and
1203 /// then manually searched. After this, insertions into a vacant entry
1204 /// still require an owned key to be provided.
1206 /// Raw entries are useful for such exotic situations as:
1208 /// * Hash memoization
1209 /// * Deferring the creation of an owned key until it is known to be required
1210 /// * Using a search key that doesn't work with the Borrow trait
1211 /// * Using custom comparison logic without newtype wrappers
1213 /// Because raw entries provide much more low-level control, it's much easier
1214 /// to put the HashMap into an inconsistent state which, while memory-safe,
1215 /// will cause the map to produce seemingly random results. Higher-level and
1216 /// more foolproof APIs like `entry` should be preferred when possible.
1218 /// In particular, the hash used to initialized the raw entry must still be
1219 /// consistent with the hash of the key that is ultimately stored in the entry.
1220 /// This is because implementations of HashMap may need to recompute hashes
1221 /// when resizing, at which point only the keys are available.
1223 /// Raw entries give mutable access to the keys. This must not be used
1224 /// to modify how the key would compare or hash, as the map will not re-evaluate
1225 /// where the key should go, meaning the keys may become "lost" if their
1226 /// location does not reflect their state. For instance, if you change a key
1227 /// so that the map now contains keys which compare equal, search may start
1228 /// acting erratically, with two keys randomly masking each other. Implementations
1229 /// are free to assume this doesn't happen (within the limits of memory-safety).
1231 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1232 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut
<'_
, K
, V
, S
> {
1233 RawEntryBuilderMut { map: self }
1236 /// Creates a raw immutable entry builder for the HashMap.
1238 /// Raw entries provide the lowest level of control for searching and
1239 /// manipulating a map. They must be manually initialized with a hash and
1240 /// then manually searched.
1242 /// This is useful for
1243 /// * Hash memoization
1244 /// * Using a search key that doesn't work with the Borrow trait
1245 /// * Using custom comparison logic without newtype wrappers
1247 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1248 /// `get` should be preferred.
1250 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1252 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1253 pub fn raw_entry(&self) -> RawEntryBuilder
<'_
, K
, V
, S
> {
1254 RawEntryBuilder { map: self }
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<K
, V
, S
> Clone
for HashMap
<K
, V
, S
>
1266 fn clone(&self) -> Self {
1267 Self { base: self.base.clone() }
1271 fn clone_from(&mut self, other
: &Self) {
1272 self.base
.clone_from(&other
.base
);
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 impl<K
, V
, S
> PartialEq
for HashMap
<K
, V
, S
>
1283 fn eq(&self, other
: &HashMap
<K
, V
, S
>) -> bool
{
1284 if self.len() != other
.len() {
1288 self.iter().all(|(key
, value
)| other
.get(key
).map_or(false, |v
| *value
== *v
))
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<K
, V
, S
> Eq
for HashMap
<K
, V
, S
>
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<K
, V
, S
> Debug
for HashMap
<K
, V
, S
>
1307 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1308 f
.debug_map().entries(self.iter()).finish()
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<K
, V
, S
> Default
for HashMap
<K
, V
, S
>
1317 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1319 fn default() -> HashMap
<K
, V
, S
> {
1320 HashMap
::with_hasher(Default
::default())
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 impl<K
, Q
: ?Sized
, V
, S
> Index
<&Q
> for HashMap
<K
, V
, S
>
1327 K
: Eq
+ Hash
+ Borrow
<Q
>,
1333 /// Returns a reference to the value corresponding to the supplied key.
1337 /// Panics if the key is not present in the `HashMap`.
1339 fn index(&self, key
: &Q
) -> &V
{
1340 self.get(key
).expect("no entry found for key")
1344 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1345 // Note: as what is currently the most convenient built-in way to construct
1346 // a HashMap, a simple usage of this function must not *require* the user
1347 // to provide a type annotation in order to infer the third type parameter
1348 // (the hasher parameter, conventionally "S").
1349 // To that end, this impl is defined using RandomState as the concrete
1350 // type of S, rather than being generic over `S: BuildHasher + Default`.
1351 // It is expected that users who want to specify a hasher will manually use
1352 // `with_capacity_and_hasher`.
1353 // If type parameter defaults worked on impls, and if type parameter
1354 // defaults could be mixed with const generics, then perhaps
1355 // this could be generalized.
1356 // See also the equivalent impl on HashSet.
1357 impl<K
, V
, const N
: usize> From
<[(K
, V
); N
]> for HashMap
<K
, V
, RandomState
>
1364 /// use std::collections::HashMap;
1366 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1367 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1368 /// assert_eq!(map1, map2);
1370 fn from(arr
: [(K
, V
); N
]) -> Self {
1371 Self::from_iter(arr
)
1375 /// An iterator over the entries of a `HashMap`.
1377 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1378 /// documentation for more.
1380 /// [`iter`]: HashMap::iter
1385 /// use std::collections::HashMap;
1387 /// let map = HashMap::from([
1390 /// let iter = map.iter();
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 pub struct Iter
<'a
, K
: 'a
, V
: 'a
> {
1394 base
: base
::Iter
<'a
, K
, V
>,
1397 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<K
, V
> Clone
for Iter
<'_
, K
, V
> {
1401 fn clone(&self) -> Self {
1402 Iter { base: self.base.clone() }
1406 #[stable(feature = "std_debug", since = "1.16.0")]
1407 impl<K
: Debug
, V
: Debug
> fmt
::Debug
for Iter
<'_
, K
, V
> {
1408 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1409 f
.debug_list().entries(self.clone()).finish()
1413 /// A mutable iterator over the entries of a `HashMap`.
1415 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1416 /// documentation for more.
1418 /// [`iter_mut`]: HashMap::iter_mut
1423 /// use std::collections::HashMap;
1425 /// let mut map = HashMap::from([
1428 /// let iter = map.iter_mut();
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 pub struct IterMut
<'a
, K
: 'a
, V
: 'a
> {
1432 base
: base
::IterMut
<'a
, K
, V
>,
1435 impl<'a
, K
, V
> IterMut
<'a
, K
, V
> {
1436 /// Returns an iterator of references over the remaining items.
1438 pub(super) fn iter(&self) -> Iter
<'_
, K
, V
> {
1439 Iter { base: self.base.rustc_iter() }
1443 /// An owning iterator over the entries of a `HashMap`.
1445 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1446 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
1448 /// [`into_iter`]: IntoIterator::into_iter
1449 /// [`IntoIterator`]: crate::iter::IntoIterator
1454 /// use std::collections::HashMap;
1456 /// let map = HashMap::from([
1459 /// let iter = map.into_iter();
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 pub struct IntoIter
<K
, V
> {
1463 base
: base
::IntoIter
<K
, V
>,
1466 impl<K
, V
> IntoIter
<K
, V
> {
1467 /// Returns an iterator of references over the remaining items.
1469 pub(super) fn iter(&self) -> Iter
<'_
, K
, V
> {
1470 Iter { base: self.base.rustc_iter() }
1474 /// An iterator over the keys of a `HashMap`.
1476 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1477 /// documentation for more.
1479 /// [`keys`]: HashMap::keys
1484 /// use std::collections::HashMap;
1486 /// let map = HashMap::from([
1489 /// let iter_keys = map.keys();
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 pub struct Keys
<'a
, K
: 'a
, V
: 'a
> {
1493 inner
: Iter
<'a
, K
, V
>,
1496 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 impl<K
, V
> Clone
for Keys
<'_
, K
, V
> {
1500 fn clone(&self) -> Self {
1501 Keys { inner: self.inner.clone() }
1505 #[stable(feature = "std_debug", since = "1.16.0")]
1506 impl<K
: Debug
, V
> fmt
::Debug
for Keys
<'_
, K
, V
> {
1507 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1508 f
.debug_list().entries(self.clone()).finish()
1512 /// An iterator over the values of a `HashMap`.
1514 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1515 /// documentation for more.
1517 /// [`values`]: HashMap::values
1522 /// use std::collections::HashMap;
1524 /// let map = HashMap::from([
1527 /// let iter_values = map.values();
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub struct Values
<'a
, K
: 'a
, V
: 'a
> {
1531 inner
: Iter
<'a
, K
, V
>,
1534 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1535 #[stable(feature = "rust1", since = "1.0.0")]
1536 impl<K
, V
> Clone
for Values
<'_
, K
, V
> {
1538 fn clone(&self) -> Self {
1539 Values { inner: self.inner.clone() }
1543 #[stable(feature = "std_debug", since = "1.16.0")]
1544 impl<K
, V
: Debug
> fmt
::Debug
for Values
<'_
, K
, V
> {
1545 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1546 f
.debug_list().entries(self.clone()).finish()
1550 /// A draining iterator over the entries of a `HashMap`.
1552 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1553 /// documentation for more.
1555 /// [`drain`]: HashMap::drain
1560 /// use std::collections::HashMap;
1562 /// let mut map = HashMap::from([
1565 /// let iter = map.drain();
1567 #[stable(feature = "drain", since = "1.6.0")]
1568 pub struct Drain
<'a
, K
: 'a
, V
: 'a
> {
1569 base
: base
::Drain
<'a
, K
, V
>,
1572 impl<'a
, K
, V
> Drain
<'a
, K
, V
> {
1573 /// Returns an iterator of references over the remaining items.
1575 pub(super) fn iter(&self) -> Iter
<'_
, K
, V
> {
1576 Iter { base: self.base.rustc_iter() }
1580 /// A draining, filtering iterator over the entries of a `HashMap`.
1582 /// This `struct` is created by the [`drain_filter`] method on [`HashMap`].
1584 /// [`drain_filter`]: HashMap::drain_filter
1589 /// #![feature(hash_drain_filter)]
1591 /// use std::collections::HashMap;
1593 /// let mut map = HashMap::from([
1596 /// let iter = map.drain_filter(|_k, v| *v % 2 == 0);
1598 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1599 pub struct DrainFilter
<'a
, K
, V
, F
>
1601 F
: FnMut(&K
, &mut V
) -> bool
,
1603 base
: base
::DrainFilter
<'a
, K
, V
, F
>,
1606 /// A mutable iterator over the values of a `HashMap`.
1608 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1609 /// documentation for more.
1611 /// [`values_mut`]: HashMap::values_mut
1616 /// use std::collections::HashMap;
1618 /// let mut map = HashMap::from([
1621 /// let iter_values = map.values_mut();
1623 #[stable(feature = "map_values_mut", since = "1.10.0")]
1624 pub struct ValuesMut
<'a
, K
: 'a
, V
: 'a
> {
1625 inner
: IterMut
<'a
, K
, V
>,
1628 /// An owning iterator over the keys of a `HashMap`.
1630 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1631 /// See its documentation for more.
1633 /// [`into_keys`]: HashMap::into_keys
1638 /// use std::collections::HashMap;
1640 /// let map = HashMap::from([
1643 /// let iter_keys = map.into_keys();
1645 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1646 pub struct IntoKeys
<K
, V
> {
1647 inner
: IntoIter
<K
, V
>,
1650 /// An owning iterator over the values of a `HashMap`.
1652 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1653 /// See its documentation for more.
1655 /// [`into_values`]: HashMap::into_values
1660 /// use std::collections::HashMap;
1662 /// let map = HashMap::from([
1665 /// let iter_keys = map.into_values();
1667 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1668 pub struct IntoValues
<K
, V
> {
1669 inner
: IntoIter
<K
, V
>,
1672 /// A builder for computing where in a HashMap a key-value pair would be stored.
1674 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1675 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1676 pub struct RawEntryBuilderMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1677 map
: &'a
mut HashMap
<K
, V
, S
>,
1680 /// A view into a single entry in a map, which may either be vacant or occupied.
1682 /// This is a lower-level version of [`Entry`].
1684 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1685 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1687 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1688 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1689 pub enum RawEntryMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1690 /// An occupied entry.
1691 Occupied(RawOccupiedEntryMut
<'a
, K
, V
, S
>),
1693 Vacant(RawVacantEntryMut
<'a
, K
, V
, S
>),
1696 /// A view into an occupied entry in a `HashMap`.
1697 /// It is part of the [`RawEntryMut`] enum.
1698 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1699 pub struct RawOccupiedEntryMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1700 base
: base
::RawOccupiedEntryMut
<'a
, K
, V
, S
>,
1703 /// A view into a vacant entry in a `HashMap`.
1704 /// It is part of the [`RawEntryMut`] enum.
1705 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1706 pub struct RawVacantEntryMut
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1707 base
: base
::RawVacantEntryMut
<'a
, K
, V
, S
>,
1710 /// A builder for computing where in a HashMap a key-value pair would be stored.
1712 /// See the [`HashMap::raw_entry`] docs for usage examples.
1713 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1714 pub struct RawEntryBuilder
<'a
, K
: 'a
, V
: 'a
, S
: 'a
> {
1715 map
: &'a HashMap
<K
, V
, S
>,
1718 impl<'a
, K
, V
, S
> RawEntryBuilderMut
<'a
, K
, V
, S
>
1722 /// Creates a `RawEntryMut` from the given key.
1724 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1725 pub fn from_key
<Q
: ?Sized
>(self, k
: &Q
) -> RawEntryMut
<'a
, K
, V
, S
>
1730 map_raw_entry(self.map
.base
.raw_entry_mut().from_key(k
))
1733 /// Creates a `RawEntryMut` from the given key and its hash.
1735 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1736 pub fn from_key_hashed_nocheck
<Q
: ?Sized
>(self, hash
: u64, k
: &Q
) -> RawEntryMut
<'a
, K
, V
, S
>
1741 map_raw_entry(self.map
.base
.raw_entry_mut().from_key_hashed_nocheck(hash
, k
))
1744 /// Creates a `RawEntryMut` from the given hash.
1746 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1747 pub fn from_hash
<F
>(self, hash
: u64, is_match
: F
) -> RawEntryMut
<'a
, K
, V
, S
>
1749 for<'b
> F
: FnMut(&'b K
) -> bool
,
1751 map_raw_entry(self.map
.base
.raw_entry_mut().from_hash(hash
, is_match
))
1755 impl<'a
, K
, V
, S
> RawEntryBuilder
<'a
, K
, V
, S
>
1759 /// Access an entry by key.
1761 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1762 pub fn from_key
<Q
: ?Sized
>(self, k
: &Q
) -> Option
<(&'a K
, &'a V
)>
1767 self.map
.base
.raw_entry().from_key(k
)
1770 /// Access an entry by a key and its hash.
1772 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1773 pub fn from_key_hashed_nocheck
<Q
: ?Sized
>(self, hash
: u64, k
: &Q
) -> Option
<(&'a K
, &'a V
)>
1778 self.map
.base
.raw_entry().from_key_hashed_nocheck(hash
, k
)
1781 /// Access an entry by hash.
1783 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1784 pub fn from_hash
<F
>(self, hash
: u64, is_match
: F
) -> Option
<(&'a K
, &'a V
)>
1786 F
: FnMut(&K
) -> bool
,
1788 self.map
.base
.raw_entry().from_hash(hash
, is_match
)
1792 impl<'a
, K
, V
, S
> RawEntryMut
<'a
, K
, V
, S
> {
1793 /// Ensures a value is in the entry by inserting the default if empty, and returns
1794 /// mutable references to the key and value in the entry.
1799 /// #![feature(hash_raw_entry)]
1800 /// use std::collections::HashMap;
1802 /// let mut map: HashMap<&str, u32> = HashMap::new();
1804 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1805 /// assert_eq!(map["poneyland"], 3);
1807 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1808 /// assert_eq!(map["poneyland"], 6);
1811 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1812 pub fn or_insert(self, default_key
: K
, default_val
: V
) -> (&'a
mut K
, &'a
mut V
)
1818 RawEntryMut
::Occupied(entry
) => entry
.into_key_value(),
1819 RawEntryMut
::Vacant(entry
) => entry
.insert(default_key
, default_val
),
1823 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1824 /// and returns mutable references to the key and value in the entry.
1829 /// #![feature(hash_raw_entry)]
1830 /// use std::collections::HashMap;
1832 /// let mut map: HashMap<&str, String> = HashMap::new();
1834 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1835 /// ("poneyland", "hoho".to_string())
1838 /// assert_eq!(map["poneyland"], "hoho".to_string());
1841 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1842 pub fn or_insert_with
<F
>(self, default: F
) -> (&'a
mut K
, &'a
mut V
)
1844 F
: FnOnce() -> (K
, V
),
1849 RawEntryMut
::Occupied(entry
) => entry
.into_key_value(),
1850 RawEntryMut
::Vacant(entry
) => {
1851 let (k
, v
) = default();
1857 /// Provides in-place mutable access to an occupied entry before any
1858 /// potential inserts into the map.
1863 /// #![feature(hash_raw_entry)]
1864 /// use std::collections::HashMap;
1866 /// let mut map: HashMap<&str, u32> = HashMap::new();
1868 /// map.raw_entry_mut()
1869 /// .from_key("poneyland")
1870 /// .and_modify(|_k, v| { *v += 1 })
1871 /// .or_insert("poneyland", 42);
1872 /// assert_eq!(map["poneyland"], 42);
1874 /// map.raw_entry_mut()
1875 /// .from_key("poneyland")
1876 /// .and_modify(|_k, v| { *v += 1 })
1877 /// .or_insert("poneyland", 0);
1878 /// assert_eq!(map["poneyland"], 43);
1881 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1882 pub fn and_modify
<F
>(self, f
: F
) -> Self
1884 F
: FnOnce(&mut K
, &mut V
),
1887 RawEntryMut
::Occupied(mut entry
) => {
1889 let (k
, v
) = entry
.get_key_value_mut();
1892 RawEntryMut
::Occupied(entry
)
1894 RawEntryMut
::Vacant(entry
) => RawEntryMut
::Vacant(entry
),
1899 impl<'a
, K
, V
, S
> RawOccupiedEntryMut
<'a
, K
, V
, S
> {
1900 /// Gets a reference to the key in the entry.
1903 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1904 pub fn key(&self) -> &K
{
1908 /// Gets a mutable reference to the key in the entry.
1911 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1912 pub fn key_mut(&mut self) -> &mut K
{
1916 /// Converts the entry into a mutable reference to the key in the entry
1917 /// with a lifetime bound to the map itself.
1919 #[must_use = "`self` will be dropped if the result is not used"]
1920 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1921 pub fn into_key(self) -> &'a
mut K
{
1922 self.base
.into_key()
1925 /// Gets a reference to the value in the entry.
1928 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1929 pub fn get(&self) -> &V
{
1933 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
1934 /// with a lifetime bound to the map itself.
1936 #[must_use = "`self` will be dropped if the result is not used"]
1937 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1938 pub fn into_mut(self) -> &'a
mut V
{
1939 self.base
.into_mut()
1942 /// Gets a mutable reference to the value in the entry.
1945 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1946 pub fn get_mut(&mut self) -> &mut V
{
1950 /// Gets a reference to the key and value in the entry.
1953 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1954 pub fn get_key_value(&mut self) -> (&K
, &V
) {
1955 self.base
.get_key_value()
1958 /// Gets a mutable reference to the key and value in the entry.
1960 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1961 pub fn get_key_value_mut(&mut self) -> (&mut K
, &mut V
) {
1962 self.base
.get_key_value_mut()
1965 /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry
1966 /// with a lifetime bound to the map itself.
1968 #[must_use = "`self` will be dropped if the result is not used"]
1969 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1970 pub fn into_key_value(self) -> (&'a
mut K
, &'a
mut V
) {
1971 self.base
.into_key_value()
1974 /// Sets the value of the entry, and returns the entry's old value.
1976 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1977 pub fn insert(&mut self, value
: V
) -> V
{
1978 self.base
.insert(value
)
1981 /// Sets the value of the entry, and returns the entry's old value.
1983 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1984 pub fn insert_key(&mut self, key
: K
) -> K
{
1985 self.base
.insert_key(key
)
1988 /// Takes the value out of the entry, and returns it.
1990 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1991 pub fn remove(self) -> V
{
1995 /// Take the ownership of the key and value from the map.
1997 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1998 pub fn remove_entry(self) -> (K
, V
) {
1999 self.base
.remove_entry()
2003 impl<'a
, K
, V
, S
> RawVacantEntryMut
<'a
, K
, V
, S
> {
2004 /// Sets the value of the entry with the `VacantEntry`'s key,
2005 /// and returns a mutable reference to it.
2007 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2008 pub fn insert(self, key
: K
, value
: V
) -> (&'a
mut K
, &'a
mut V
)
2013 self.base
.insert(key
, value
)
2016 /// Sets the value of the entry with the VacantEntry's key,
2017 /// and returns a mutable reference to it.
2019 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2020 pub fn insert_hashed_nocheck(self, hash
: u64, key
: K
, value
: V
) -> (&'a
mut K
, &'a
mut V
)
2025 self.base
.insert_hashed_nocheck(hash
, key
, value
)
2029 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2030 impl<K
, V
, S
> Debug
for RawEntryBuilderMut
<'_
, K
, V
, S
> {
2031 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2032 f
.debug_struct("RawEntryBuilder").finish_non_exhaustive()
2036 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2037 impl<K
: Debug
, V
: Debug
, S
> Debug
for RawEntryMut
<'_
, K
, V
, S
> {
2038 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2040 RawEntryMut
::Vacant(ref v
) => f
.debug_tuple("RawEntry").field(v
).finish(),
2041 RawEntryMut
::Occupied(ref o
) => f
.debug_tuple("RawEntry").field(o
).finish(),
2046 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2047 impl<K
: Debug
, V
: Debug
, S
> Debug
for RawOccupiedEntryMut
<'_
, K
, V
, S
> {
2048 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2049 f
.debug_struct("RawOccupiedEntryMut")
2050 .field("key", self.key())
2051 .field("value", self.get())
2052 .finish_non_exhaustive()
2056 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2057 impl<K
, V
, S
> Debug
for RawVacantEntryMut
<'_
, K
, V
, S
> {
2058 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2059 f
.debug_struct("RawVacantEntryMut").finish_non_exhaustive()
2063 #[unstable(feature = "hash_raw_entry", issue = "56167")]
2064 impl<K
, V
, S
> Debug
for RawEntryBuilder
<'_
, K
, V
, S
> {
2065 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2066 f
.debug_struct("RawEntryBuilder").finish_non_exhaustive()
2070 /// A view into a single entry in a map, which may either be vacant or occupied.
2072 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2074 /// [`entry`]: HashMap::entry
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 #[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
2077 pub enum Entry
<'a
, K
: 'a
, V
: 'a
> {
2078 /// An occupied entry.
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
2087 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2088 impl<K
: Debug
, V
: Debug
> Debug
for Entry
<'_
, K
, V
> {
2089 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2091 Vacant(ref v
) => f
.debug_tuple("Entry").field(v
).finish(),
2092 Occupied(ref o
) => f
.debug_tuple("Entry").field(o
).finish(),
2097 /// A view into an occupied entry in a `HashMap`.
2098 /// It is part of the [`Entry`] enum.
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 pub struct OccupiedEntry
<'a
, K
: 'a
, V
: 'a
> {
2101 base
: base
::RustcOccupiedEntry
<'a
, K
, V
>,
2104 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2105 impl<K
: Debug
, V
: Debug
> Debug
for OccupiedEntry
<'_
, K
, V
> {
2106 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2107 f
.debug_struct("OccupiedEntry")
2108 .field("key", self.key())
2109 .field("value", self.get())
2110 .finish_non_exhaustive()
2114 /// A view into a vacant entry in a `HashMap`.
2115 /// It is part of the [`Entry`] enum.
2116 #[stable(feature = "rust1", since = "1.0.0")]
2117 pub struct VacantEntry
<'a
, K
: 'a
, V
: 'a
> {
2118 base
: base
::RustcVacantEntry
<'a
, K
, V
>,
2121 #[stable(feature = "debug_hash_map", since = "1.12.0")]
2122 impl<K
: Debug
, V
> Debug
for VacantEntry
<'_
, K
, V
> {
2123 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2124 f
.debug_tuple("VacantEntry").field(self.key()).finish()
2128 /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
2130 /// Contains the occupied entry, and the value that was not inserted.
2131 #[unstable(feature = "map_try_insert", issue = "82766")]
2132 pub struct OccupiedError
<'a
, K
: 'a
, V
: 'a
> {
2133 /// The entry in the map that was already occupied.
2134 pub entry
: OccupiedEntry
<'a
, K
, V
>,
2135 /// The value which was not inserted, because the entry was already occupied.
2139 #[unstable(feature = "map_try_insert", issue = "82766")]
2140 impl<K
: Debug
, V
: Debug
> Debug
for OccupiedError
<'_
, K
, V
> {
2141 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2142 f
.debug_struct("OccupiedError")
2143 .field("key", self.entry
.key())
2144 .field("old_value", self.entry
.get())
2145 .field("new_value", &self.value
)
2146 .finish_non_exhaustive()
2150 #[unstable(feature = "map_try_insert", issue = "82766")]
2151 impl<'a
, K
: Debug
, V
: Debug
> fmt
::Display
for OccupiedError
<'a
, K
, V
> {
2152 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2155 "failed to insert {:?}, key {:?} already exists with value {:?}",
2163 #[unstable(feature = "map_try_insert", issue = "82766")]
2164 impl<'a
, K
: fmt
::Debug
, V
: fmt
::Debug
> Error
for OccupiedError
<'a
, K
, V
> {
2165 #[allow(deprecated)]
2166 fn description(&self) -> &str {
2167 "key already exists"
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 impl<'a
, K
, V
, S
> IntoIterator
for &'a HashMap
<K
, V
, S
> {
2173 type Item
= (&'a K
, &'a V
);
2174 type IntoIter
= Iter
<'a
, K
, V
>;
2177 #[rustc_lint_query_instability]
2178 fn into_iter(self) -> Iter
<'a
, K
, V
> {
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 impl<'a
, K
, V
, S
> IntoIterator
for &'a
mut HashMap
<K
, V
, S
> {
2185 type Item
= (&'a K
, &'a
mut V
);
2186 type IntoIter
= IterMut
<'a
, K
, V
>;
2189 #[rustc_lint_query_instability]
2190 fn into_iter(self) -> IterMut
<'a
, K
, V
> {
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 impl<K
, V
, S
> IntoIterator
for HashMap
<K
, V
, S
> {
2198 type IntoIter
= IntoIter
<K
, V
>;
2200 /// Creates a consuming iterator, that is, one that moves each key-value
2201 /// pair out of the map in arbitrary order. The map cannot be used after
2207 /// use std::collections::HashMap;
2209 /// let map = HashMap::from([
2215 /// // Not possible with .iter()
2216 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2219 #[rustc_lint_query_instability]
2220 fn into_iter(self) -> IntoIter
<K
, V
> {
2221 IntoIter { base: self.base.into_iter() }
2225 #[stable(feature = "rust1", since = "1.0.0")]
2226 impl<'a
, K
, V
> Iterator
for Iter
<'a
, K
, V
> {
2227 type Item
= (&'a K
, &'a V
);
2230 fn next(&mut self) -> Option
<(&'a K
, &'a V
)> {
2234 fn size_hint(&self) -> (usize, Option
<usize>) {
2235 self.base
.size_hint()
2238 #[stable(feature = "rust1", since = "1.0.0")]
2239 impl<K
, V
> ExactSizeIterator
for Iter
<'_
, K
, V
> {
2241 fn len(&self) -> usize {
2246 #[stable(feature = "fused", since = "1.26.0")]
2247 impl<K
, V
> FusedIterator
for Iter
<'_
, K
, V
> {}
2249 #[stable(feature = "rust1", since = "1.0.0")]
2250 impl<'a
, K
, V
> Iterator
for IterMut
<'a
, K
, V
> {
2251 type Item
= (&'a K
, &'a
mut V
);
2254 fn next(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
2258 fn size_hint(&self) -> (usize, Option
<usize>) {
2259 self.base
.size_hint()
2262 #[stable(feature = "rust1", since = "1.0.0")]
2263 impl<K
, V
> ExactSizeIterator
for IterMut
<'_
, K
, V
> {
2265 fn len(&self) -> usize {
2269 #[stable(feature = "fused", since = "1.26.0")]
2270 impl<K
, V
> FusedIterator
for IterMut
<'_
, K
, V
> {}
2272 #[stable(feature = "std_debug", since = "1.16.0")]
2273 impl<K
, V
> fmt
::Debug
for IterMut
<'_
, K
, V
>
2278 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2279 f
.debug_list().entries(self.iter()).finish()
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 impl<K
, V
> Iterator
for IntoIter
<K
, V
> {
2288 fn next(&mut self) -> Option
<(K
, V
)> {
2292 fn size_hint(&self) -> (usize, Option
<usize>) {
2293 self.base
.size_hint()
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl<K
, V
> ExactSizeIterator
for IntoIter
<K
, V
> {
2299 fn len(&self) -> usize {
2303 #[stable(feature = "fused", since = "1.26.0")]
2304 impl<K
, V
> FusedIterator
for IntoIter
<K
, V
> {}
2306 #[stable(feature = "std_debug", since = "1.16.0")]
2307 impl<K
: Debug
, V
: Debug
> fmt
::Debug
for IntoIter
<K
, V
> {
2308 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2309 f
.debug_list().entries(self.iter()).finish()
2313 #[stable(feature = "rust1", since = "1.0.0")]
2314 impl<'a
, K
, V
> Iterator
for Keys
<'a
, K
, V
> {
2318 fn next(&mut self) -> Option
<&'a K
> {
2319 self.inner
.next().map(|(k
, _
)| k
)
2322 fn size_hint(&self) -> (usize, Option
<usize>) {
2323 self.inner
.size_hint()
2326 #[stable(feature = "rust1", since = "1.0.0")]
2327 impl<K
, V
> ExactSizeIterator
for Keys
<'_
, K
, V
> {
2329 fn len(&self) -> usize {
2333 #[stable(feature = "fused", since = "1.26.0")]
2334 impl<K
, V
> FusedIterator
for Keys
<'_
, K
, V
> {}
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 impl<'a
, K
, V
> Iterator
for Values
<'a
, K
, V
> {
2341 fn next(&mut self) -> Option
<&'a V
> {
2342 self.inner
.next().map(|(_
, v
)| v
)
2345 fn size_hint(&self) -> (usize, Option
<usize>) {
2346 self.inner
.size_hint()
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<K
, V
> ExactSizeIterator
for Values
<'_
, K
, V
> {
2352 fn len(&self) -> usize {
2356 #[stable(feature = "fused", since = "1.26.0")]
2357 impl<K
, V
> FusedIterator
for Values
<'_
, K
, V
> {}
2359 #[stable(feature = "map_values_mut", since = "1.10.0")]
2360 impl<'a
, K
, V
> Iterator
for ValuesMut
<'a
, K
, V
> {
2361 type Item
= &'a
mut V
;
2364 fn next(&mut self) -> Option
<&'a
mut V
> {
2365 self.inner
.next().map(|(_
, v
)| v
)
2368 fn size_hint(&self) -> (usize, Option
<usize>) {
2369 self.inner
.size_hint()
2372 #[stable(feature = "map_values_mut", since = "1.10.0")]
2373 impl<K
, V
> ExactSizeIterator
for ValuesMut
<'_
, K
, V
> {
2375 fn len(&self) -> usize {
2379 #[stable(feature = "fused", since = "1.26.0")]
2380 impl<K
, V
> FusedIterator
for ValuesMut
<'_
, K
, V
> {}
2382 #[stable(feature = "std_debug", since = "1.16.0")]
2383 impl<K
, V
: fmt
::Debug
> fmt
::Debug
for ValuesMut
<'_
, K
, V
> {
2384 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2385 f
.debug_list().entries(self.inner
.iter().map(|(_
, val
)| val
)).finish()
2389 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2390 impl<K
, V
> Iterator
for IntoKeys
<K
, V
> {
2394 fn next(&mut self) -> Option
<K
> {
2395 self.inner
.next().map(|(k
, _
)| k
)
2398 fn size_hint(&self) -> (usize, Option
<usize>) {
2399 self.inner
.size_hint()
2402 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2403 impl<K
, V
> ExactSizeIterator
for IntoKeys
<K
, V
> {
2405 fn len(&self) -> usize {
2409 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2410 impl<K
, V
> FusedIterator
for IntoKeys
<K
, V
> {}
2412 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2413 impl<K
: Debug
, V
> fmt
::Debug
for IntoKeys
<K
, V
> {
2414 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2415 f
.debug_list().entries(self.inner
.iter().map(|(k
, _
)| k
)).finish()
2419 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2420 impl<K
, V
> Iterator
for IntoValues
<K
, V
> {
2424 fn next(&mut self) -> Option
<V
> {
2425 self.inner
.next().map(|(_
, v
)| v
)
2428 fn size_hint(&self) -> (usize, Option
<usize>) {
2429 self.inner
.size_hint()
2432 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2433 impl<K
, V
> ExactSizeIterator
for IntoValues
<K
, V
> {
2435 fn len(&self) -> usize {
2439 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2440 impl<K
, V
> FusedIterator
for IntoValues
<K
, V
> {}
2442 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2443 impl<K
, V
: Debug
> fmt
::Debug
for IntoValues
<K
, V
> {
2444 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2445 f
.debug_list().entries(self.inner
.iter().map(|(_
, v
)| v
)).finish()
2449 #[stable(feature = "drain", since = "1.6.0")]
2450 impl<'a
, K
, V
> Iterator
for Drain
<'a
, K
, V
> {
2454 fn next(&mut self) -> Option
<(K
, V
)> {
2458 fn size_hint(&self) -> (usize, Option
<usize>) {
2459 self.base
.size_hint()
2462 #[stable(feature = "drain", since = "1.6.0")]
2463 impl<K
, V
> ExactSizeIterator
for Drain
<'_
, K
, V
> {
2465 fn len(&self) -> usize {
2469 #[stable(feature = "fused", since = "1.26.0")]
2470 impl<K
, V
> FusedIterator
for Drain
<'_
, K
, V
> {}
2472 #[stable(feature = "std_debug", since = "1.16.0")]
2473 impl<K
, V
> fmt
::Debug
for Drain
<'_
, K
, V
>
2478 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2479 f
.debug_list().entries(self.iter()).finish()
2483 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2484 impl<K
, V
, F
> Iterator
for DrainFilter
<'_
, K
, V
, F
>
2486 F
: FnMut(&K
, &mut V
) -> bool
,
2491 fn next(&mut self) -> Option
<(K
, V
)> {
2495 fn size_hint(&self) -> (usize, Option
<usize>) {
2496 self.base
.size_hint()
2500 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2501 impl<K
, V
, F
> FusedIterator
for DrainFilter
<'_
, K
, V
, F
> where F
: FnMut(&K
, &mut V
) -> bool {}
2503 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2504 impl<'a
, K
, V
, F
> fmt
::Debug
for DrainFilter
<'a
, K
, V
, F
>
2506 F
: FnMut(&K
, &mut V
) -> bool
,
2508 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
2509 f
.debug_struct("DrainFilter").finish_non_exhaustive()
2513 impl<'a
, K
, V
> Entry
<'a
, K
, V
> {
2514 /// Ensures a value is in the entry by inserting the default if empty, and returns
2515 /// a mutable reference to the value in the entry.
2520 /// use std::collections::HashMap;
2522 /// let mut map: HashMap<&str, u32> = HashMap::new();
2524 /// map.entry("poneyland").or_insert(3);
2525 /// assert_eq!(map["poneyland"], 3);
2527 /// *map.entry("poneyland").or_insert(10) *= 2;
2528 /// assert_eq!(map["poneyland"], 6);
2531 #[stable(feature = "rust1", since = "1.0.0")]
2532 pub fn or_insert(self, default: V
) -> &'a
mut V
{
2534 Occupied(entry
) => entry
.into_mut(),
2535 Vacant(entry
) => entry
.insert(default),
2539 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2540 /// and returns a mutable reference to the value in the entry.
2545 /// use std::collections::HashMap;
2547 /// let mut map: HashMap<&str, String> = HashMap::new();
2548 /// let s = "hoho".to_string();
2550 /// map.entry("poneyland").or_insert_with(|| s);
2552 /// assert_eq!(map["poneyland"], "hoho".to_string());
2555 #[stable(feature = "rust1", since = "1.0.0")]
2556 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
2558 Occupied(entry
) => entry
.into_mut(),
2559 Vacant(entry
) => entry
.insert(default()),
2563 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2564 /// This method allows for generating key-derived values for insertion by providing the default
2565 /// function a reference to the key that was moved during the `.entry(key)` method call.
2567 /// The reference to the moved key is provided so that cloning or copying the key is
2568 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2573 /// use std::collections::HashMap;
2575 /// let mut map: HashMap<&str, usize> = HashMap::new();
2577 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2579 /// assert_eq!(map["poneyland"], 9);
2582 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2583 pub fn or_insert_with_key
<F
: FnOnce(&K
) -> V
>(self, default: F
) -> &'a
mut V
{
2585 Occupied(entry
) => entry
.into_mut(),
2587 let value
= default(entry
.key());
2593 /// Returns a reference to this entry's key.
2598 /// use std::collections::HashMap;
2600 /// let mut map: HashMap<&str, u32> = HashMap::new();
2601 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2604 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2605 pub fn key(&self) -> &K
{
2607 Occupied(ref entry
) => entry
.key(),
2608 Vacant(ref entry
) => entry
.key(),
2612 /// Provides in-place mutable access to an occupied entry before any
2613 /// potential inserts into the map.
2618 /// use std::collections::HashMap;
2620 /// let mut map: HashMap<&str, u32> = HashMap::new();
2622 /// map.entry("poneyland")
2623 /// .and_modify(|e| { *e += 1 })
2625 /// assert_eq!(map["poneyland"], 42);
2627 /// map.entry("poneyland")
2628 /// .and_modify(|e| { *e += 1 })
2630 /// assert_eq!(map["poneyland"], 43);
2633 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2634 pub fn and_modify
<F
>(self, f
: F
) -> Self
2639 Occupied(mut entry
) => {
2643 Vacant(entry
) => Vacant(entry
),
2647 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2652 /// #![feature(entry_insert)]
2653 /// use std::collections::HashMap;
2655 /// let mut map: HashMap<&str, String> = HashMap::new();
2656 /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2658 /// assert_eq!(entry.key(), &"poneyland");
2661 #[unstable(feature = "entry_insert", issue = "65225")]
2662 pub fn insert_entry(self, value
: V
) -> OccupiedEntry
<'a
, K
, V
> {
2664 Occupied(mut entry
) => {
2665 entry
.insert(value
);
2668 Vacant(entry
) => entry
.insert_entry(value
),
2673 impl<'a
, K
, V
: Default
> Entry
<'a
, K
, V
> {
2674 /// Ensures a value is in the entry by inserting the default value if empty,
2675 /// and returns a mutable reference to the value in the entry.
2681 /// use std::collections::HashMap;
2683 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2684 /// map.entry("poneyland").or_default();
2686 /// assert_eq!(map["poneyland"], None);
2690 #[stable(feature = "entry_or_default", since = "1.28.0")]
2691 pub fn or_default(self) -> &'a
mut V
{
2693 Occupied(entry
) => entry
.into_mut(),
2694 Vacant(entry
) => entry
.insert(Default
::default()),
2699 impl<'a
, K
, V
> OccupiedEntry
<'a
, K
, V
> {
2700 /// Gets a reference to the key in the entry.
2705 /// use std::collections::HashMap;
2707 /// let mut map: HashMap<&str, u32> = HashMap::new();
2708 /// map.entry("poneyland").or_insert(12);
2709 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2712 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2713 pub fn key(&self) -> &K
{
2717 /// Take the ownership of the key and value from the map.
2722 /// use std::collections::HashMap;
2723 /// use std::collections::hash_map::Entry;
2725 /// let mut map: HashMap<&str, u32> = HashMap::new();
2726 /// map.entry("poneyland").or_insert(12);
2728 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2729 /// // We delete the entry from the map.
2730 /// o.remove_entry();
2733 /// assert_eq!(map.contains_key("poneyland"), false);
2736 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2737 pub fn remove_entry(self) -> (K
, V
) {
2738 self.base
.remove_entry()
2741 /// Gets a reference to the value in the entry.
2746 /// use std::collections::HashMap;
2747 /// use std::collections::hash_map::Entry;
2749 /// let mut map: HashMap<&str, u32> = HashMap::new();
2750 /// map.entry("poneyland").or_insert(12);
2752 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2753 /// assert_eq!(o.get(), &12);
2757 #[stable(feature = "rust1", since = "1.0.0")]
2758 pub fn get(&self) -> &V
{
2762 /// Gets a mutable reference to the value in the entry.
2764 /// If you need a reference to the `OccupiedEntry` which may outlive the
2765 /// destruction of the `Entry` value, see [`into_mut`].
2767 /// [`into_mut`]: Self::into_mut
2772 /// use std::collections::HashMap;
2773 /// use std::collections::hash_map::Entry;
2775 /// let mut map: HashMap<&str, u32> = HashMap::new();
2776 /// map.entry("poneyland").or_insert(12);
2778 /// assert_eq!(map["poneyland"], 12);
2779 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2780 /// *o.get_mut() += 10;
2781 /// assert_eq!(*o.get(), 22);
2783 /// // We can use the same Entry multiple times.
2784 /// *o.get_mut() += 2;
2787 /// assert_eq!(map["poneyland"], 24);
2790 #[stable(feature = "rust1", since = "1.0.0")]
2791 pub fn get_mut(&mut self) -> &mut V
{
2795 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2796 /// with a lifetime bound to the map itself.
2798 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2800 /// [`get_mut`]: Self::get_mut
2805 /// use std::collections::HashMap;
2806 /// use std::collections::hash_map::Entry;
2808 /// let mut map: HashMap<&str, u32> = HashMap::new();
2809 /// map.entry("poneyland").or_insert(12);
2811 /// assert_eq!(map["poneyland"], 12);
2812 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2813 /// *o.into_mut() += 10;
2816 /// assert_eq!(map["poneyland"], 22);
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 pub fn into_mut(self) -> &'a
mut V
{
2821 self.base
.into_mut()
2824 /// Sets the value of the entry, and returns the entry's old value.
2829 /// use std::collections::HashMap;
2830 /// use std::collections::hash_map::Entry;
2832 /// let mut map: HashMap<&str, u32> = HashMap::new();
2833 /// map.entry("poneyland").or_insert(12);
2835 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2836 /// assert_eq!(o.insert(15), 12);
2839 /// assert_eq!(map["poneyland"], 15);
2842 #[stable(feature = "rust1", since = "1.0.0")]
2843 pub fn insert(&mut self, value
: V
) -> V
{
2844 self.base
.insert(value
)
2847 /// Takes the value out of the entry, and returns it.
2852 /// use std::collections::HashMap;
2853 /// use std::collections::hash_map::Entry;
2855 /// let mut map: HashMap<&str, u32> = HashMap::new();
2856 /// map.entry("poneyland").or_insert(12);
2858 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2859 /// assert_eq!(o.remove(), 12);
2862 /// assert_eq!(map.contains_key("poneyland"), false);
2865 #[stable(feature = "rust1", since = "1.0.0")]
2866 pub fn remove(self) -> V
{
2870 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2871 /// the key used to create this entry.
2876 /// #![feature(map_entry_replace)]
2877 /// use std::collections::hash_map::{Entry, HashMap};
2878 /// use std::rc::Rc;
2880 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2881 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2883 /// let my_key = Rc::new("Stringthing".to_string());
2885 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2886 /// // Also replace the key with a handle to our other key.
2887 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2892 #[unstable(feature = "map_entry_replace", issue = "44286")]
2893 pub fn replace_entry(self, value
: V
) -> (K
, V
) {
2894 self.base
.replace_entry(value
)
2897 /// Replaces the key in the hash map with the key used to create this entry.
2902 /// #![feature(map_entry_replace)]
2903 /// use std::collections::hash_map::{Entry, HashMap};
2904 /// use std::rc::Rc;
2906 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2907 /// let known_strings: Vec<Rc<String>> = Vec::new();
2909 /// // Initialise known strings, run program, etc.
2911 /// reclaim_memory(&mut map, &known_strings);
2913 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2914 /// for s in known_strings {
2915 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2916 /// // Replaces the entry's key with our version of it in `known_strings`.
2917 /// entry.replace_key();
2923 #[unstable(feature = "map_entry_replace", issue = "44286")]
2924 pub fn replace_key(self) -> K
{
2925 self.base
.replace_key()
2929 impl<'a
, K
: 'a
, V
: 'a
> VacantEntry
<'a
, K
, V
> {
2930 /// Gets a reference to the key that would be used when inserting a value
2931 /// through the `VacantEntry`.
2936 /// use std::collections::HashMap;
2938 /// let mut map: HashMap<&str, u32> = HashMap::new();
2939 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2942 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2943 pub fn key(&self) -> &K
{
2947 /// Take ownership of the key.
2952 /// use std::collections::HashMap;
2953 /// use std::collections::hash_map::Entry;
2955 /// let mut map: HashMap<&str, u32> = HashMap::new();
2957 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2962 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2963 pub fn into_key(self) -> K
{
2964 self.base
.into_key()
2967 /// Sets the value of the entry with the `VacantEntry`'s key,
2968 /// and returns a mutable reference to it.
2973 /// use std::collections::HashMap;
2974 /// use std::collections::hash_map::Entry;
2976 /// let mut map: HashMap<&str, u32> = HashMap::new();
2978 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2981 /// assert_eq!(map["poneyland"], 37);
2984 #[stable(feature = "rust1", since = "1.0.0")]
2985 pub fn insert(self, value
: V
) -> &'a
mut V
{
2986 self.base
.insert(value
)
2989 /// Sets the value of the entry with the `VacantEntry`'s key,
2990 /// and returns an `OccupiedEntry`.
2995 /// #![feature(entry_insert)]
2996 /// use std::collections::HashMap;
2997 /// use std::collections::hash_map::Entry;
2999 /// let mut map: HashMap<&str, u32> = HashMap::new();
3001 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3002 /// o.insert_entry(37);
3004 /// assert_eq!(map["poneyland"], 37);
3007 #[unstable(feature = "entry_insert", issue = "65225")]
3008 pub fn insert_entry(self, value
: V
) -> OccupiedEntry
<'a
, K
, V
> {
3009 let base
= self.base
.insert_entry(value
);
3010 OccupiedEntry { base }
3014 #[stable(feature = "rust1", since = "1.0.0")]
3015 impl<K
, V
, S
> FromIterator
<(K
, V
)> for HashMap
<K
, V
, S
>
3018 S
: BuildHasher
+ Default
,
3020 fn from_iter
<T
: IntoIterator
<Item
= (K
, V
)>>(iter
: T
) -> HashMap
<K
, V
, S
> {
3021 let mut map
= HashMap
::with_hasher(Default
::default());
3027 /// Inserts all new key-values from the iterator and replaces values with existing
3028 /// keys with new values returned from the iterator.
3029 #[stable(feature = "rust1", since = "1.0.0")]
3030 impl<K
, V
, S
> Extend
<(K
, V
)> for HashMap
<K
, V
, S
>
3036 fn extend
<T
: IntoIterator
<Item
= (K
, V
)>>(&mut self, iter
: T
) {
3037 self.base
.extend(iter
)
3041 fn extend_one(&mut self, (k
, v
): (K
, V
)) {
3042 self.base
.insert(k
, v
);
3046 fn extend_reserve(&mut self, additional
: usize) {
3047 self.base
.extend_reserve(additional
);
3051 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3052 impl<'a
, K
, V
, S
> Extend
<(&'a K
, &'a V
)> for HashMap
<K
, V
, S
>
3054 K
: Eq
+ Hash
+ Copy
,
3059 fn extend
<T
: IntoIterator
<Item
= (&'a K
, &'a V
)>>(&mut self, iter
: T
) {
3060 self.base
.extend(iter
)
3064 fn extend_one(&mut self, (&k
, &v
): (&'a K
, &'a V
)) {
3065 self.base
.insert(k
, v
);
3069 fn extend_reserve(&mut self, additional
: usize) {
3070 Extend
::<(K
, V
)>::extend_reserve(self, additional
)
3074 /// `RandomState` is the default state for [`HashMap`] types.
3076 /// A particular instance `RandomState` will create the same instances of
3077 /// [`Hasher`], but the hashers created by two different `RandomState`
3078 /// instances are unlikely to produce the same result for the same values.
3083 /// use std::collections::HashMap;
3084 /// use std::collections::hash_map::RandomState;
3086 /// let s = RandomState::new();
3087 /// let mut map = HashMap::with_hasher(s);
3088 /// map.insert(1, 2);
3091 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3092 pub struct RandomState
{
3098 /// Constructs a new `RandomState` that is initialized with random keys.
3103 /// use std::collections::hash_map::RandomState;
3105 /// let s = RandomState::new();
3108 #[allow(deprecated)]
3111 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3112 pub fn new() -> RandomState
{
3113 // Historically this function did not cache keys from the OS and instead
3114 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
3115 // was discovered, however, that because we re-seed the thread-local RNG
3116 // from the OS periodically that this can cause excessive slowdown when
3117 // many hash maps are created on a thread. To solve this performance
3118 // trap we cache the first set of randomly generated keys per-thread.
3120 // Later in #36481 it was discovered that exposing a deterministic
3121 // iteration order allows a form of DOS attack. To counter that we
3122 // increment one of the seeds on every RandomState creation, giving
3123 // every corresponding HashMap a different iteration order.
3124 thread_local
!(static KEYS
: Cell
<(u64, u64)> = {
3125 Cell
::new(sys
::hashmap_random_keys())
3129 let (k0
, k1
) = keys
.get();
3130 keys
.set((k0
.wrapping_add(1), k1
));
3131 RandomState { k0, k1 }
3136 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3137 impl BuildHasher
for RandomState
{
3138 type Hasher
= DefaultHasher
;
3140 #[allow(deprecated)]
3141 fn build_hasher(&self) -> DefaultHasher
{
3142 DefaultHasher(SipHasher13
::new_with_keys(self.k0
, self.k1
))
3146 /// The default [`Hasher`] used by [`RandomState`].
3148 /// The internal algorithm is not specified, and so it and its hashes should
3149 /// not be relied upon over releases.
3150 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3151 #[allow(deprecated)]
3152 #[derive(Clone, Debug)]
3153 pub struct DefaultHasher(SipHasher13
);
3155 impl DefaultHasher
{
3156 /// Creates a new `DefaultHasher`.
3158 /// This hasher is not guaranteed to be the same as all other
3159 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
3160 /// instances created through `new` or `default`.
3161 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3163 #[allow(deprecated)]
3165 pub fn new() -> DefaultHasher
{
3166 DefaultHasher(SipHasher13
::new_with_keys(0, 0))
3170 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3171 impl Default
for DefaultHasher
{
3172 /// Creates a new `DefaultHasher` using [`new`].
3173 /// See its documentation for more.
3175 /// [`new`]: DefaultHasher::new
3177 fn default() -> DefaultHasher
{
3178 DefaultHasher
::new()
3182 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
3183 impl Hasher
for DefaultHasher
{
3184 // The underlying `SipHasher13` doesn't override the other
3185 // `write_*` methods, so it's ok not to forward them here.
3188 fn write(&mut self, msg
: &[u8]) {
3193 fn write_str(&mut self, s
: &str) {
3194 self.0.write_str(s
);
3198 fn finish(&self) -> u64 {
3203 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
3204 impl Default
for RandomState
{
3205 /// Constructs a new `RandomState`.
3207 fn default() -> RandomState
{
3212 #[stable(feature = "std_debug", since = "1.16.0")]
3213 impl fmt
::Debug
for RandomState
{
3214 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
3215 f
.debug_struct("RandomState").finish_non_exhaustive()
3220 fn map_entry
<'a
, K
: 'a
, V
: 'a
>(raw
: base
::RustcEntry
<'a
, K
, V
>) -> Entry
<'a
, K
, V
> {
3222 base
::RustcEntry
::Occupied(base
) => Entry
::Occupied(OccupiedEntry { base }
),
3223 base
::RustcEntry
::Vacant(base
) => Entry
::Vacant(VacantEntry { base }
),
3228 pub(super) fn map_try_reserve_error(err
: hashbrown
::TryReserveError
) -> TryReserveError
{
3230 hashbrown
::TryReserveError
::CapacityOverflow
=> {
3231 TryReserveErrorKind
::CapacityOverflow
.into()
3233 hashbrown
::TryReserveError
::AllocError { layout }
=> {
3234 TryReserveErrorKind
::AllocError { layout, non_exhaustive: () }
.into()
3240 fn map_raw_entry
<'a
, K
: 'a
, V
: 'a
, S
: 'a
>(
3241 raw
: base
::RawEntryMut
<'a
, K
, V
, S
>,
3242 ) -> RawEntryMut
<'a
, K
, V
, S
> {
3244 base
::RawEntryMut
::Occupied(base
) => RawEntryMut
::Occupied(RawOccupiedEntryMut { base }
),
3245 base
::RawEntryMut
::Vacant(base
) => RawEntryMut
::Vacant(RawVacantEntryMut { base }
),
3250 fn assert_covariance() {
3251 fn map_key
<'new
>(v
: HashMap
<&'
static str, u8>) -> HashMap
<&'new
str, u8> {
3254 fn map_val
<'new
>(v
: HashMap
<u8, &'
static str>) -> HashMap
<u8, &'new
str> {
3257 fn iter_key
<'a
, 'new
>(v
: Iter
<'a
, &'
static str, u8>) -> Iter
<'a
, &'new
str, u8> {
3260 fn iter_val
<'a
, 'new
>(v
: Iter
<'a
, u8, &'
static str>) -> Iter
<'a
, u8, &'new
str> {
3263 fn into_iter_key
<'new
>(v
: IntoIter
<&'
static str, u8>) -> IntoIter
<&'new
str, u8> {
3266 fn into_iter_val
<'new
>(v
: IntoIter
<u8, &'
static str>) -> IntoIter
<u8, &'new
str> {
3269 fn keys_key
<'a
, 'new
>(v
: Keys
<'a
, &'
static str, u8>) -> Keys
<'a
, &'new
str, u8> {
3272 fn keys_val
<'a
, 'new
>(v
: Keys
<'a
, u8, &'
static str>) -> Keys
<'a
, u8, &'new
str> {
3275 fn values_key
<'a
, 'new
>(v
: Values
<'a
, &'
static str, u8>) -> Values
<'a
, &'new
str, u8> {
3278 fn values_val
<'a
, 'new
>(v
: Values
<'a
, u8, &'
static str>) -> Values
<'a
, u8, &'new
str> {
3282 d
: Drain
<'
static, &'
static str, &'
static str>,
3283 ) -> Drain
<'new
, &'new
str, &'new
str> {