1 // ignore-tidy-filelength
5 use hashbrown::hash_map as base;
7 use crate::borrow::Borrow;
9 use crate::collections::TryReserveError;
10 use crate::fmt::{self, Debug};
12 use crate::hash::{BuildHasher, Hash, Hasher, SipHasher13};
13 use crate::iter::{FromIterator, FusedIterator};
14 use crate::ops::Index;
17 /// A hash map implemented with quadratic probing and SIMD lookup.
19 /// By default, `HashMap` uses a hashing algorithm selected to provide
20 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
21 /// reasonable best-effort is made to generate this seed from a high quality,
22 /// secure source of randomness provided by the host without blocking the
23 /// program. Because of this, the randomness of the seed depends on the output
24 /// quality of the system's random number generator when the seed is created.
25 /// In particular, seeds generated when the system's entropy pool is abnormally
26 /// low such as during system boot may be of a lower quality.
28 /// The default hashing algorithm is currently SipHash 1-3, though this is
29 /// subject to change at any point in the future. While its performance is very
30 /// competitive for medium sized keys, other hashing algorithms will outperform
31 /// it for small keys such as integers as well as large keys such as long
32 /// strings, though those algorithms will typically *not* protect against
33 /// attacks such as HashDoS.
35 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
36 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
37 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
39 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
40 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
41 /// If you implement these yourself, it is important that the following
45 /// k1 == k2 -> hash(k1) == hash(k2)
48 /// In other words, if two keys are equal, their hashes must be equal.
50 /// It is a logic error for a key to be modified in such a way that the key's
51 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
52 /// the [`Eq`] trait, changes while it is in the map. This is normally only
53 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
55 /// The hash table implementation is a Rust port of Google's [SwissTable].
56 /// The original C++ version of SwissTable can be found [here], and this
57 /// [CppCon talk] gives an overview of how the algorithm works.
59 /// [SwissTable]: https://abseil.io/blog/20180927-swisstables
60 /// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
61 /// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
66 /// use std::collections::HashMap;
68 /// // Type inference lets us omit an explicit type signature (which
69 /// // would be `HashMap<String, String>` in this example).
70 /// let mut book_reviews = HashMap::new();
72 /// // Review some books.
73 /// book_reviews.insert(
74 /// "Adventures of Huckleberry Finn".to_string(),
75 /// "My favorite book.".to_string(),
77 /// book_reviews.insert(
78 /// "Grimms' Fairy Tales".to_string(),
79 /// "Masterpiece.".to_string(),
81 /// book_reviews.insert(
82 /// "Pride and Prejudice".to_string(),
83 /// "Very enjoyable.".to_string(),
85 /// book_reviews.insert(
86 /// "The Adventures of Sherlock Holmes".to_string(),
87 /// "Eye lyked it alot.".to_string(),
90 /// // Check for a specific one.
91 /// // When collections store owned values (String), they can still be
92 /// // queried using references (&str).
93 /// if !book_reviews.contains_key("Les Misérables") {
94 /// println!("We've got {} reviews, but Les Misérables ain't one.",
95 /// book_reviews.len());
98 /// // oops, this review has a lot of spelling mistakes, let's delete it.
99 /// book_reviews.remove("The Adventures of Sherlock Holmes");
101 /// // Look up the values associated with some keys.
102 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
103 /// for &book in &to_find {
104 /// match book_reviews.get(book) {
105 /// Some(review) => println!("{}: {}", book, review),
106 /// None => println!("{} is unreviewed.", book)
110 /// // Look up the value for a key (will panic if the key is not found).
111 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
113 /// // Iterate over everything.
114 /// for (book, review) in &book_reviews {
115 /// println!("{}: \"{}\"", book, review);
119 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
120 /// for more complex methods of getting, setting, updating and removing keys and
124 /// use std::collections::HashMap;
126 /// // type inference lets us omit an explicit type signature (which
127 /// // would be `HashMap<&str, u8>` in this example).
128 /// let mut player_stats = HashMap::new();
130 /// fn random_stat_buff() -> u8 {
131 /// // could actually return some random value here - let's just return
132 /// // some fixed value for now
136 /// // insert a key only if it doesn't already exist
137 /// player_stats.entry("health").or_insert(100);
139 /// // insert a key using a function that provides a new value only if it
140 /// // doesn't already exist
141 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
143 /// // update a key, guarding against the key possibly not being set
144 /// let stat = player_stats.entry("attack").or_insert(100);
145 /// *stat += random_stat_buff();
148 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
149 /// We must also derive [`PartialEq`].
151 /// [`RefCell`]: crate::cell::RefCell
152 /// [`Cell`]: crate::cell::Cell
153 /// [`default`]: Default::default
154 /// [`with_hasher`]: Self::with_hasher
155 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
156 /// [`fnv`]: https://crates.io/crates/fnv
159 /// use std::collections::HashMap;
161 /// #[derive(Hash, Eq, PartialEq, Debug)]
168 /// /// Creates a new Viking.
169 /// fn new(name: &str, country: &str) -> Viking {
170 /// Viking { name: name.to_string(), country: country.to_string() }
174 /// // Use a HashMap to store the vikings' health points.
175 /// let mut vikings = HashMap::new();
177 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
178 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
179 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
181 /// // Use derived implementation to print the status of the vikings.
182 /// for (viking, health) in &vikings {
183 /// println!("{:?} has {} hp", viking, health);
187 /// A `HashMap` with fixed list of elements can be initialized from an array:
190 /// use std::collections::HashMap;
192 /// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
193 /// .iter().cloned().collect();
194 /// // use the values stored in map
198 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_type")]
199 #[stable(feature = "rust1", since = "1.0.0")]
200 pub struct HashMap<K, V, S = RandomState> {
201 base: base::HashMap<K, V, S>,
204 impl<K, V> HashMap<K, V, RandomState> {
205 /// Creates an empty `HashMap`.
207 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
208 /// is first inserted into.
213 /// use std::collections::HashMap;
214 /// let mut map: HashMap<&str, i32> = HashMap::new();
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn new() -> HashMap<K, V, RandomState> {
222 /// Creates an empty `HashMap` with the specified capacity.
224 /// The hash map will be able to hold at least `capacity` elements without
225 /// reallocating. If `capacity` is 0, the hash map will not allocate.
230 /// use std::collections::HashMap;
231 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
236 HashMap::with_capacity_and_hasher(capacity, Default::default())
240 impl<K, V, S> HashMap<K, V, S> {
241 /// Creates an empty `HashMap` which will use the given hash builder to hash
244 /// The created map has the default initial capacity.
246 /// Warning: `hash_builder` is normally randomly generated, and
247 /// is designed to allow HashMaps to be resistant to attacks that
248 /// cause many collisions and very poor performance. Setting it
249 /// manually using this function can expose a DoS attack vector.
251 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
252 /// the HashMap to be useful, see its documentation for details.
257 /// use std::collections::HashMap;
258 /// use std::collections::hash_map::RandomState;
260 /// let s = RandomState::new();
261 /// let mut map = HashMap::with_hasher(s);
262 /// map.insert(1, 2);
265 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
266 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
267 HashMap { base: base::HashMap::with_hasher(hash_builder) }
270 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
271 /// to hash the keys.
273 /// The hash map will be able to hold at least `capacity` elements without
274 /// reallocating. If `capacity` is 0, the hash map will not allocate.
276 /// Warning: `hash_builder` is normally randomly generated, and
277 /// is designed to allow HashMaps to be resistant to attacks that
278 /// cause many collisions and very poor performance. Setting it
279 /// manually using this function can expose a DoS attack vector.
281 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
282 /// the HashMap to be useful, see its documentation for details.
287 /// use std::collections::HashMap;
288 /// use std::collections::hash_map::RandomState;
290 /// let s = RandomState::new();
291 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
292 /// map.insert(1, 2);
295 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
296 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
297 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
300 /// Returns the number of elements the map can hold without reallocating.
302 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
303 /// more, but is guaranteed to be able to hold at least this many.
308 /// use std::collections::HashMap;
309 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
310 /// assert!(map.capacity() >= 100);
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub fn capacity(&self) -> usize {
318 /// An iterator visiting all keys in arbitrary order.
319 /// The iterator element type is `&'a K`.
324 /// use std::collections::HashMap;
326 /// let mut map = HashMap::new();
327 /// map.insert("a", 1);
328 /// map.insert("b", 2);
329 /// map.insert("c", 3);
331 /// for key in map.keys() {
332 /// println!("{}", key);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn keys(&self) -> Keys<'_, K, V> {
337 Keys { inner: self.iter() }
340 /// An iterator visiting all values in arbitrary order.
341 /// The iterator element type is `&'a V`.
346 /// use std::collections::HashMap;
348 /// let mut map = HashMap::new();
349 /// map.insert("a", 1);
350 /// map.insert("b", 2);
351 /// map.insert("c", 3);
353 /// for val in map.values() {
354 /// println!("{}", val);
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn values(&self) -> Values<'_, K, V> {
359 Values { inner: self.iter() }
362 /// An iterator visiting all values mutably in arbitrary order.
363 /// The iterator element type is `&'a mut V`.
368 /// use std::collections::HashMap;
370 /// let mut map = HashMap::new();
372 /// map.insert("a", 1);
373 /// map.insert("b", 2);
374 /// map.insert("c", 3);
376 /// for val in map.values_mut() {
377 /// *val = *val + 10;
380 /// for val in map.values() {
381 /// println!("{}", val);
384 #[stable(feature = "map_values_mut", since = "1.10.0")]
385 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
386 ValuesMut { inner: self.iter_mut() }
389 /// An iterator visiting all key-value pairs in arbitrary order.
390 /// The iterator element type is `(&'a K, &'a V)`.
395 /// use std::collections::HashMap;
397 /// let mut map = HashMap::new();
398 /// map.insert("a", 1);
399 /// map.insert("b", 2);
400 /// map.insert("c", 3);
402 /// for (key, val) in map.iter() {
403 /// println!("key: {} val: {}", key, val);
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn iter(&self) -> Iter<'_, K, V> {
408 Iter { base: self.base.iter() }
411 /// An iterator visiting all key-value pairs in arbitrary order,
412 /// with mutable references to the values.
413 /// The iterator element type is `(&'a K, &'a mut V)`.
418 /// use std::collections::HashMap;
420 /// let mut map = HashMap::new();
421 /// map.insert("a", 1);
422 /// map.insert("b", 2);
423 /// map.insert("c", 3);
425 /// // Update all values
426 /// for (_, val) in map.iter_mut() {
430 /// for (key, val) in &map {
431 /// println!("key: {} val: {}", key, val);
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
436 IterMut { base: self.base.iter_mut() }
439 /// Returns the number of elements in the map.
444 /// use std::collections::HashMap;
446 /// let mut a = HashMap::new();
447 /// assert_eq!(a.len(), 0);
448 /// a.insert(1, "a");
449 /// assert_eq!(a.len(), 1);
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn len(&self) -> usize {
456 /// Returns `true` if the map contains no elements.
461 /// use std::collections::HashMap;
463 /// let mut a = HashMap::new();
464 /// assert!(a.is_empty());
465 /// a.insert(1, "a");
466 /// assert!(!a.is_empty());
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn is_empty(&self) -> bool {
474 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
475 /// allocated memory for reuse.
480 /// use std::collections::HashMap;
482 /// let mut a = HashMap::new();
483 /// a.insert(1, "a");
484 /// a.insert(2, "b");
486 /// for (k, v) in a.drain().take(1) {
487 /// assert!(k == 1 || k == 2);
488 /// assert!(v == "a" || v == "b");
491 /// assert!(a.is_empty());
494 #[stable(feature = "drain", since = "1.6.0")]
495 pub fn drain(&mut self) -> Drain<'_, K, V> {
496 Drain { base: self.base.drain() }
499 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
505 /// use std::collections::HashMap;
507 /// let mut a = HashMap::new();
508 /// a.insert(1, "a");
510 /// assert!(a.is_empty());
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn clear(&mut self) {
518 /// Returns a reference to the map's [`BuildHasher`].
523 /// use std::collections::HashMap;
524 /// use std::collections::hash_map::RandomState;
526 /// let hasher = RandomState::new();
527 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
528 /// let hasher: &RandomState = map.hasher();
531 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
532 pub fn hasher(&self) -> &S {
537 impl<K, V, S> HashMap<K, V, S>
542 /// Reserves capacity for at least `additional` more elements to be inserted
543 /// in the `HashMap`. The collection may reserve more space to avoid
544 /// frequent reallocations.
548 /// Panics if the new allocation size overflows [`usize`].
553 /// use std::collections::HashMap;
554 /// let mut map: HashMap<&str, i32> = HashMap::new();
558 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn reserve(&mut self, additional: usize) {
560 self.base.reserve(additional)
563 /// Tries to reserve capacity for at least `additional` more elements to be inserted
564 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
565 /// frequent reallocations.
569 /// If the capacity overflows, or the allocator reports a failure, then an error
575 /// #![feature(try_reserve)]
576 /// use std::collections::HashMap;
577 /// let mut map: HashMap<&str, isize> = HashMap::new();
578 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
581 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
582 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
583 self.base.try_reserve(additional).map_err(map_try_reserve_error)
586 /// Shrinks the capacity of the map as much as possible. It will drop
587 /// down as much as possible while maintaining the internal rules
588 /// and possibly leaving some space in accordance with the resize policy.
593 /// use std::collections::HashMap;
595 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
596 /// map.insert(1, 2);
597 /// map.insert(3, 4);
598 /// assert!(map.capacity() >= 100);
599 /// map.shrink_to_fit();
600 /// assert!(map.capacity() >= 2);
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn shrink_to_fit(&mut self) {
605 self.base.shrink_to_fit();
608 /// Shrinks the capacity of the map with a lower limit. It will drop
609 /// down no lower than the supplied limit while maintaining the internal rules
610 /// and possibly leaving some space in accordance with the resize policy.
612 /// Panics if the current capacity is smaller than the supplied
613 /// minimum capacity.
618 /// #![feature(shrink_to)]
619 /// use std::collections::HashMap;
621 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
622 /// map.insert(1, 2);
623 /// map.insert(3, 4);
624 /// assert!(map.capacity() >= 100);
625 /// map.shrink_to(10);
626 /// assert!(map.capacity() >= 10);
627 /// map.shrink_to(0);
628 /// assert!(map.capacity() >= 2);
631 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
632 pub fn shrink_to(&mut self, min_capacity: usize) {
633 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
634 self.base.shrink_to(min_capacity);
637 /// Gets the given key's corresponding entry in the map for in-place manipulation.
642 /// use std::collections::HashMap;
644 /// let mut letters = HashMap::new();
646 /// for ch in "a short treatise on fungi".chars() {
647 /// let counter = letters.entry(ch).or_insert(0);
651 /// assert_eq!(letters[&'s'], 2);
652 /// assert_eq!(letters[&'t'], 3);
653 /// assert_eq!(letters[&'u'], 1);
654 /// assert_eq!(letters.get(&'y'), None);
657 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
659 map_entry(self.base.rustc_entry(key))
662 /// Returns a reference to the value corresponding to the key.
664 /// The key may be any borrowed form of the map's key type, but
665 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
671 /// use std::collections::HashMap;
673 /// let mut map = HashMap::new();
674 /// map.insert(1, "a");
675 /// assert_eq!(map.get(&1), Some(&"a"));
676 /// assert_eq!(map.get(&2), None);
678 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
688 /// Returns the key-value pair corresponding to the supplied key.
690 /// The supplied key may be any borrowed form of the map's key type, but
691 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
697 /// use std::collections::HashMap;
699 /// let mut map = HashMap::new();
700 /// map.insert(1, "a");
701 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
702 /// assert_eq!(map.get_key_value(&2), None);
704 #[stable(feature = "map_get_key_value", since = "1.40.0")]
706 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
711 self.base.get_key_value(k)
714 /// Returns `true` if the map contains a value for the specified key.
716 /// The key may be any borrowed form of the map's key type, but
717 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
723 /// use std::collections::HashMap;
725 /// let mut map = HashMap::new();
726 /// map.insert(1, "a");
727 /// assert_eq!(map.contains_key(&1), true);
728 /// assert_eq!(map.contains_key(&2), false);
730 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
737 self.base.contains_key(k)
740 /// Returns a mutable reference to the value corresponding to the key.
742 /// The key may be any borrowed form of the map's key type, but
743 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
749 /// use std::collections::HashMap;
751 /// let mut map = HashMap::new();
752 /// map.insert(1, "a");
753 /// if let Some(x) = map.get_mut(&1) {
756 /// assert_eq!(map[&1], "b");
758 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
768 /// Inserts a key-value pair into the map.
770 /// If the map did not have this key present, [`None`] is returned.
772 /// If the map did have this key present, the value is updated, and the old
773 /// value is returned. The key is not updated, though; this matters for
774 /// types that can be `==` without being identical. See the [module-level
775 /// documentation] for more.
777 /// [module-level documentation]: crate::collections#insert-and-complex-keys
782 /// use std::collections::HashMap;
784 /// let mut map = HashMap::new();
785 /// assert_eq!(map.insert(37, "a"), None);
786 /// assert_eq!(map.is_empty(), false);
788 /// map.insert(37, "b");
789 /// assert_eq!(map.insert(37, "c"), Some("b"));
790 /// assert_eq!(map[&37], "c");
792 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
795 self.base.insert(k, v)
798 /// Removes a key from the map, returning the value at the key if the key
799 /// was previously in the map.
801 /// The key may be any borrowed form of the map's key type, but
802 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
808 /// use std::collections::HashMap;
810 /// let mut map = HashMap::new();
811 /// map.insert(1, "a");
812 /// assert_eq!(map.remove(&1), Some("a"));
813 /// assert_eq!(map.remove(&1), None);
815 #[stable(feature = "rust1", since = "1.0.0")]
817 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
825 /// Removes a key from the map, returning the stored key and value if the
826 /// key was previously in the map.
828 /// The key may be any borrowed form of the map's key type, but
829 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
835 /// use std::collections::HashMap;
838 /// let mut map = HashMap::new();
839 /// map.insert(1, "a");
840 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
841 /// assert_eq!(map.remove(&1), None);
844 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
846 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
851 self.base.remove_entry(k)
854 /// Retains only the elements specified by the predicate.
856 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
861 /// use std::collections::HashMap;
863 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
864 /// map.retain(|&k, _| k % 2 == 0);
865 /// assert_eq!(map.len(), 4);
867 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
869 pub fn retain<F>(&mut self, f: F)
871 F: FnMut(&K, &mut V) -> bool,
876 /// Creates a consuming iterator visiting all the keys in arbitrary order.
877 /// The map cannot be used after calling this.
878 /// The iterator element type is `K`.
883 /// #![feature(map_into_keys_values)]
884 /// use std::collections::HashMap;
886 /// let mut map = HashMap::new();
887 /// map.insert("a", 1);
888 /// map.insert("b", 2);
889 /// map.insert("c", 3);
891 /// let vec: Vec<&str> = map.into_keys().collect();
894 #[unstable(feature = "map_into_keys_values", issue = "75294")]
895 pub fn into_keys(self) -> IntoKeys<K, V> {
896 IntoKeys { inner: self.into_iter() }
899 /// Creates a consuming iterator visiting all the values in arbitrary order.
900 /// The map cannot be used after calling this.
901 /// The iterator element type is `V`.
906 /// #![feature(map_into_keys_values)]
907 /// use std::collections::HashMap;
909 /// let mut map = HashMap::new();
910 /// map.insert("a", 1);
911 /// map.insert("b", 2);
912 /// map.insert("c", 3);
914 /// let vec: Vec<i32> = map.into_values().collect();
917 #[unstable(feature = "map_into_keys_values", issue = "75294")]
918 pub fn into_values(self) -> IntoValues<K, V> {
919 IntoValues { inner: self.into_iter() }
923 impl<K, V, S> HashMap<K, V, S>
927 /// Creates a raw entry builder for the HashMap.
929 /// Raw entries provide the lowest level of control for searching and
930 /// manipulating a map. They must be manually initialized with a hash and
931 /// then manually searched. After this, insertions into a vacant entry
932 /// still require an owned key to be provided.
934 /// Raw entries are useful for such exotic situations as:
936 /// * Hash memoization
937 /// * Deferring the creation of an owned key until it is known to be required
938 /// * Using a search key that doesn't work with the Borrow trait
939 /// * Using custom comparison logic without newtype wrappers
941 /// Because raw entries provide much more low-level control, it's much easier
942 /// to put the HashMap into an inconsistent state which, while memory-safe,
943 /// will cause the map to produce seemingly random results. Higher-level and
944 /// more foolproof APIs like `entry` should be preferred when possible.
946 /// In particular, the hash used to initialized the raw entry must still be
947 /// consistent with the hash of the key that is ultimately stored in the entry.
948 /// This is because implementations of HashMap may need to recompute hashes
949 /// when resizing, at which point only the keys are available.
951 /// Raw entries give mutable access to the keys. This must not be used
952 /// to modify how the key would compare or hash, as the map will not re-evaluate
953 /// where the key should go, meaning the keys may become "lost" if their
954 /// location does not reflect their state. For instance, if you change a key
955 /// so that the map now contains keys which compare equal, search may start
956 /// acting erratically, with two keys randomly masking each other. Implementations
957 /// are free to assume this doesn't happen (within the limits of memory-safety).
959 #[unstable(feature = "hash_raw_entry", issue = "56167")]
960 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
961 RawEntryBuilderMut { map: self }
964 /// Creates a raw immutable entry builder for the HashMap.
966 /// Raw entries provide the lowest level of control for searching and
967 /// manipulating a map. They must be manually initialized with a hash and
968 /// then manually searched.
970 /// This is useful for
971 /// * Hash memoization
972 /// * Using a search key that doesn't work with the Borrow trait
973 /// * Using custom comparison logic without newtype wrappers
975 /// Unless you are in such a situation, higher-level and more foolproof APIs like
976 /// `get` should be preferred.
978 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
980 #[unstable(feature = "hash_raw_entry", issue = "56167")]
981 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
982 RawEntryBuilder { map: self }
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<K, V, S> PartialEq for HashMap<K, V, S>
993 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
994 if self.len() != other.len() {
998 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 impl<K, V, S> Eq for HashMap<K, V, S>
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<K, V, S> Debug for HashMap<K, V, S>
1017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018 f.debug_map().entries(self.iter()).finish()
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<K, V, S> Default for HashMap<K, V, S>
1027 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1029 fn default() -> HashMap<K, V, S> {
1030 HashMap::with_hasher(Default::default())
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1037 K: Eq + Hash + Borrow<Q>,
1043 /// Returns a reference to the value corresponding to the supplied key.
1047 /// Panics if the key is not present in the `HashMap`.
1049 fn index(&self, key: &Q) -> &V {
1050 self.get(key).expect("no entry found for key")
1054 /// An iterator over the entries of a `HashMap`.
1056 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1057 /// documentation for more.
1059 /// [`iter`]: HashMap::iter
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub struct Iter<'a, K: 'a, V: 'a> {
1062 base: base::Iter<'a, K, V>,
1065 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<K, V> Clone for Iter<'_, K, V> {
1069 fn clone(&self) -> Self {
1070 Iter { base: self.base.clone() }
1074 #[stable(feature = "std_debug", since = "1.16.0")]
1075 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1076 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1077 f.debug_list().entries(self.clone()).finish()
1081 /// A mutable iterator over the entries of a `HashMap`.
1083 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1084 /// documentation for more.
1086 /// [`iter_mut`]: HashMap::iter_mut
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub struct IterMut<'a, K: 'a, V: 'a> {
1089 base: base::IterMut<'a, K, V>,
1092 impl<'a, K, V> IterMut<'a, K, V> {
1093 /// Returns a iterator of references over the remaining items.
1095 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1096 Iter { base: self.base.rustc_iter() }
1100 /// An owning iterator over the entries of a `HashMap`.
1102 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1103 /// (provided by the `IntoIterator` trait). See its documentation for more.
1105 /// [`into_iter`]: IntoIterator::into_iter
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub struct IntoIter<K, V> {
1108 base: base::IntoIter<K, V>,
1111 impl<K, V> IntoIter<K, V> {
1112 /// Returns a iterator of references over the remaining items.
1114 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1115 Iter { base: self.base.rustc_iter() }
1119 /// An iterator over the keys of a `HashMap`.
1121 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1122 /// documentation for more.
1124 /// [`keys`]: HashMap::keys
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub struct Keys<'a, K: 'a, V: 'a> {
1127 inner: Iter<'a, K, V>,
1130 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<K, V> Clone for Keys<'_, K, V> {
1134 fn clone(&self) -> Self {
1135 Keys { inner: self.inner.clone() }
1139 #[stable(feature = "std_debug", since = "1.16.0")]
1140 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1142 f.debug_list().entries(self.clone()).finish()
1146 /// An iterator over the values of a `HashMap`.
1148 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1149 /// documentation for more.
1151 /// [`values`]: HashMap::values
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub struct Values<'a, K: 'a, V: 'a> {
1154 inner: Iter<'a, K, V>,
1157 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<K, V> Clone for Values<'_, K, V> {
1161 fn clone(&self) -> Self {
1162 Values { inner: self.inner.clone() }
1166 #[stable(feature = "std_debug", since = "1.16.0")]
1167 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1169 f.debug_list().entries(self.clone()).finish()
1173 /// A draining iterator over the entries of a `HashMap`.
1175 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1176 /// documentation for more.
1178 /// [`drain`]: HashMap::drain
1179 #[stable(feature = "drain", since = "1.6.0")]
1180 pub struct Drain<'a, K: 'a, V: 'a> {
1181 base: base::Drain<'a, K, V>,
1184 impl<'a, K, V> Drain<'a, K, V> {
1185 /// Returns a iterator of references over the remaining items.
1187 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1188 Iter { base: self.base.rustc_iter() }
1192 /// A mutable iterator over the values of a `HashMap`.
1194 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1195 /// documentation for more.
1197 /// [`values_mut`]: HashMap::values_mut
1198 #[stable(feature = "map_values_mut", since = "1.10.0")]
1199 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1200 inner: IterMut<'a, K, V>,
1203 /// An owning iterator over the keys of a `HashMap`.
1205 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1206 /// See its documentation for more.
1208 /// [`into_keys`]: HashMap::into_keys
1209 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1210 pub struct IntoKeys<K, V> {
1211 inner: IntoIter<K, V>,
1214 /// An owning iterator over the values of a `HashMap`.
1216 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1217 /// See its documentation for more.
1219 /// [`into_values`]: HashMap::into_values
1220 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1221 pub struct IntoValues<K, V> {
1222 inner: IntoIter<K, V>,
1225 /// A builder for computing where in a HashMap a key-value pair would be stored.
1227 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1229 /// [`HashMap::raw_entry_mut`]: HashMap::raw_entry_mut
1231 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1232 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1233 map: &'a mut HashMap<K, V, S>,
1236 /// A view into a single entry in a map, which may either be vacant or occupied.
1238 /// This is a lower-level version of [`Entry`].
1240 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1241 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1243 /// [`Entry`]: enum.Entry.html
1244 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1245 /// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html
1246 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1247 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1248 /// An occupied entry.
1249 Occupied(RawOccupiedEntryMut<'a, K, V>),
1251 Vacant(RawVacantEntryMut<'a, K, V, S>),
1254 /// A view into an occupied entry in a `HashMap`.
1255 /// It is part of the [`RawEntryMut`] enum.
1256 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1257 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1258 base: base::RawOccupiedEntryMut<'a, K, V>,
1261 /// A view into a vacant entry in a `HashMap`.
1262 /// It is part of the [`RawEntryMut`] enum.
1263 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1264 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1265 base: base::RawVacantEntryMut<'a, K, V, S>,
1268 /// A builder for computing where in a HashMap a key-value pair would be stored.
1270 /// See the [`HashMap::raw_entry`] docs for usage examples.
1272 /// [`HashMap::raw_entry`]: HashMap::raw_entry
1273 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1274 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1275 map: &'a HashMap<K, V, S>,
1278 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1282 /// Creates a `RawEntryMut` from the given key.
1284 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1285 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1290 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1293 /// Creates a `RawEntryMut` from the given key and its hash.
1295 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1296 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1301 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1304 /// Creates a `RawEntryMut` from the given hash.
1306 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1307 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1309 for<'b> F: FnMut(&'b K) -> bool,
1311 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1315 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1319 /// Access an entry by key.
1321 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1322 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1327 self.map.base.raw_entry().from_key(k)
1330 /// Access an entry by a key and its hash.
1332 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1333 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1338 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1341 /// Access an entry by hash.
1343 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1344 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1346 F: FnMut(&K) -> bool,
1348 self.map.base.raw_entry().from_hash(hash, is_match)
1352 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1353 /// Ensures a value is in the entry by inserting the default if empty, and returns
1354 /// mutable references to the key and value in the entry.
1359 /// #![feature(hash_raw_entry)]
1360 /// use std::collections::HashMap;
1362 /// let mut map: HashMap<&str, u32> = HashMap::new();
1364 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1365 /// assert_eq!(map["poneyland"], 3);
1367 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1368 /// assert_eq!(map["poneyland"], 6);
1371 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1372 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1378 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1379 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1383 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1384 /// and returns mutable references to the key and value in the entry.
1389 /// #![feature(hash_raw_entry)]
1390 /// use std::collections::HashMap;
1392 /// let mut map: HashMap<&str, String> = HashMap::new();
1394 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1395 /// ("poneyland", "hoho".to_string())
1398 /// assert_eq!(map["poneyland"], "hoho".to_string());
1401 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1402 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1404 F: FnOnce() -> (K, V),
1409 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1410 RawEntryMut::Vacant(entry) => {
1411 let (k, v) = default();
1417 /// Provides in-place mutable access to an occupied entry before any
1418 /// potential inserts into the map.
1423 /// #![feature(hash_raw_entry)]
1424 /// use std::collections::HashMap;
1426 /// let mut map: HashMap<&str, u32> = HashMap::new();
1428 /// map.raw_entry_mut()
1429 /// .from_key("poneyland")
1430 /// .and_modify(|_k, v| { *v += 1 })
1431 /// .or_insert("poneyland", 42);
1432 /// assert_eq!(map["poneyland"], 42);
1434 /// map.raw_entry_mut()
1435 /// .from_key("poneyland")
1436 /// .and_modify(|_k, v| { *v += 1 })
1437 /// .or_insert("poneyland", 0);
1438 /// assert_eq!(map["poneyland"], 43);
1441 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1442 pub fn and_modify<F>(self, f: F) -> Self
1444 F: FnOnce(&mut K, &mut V),
1447 RawEntryMut::Occupied(mut entry) => {
1449 let (k, v) = entry.get_key_value_mut();
1452 RawEntryMut::Occupied(entry)
1454 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1459 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
1460 /// Gets a reference to the key in the entry.
1462 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1463 pub fn key(&self) -> &K {
1467 /// Gets a mutable reference to the key in the entry.
1469 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1470 pub fn key_mut(&mut self) -> &mut K {
1474 /// Converts the entry into a mutable reference to the key in the entry
1475 /// with a lifetime bound to the map itself.
1477 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1478 pub fn into_key(self) -> &'a mut K {
1479 self.base.into_key()
1482 /// Gets a reference to the value in the entry.
1484 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1485 pub fn get(&self) -> &V {
1489 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1490 /// with a lifetime bound to the map itself.
1492 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1493 pub fn into_mut(self) -> &'a mut V {
1494 self.base.into_mut()
1497 /// Gets a mutable reference to the value in the entry.
1499 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1500 pub fn get_mut(&mut self) -> &mut V {
1504 /// Gets a reference to the key and value in the entry.
1506 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1507 pub fn get_key_value(&mut self) -> (&K, &V) {
1508 self.base.get_key_value()
1511 /// Gets a mutable reference to the key and value in the entry.
1513 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1514 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1515 self.base.get_key_value_mut()
1518 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
1519 /// with a lifetime bound to the map itself.
1521 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1522 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1523 self.base.into_key_value()
1526 /// Sets the value of the entry, and returns the entry's old value.
1528 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1529 pub fn insert(&mut self, value: V) -> V {
1530 self.base.insert(value)
1533 /// Sets the value of the entry, and returns the entry's old value.
1535 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1536 pub fn insert_key(&mut self, key: K) -> K {
1537 self.base.insert_key(key)
1540 /// Takes the value out of the entry, and returns it.
1542 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1543 pub fn remove(self) -> V {
1547 /// Take the ownership of the key and value from the map.
1549 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1550 pub fn remove_entry(self) -> (K, V) {
1551 self.base.remove_entry()
1555 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1556 /// Sets the value of the entry with the VacantEntry's key,
1557 /// and returns a mutable reference to it.
1559 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1560 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1565 self.base.insert(key, value)
1568 /// Sets the value of the entry with the VacantEntry's key,
1569 /// and returns a mutable reference to it.
1571 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1572 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1577 self.base.insert_hashed_nocheck(hash, key, value)
1581 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1582 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1583 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1584 f.debug_struct("RawEntryBuilder").finish()
1588 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1589 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1593 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1598 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1599 impl<K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'_, K, V> {
1600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1601 f.debug_struct("RawOccupiedEntryMut")
1602 .field("key", self.key())
1603 .field("value", self.get())
1608 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1609 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1610 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1611 f.debug_struct("RawVacantEntryMut").finish()
1615 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1616 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1618 f.debug_struct("RawEntryBuilder").finish()
1622 /// A view into a single entry in a map, which may either be vacant or occupied.
1624 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1626 /// [`entry`]: HashMap::entry
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 pub enum Entry<'a, K: 'a, V: 'a> {
1629 /// An occupied entry.
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1638 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1639 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1642 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1643 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1648 /// A view into an occupied entry in a `HashMap`.
1649 /// It is part of the [`Entry`] enum.
1651 /// [`Entry`]: enum.Entry.html
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1654 base: base::RustcOccupiedEntry<'a, K, V>,
1657 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1658 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1660 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
1664 /// A view into a vacant entry in a `HashMap`.
1665 /// It is part of the [`Entry`] enum.
1667 /// [`Entry`]: enum.Entry.html
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1670 base: base::RustcVacantEntry<'a, K, V>,
1673 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1674 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1676 f.debug_tuple("VacantEntry").field(self.key()).finish()
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1682 type Item = (&'a K, &'a V);
1683 type IntoIter = Iter<'a, K, V>;
1686 fn into_iter(self) -> Iter<'a, K, V> {
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1693 type Item = (&'a K, &'a mut V);
1694 type IntoIter = IterMut<'a, K, V>;
1697 fn into_iter(self) -> IterMut<'a, K, V> {
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1705 type IntoIter = IntoIter<K, V>;
1707 /// Creates a consuming iterator, that is, one that moves each key-value
1708 /// pair out of the map in arbitrary order. The map cannot be used after
1714 /// use std::collections::HashMap;
1716 /// let mut map = HashMap::new();
1717 /// map.insert("a", 1);
1718 /// map.insert("b", 2);
1719 /// map.insert("c", 3);
1721 /// // Not possible with .iter()
1722 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1725 fn into_iter(self) -> IntoIter<K, V> {
1726 IntoIter { base: self.base.into_iter() }
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1732 type Item = (&'a K, &'a V);
1735 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1739 fn size_hint(&self) -> (usize, Option<usize>) {
1740 self.base.size_hint()
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1746 fn len(&self) -> usize {
1751 #[stable(feature = "fused", since = "1.26.0")]
1752 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1756 type Item = (&'a K, &'a mut V);
1759 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1763 fn size_hint(&self) -> (usize, Option<usize>) {
1764 self.base.size_hint()
1767 #[stable(feature = "rust1", since = "1.0.0")]
1768 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1770 fn len(&self) -> usize {
1774 #[stable(feature = "fused", since = "1.26.0")]
1775 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1777 #[stable(feature = "std_debug", since = "1.16.0")]
1778 impl<K, V> fmt::Debug for IterMut<'_, K, V>
1783 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1784 f.debug_list().entries(self.iter()).finish()
1788 #[stable(feature = "rust1", since = "1.0.0")]
1789 impl<K, V> Iterator for IntoIter<K, V> {
1793 fn next(&mut self) -> Option<(K, V)> {
1797 fn size_hint(&self) -> (usize, Option<usize>) {
1798 self.base.size_hint()
1801 #[stable(feature = "rust1", since = "1.0.0")]
1802 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1804 fn len(&self) -> usize {
1808 #[stable(feature = "fused", since = "1.26.0")]
1809 impl<K, V> FusedIterator for IntoIter<K, V> {}
1811 #[stable(feature = "std_debug", since = "1.16.0")]
1812 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1813 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1814 f.debug_list().entries(self.iter()).finish()
1818 #[stable(feature = "rust1", since = "1.0.0")]
1819 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1823 fn next(&mut self) -> Option<&'a K> {
1824 self.inner.next().map(|(k, _)| k)
1827 fn size_hint(&self) -> (usize, Option<usize>) {
1828 self.inner.size_hint()
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1834 fn len(&self) -> usize {
1838 #[stable(feature = "fused", since = "1.26.0")]
1839 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 impl<'a, K, V> Iterator for Values<'a, K, V> {
1846 fn next(&mut self) -> Option<&'a V> {
1847 self.inner.next().map(|(_, v)| v)
1850 fn size_hint(&self) -> (usize, Option<usize>) {
1851 self.inner.size_hint()
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1857 fn len(&self) -> usize {
1861 #[stable(feature = "fused", since = "1.26.0")]
1862 impl<K, V> FusedIterator for Values<'_, K, V> {}
1864 #[stable(feature = "map_values_mut", since = "1.10.0")]
1865 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1866 type Item = &'a mut V;
1869 fn next(&mut self) -> Option<&'a mut V> {
1870 self.inner.next().map(|(_, v)| v)
1873 fn size_hint(&self) -> (usize, Option<usize>) {
1874 self.inner.size_hint()
1877 #[stable(feature = "map_values_mut", since = "1.10.0")]
1878 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1880 fn len(&self) -> usize {
1884 #[stable(feature = "fused", since = "1.26.0")]
1885 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1887 #[stable(feature = "std_debug", since = "1.16.0")]
1888 impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894 f.debug_list().entries(self.inner.iter()).finish()
1898 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1899 impl<K, V> Iterator for IntoKeys<K, V> {
1903 fn next(&mut self) -> Option<K> {
1904 self.inner.next().map(|(k, _)| k)
1907 fn size_hint(&self) -> (usize, Option<usize>) {
1908 self.inner.size_hint()
1911 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1912 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1914 fn len(&self) -> usize {
1918 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1919 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1921 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1922 impl<K: Debug, V: Debug> fmt::Debug for IntoKeys<K, V> {
1923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1924 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
1928 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1929 impl<K, V> Iterator for IntoValues<K, V> {
1933 fn next(&mut self) -> Option<V> {
1934 self.inner.next().map(|(_, v)| v)
1937 fn size_hint(&self) -> (usize, Option<usize>) {
1938 self.inner.size_hint()
1941 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1942 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1944 fn len(&self) -> usize {
1948 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1949 impl<K, V> FusedIterator for IntoValues<K, V> {}
1951 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1952 impl<K: Debug, V: Debug> fmt::Debug for IntoValues<K, V> {
1953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1954 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
1958 #[stable(feature = "drain", since = "1.6.0")]
1959 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1963 fn next(&mut self) -> Option<(K, V)> {
1967 fn size_hint(&self) -> (usize, Option<usize>) {
1968 self.base.size_hint()
1971 #[stable(feature = "drain", since = "1.6.0")]
1972 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
1974 fn len(&self) -> usize {
1978 #[stable(feature = "fused", since = "1.26.0")]
1979 impl<K, V> FusedIterator for Drain<'_, K, V> {}
1981 #[stable(feature = "std_debug", since = "1.16.0")]
1982 impl<K, V> fmt::Debug for Drain<'_, K, V>
1987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1988 f.debug_list().entries(self.iter()).finish()
1992 impl<'a, K, V> Entry<'a, K, V> {
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 /// Ensures a value is in the entry by inserting the default if empty, and returns
1995 /// a mutable reference to the value in the entry.
2000 /// use std::collections::HashMap;
2002 /// let mut map: HashMap<&str, u32> = HashMap::new();
2004 /// map.entry("poneyland").or_insert(3);
2005 /// assert_eq!(map["poneyland"], 3);
2007 /// *map.entry("poneyland").or_insert(10) *= 2;
2008 /// assert_eq!(map["poneyland"], 6);
2011 pub fn or_insert(self, default: V) -> &'a mut V {
2013 Occupied(entry) => entry.into_mut(),
2014 Vacant(entry) => entry.insert(default),
2018 #[stable(feature = "rust1", since = "1.0.0")]
2019 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2020 /// and returns a mutable reference to the value in the entry.
2025 /// use std::collections::HashMap;
2027 /// let mut map: HashMap<&str, String> = HashMap::new();
2028 /// let s = "hoho".to_string();
2030 /// map.entry("poneyland").or_insert_with(|| s);
2032 /// assert_eq!(map["poneyland"], "hoho".to_string());
2035 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2037 Occupied(entry) => entry.into_mut(),
2038 Vacant(entry) => entry.insert(default()),
2042 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2043 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2044 /// which takes the key as its argument, and returns a mutable reference to the value in the
2050 /// #![feature(or_insert_with_key)]
2051 /// use std::collections::HashMap;
2053 /// let mut map: HashMap<&str, usize> = HashMap::new();
2055 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2057 /// assert_eq!(map["poneyland"], 9);
2060 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2062 Occupied(entry) => entry.into_mut(),
2064 let value = default(entry.key());
2070 /// Returns a reference to this entry's key.
2075 /// use std::collections::HashMap;
2077 /// let mut map: HashMap<&str, u32> = HashMap::new();
2078 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2081 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2082 pub fn key(&self) -> &K {
2084 Occupied(ref entry) => entry.key(),
2085 Vacant(ref entry) => entry.key(),
2089 /// Provides in-place mutable access to an occupied entry before any
2090 /// potential inserts into the map.
2095 /// use std::collections::HashMap;
2097 /// let mut map: HashMap<&str, u32> = HashMap::new();
2099 /// map.entry("poneyland")
2100 /// .and_modify(|e| { *e += 1 })
2102 /// assert_eq!(map["poneyland"], 42);
2104 /// map.entry("poneyland")
2105 /// .and_modify(|e| { *e += 1 })
2107 /// assert_eq!(map["poneyland"], 43);
2110 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2111 pub fn and_modify<F>(self, f: F) -> Self
2116 Occupied(mut entry) => {
2120 Vacant(entry) => Vacant(entry),
2124 /// Sets the value of the entry, and returns an OccupiedEntry.
2129 /// #![feature(entry_insert)]
2130 /// use std::collections::HashMap;
2132 /// let mut map: HashMap<&str, String> = HashMap::new();
2133 /// let entry = map.entry("poneyland").insert("hoho".to_string());
2135 /// assert_eq!(entry.key(), &"poneyland");
2138 #[unstable(feature = "entry_insert", issue = "65225")]
2139 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
2141 Occupied(mut entry) => {
2142 entry.insert(value);
2145 Vacant(entry) => entry.insert_entry(value),
2150 impl<'a, K, V: Default> Entry<'a, K, V> {
2151 #[stable(feature = "entry_or_default", since = "1.28.0")]
2152 /// Ensures a value is in the entry by inserting the default value if empty,
2153 /// and returns a mutable reference to the value in the entry.
2159 /// use std::collections::HashMap;
2161 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2162 /// map.entry("poneyland").or_default();
2164 /// assert_eq!(map["poneyland"], None);
2168 pub fn or_default(self) -> &'a mut V {
2170 Occupied(entry) => entry.into_mut(),
2171 Vacant(entry) => entry.insert(Default::default()),
2176 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2177 /// Gets a reference to the key in the entry.
2182 /// use std::collections::HashMap;
2184 /// let mut map: HashMap<&str, u32> = HashMap::new();
2185 /// map.entry("poneyland").or_insert(12);
2186 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2189 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2190 pub fn key(&self) -> &K {
2194 /// Take the ownership of the key and value from the map.
2199 /// use std::collections::HashMap;
2200 /// use std::collections::hash_map::Entry;
2202 /// let mut map: HashMap<&str, u32> = HashMap::new();
2203 /// map.entry("poneyland").or_insert(12);
2205 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2206 /// // We delete the entry from the map.
2207 /// o.remove_entry();
2210 /// assert_eq!(map.contains_key("poneyland"), false);
2213 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2214 pub fn remove_entry(self) -> (K, V) {
2215 self.base.remove_entry()
2218 /// Gets a reference to the value in the entry.
2223 /// use std::collections::HashMap;
2224 /// use std::collections::hash_map::Entry;
2226 /// let mut map: HashMap<&str, u32> = HashMap::new();
2227 /// map.entry("poneyland").or_insert(12);
2229 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2230 /// assert_eq!(o.get(), &12);
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 pub fn get(&self) -> &V {
2239 /// Gets a mutable reference to the value in the entry.
2241 /// If you need a reference to the `OccupiedEntry` which may outlive the
2242 /// destruction of the `Entry` value, see [`into_mut`].
2244 /// [`into_mut`]: Self::into_mut
2249 /// use std::collections::HashMap;
2250 /// use std::collections::hash_map::Entry;
2252 /// let mut map: HashMap<&str, u32> = HashMap::new();
2253 /// map.entry("poneyland").or_insert(12);
2255 /// assert_eq!(map["poneyland"], 12);
2256 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2257 /// *o.get_mut() += 10;
2258 /// assert_eq!(*o.get(), 22);
2260 /// // We can use the same Entry multiple times.
2261 /// *o.get_mut() += 2;
2264 /// assert_eq!(map["poneyland"], 24);
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 pub fn get_mut(&mut self) -> &mut V {
2272 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2273 /// with a lifetime bound to the map itself.
2275 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2277 /// [`get_mut`]: Self::get_mut
2282 /// use std::collections::HashMap;
2283 /// use std::collections::hash_map::Entry;
2285 /// let mut map: HashMap<&str, u32> = HashMap::new();
2286 /// map.entry("poneyland").or_insert(12);
2288 /// assert_eq!(map["poneyland"], 12);
2289 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2290 /// *o.into_mut() += 10;
2293 /// assert_eq!(map["poneyland"], 22);
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 pub fn into_mut(self) -> &'a mut V {
2298 self.base.into_mut()
2301 /// Sets the value of the entry, and returns the entry's old value.
2306 /// use std::collections::HashMap;
2307 /// use std::collections::hash_map::Entry;
2309 /// let mut map: HashMap<&str, u32> = HashMap::new();
2310 /// map.entry("poneyland").or_insert(12);
2312 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2313 /// assert_eq!(o.insert(15), 12);
2316 /// assert_eq!(map["poneyland"], 15);
2319 #[stable(feature = "rust1", since = "1.0.0")]
2320 pub fn insert(&mut self, value: V) -> V {
2321 self.base.insert(value)
2324 /// Takes the value out of the entry, and returns it.
2329 /// use std::collections::HashMap;
2330 /// use std::collections::hash_map::Entry;
2332 /// let mut map: HashMap<&str, u32> = HashMap::new();
2333 /// map.entry("poneyland").or_insert(12);
2335 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2336 /// assert_eq!(o.remove(), 12);
2339 /// assert_eq!(map.contains_key("poneyland"), false);
2342 #[stable(feature = "rust1", since = "1.0.0")]
2343 pub fn remove(self) -> V {
2347 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2348 /// the key used to create this entry.
2353 /// #![feature(map_entry_replace)]
2354 /// use std::collections::hash_map::{Entry, HashMap};
2355 /// use std::rc::Rc;
2357 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2358 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2360 /// let my_key = Rc::new("Stringthing".to_string());
2362 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2363 /// // Also replace the key with a handle to our other key.
2364 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2369 #[unstable(feature = "map_entry_replace", issue = "44286")]
2370 pub fn replace_entry(self, value: V) -> (K, V) {
2371 self.base.replace_entry(value)
2374 /// Replaces the key in the hash map with the key used to create this entry.
2379 /// #![feature(map_entry_replace)]
2380 /// use std::collections::hash_map::{Entry, HashMap};
2381 /// use std::rc::Rc;
2383 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2384 /// let known_strings: Vec<Rc<String>> = Vec::new();
2386 /// // Initialise known strings, run program, etc.
2388 /// reclaim_memory(&mut map, &known_strings);
2390 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2391 /// for s in known_strings {
2392 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2393 /// // Replaces the entry's key with our version of it in `known_strings`.
2394 /// entry.replace_key();
2400 #[unstable(feature = "map_entry_replace", issue = "44286")]
2401 pub fn replace_key(self) -> K {
2402 self.base.replace_key()
2406 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2407 /// Gets a reference to the key that would be used when inserting a value
2408 /// through the `VacantEntry`.
2413 /// use std::collections::HashMap;
2415 /// let mut map: HashMap<&str, u32> = HashMap::new();
2416 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2419 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2420 pub fn key(&self) -> &K {
2424 /// Take ownership of the key.
2429 /// use std::collections::HashMap;
2430 /// use std::collections::hash_map::Entry;
2432 /// let mut map: HashMap<&str, u32> = HashMap::new();
2434 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2439 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2440 pub fn into_key(self) -> K {
2441 self.base.into_key()
2444 /// Sets the value of the entry with the VacantEntry's key,
2445 /// and returns a mutable reference to it.
2450 /// use std::collections::HashMap;
2451 /// use std::collections::hash_map::Entry;
2453 /// let mut map: HashMap<&str, u32> = HashMap::new();
2455 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2458 /// assert_eq!(map["poneyland"], 37);
2461 #[stable(feature = "rust1", since = "1.0.0")]
2462 pub fn insert(self, value: V) -> &'a mut V {
2463 self.base.insert(value)
2466 /// Sets the value of the entry with the VacantEntry's key,
2467 /// and returns an OccupiedEntry.
2472 /// use std::collections::HashMap;
2473 /// use std::collections::hash_map::Entry;
2475 /// let mut map: HashMap<&str, u32> = HashMap::new();
2477 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2480 /// assert_eq!(map["poneyland"], 37);
2483 fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2484 let base = self.base.insert_entry(value);
2485 OccupiedEntry { base }
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2493 S: BuildHasher + Default,
2495 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2496 let mut map = HashMap::with_hasher(Default::default());
2502 /// Inserts all new key-values from the iterator and replaces values with existing
2503 /// keys with new values returned from the iterator.
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2511 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2512 self.base.extend(iter)
2516 fn extend_one(&mut self, (k, v): (K, V)) {
2517 self.base.insert(k, v);
2521 fn extend_reserve(&mut self, additional: usize) {
2522 // self.base.extend_reserve(additional);
2523 // FIXME: hashbrown should implement this method.
2524 // But until then, use the same reservation logic:
2526 // Reserve the entire hint lower bound if the map is empty.
2527 // Otherwise reserve half the hint (rounded up), so the map
2528 // will only resize twice in the worst case.
2529 let reserve = if self.is_empty() { additional } else { (additional + 1) / 2 };
2530 self.base.reserve(reserve);
2534 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2535 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2537 K: Eq + Hash + Copy,
2542 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2543 self.base.extend(iter)
2547 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2548 self.base.insert(k, v);
2552 fn extend_reserve(&mut self, additional: usize) {
2553 Extend::<(K, V)>::extend_reserve(self, additional)
2557 /// `RandomState` is the default state for [`HashMap`] types.
2559 /// A particular instance `RandomState` will create the same instances of
2560 /// [`Hasher`], but the hashers created by two different `RandomState`
2561 /// instances are unlikely to produce the same result for the same values.
2566 /// use std::collections::HashMap;
2567 /// use std::collections::hash_map::RandomState;
2569 /// let s = RandomState::new();
2570 /// let mut map = HashMap::with_hasher(s);
2571 /// map.insert(1, 2);
2574 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2575 pub struct RandomState {
2581 /// Constructs a new `RandomState` that is initialized with random keys.
2586 /// use std::collections::hash_map::RandomState;
2588 /// let s = RandomState::new();
2591 #[allow(deprecated)]
2593 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2594 pub fn new() -> RandomState {
2595 // Historically this function did not cache keys from the OS and instead
2596 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2597 // was discovered, however, that because we re-seed the thread-local RNG
2598 // from the OS periodically that this can cause excessive slowdown when
2599 // many hash maps are created on a thread. To solve this performance
2600 // trap we cache the first set of randomly generated keys per-thread.
2602 // Later in #36481 it was discovered that exposing a deterministic
2603 // iteration order allows a form of DOS attack. To counter that we
2604 // increment one of the seeds on every RandomState creation, giving
2605 // every corresponding HashMap a different iteration order.
2606 thread_local!(static KEYS: Cell<(u64, u64)> = {
2607 Cell::new(sys::hashmap_random_keys())
2611 let (k0, k1) = keys.get();
2612 keys.set((k0.wrapping_add(1), k1));
2613 RandomState { k0, k1 }
2618 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2619 impl BuildHasher for RandomState {
2620 type Hasher = DefaultHasher;
2622 #[allow(deprecated)]
2623 fn build_hasher(&self) -> DefaultHasher {
2624 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2628 /// The default [`Hasher`] used by [`RandomState`].
2630 /// The internal algorithm is not specified, and so it and its hashes should
2631 /// not be relied upon over releases.
2632 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2633 #[allow(deprecated)]
2634 #[derive(Clone, Debug)]
2635 pub struct DefaultHasher(SipHasher13);
2637 impl DefaultHasher {
2638 /// Creates a new `DefaultHasher`.
2640 /// This hasher is not guaranteed to be the same as all other
2641 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2642 /// instances created through `new` or `default`.
2643 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2644 #[allow(deprecated)]
2645 pub fn new() -> DefaultHasher {
2646 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2650 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2651 impl Default for DefaultHasher {
2652 // FIXME: here should link `new` to [DefaultHasher::new], but it occurs intra-doc link
2653 // resolution failure when re-exporting libstd items. When #56922 fixed,
2654 // link `new` to [DefaultHasher::new] again.
2655 /// Creates a new `DefaultHasher` using `new`.
2656 /// See its documentation for more.
2657 fn default() -> DefaultHasher {
2658 DefaultHasher::new()
2662 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2663 impl Hasher for DefaultHasher {
2665 fn write(&mut self, msg: &[u8]) {
2670 fn finish(&self) -> u64 {
2675 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2676 impl Default for RandomState {
2677 /// Constructs a new `RandomState`.
2679 fn default() -> RandomState {
2684 #[stable(feature = "std_debug", since = "1.16.0")]
2685 impl fmt::Debug for RandomState {
2686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2687 f.pad("RandomState { .. }")
2692 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2694 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2695 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2700 fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
2702 hashbrown::TryReserveError::CapacityOverflow => TryReserveError::CapacityOverflow,
2703 hashbrown::TryReserveError::AllocError { layout } => {
2704 TryReserveError::AllocError { layout, non_exhaustive: () }
2710 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
2711 raw: base::RawEntryMut<'a, K, V, S>,
2712 ) -> RawEntryMut<'a, K, V, S> {
2714 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
2715 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
2720 fn assert_covariance() {
2721 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2724 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2727 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2730 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2733 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2736 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2739 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2742 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2745 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2748 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2752 d: Drain<'static, &'static str, &'static str>,
2753 ) -> Drain<'new, &'new str, &'new str> {
2760 use super::Entry::{Occupied, Vacant};
2762 use super::RandomState;
2763 use crate::cell::RefCell;
2764 use rand::{thread_rng, Rng};
2765 use realstd::collections::TryReserveError::*;
2767 // https://github.com/rust-lang/rust/issues/62301
2768 fn _assert_hashmap_is_unwind_safe() {
2769 fn assert_unwind_safe<T: crate::panic::UnwindSafe>() {}
2770 assert_unwind_safe::<HashMap<(), crate::cell::UnsafeCell<()>>>();
2774 fn test_zero_capacities() {
2775 type HM = HashMap<i32, i32>;
2778 assert_eq!(m.capacity(), 0);
2780 let m = HM::default();
2781 assert_eq!(m.capacity(), 0);
2783 let m = HM::with_hasher(RandomState::new());
2784 assert_eq!(m.capacity(), 0);
2786 let m = HM::with_capacity(0);
2787 assert_eq!(m.capacity(), 0);
2789 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2790 assert_eq!(m.capacity(), 0);
2792 let mut m = HM::new();
2798 assert_eq!(m.capacity(), 0);
2800 let mut m = HM::new();
2802 assert_eq!(m.capacity(), 0);
2806 fn test_create_capacity_zero() {
2807 let mut m = HashMap::with_capacity(0);
2809 assert!(m.insert(1, 1).is_none());
2811 assert!(m.contains_key(&1));
2812 assert!(!m.contains_key(&0));
2817 let mut m = HashMap::new();
2818 assert_eq!(m.len(), 0);
2819 assert!(m.insert(1, 2).is_none());
2820 assert_eq!(m.len(), 1);
2821 assert!(m.insert(2, 4).is_none());
2822 assert_eq!(m.len(), 2);
2823 assert_eq!(*m.get(&1).unwrap(), 2);
2824 assert_eq!(*m.get(&2).unwrap(), 4);
2829 let mut m = HashMap::new();
2830 assert_eq!(m.len(), 0);
2831 assert!(m.insert(1, 2).is_none());
2832 assert_eq!(m.len(), 1);
2833 assert!(m.insert(2, 4).is_none());
2834 assert_eq!(m.len(), 2);
2836 assert_eq!(*m2.get(&1).unwrap(), 2);
2837 assert_eq!(*m2.get(&2).unwrap(), 4);
2838 assert_eq!(m2.len(), 2);
2841 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
2843 #[derive(Hash, PartialEq, Eq)]
2849 fn new(k: usize) -> Droppable {
2850 DROP_VECTOR.with(|slot| {
2851 slot.borrow_mut()[k] += 1;
2858 impl Drop for Droppable {
2859 fn drop(&mut self) {
2860 DROP_VECTOR.with(|slot| {
2861 slot.borrow_mut()[self.k] -= 1;
2866 impl Clone for Droppable {
2867 fn clone(&self) -> Droppable {
2868 Droppable::new(self.k)
2874 DROP_VECTOR.with(|slot| {
2875 *slot.borrow_mut() = vec![0; 200];
2879 let mut m = HashMap::new();
2881 DROP_VECTOR.with(|v| {
2883 assert_eq!(v.borrow()[i], 0);
2888 let d1 = Droppable::new(i);
2889 let d2 = Droppable::new(i + 100);
2893 DROP_VECTOR.with(|v| {
2895 assert_eq!(v.borrow()[i], 1);
2900 let k = Droppable::new(i);
2901 let v = m.remove(&k);
2903 assert!(v.is_some());
2905 DROP_VECTOR.with(|v| {
2906 assert_eq!(v.borrow()[i], 1);
2907 assert_eq!(v.borrow()[i + 100], 1);
2911 DROP_VECTOR.with(|v| {
2913 assert_eq!(v.borrow()[i], 0);
2914 assert_eq!(v.borrow()[i + 100], 0);
2918 assert_eq!(v.borrow()[i], 1);
2919 assert_eq!(v.borrow()[i + 100], 1);
2924 DROP_VECTOR.with(|v| {
2926 assert_eq!(v.borrow()[i], 0);
2932 fn test_into_iter_drops() {
2933 DROP_VECTOR.with(|v| {
2934 *v.borrow_mut() = vec![0; 200];
2938 let mut hm = HashMap::new();
2940 DROP_VECTOR.with(|v| {
2942 assert_eq!(v.borrow()[i], 0);
2947 let d1 = Droppable::new(i);
2948 let d2 = Droppable::new(i + 100);
2952 DROP_VECTOR.with(|v| {
2954 assert_eq!(v.borrow()[i], 1);
2961 // By the way, ensure that cloning doesn't screw up the dropping.
2965 let mut half = hm.into_iter().take(50);
2967 DROP_VECTOR.with(|v| {
2969 assert_eq!(v.borrow()[i], 1);
2973 for _ in half.by_ref() {}
2975 DROP_VECTOR.with(|v| {
2976 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
2978 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
2985 DROP_VECTOR.with(|v| {
2987 assert_eq!(v.borrow()[i], 0);
2993 fn test_empty_remove() {
2994 let mut m: HashMap<i32, bool> = HashMap::new();
2995 assert_eq!(m.remove(&0), None);
2999 fn test_empty_entry() {
3000 let mut m: HashMap<i32, bool> = HashMap::new();
3002 Occupied(_) => panic!(),
3005 assert!(*m.entry(0).or_insert(true));
3006 assert_eq!(m.len(), 1);
3010 fn test_empty_iter() {
3011 let mut m: HashMap<i32, bool> = HashMap::new();
3012 assert_eq!(m.drain().next(), None);
3013 assert_eq!(m.keys().next(), None);
3014 assert_eq!(m.values().next(), None);
3015 assert_eq!(m.values_mut().next(), None);
3016 assert_eq!(m.iter().next(), None);
3017 assert_eq!(m.iter_mut().next(), None);
3018 assert_eq!(m.len(), 0);
3019 assert!(m.is_empty());
3020 assert_eq!(m.into_iter().next(), None);
3024 fn test_lots_of_insertions() {
3025 let mut m = HashMap::new();
3027 // Try this a few times to make sure we never screw up the hashmap's
3030 assert!(m.is_empty());
3033 assert!(m.insert(i, i).is_none());
3037 assert_eq!(r, Some(&j));
3040 for j in i + 1..1001 {
3042 assert_eq!(r, None);
3046 for i in 1001..2001 {
3047 assert!(!m.contains_key(&i));
3052 assert!(m.remove(&i).is_some());
3055 assert!(!m.contains_key(&j));
3058 for j in i + 1..1001 {
3059 assert!(m.contains_key(&j));
3064 assert!(!m.contains_key(&i));
3068 assert!(m.insert(i, i).is_none());
3072 for i in (1..1001).rev() {
3073 assert!(m.remove(&i).is_some());
3076 assert!(!m.contains_key(&j));
3080 assert!(m.contains_key(&j));
3087 fn test_find_mut() {
3088 let mut m = HashMap::new();
3089 assert!(m.insert(1, 12).is_none());
3090 assert!(m.insert(2, 8).is_none());
3091 assert!(m.insert(5, 14).is_none());
3093 match m.get_mut(&5) {
3095 Some(x) => *x = new,
3097 assert_eq!(m.get(&5), Some(&new));
3101 fn test_insert_overwrite() {
3102 let mut m = HashMap::new();
3103 assert!(m.insert(1, 2).is_none());
3104 assert_eq!(*m.get(&1).unwrap(), 2);
3105 assert!(!m.insert(1, 3).is_none());
3106 assert_eq!(*m.get(&1).unwrap(), 3);
3110 fn test_insert_conflicts() {
3111 let mut m = HashMap::with_capacity(4);
3112 assert!(m.insert(1, 2).is_none());
3113 assert!(m.insert(5, 3).is_none());
3114 assert!(m.insert(9, 4).is_none());
3115 assert_eq!(*m.get(&9).unwrap(), 4);
3116 assert_eq!(*m.get(&5).unwrap(), 3);
3117 assert_eq!(*m.get(&1).unwrap(), 2);
3121 fn test_conflict_remove() {
3122 let mut m = HashMap::with_capacity(4);
3123 assert!(m.insert(1, 2).is_none());
3124 assert_eq!(*m.get(&1).unwrap(), 2);
3125 assert!(m.insert(5, 3).is_none());
3126 assert_eq!(*m.get(&1).unwrap(), 2);
3127 assert_eq!(*m.get(&5).unwrap(), 3);
3128 assert!(m.insert(9, 4).is_none());
3129 assert_eq!(*m.get(&1).unwrap(), 2);
3130 assert_eq!(*m.get(&5).unwrap(), 3);
3131 assert_eq!(*m.get(&9).unwrap(), 4);
3132 assert!(m.remove(&1).is_some());
3133 assert_eq!(*m.get(&9).unwrap(), 4);
3134 assert_eq!(*m.get(&5).unwrap(), 3);
3138 fn test_is_empty() {
3139 let mut m = HashMap::with_capacity(4);
3140 assert!(m.insert(1, 2).is_none());
3141 assert!(!m.is_empty());
3142 assert!(m.remove(&1).is_some());
3143 assert!(m.is_empty());
3148 let mut m = HashMap::new();
3150 assert_eq!(m.remove(&1), Some(2));
3151 assert_eq!(m.remove(&1), None);
3155 fn test_remove_entry() {
3156 let mut m = HashMap::new();
3158 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3159 assert_eq!(m.remove(&1), None);
3164 let mut m = HashMap::with_capacity(4);
3166 assert!(m.insert(i, i * 2).is_none());
3168 assert_eq!(m.len(), 32);
3170 let mut observed: u32 = 0;
3173 assert_eq!(*v, *k * 2);
3174 observed |= 1 << *k;
3176 assert_eq!(observed, 0xFFFF_FFFF);
3181 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3182 let map: HashMap<_, _> = vec.into_iter().collect();
3183 let keys: Vec<_> = map.keys().cloned().collect();
3184 assert_eq!(keys.len(), 3);
3185 assert!(keys.contains(&1));
3186 assert!(keys.contains(&2));
3187 assert!(keys.contains(&3));
3192 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3193 let map: HashMap<_, _> = vec.into_iter().collect();
3194 let values: Vec<_> = map.values().cloned().collect();
3195 assert_eq!(values.len(), 3);
3196 assert!(values.contains(&'a'));
3197 assert!(values.contains(&'b'));
3198 assert!(values.contains(&'c'));
3202 fn test_values_mut() {
3203 let vec = vec![(1, 1), (2, 2), (3, 3)];
3204 let mut map: HashMap<_, _> = vec.into_iter().collect();
3205 for value in map.values_mut() {
3206 *value = (*value) * 2
3208 let values: Vec<_> = map.values().cloned().collect();
3209 assert_eq!(values.len(), 3);
3210 assert!(values.contains(&2));
3211 assert!(values.contains(&4));
3212 assert!(values.contains(&6));
3216 fn test_into_keys() {
3217 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3218 let map: HashMap<_, _> = vec.into_iter().collect();
3219 let keys: Vec<_> = map.into_keys().collect();
3221 assert_eq!(keys.len(), 3);
3222 assert!(keys.contains(&1));
3223 assert!(keys.contains(&2));
3224 assert!(keys.contains(&3));
3228 fn test_into_values() {
3229 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3230 let map: HashMap<_, _> = vec.into_iter().collect();
3231 let values: Vec<_> = map.into_values().collect();
3233 assert_eq!(values.len(), 3);
3234 assert!(values.contains(&'a'));
3235 assert!(values.contains(&'b'));
3236 assert!(values.contains(&'c'));
3241 let mut m = HashMap::new();
3242 assert!(m.get(&1).is_none());
3246 Some(v) => assert_eq!(*v, 2),
3252 let mut m1 = HashMap::new();
3257 let mut m2 = HashMap::new();
3270 let mut map = HashMap::new();
3271 let empty: HashMap<i32, i32> = HashMap::new();
3276 let map_str = format!("{:?}", map);
3278 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
3279 assert_eq!(format!("{:?}", empty), "{}");
3283 fn test_reserve_shrink_to_fit() {
3284 let mut m = HashMap::new();
3287 assert!(m.capacity() >= m.len());
3293 let usable_cap = m.capacity();
3294 for i in 128..(128 + 256) {
3296 assert_eq!(m.capacity(), usable_cap);
3299 for i in 100..(128 + 256) {
3300 assert_eq!(m.remove(&i), Some(i));
3304 assert_eq!(m.len(), 100);
3305 assert!(!m.is_empty());
3306 assert!(m.capacity() >= m.len());
3309 assert_eq!(m.remove(&i), Some(i));
3314 assert_eq!(m.len(), 1);
3315 assert!(m.capacity() >= m.len());
3316 assert_eq!(m.remove(&0), Some(0));
3320 fn test_from_iter() {
3321 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3323 let map: HashMap<_, _> = xs.iter().cloned().collect();
3325 for &(k, v) in &xs {
3326 assert_eq!(map.get(&k), Some(&v));
3329 assert_eq!(map.iter().len(), xs.len() - 1);
3333 fn test_size_hint() {
3334 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3336 let map: HashMap<_, _> = xs.iter().cloned().collect();
3338 let mut iter = map.iter();
3340 for _ in iter.by_ref().take(3) {}
3342 assert_eq!(iter.size_hint(), (3, Some(3)));
3346 fn test_iter_len() {
3347 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3349 let map: HashMap<_, _> = xs.iter().cloned().collect();
3351 let mut iter = map.iter();
3353 for _ in iter.by_ref().take(3) {}
3355 assert_eq!(iter.len(), 3);
3359 fn test_mut_size_hint() {
3360 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3362 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3364 let mut iter = map.iter_mut();
3366 for _ in iter.by_ref().take(3) {}
3368 assert_eq!(iter.size_hint(), (3, Some(3)));
3372 fn test_iter_mut_len() {
3373 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3375 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3377 let mut iter = map.iter_mut();
3379 for _ in iter.by_ref().take(3) {}
3381 assert_eq!(iter.len(), 3);
3386 let mut map = HashMap::new();
3392 assert_eq!(map[&2], 1);
3397 fn test_index_nonexistent() {
3398 let mut map = HashMap::new();
3409 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3411 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3413 // Existing key (insert)
3414 match map.entry(1) {
3415 Vacant(_) => unreachable!(),
3416 Occupied(mut view) => {
3417 assert_eq!(view.get(), &10);
3418 assert_eq!(view.insert(100), 10);
3421 assert_eq!(map.get(&1).unwrap(), &100);
3422 assert_eq!(map.len(), 6);
3424 // Existing key (update)
3425 match map.entry(2) {
3426 Vacant(_) => unreachable!(),
3427 Occupied(mut view) => {
3428 let v = view.get_mut();
3429 let new_v = (*v) * 10;
3433 assert_eq!(map.get(&2).unwrap(), &200);
3434 assert_eq!(map.len(), 6);
3436 // Existing key (take)
3437 match map.entry(3) {
3438 Vacant(_) => unreachable!(),
3440 assert_eq!(view.remove(), 30);
3443 assert_eq!(map.get(&3), None);
3444 assert_eq!(map.len(), 5);
3446 // Inexistent key (insert)
3447 match map.entry(10) {
3448 Occupied(_) => unreachable!(),
3450 assert_eq!(*view.insert(1000), 1000);
3453 assert_eq!(map.get(&10).unwrap(), &1000);
3454 assert_eq!(map.len(), 6);
3458 fn test_entry_take_doesnt_corrupt() {
3459 #![allow(deprecated)] //rand
3461 fn check(m: &HashMap<i32, ()>) {
3463 assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
3467 let mut m = HashMap::new();
3468 let mut rng = thread_rng();
3470 // Populate the map with some items.
3472 let x = rng.gen_range(-10, 10);
3477 let x = rng.gen_range(-10, 10);
3490 fn test_extend_ref() {
3491 let mut a = HashMap::new();
3493 let mut b = HashMap::new();
3495 b.insert(3, "three");
3499 assert_eq!(a.len(), 3);
3500 assert_eq!(a[&1], "one");
3501 assert_eq!(a[&2], "two");
3502 assert_eq!(a[&3], "three");
3506 fn test_capacity_not_less_than_len() {
3507 let mut a = HashMap::new();
3515 assert!(a.capacity() > a.len());
3517 let free = a.capacity() - a.len();
3523 assert_eq!(a.len(), a.capacity());
3525 // Insert at capacity should cause allocation.
3527 assert!(a.capacity() > a.len());
3531 fn test_occupied_entry_key() {
3532 let mut a = HashMap::new();
3533 let key = "hello there";
3534 let value = "value goes here";
3535 assert!(a.is_empty());
3536 a.insert(key.clone(), value.clone());
3537 assert_eq!(a.len(), 1);
3538 assert_eq!(a[key], value);
3540 match a.entry(key.clone()) {
3541 Vacant(_) => panic!(),
3542 Occupied(e) => assert_eq!(key, *e.key()),
3544 assert_eq!(a.len(), 1);
3545 assert_eq!(a[key], value);
3549 fn test_vacant_entry_key() {
3550 let mut a = HashMap::new();
3551 let key = "hello there";
3552 let value = "value goes here";
3554 assert!(a.is_empty());
3555 match a.entry(key.clone()) {
3556 Occupied(_) => panic!(),
3558 assert_eq!(key, *e.key());
3559 e.insert(value.clone());
3562 assert_eq!(a.len(), 1);
3563 assert_eq!(a[key], value);
3568 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
3570 map.retain(|&k, _| k % 2 == 0);
3571 assert_eq!(map.len(), 50);
3572 assert_eq!(map[&2], 20);
3573 assert_eq!(map[&4], 40);
3574 assert_eq!(map[&6], 60);
3578 fn test_try_reserve() {
3579 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
3581 const MAX_USIZE: usize = usize::MAX;
3583 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
3585 panic!("usize::MAX should trigger an overflow!");
3588 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE / 8) {
3590 panic!("usize::MAX / 8 should trigger an OOM!")
3595 fn test_raw_entry() {
3596 use super::RawEntryMut::{Occupied, Vacant};
3598 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3600 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3602 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
3603 use core::hash::{BuildHasher, Hash, Hasher};
3605 let mut hasher = map.hasher().build_hasher();
3606 k.hash(&mut hasher);
3610 // Existing key (insert)
3611 match map.raw_entry_mut().from_key(&1) {
3612 Vacant(_) => unreachable!(),
3613 Occupied(mut view) => {
3614 assert_eq!(view.get(), &10);
3615 assert_eq!(view.insert(100), 10);
3618 let hash1 = compute_hash(&map, 1);
3619 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
3620 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
3621 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
3622 assert_eq!(map.len(), 6);
3624 // Existing key (update)
3625 match map.raw_entry_mut().from_key(&2) {
3626 Vacant(_) => unreachable!(),
3627 Occupied(mut view) => {
3628 let v = view.get_mut();
3629 let new_v = (*v) * 10;
3633 let hash2 = compute_hash(&map, 2);
3634 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
3635 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
3636 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
3637 assert_eq!(map.len(), 6);
3639 // Existing key (take)
3640 let hash3 = compute_hash(&map, 3);
3641 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
3642 Vacant(_) => unreachable!(),
3644 assert_eq!(view.remove_entry(), (3, 30));
3647 assert_eq!(map.raw_entry().from_key(&3), None);
3648 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
3649 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
3650 assert_eq!(map.len(), 5);
3652 // Nonexistent key (insert)
3653 match map.raw_entry_mut().from_key(&10) {
3654 Occupied(_) => unreachable!(),
3656 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
3659 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
3660 assert_eq!(map.len(), 6);
3662 // Ensure all lookup methods produce equivalent results.
3664 let hash = compute_hash(&map, k);
3665 let v = map.get(&k).cloned();
3666 let kv = v.as_ref().map(|v| (&k, v));
3668 assert_eq!(map.raw_entry().from_key(&k), kv);
3669 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
3670 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
3672 match map.raw_entry_mut().from_key(&k) {
3673 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3674 Vacant(_) => assert_eq!(v, None),
3676 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
3677 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3678 Vacant(_) => assert_eq!(v, None),
3680 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
3681 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3682 Vacant(_) => assert_eq!(v, None),