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 /// [`Eq`]: ../../std/cmp/trait.Eq.html
152 /// [`Hash`]: ../../std/hash/trait.Hash.html
153 /// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
154 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
155 /// [`Cell`]: ../../std/cell/struct.Cell.html
156 /// [`default`]: #method.default
157 /// [`with_hasher`]: #method.with_hasher
158 /// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
159 /// [`fnv`]: https://crates.io/crates/fnv
162 /// use std::collections::HashMap;
164 /// #[derive(Hash, Eq, PartialEq, Debug)]
171 /// /// Creates a new Viking.
172 /// fn new(name: &str, country: &str) -> Viking {
173 /// Viking { name: name.to_string(), country: country.to_string() }
177 /// // Use a HashMap to store the vikings' health points.
178 /// let mut vikings = HashMap::new();
180 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
181 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
182 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
184 /// // Use derived implementation to print the status of the vikings.
185 /// for (viking, health) in &vikings {
186 /// println!("{:?} has {} hp", viking, health);
190 /// A `HashMap` with fixed list of elements can be initialized from an array:
193 /// use std::collections::HashMap;
195 /// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
196 /// .iter().cloned().collect();
197 /// // use the values stored in map
201 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_type")]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub struct HashMap<K, V, S = RandomState> {
204 base: base::HashMap<K, V, S>,
207 impl<K, V> HashMap<K, V, RandomState> {
208 /// Creates an empty `HashMap`.
210 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
211 /// is first inserted into.
216 /// use std::collections::HashMap;
217 /// let mut map: HashMap<&str, i32> = HashMap::new();
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub fn new() -> HashMap<K, V, RandomState> {
225 /// Creates an empty `HashMap` with the specified capacity.
227 /// The hash map will be able to hold at least `capacity` elements without
228 /// reallocating. If `capacity` is 0, the hash map will not allocate.
233 /// use std::collections::HashMap;
234 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
237 #[stable(feature = "rust1", since = "1.0.0")]
238 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
239 HashMap::with_capacity_and_hasher(capacity, Default::default())
243 impl<K, V, S> HashMap<K, V, S> {
244 /// Creates an empty `HashMap` which will use the given hash builder to hash
247 /// The created map has the default initial capacity.
249 /// Warning: `hash_builder` is normally randomly generated, and
250 /// is designed to allow HashMaps to be resistant to attacks that
251 /// cause many collisions and very poor performance. Setting it
252 /// manually using this function can expose a DoS attack vector.
254 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
255 /// the HashMap to be useful, see its documentation for details.
260 /// use std::collections::HashMap;
261 /// use std::collections::hash_map::RandomState;
263 /// let s = RandomState::new();
264 /// let mut map = HashMap::with_hasher(s);
265 /// map.insert(1, 2);
268 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
270 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
271 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
272 HashMap { base: base::HashMap::with_hasher(hash_builder) }
275 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
276 /// to hash the keys.
278 /// The hash map will be able to hold at least `capacity` elements without
279 /// reallocating. If `capacity` is 0, the hash map will not allocate.
281 /// Warning: `hash_builder` is normally randomly generated, and
282 /// is designed to allow HashMaps to be resistant to attacks that
283 /// cause many collisions and very poor performance. Setting it
284 /// manually using this function can expose a DoS attack vector.
286 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
287 /// the HashMap to be useful, see its documentation for details.
292 /// use std::collections::HashMap;
293 /// use std::collections::hash_map::RandomState;
295 /// let s = RandomState::new();
296 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
297 /// map.insert(1, 2);
300 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
302 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
303 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
304 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
307 /// Returns the number of elements the map can hold without reallocating.
309 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
310 /// more, but is guaranteed to be able to hold at least this many.
315 /// use std::collections::HashMap;
316 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
317 /// assert!(map.capacity() >= 100);
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn capacity(&self) -> usize {
325 /// An iterator visiting all keys in arbitrary order.
326 /// The iterator element type is `&'a K`.
331 /// use std::collections::HashMap;
333 /// let mut map = HashMap::new();
334 /// map.insert("a", 1);
335 /// map.insert("b", 2);
336 /// map.insert("c", 3);
338 /// for key in map.keys() {
339 /// println!("{}", key);
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub fn keys(&self) -> Keys<'_, K, V> {
344 Keys { inner: self.iter() }
347 /// An iterator visiting all values in arbitrary order.
348 /// The iterator element type is `&'a V`.
353 /// use std::collections::HashMap;
355 /// let mut map = HashMap::new();
356 /// map.insert("a", 1);
357 /// map.insert("b", 2);
358 /// map.insert("c", 3);
360 /// for val in map.values() {
361 /// println!("{}", val);
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub fn values(&self) -> Values<'_, K, V> {
366 Values { inner: self.iter() }
369 /// An iterator visiting all values mutably in arbitrary order.
370 /// The iterator element type is `&'a mut V`.
375 /// use std::collections::HashMap;
377 /// let mut map = HashMap::new();
379 /// map.insert("a", 1);
380 /// map.insert("b", 2);
381 /// map.insert("c", 3);
383 /// for val in map.values_mut() {
384 /// *val = *val + 10;
387 /// for val in map.values() {
388 /// println!("{}", val);
391 #[stable(feature = "map_values_mut", since = "1.10.0")]
392 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
393 ValuesMut { inner: self.iter_mut() }
396 /// An iterator visiting all key-value pairs in arbitrary order.
397 /// The iterator element type is `(&'a K, &'a V)`.
402 /// use std::collections::HashMap;
404 /// let mut map = HashMap::new();
405 /// map.insert("a", 1);
406 /// map.insert("b", 2);
407 /// map.insert("c", 3);
409 /// for (key, val) in map.iter() {
410 /// println!("key: {} val: {}", key, val);
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn iter(&self) -> Iter<'_, K, V> {
415 Iter { base: self.base.iter() }
418 /// An iterator visiting all key-value pairs in arbitrary order,
419 /// with mutable references to the values.
420 /// The iterator element type is `(&'a K, &'a mut V)`.
425 /// use std::collections::HashMap;
427 /// let mut map = HashMap::new();
428 /// map.insert("a", 1);
429 /// map.insert("b", 2);
430 /// map.insert("c", 3);
432 /// // Update all values
433 /// for (_, val) in map.iter_mut() {
437 /// for (key, val) in &map {
438 /// println!("key: {} val: {}", key, val);
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
443 IterMut { base: self.base.iter_mut() }
446 /// Returns the number of elements in the map.
451 /// use std::collections::HashMap;
453 /// let mut a = HashMap::new();
454 /// assert_eq!(a.len(), 0);
455 /// a.insert(1, "a");
456 /// assert_eq!(a.len(), 1);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn len(&self) -> usize {
463 /// Returns `true` if the map contains no elements.
468 /// use std::collections::HashMap;
470 /// let mut a = HashMap::new();
471 /// assert!(a.is_empty());
472 /// a.insert(1, "a");
473 /// assert!(!a.is_empty());
476 #[stable(feature = "rust1", since = "1.0.0")]
477 pub fn is_empty(&self) -> bool {
481 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
482 /// allocated memory for reuse.
487 /// use std::collections::HashMap;
489 /// let mut a = HashMap::new();
490 /// a.insert(1, "a");
491 /// a.insert(2, "b");
493 /// for (k, v) in a.drain().take(1) {
494 /// assert!(k == 1 || k == 2);
495 /// assert!(v == "a" || v == "b");
498 /// assert!(a.is_empty());
501 #[stable(feature = "drain", since = "1.6.0")]
502 pub fn drain(&mut self) -> Drain<'_, K, V> {
503 Drain { base: self.base.drain() }
506 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
512 /// use std::collections::HashMap;
514 /// let mut a = HashMap::new();
515 /// a.insert(1, "a");
517 /// assert!(a.is_empty());
519 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn clear(&mut self) {
525 /// Returns a reference to the map's [`BuildHasher`].
527 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
532 /// use std::collections::HashMap;
533 /// use std::collections::hash_map::RandomState;
535 /// let hasher = RandomState::new();
536 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
537 /// let hasher: &RandomState = map.hasher();
540 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
541 pub fn hasher(&self) -> &S {
546 impl<K, V, S> HashMap<K, V, S>
551 /// Reserves capacity for at least `additional` more elements to be inserted
552 /// in the `HashMap`. The collection may reserve more space to avoid
553 /// frequent reallocations.
557 /// Panics if the new allocation size overflows [`usize`].
559 /// [`usize`]: ../../std/primitive.usize.html
564 /// use std::collections::HashMap;
565 /// let mut map: HashMap<&str, i32> = HashMap::new();
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn reserve(&mut self, additional: usize) {
571 self.base.reserve(additional)
574 /// Tries to reserve capacity for at least `additional` more elements to be inserted
575 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
576 /// frequent reallocations.
580 /// If the capacity overflows, or the allocator reports a failure, then an error
586 /// #![feature(try_reserve)]
587 /// use std::collections::HashMap;
588 /// let mut map: HashMap<&str, isize> = HashMap::new();
589 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
592 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
593 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
594 self.base.try_reserve(additional).map_err(map_collection_alloc_err)
597 /// Shrinks the capacity of the map as much as possible. It will drop
598 /// down as much as possible while maintaining the internal rules
599 /// and possibly leaving some space in accordance with the resize policy.
604 /// use std::collections::HashMap;
606 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
607 /// map.insert(1, 2);
608 /// map.insert(3, 4);
609 /// assert!(map.capacity() >= 100);
610 /// map.shrink_to_fit();
611 /// assert!(map.capacity() >= 2);
614 #[stable(feature = "rust1", since = "1.0.0")]
615 pub fn shrink_to_fit(&mut self) {
616 self.base.shrink_to_fit();
619 /// Shrinks the capacity of the map with a lower limit. It will drop
620 /// down no lower than the supplied limit while maintaining the internal rules
621 /// and possibly leaving some space in accordance with the resize policy.
623 /// Panics if the current capacity is smaller than the supplied
624 /// minimum capacity.
629 /// #![feature(shrink_to)]
630 /// use std::collections::HashMap;
632 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
633 /// map.insert(1, 2);
634 /// map.insert(3, 4);
635 /// assert!(map.capacity() >= 100);
636 /// map.shrink_to(10);
637 /// assert!(map.capacity() >= 10);
638 /// map.shrink_to(0);
639 /// assert!(map.capacity() >= 2);
642 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
643 pub fn shrink_to(&mut self, min_capacity: usize) {
644 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
645 self.base.shrink_to(min_capacity);
648 /// Gets the given key's corresponding entry in the map for in-place manipulation.
653 /// use std::collections::HashMap;
655 /// let mut letters = HashMap::new();
657 /// for ch in "a short treatise on fungi".chars() {
658 /// let counter = letters.entry(ch).or_insert(0);
662 /// assert_eq!(letters[&'s'], 2);
663 /// assert_eq!(letters[&'t'], 3);
664 /// assert_eq!(letters[&'u'], 1);
665 /// assert_eq!(letters.get(&'y'), None);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
670 map_entry(self.base.rustc_entry(key))
673 /// Returns a reference to the value corresponding to the key.
675 /// The key may be any borrowed form of the map's key type, but
676 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
679 /// [`Eq`]: ../../std/cmp/trait.Eq.html
680 /// [`Hash`]: ../../std/hash/trait.Hash.html
685 /// use std::collections::HashMap;
687 /// let mut map = HashMap::new();
688 /// map.insert(1, "a");
689 /// assert_eq!(map.get(&1), Some(&"a"));
690 /// assert_eq!(map.get(&2), None);
692 #[stable(feature = "rust1", since = "1.0.0")]
694 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
702 /// Returns the key-value pair corresponding to the supplied key.
704 /// The supplied key may be any borrowed form of the map's key type, but
705 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
708 /// [`Eq`]: ../../std/cmp/trait.Eq.html
709 /// [`Hash`]: ../../std/hash/trait.Hash.html
714 /// use std::collections::HashMap;
716 /// let mut map = HashMap::new();
717 /// map.insert(1, "a");
718 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
719 /// assert_eq!(map.get_key_value(&2), None);
721 #[stable(feature = "map_get_key_value", since = "1.40.0")]
723 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
728 self.base.get_key_value(k)
731 /// Returns `true` if the map contains a value for the specified key.
733 /// The key may be any borrowed form of the map's key type, but
734 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
737 /// [`Eq`]: ../../std/cmp/trait.Eq.html
738 /// [`Hash`]: ../../std/hash/trait.Hash.html
743 /// use std::collections::HashMap;
745 /// let mut map = HashMap::new();
746 /// map.insert(1, "a");
747 /// assert_eq!(map.contains_key(&1), true);
748 /// assert_eq!(map.contains_key(&2), false);
750 #[stable(feature = "rust1", since = "1.0.0")]
752 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
757 self.base.contains_key(k)
760 /// Returns a mutable reference to the value corresponding to the key.
762 /// The key may be any borrowed form of the map's key type, but
763 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
766 /// [`Eq`]: ../../std/cmp/trait.Eq.html
767 /// [`Hash`]: ../../std/hash/trait.Hash.html
772 /// use std::collections::HashMap;
774 /// let mut map = HashMap::new();
775 /// map.insert(1, "a");
776 /// if let Some(x) = map.get_mut(&1) {
779 /// assert_eq!(map[&1], "b");
781 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
791 /// Inserts a key-value pair into the map.
793 /// If the map did not have this key present, [`None`] is returned.
795 /// If the map did have this key present, the value is updated, and the old
796 /// value is returned. The key is not updated, though; this matters for
797 /// types that can be `==` without being identical. See the [module-level
798 /// documentation] for more.
800 /// [`None`]: ../../std/option/enum.Option.html#variant.None
801 /// [module-level documentation]: index.html#insert-and-complex-keys
806 /// use std::collections::HashMap;
808 /// let mut map = HashMap::new();
809 /// assert_eq!(map.insert(37, "a"), None);
810 /// assert_eq!(map.is_empty(), false);
812 /// map.insert(37, "b");
813 /// assert_eq!(map.insert(37, "c"), Some("b"));
814 /// assert_eq!(map[&37], "c");
816 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
819 self.base.insert(k, v)
822 /// Removes a key from the map, returning the value at the key if the key
823 /// was previously in the map.
825 /// The key may be any borrowed form of the map's key type, but
826 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
829 /// [`Eq`]: ../../std/cmp/trait.Eq.html
830 /// [`Hash`]: ../../std/hash/trait.Hash.html
835 /// use std::collections::HashMap;
837 /// let mut map = HashMap::new();
838 /// map.insert(1, "a");
839 /// assert_eq!(map.remove(&1), Some("a"));
840 /// assert_eq!(map.remove(&1), None);
842 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
852 /// Removes a key from the map, returning the stored key and value if the
853 /// key was previously in the map.
855 /// The key may be any borrowed form of the map's key type, but
856 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
859 /// [`Eq`]: ../../std/cmp/trait.Eq.html
860 /// [`Hash`]: ../../std/hash/trait.Hash.html
865 /// use std::collections::HashMap;
868 /// let mut map = HashMap::new();
869 /// map.insert(1, "a");
870 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
871 /// assert_eq!(map.remove(&1), None);
874 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
876 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
881 self.base.remove_entry(k)
884 /// Retains only the elements specified by the predicate.
886 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
891 /// use std::collections::HashMap;
893 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
894 /// map.retain(|&k, _| k % 2 == 0);
895 /// assert_eq!(map.len(), 4);
897 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
899 pub fn retain<F>(&mut self, f: F)
901 F: FnMut(&K, &mut V) -> bool,
907 impl<K, V, S> HashMap<K, V, S>
911 /// Creates a raw entry builder for the HashMap.
913 /// Raw entries provide the lowest level of control for searching and
914 /// manipulating a map. They must be manually initialized with a hash and
915 /// then manually searched. After this, insertions into a vacant entry
916 /// still require an owned key to be provided.
918 /// Raw entries are useful for such exotic situations as:
920 /// * Hash memoization
921 /// * Deferring the creation of an owned key until it is known to be required
922 /// * Using a search key that doesn't work with the Borrow trait
923 /// * Using custom comparison logic without newtype wrappers
925 /// Because raw entries provide much more low-level control, it's much easier
926 /// to put the HashMap into an inconsistent state which, while memory-safe,
927 /// will cause the map to produce seemingly random results. Higher-level and
928 /// more foolproof APIs like `entry` should be preferred when possible.
930 /// In particular, the hash used to initialized the raw entry must still be
931 /// consistent with the hash of the key that is ultimately stored in the entry.
932 /// This is because implementations of HashMap may need to recompute hashes
933 /// when resizing, at which point only the keys are available.
935 /// Raw entries give mutable access to the keys. This must not be used
936 /// to modify how the key would compare or hash, as the map will not re-evaluate
937 /// where the key should go, meaning the keys may become "lost" if their
938 /// location does not reflect their state. For instance, if you change a key
939 /// so that the map now contains keys which compare equal, search may start
940 /// acting erratically, with two keys randomly masking each other. Implementations
941 /// are free to assume this doesn't happen (within the limits of memory-safety).
943 #[unstable(feature = "hash_raw_entry", issue = "56167")]
944 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
945 RawEntryBuilderMut { map: self }
948 /// Creates a raw immutable entry builder for the HashMap.
950 /// Raw entries provide the lowest level of control for searching and
951 /// manipulating a map. They must be manually initialized with a hash and
952 /// then manually searched.
954 /// This is useful for
955 /// * Hash memoization
956 /// * Using a search key that doesn't work with the Borrow trait
957 /// * Using custom comparison logic without newtype wrappers
959 /// Unless you are in such a situation, higher-level and more foolproof APIs like
960 /// `get` should be preferred.
962 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
964 #[unstable(feature = "hash_raw_entry", issue = "56167")]
965 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
966 RawEntryBuilder { map: self }
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<K, V, S> PartialEq for HashMap<K, V, S>
977 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
978 if self.len() != other.len() {
982 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<K, V, S> Eq for HashMap<K, V, S>
995 #[stable(feature = "rust1", since = "1.0.0")]
996 impl<K, V, S> Debug for HashMap<K, V, S>
1001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002 f.debug_map().entries(self.iter()).finish()
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<K, V, S> Default for HashMap<K, V, S>
1011 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1013 fn default() -> HashMap<K, V, S> {
1014 HashMap::with_hasher(Default::default())
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1021 K: Eq + Hash + Borrow<Q>,
1027 /// Returns a reference to the value corresponding to the supplied key.
1031 /// Panics if the key is not present in the `HashMap`.
1033 fn index(&self, key: &Q) -> &V {
1034 self.get(key).expect("no entry found for key")
1038 /// An iterator over the entries of a `HashMap`.
1040 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1041 /// documentation for more.
1043 /// [`iter`]: struct.HashMap.html#method.iter
1044 /// [`HashMap`]: struct.HashMap.html
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 pub struct Iter<'a, K: 'a, V: 'a> {
1047 base: base::Iter<'a, K, V>,
1050 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<K, V> Clone for Iter<'_, K, V> {
1054 fn clone(&self) -> Self {
1055 Iter { base: self.base.clone() }
1059 #[stable(feature = "std_debug", since = "1.16.0")]
1060 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1061 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1062 f.debug_list().entries(self.clone()).finish()
1066 /// A mutable iterator over the entries of a `HashMap`.
1068 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1069 /// documentation for more.
1071 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1072 /// [`HashMap`]: struct.HashMap.html
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 pub struct IterMut<'a, K: 'a, V: 'a> {
1075 base: base::IterMut<'a, K, V>,
1078 impl<'a, K, V> IterMut<'a, K, V> {
1079 /// Returns a iterator of references over the remaining items.
1081 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1082 Iter { base: self.base.rustc_iter() }
1086 /// An owning iterator over the entries of a `HashMap`.
1088 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1089 /// (provided by the `IntoIterator` trait). See its documentation for more.
1091 /// [`into_iter`]: struct.HashMap.html#method.into_iter
1092 /// [`HashMap`]: struct.HashMap.html
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub struct IntoIter<K, V> {
1095 base: base::IntoIter<K, V>,
1098 impl<K, V> IntoIter<K, V> {
1099 /// Returns a iterator of references over the remaining items.
1101 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1102 Iter { base: self.base.rustc_iter() }
1106 /// An iterator over the keys of a `HashMap`.
1108 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1109 /// documentation for more.
1111 /// [`keys`]: struct.HashMap.html#method.keys
1112 /// [`HashMap`]: struct.HashMap.html
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub struct Keys<'a, K: 'a, V: 'a> {
1115 inner: Iter<'a, K, V>,
1118 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl<K, V> Clone for Keys<'_, K, V> {
1122 fn clone(&self) -> Self {
1123 Keys { inner: self.inner.clone() }
1127 #[stable(feature = "std_debug", since = "1.16.0")]
1128 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1130 f.debug_list().entries(self.clone()).finish()
1134 /// An iterator over the values of a `HashMap`.
1136 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1137 /// documentation for more.
1139 /// [`values`]: struct.HashMap.html#method.values
1140 /// [`HashMap`]: struct.HashMap.html
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub struct Values<'a, K: 'a, V: 'a> {
1143 inner: Iter<'a, K, V>,
1146 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<K, V> Clone for Values<'_, K, V> {
1150 fn clone(&self) -> Self {
1151 Values { inner: self.inner.clone() }
1155 #[stable(feature = "std_debug", since = "1.16.0")]
1156 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158 f.debug_list().entries(self.clone()).finish()
1162 /// A draining iterator over the entries of a `HashMap`.
1164 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1165 /// documentation for more.
1167 /// [`drain`]: struct.HashMap.html#method.drain
1168 /// [`HashMap`]: struct.HashMap.html
1169 #[stable(feature = "drain", since = "1.6.0")]
1170 pub struct Drain<'a, K: 'a, V: 'a> {
1171 base: base::Drain<'a, K, V>,
1174 impl<'a, K, V> Drain<'a, K, V> {
1175 /// Returns a iterator of references over the remaining items.
1177 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1178 Iter { base: self.base.rustc_iter() }
1182 /// A mutable iterator over the values of a `HashMap`.
1184 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1185 /// documentation for more.
1187 /// [`values_mut`]: struct.HashMap.html#method.values_mut
1188 /// [`HashMap`]: struct.HashMap.html
1189 #[stable(feature = "map_values_mut", since = "1.10.0")]
1190 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1191 inner: IterMut<'a, K, V>,
1194 /// A builder for computing where in a HashMap a key-value pair would be stored.
1196 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1198 /// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1200 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1201 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1202 map: &'a mut HashMap<K, V, S>,
1205 /// A view into a single entry in a map, which may either be vacant or occupied.
1207 /// This is a lower-level version of [`Entry`].
1209 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1210 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1212 /// [`HashMap`]: struct.HashMap.html
1213 /// [`Entry`]: enum.Entry.html
1214 /// [`raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1215 /// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html
1216 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1217 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1218 /// An occupied entry.
1219 Occupied(RawOccupiedEntryMut<'a, K, V>),
1221 Vacant(RawVacantEntryMut<'a, K, V, S>),
1224 /// A view into an occupied entry in a `HashMap`.
1225 /// It is part of the [`RawEntryMut`] enum.
1227 /// [`RawEntryMut`]: enum.RawEntryMut.html
1228 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1229 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1230 base: base::RawOccupiedEntryMut<'a, K, V>,
1233 /// A view into a vacant entry in a `HashMap`.
1234 /// It is part of the [`RawEntryMut`] enum.
1236 /// [`RawEntryMut`]: enum.RawEntryMut.html
1237 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1238 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1239 base: base::RawVacantEntryMut<'a, K, V, S>,
1242 /// A builder for computing where in a HashMap a key-value pair would be stored.
1244 /// See the [`HashMap::raw_entry`] docs for usage examples.
1246 /// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1247 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1248 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1249 map: &'a HashMap<K, V, S>,
1252 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1256 /// Creates a `RawEntryMut` from the given key.
1258 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1259 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1264 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1267 /// Creates a `RawEntryMut` from the given key and its hash.
1269 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1270 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1275 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1278 /// Creates a `RawEntryMut` from the given hash.
1280 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1281 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1283 for<'b> F: FnMut(&'b K) -> bool,
1285 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1289 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1293 /// Access an entry by key.
1295 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1296 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1301 self.map.base.raw_entry().from_key(k)
1304 /// Access an entry by a key and its hash.
1306 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1307 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1312 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1315 /// Access an entry by hash.
1317 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1318 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1320 F: FnMut(&K) -> bool,
1322 self.map.base.raw_entry().from_hash(hash, is_match)
1326 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1327 /// Ensures a value is in the entry by inserting the default if empty, and returns
1328 /// mutable references to the key and value in the entry.
1333 /// #![feature(hash_raw_entry)]
1334 /// use std::collections::HashMap;
1336 /// let mut map: HashMap<&str, u32> = HashMap::new();
1338 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1339 /// assert_eq!(map["poneyland"], 3);
1341 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1342 /// assert_eq!(map["poneyland"], 6);
1345 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1346 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1352 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1353 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1357 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1358 /// and returns mutable references to the key and value in the entry.
1363 /// #![feature(hash_raw_entry)]
1364 /// use std::collections::HashMap;
1366 /// let mut map: HashMap<&str, String> = HashMap::new();
1368 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1369 /// ("poneyland", "hoho".to_string())
1372 /// assert_eq!(map["poneyland"], "hoho".to_string());
1375 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1376 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1378 F: FnOnce() -> (K, V),
1383 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1384 RawEntryMut::Vacant(entry) => {
1385 let (k, v) = default();
1391 /// Provides in-place mutable access to an occupied entry before any
1392 /// potential inserts into the map.
1397 /// #![feature(hash_raw_entry)]
1398 /// use std::collections::HashMap;
1400 /// let mut map: HashMap<&str, u32> = HashMap::new();
1402 /// map.raw_entry_mut()
1403 /// .from_key("poneyland")
1404 /// .and_modify(|_k, v| { *v += 1 })
1405 /// .or_insert("poneyland", 42);
1406 /// assert_eq!(map["poneyland"], 42);
1408 /// map.raw_entry_mut()
1409 /// .from_key("poneyland")
1410 /// .and_modify(|_k, v| { *v += 1 })
1411 /// .or_insert("poneyland", 0);
1412 /// assert_eq!(map["poneyland"], 43);
1415 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1416 pub fn and_modify<F>(self, f: F) -> Self
1418 F: FnOnce(&mut K, &mut V),
1421 RawEntryMut::Occupied(mut entry) => {
1423 let (k, v) = entry.get_key_value_mut();
1426 RawEntryMut::Occupied(entry)
1428 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1433 impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
1434 /// Gets a reference to the key in the entry.
1436 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1437 pub fn key(&self) -> &K {
1441 /// Gets a mutable reference to the key in the entry.
1443 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1444 pub fn key_mut(&mut self) -> &mut K {
1448 /// Converts the entry into a mutable reference to the key in the entry
1449 /// with a lifetime bound to the map itself.
1451 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1452 pub fn into_key(self) -> &'a mut K {
1453 self.base.into_key()
1456 /// Gets a reference to the value in the entry.
1458 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1459 pub fn get(&self) -> &V {
1463 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1464 /// with a lifetime bound to the map itself.
1466 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1467 pub fn into_mut(self) -> &'a mut V {
1468 self.base.into_mut()
1471 /// Gets a mutable reference to the value in the entry.
1473 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1474 pub fn get_mut(&mut self) -> &mut V {
1478 /// Gets a reference to the key and value in the entry.
1480 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1481 pub fn get_key_value(&mut self) -> (&K, &V) {
1482 self.base.get_key_value()
1485 /// Gets a mutable reference to the key and value in the entry.
1487 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1488 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1489 self.base.get_key_value_mut()
1492 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
1493 /// with a lifetime bound to the map itself.
1495 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1496 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1497 self.base.into_key_value()
1500 /// Sets the value of the entry, and returns the entry's old value.
1502 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1503 pub fn insert(&mut self, value: V) -> V {
1504 self.base.insert(value)
1507 /// Sets the value of the entry, and returns the entry's old value.
1509 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1510 pub fn insert_key(&mut self, key: K) -> K {
1511 self.base.insert_key(key)
1514 /// Takes the value out of the entry, and returns it.
1516 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1517 pub fn remove(self) -> V {
1521 /// Take the ownership of the key and value from the map.
1523 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1524 pub fn remove_entry(self) -> (K, V) {
1525 self.base.remove_entry()
1529 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1530 /// Sets the value of the entry with the VacantEntry's key,
1531 /// and returns a mutable reference to it.
1533 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1534 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1539 self.base.insert(key, value)
1542 /// Sets the value of the entry with the VacantEntry's key,
1543 /// and returns a mutable reference to it.
1545 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1546 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1551 self.base.insert_hashed_nocheck(hash, key, value)
1555 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1556 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1558 f.debug_struct("RawEntryBuilder").finish()
1562 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1563 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1564 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1566 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1567 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1572 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1573 impl<K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'_, K, V> {
1574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1575 f.debug_struct("RawOccupiedEntryMut")
1576 .field("key", self.key())
1577 .field("value", self.get())
1582 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1583 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1584 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1585 f.debug_struct("RawVacantEntryMut").finish()
1589 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1590 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592 f.debug_struct("RawEntryBuilder").finish()
1596 /// A view into a single entry in a map, which may either be vacant or occupied.
1598 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1600 /// [`HashMap`]: struct.HashMap.html
1601 /// [`entry`]: struct.HashMap.html#method.entry
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 pub enum Entry<'a, K: 'a, V: 'a> {
1604 /// An occupied entry.
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1613 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1614 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1617 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1618 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1623 /// A view into an occupied entry in a `HashMap`.
1624 /// It is part of the [`Entry`] enum.
1626 /// [`Entry`]: enum.Entry.html
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1629 base: base::RustcOccupiedEntry<'a, K, V>,
1632 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1633 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1635 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
1639 /// A view into a vacant entry in a `HashMap`.
1640 /// It is part of the [`Entry`] enum.
1642 /// [`Entry`]: enum.Entry.html
1643 #[stable(feature = "rust1", since = "1.0.0")]
1644 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1645 base: base::RustcVacantEntry<'a, K, V>,
1648 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1649 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1650 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1651 f.debug_tuple("VacantEntry").field(self.key()).finish()
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1657 type Item = (&'a K, &'a V);
1658 type IntoIter = Iter<'a, K, V>;
1661 fn into_iter(self) -> Iter<'a, K, V> {
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1668 type Item = (&'a K, &'a mut V);
1669 type IntoIter = IterMut<'a, K, V>;
1672 fn into_iter(self) -> IterMut<'a, K, V> {
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1680 type IntoIter = IntoIter<K, V>;
1682 /// Creates a consuming iterator, that is, one that moves each key-value
1683 /// pair out of the map in arbitrary order. The map cannot be used after
1689 /// use std::collections::HashMap;
1691 /// let mut map = HashMap::new();
1692 /// map.insert("a", 1);
1693 /// map.insert("b", 2);
1694 /// map.insert("c", 3);
1696 /// // Not possible with .iter()
1697 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1700 fn into_iter(self) -> IntoIter<K, V> {
1701 IntoIter { base: self.base.into_iter() }
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1707 type Item = (&'a K, &'a V);
1710 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1714 fn size_hint(&self) -> (usize, Option<usize>) {
1715 self.base.size_hint()
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1721 fn len(&self) -> usize {
1726 #[stable(feature = "fused", since = "1.26.0")]
1727 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1731 type Item = (&'a K, &'a mut V);
1734 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1738 fn size_hint(&self) -> (usize, Option<usize>) {
1739 self.base.size_hint()
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1745 fn len(&self) -> usize {
1749 #[stable(feature = "fused", since = "1.26.0")]
1750 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1752 #[stable(feature = "std_debug", since = "1.16.0")]
1753 impl<K, V> fmt::Debug for IterMut<'_, K, V>
1758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1759 f.debug_list().entries(self.iter()).finish()
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl<K, V> Iterator for IntoIter<K, V> {
1768 fn next(&mut self) -> Option<(K, V)> {
1772 fn size_hint(&self) -> (usize, Option<usize>) {
1773 self.base.size_hint()
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1779 fn len(&self) -> usize {
1783 #[stable(feature = "fused", since = "1.26.0")]
1784 impl<K, V> FusedIterator for IntoIter<K, V> {}
1786 #[stable(feature = "std_debug", since = "1.16.0")]
1787 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1788 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1789 f.debug_list().entries(self.iter()).finish()
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1798 fn next(&mut self) -> Option<&'a K> {
1799 self.inner.next().map(|(k, _)| k)
1802 fn size_hint(&self) -> (usize, Option<usize>) {
1803 self.inner.size_hint()
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1809 fn len(&self) -> usize {
1813 #[stable(feature = "fused", since = "1.26.0")]
1814 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 impl<'a, K, V> Iterator for Values<'a, K, V> {
1821 fn next(&mut self) -> Option<&'a V> {
1822 self.inner.next().map(|(_, v)| v)
1825 fn size_hint(&self) -> (usize, Option<usize>) {
1826 self.inner.size_hint()
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1832 fn len(&self) -> usize {
1836 #[stable(feature = "fused", since = "1.26.0")]
1837 impl<K, V> FusedIterator for Values<'_, K, V> {}
1839 #[stable(feature = "map_values_mut", since = "1.10.0")]
1840 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1841 type Item = &'a mut V;
1844 fn next(&mut self) -> Option<&'a mut V> {
1845 self.inner.next().map(|(_, v)| v)
1848 fn size_hint(&self) -> (usize, Option<usize>) {
1849 self.inner.size_hint()
1852 #[stable(feature = "map_values_mut", since = "1.10.0")]
1853 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1855 fn len(&self) -> usize {
1859 #[stable(feature = "fused", since = "1.26.0")]
1860 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1862 #[stable(feature = "std_debug", since = "1.16.0")]
1863 impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1869 f.debug_list().entries(self.inner.iter()).finish()
1873 #[stable(feature = "drain", since = "1.6.0")]
1874 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1878 fn next(&mut self) -> Option<(K, V)> {
1882 fn size_hint(&self) -> (usize, Option<usize>) {
1883 self.base.size_hint()
1886 #[stable(feature = "drain", since = "1.6.0")]
1887 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
1889 fn len(&self) -> usize {
1893 #[stable(feature = "fused", since = "1.26.0")]
1894 impl<K, V> FusedIterator for Drain<'_, K, V> {}
1896 #[stable(feature = "std_debug", since = "1.16.0")]
1897 impl<K, V> fmt::Debug for Drain<'_, K, V>
1902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1903 f.debug_list().entries(self.iter()).finish()
1907 impl<'a, K, V> Entry<'a, K, V> {
1908 #[stable(feature = "rust1", since = "1.0.0")]
1909 /// Ensures a value is in the entry by inserting the default if empty, and returns
1910 /// a mutable reference to the value in the entry.
1915 /// use std::collections::HashMap;
1917 /// let mut map: HashMap<&str, u32> = HashMap::new();
1919 /// map.entry("poneyland").or_insert(3);
1920 /// assert_eq!(map["poneyland"], 3);
1922 /// *map.entry("poneyland").or_insert(10) *= 2;
1923 /// assert_eq!(map["poneyland"], 6);
1926 pub fn or_insert(self, default: V) -> &'a mut V {
1928 Occupied(entry) => entry.into_mut(),
1929 Vacant(entry) => entry.insert(default),
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1935 /// and returns a mutable reference to the value in the entry.
1940 /// use std::collections::HashMap;
1942 /// let mut map: HashMap<&str, String> = HashMap::new();
1943 /// let s = "hoho".to_string();
1945 /// map.entry("poneyland").or_insert_with(|| s);
1947 /// assert_eq!(map["poneyland"], "hoho".to_string());
1950 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1952 Occupied(entry) => entry.into_mut(),
1953 Vacant(entry) => entry.insert(default()),
1957 #[unstable(feature = "or_insert_with_key", issue = "71024")]
1958 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
1959 /// which takes the key as its argument, and returns a mutable reference to the value in the
1965 /// #![feature(or_insert_with_key)]
1966 /// use std::collections::HashMap;
1968 /// let mut map: HashMap<&str, usize> = HashMap::new();
1970 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
1972 /// assert_eq!(map["poneyland"], 9);
1975 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
1977 Occupied(entry) => entry.into_mut(),
1979 let value = default(entry.key());
1985 /// Returns a reference to this entry's key.
1990 /// use std::collections::HashMap;
1992 /// let mut map: HashMap<&str, u32> = HashMap::new();
1993 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1996 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1997 pub fn key(&self) -> &K {
1999 Occupied(ref entry) => entry.key(),
2000 Vacant(ref entry) => entry.key(),
2004 /// Provides in-place mutable access to an occupied entry before any
2005 /// potential inserts into the map.
2010 /// use std::collections::HashMap;
2012 /// let mut map: HashMap<&str, u32> = HashMap::new();
2014 /// map.entry("poneyland")
2015 /// .and_modify(|e| { *e += 1 })
2017 /// assert_eq!(map["poneyland"], 42);
2019 /// map.entry("poneyland")
2020 /// .and_modify(|e| { *e += 1 })
2022 /// assert_eq!(map["poneyland"], 43);
2025 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2026 pub fn and_modify<F>(self, f: F) -> Self
2031 Occupied(mut entry) => {
2035 Vacant(entry) => Vacant(entry),
2039 /// Sets the value of the entry, and returns an OccupiedEntry.
2044 /// #![feature(entry_insert)]
2045 /// use std::collections::HashMap;
2047 /// let mut map: HashMap<&str, String> = HashMap::new();
2048 /// let entry = map.entry("poneyland").insert("hoho".to_string());
2050 /// assert_eq!(entry.key(), &"poneyland");
2053 #[unstable(feature = "entry_insert", issue = "65225")]
2054 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
2056 Occupied(mut entry) => {
2057 entry.insert(value);
2060 Vacant(entry) => entry.insert_entry(value),
2065 impl<'a, K, V: Default> Entry<'a, K, V> {
2066 #[stable(feature = "entry_or_default", since = "1.28.0")]
2067 /// Ensures a value is in the entry by inserting the default value if empty,
2068 /// and returns a mutable reference to the value in the entry.
2074 /// use std::collections::HashMap;
2076 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2077 /// map.entry("poneyland").or_default();
2079 /// assert_eq!(map["poneyland"], None);
2083 pub fn or_default(self) -> &'a mut V {
2085 Occupied(entry) => entry.into_mut(),
2086 Vacant(entry) => entry.insert(Default::default()),
2091 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2092 /// Gets a reference to the key in the entry.
2097 /// use std::collections::HashMap;
2099 /// let mut map: HashMap<&str, u32> = HashMap::new();
2100 /// map.entry("poneyland").or_insert(12);
2101 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2104 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2105 pub fn key(&self) -> &K {
2109 /// Take the ownership of the key and value from the map.
2114 /// use std::collections::HashMap;
2115 /// use std::collections::hash_map::Entry;
2117 /// let mut map: HashMap<&str, u32> = HashMap::new();
2118 /// map.entry("poneyland").or_insert(12);
2120 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2121 /// // We delete the entry from the map.
2122 /// o.remove_entry();
2125 /// assert_eq!(map.contains_key("poneyland"), false);
2128 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2129 pub fn remove_entry(self) -> (K, V) {
2130 self.base.remove_entry()
2133 /// Gets a reference to the value in the entry.
2138 /// use std::collections::HashMap;
2139 /// use std::collections::hash_map::Entry;
2141 /// let mut map: HashMap<&str, u32> = HashMap::new();
2142 /// map.entry("poneyland").or_insert(12);
2144 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2145 /// assert_eq!(o.get(), &12);
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 pub fn get(&self) -> &V {
2154 /// Gets a mutable reference to the value in the entry.
2156 /// If you need a reference to the `OccupiedEntry` which may outlive the
2157 /// destruction of the `Entry` value, see [`into_mut`].
2159 /// [`into_mut`]: #method.into_mut
2164 /// use std::collections::HashMap;
2165 /// use std::collections::hash_map::Entry;
2167 /// let mut map: HashMap<&str, u32> = HashMap::new();
2168 /// map.entry("poneyland").or_insert(12);
2170 /// assert_eq!(map["poneyland"], 12);
2171 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2172 /// *o.get_mut() += 10;
2173 /// assert_eq!(*o.get(), 22);
2175 /// // We can use the same Entry multiple times.
2176 /// *o.get_mut() += 2;
2179 /// assert_eq!(map["poneyland"], 24);
2182 #[stable(feature = "rust1", since = "1.0.0")]
2183 pub fn get_mut(&mut self) -> &mut V {
2187 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2188 /// with a lifetime bound to the map itself.
2190 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2192 /// [`get_mut`]: #method.get_mut
2197 /// use std::collections::HashMap;
2198 /// use std::collections::hash_map::Entry;
2200 /// let mut map: HashMap<&str, u32> = HashMap::new();
2201 /// map.entry("poneyland").or_insert(12);
2203 /// assert_eq!(map["poneyland"], 12);
2204 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2205 /// *o.into_mut() += 10;
2208 /// assert_eq!(map["poneyland"], 22);
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 pub fn into_mut(self) -> &'a mut V {
2213 self.base.into_mut()
2216 /// Sets the value of the entry, and returns the entry's old value.
2221 /// use std::collections::HashMap;
2222 /// use std::collections::hash_map::Entry;
2224 /// let mut map: HashMap<&str, u32> = HashMap::new();
2225 /// map.entry("poneyland").or_insert(12);
2227 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2228 /// assert_eq!(o.insert(15), 12);
2231 /// assert_eq!(map["poneyland"], 15);
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 pub fn insert(&mut self, value: V) -> V {
2236 self.base.insert(value)
2239 /// Takes the value out of the entry, and returns it.
2244 /// use std::collections::HashMap;
2245 /// use std::collections::hash_map::Entry;
2247 /// let mut map: HashMap<&str, u32> = HashMap::new();
2248 /// map.entry("poneyland").or_insert(12);
2250 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2251 /// assert_eq!(o.remove(), 12);
2254 /// assert_eq!(map.contains_key("poneyland"), false);
2257 #[stable(feature = "rust1", since = "1.0.0")]
2258 pub fn remove(self) -> V {
2262 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2263 /// the key used to create this entry.
2268 /// #![feature(map_entry_replace)]
2269 /// use std::collections::hash_map::{Entry, HashMap};
2270 /// use std::rc::Rc;
2272 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2273 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2275 /// let my_key = Rc::new("Stringthing".to_string());
2277 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2278 /// // Also replace the key with a handle to our other key.
2279 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2284 #[unstable(feature = "map_entry_replace", issue = "44286")]
2285 pub fn replace_entry(self, value: V) -> (K, V) {
2286 self.base.replace_entry(value)
2289 /// Replaces the key in the hash map with the key used to create this entry.
2294 /// #![feature(map_entry_replace)]
2295 /// use std::collections::hash_map::{Entry, HashMap};
2296 /// use std::rc::Rc;
2298 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2299 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2301 /// // Initialise known strings, run program, etc.
2303 /// reclaim_memory(&mut map, &known_strings);
2305 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2306 /// for s in known_strings {
2307 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2308 /// // Replaces the entry's key with our version of it in `known_strings`.
2309 /// entry.replace_key();
2315 #[unstable(feature = "map_entry_replace", issue = "44286")]
2316 pub fn replace_key(self) -> K {
2317 self.base.replace_key()
2321 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2322 /// Gets a reference to the key that would be used when inserting a value
2323 /// through the `VacantEntry`.
2328 /// use std::collections::HashMap;
2330 /// let mut map: HashMap<&str, u32> = HashMap::new();
2331 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2334 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2335 pub fn key(&self) -> &K {
2339 /// Take ownership of the key.
2344 /// use std::collections::HashMap;
2345 /// use std::collections::hash_map::Entry;
2347 /// let mut map: HashMap<&str, u32> = HashMap::new();
2349 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2354 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2355 pub fn into_key(self) -> K {
2356 self.base.into_key()
2359 /// Sets the value of the entry with the VacantEntry's key,
2360 /// and returns a mutable reference to it.
2365 /// use std::collections::HashMap;
2366 /// use std::collections::hash_map::Entry;
2368 /// let mut map: HashMap<&str, u32> = HashMap::new();
2370 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2373 /// assert_eq!(map["poneyland"], 37);
2376 #[stable(feature = "rust1", since = "1.0.0")]
2377 pub fn insert(self, value: V) -> &'a mut V {
2378 self.base.insert(value)
2381 /// Sets the value of the entry with the VacantEntry's key,
2382 /// and returns an OccupiedEntry.
2387 /// use std::collections::HashMap;
2388 /// use std::collections::hash_map::Entry;
2390 /// let mut map: HashMap<&str, u32> = HashMap::new();
2392 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2395 /// assert_eq!(map["poneyland"], 37);
2398 fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2399 let base = self.base.insert_entry(value);
2400 OccupiedEntry { base }
2404 #[stable(feature = "rust1", since = "1.0.0")]
2405 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2408 S: BuildHasher + Default,
2410 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2411 let mut map = HashMap::with_hasher(Default::default());
2417 /// Inserts all new key-values from the iterator and replaces values with existing
2418 /// keys with new values returned from the iterator.
2419 #[stable(feature = "rust1", since = "1.0.0")]
2420 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2426 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2427 self.base.extend(iter)
2431 fn extend_one(&mut self, (k, v): (K, V)) {
2432 self.base.insert(k, v);
2436 fn extend_reserve(&mut self, additional: usize) {
2437 // self.base.extend_reserve(additional);
2438 // FIXME: hashbrown should implement this method.
2439 // But until then, use the same reservation logic:
2441 // Reserve the entire hint lower bound if the map is empty.
2442 // Otherwise reserve half the hint (rounded up), so the map
2443 // will only resize twice in the worst case.
2444 let reserve = if self.is_empty() { additional } else { (additional + 1) / 2 };
2445 self.base.reserve(reserve);
2449 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2450 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2452 K: Eq + Hash + Copy,
2457 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2458 self.base.extend(iter)
2462 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2463 self.base.insert(k, v);
2467 fn extend_reserve(&mut self, additional: usize) {
2468 Extend::<(K, V)>::extend_reserve(self, additional)
2472 /// `RandomState` is the default state for [`HashMap`] types.
2474 /// A particular instance `RandomState` will create the same instances of
2475 /// [`Hasher`], but the hashers created by two different `RandomState`
2476 /// instances are unlikely to produce the same result for the same values.
2478 /// [`HashMap`]: struct.HashMap.html
2479 /// [`Hasher`]: ../../hash/trait.Hasher.html
2484 /// use std::collections::HashMap;
2485 /// use std::collections::hash_map::RandomState;
2487 /// let s = RandomState::new();
2488 /// let mut map = HashMap::with_hasher(s);
2489 /// map.insert(1, 2);
2492 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2493 pub struct RandomState {
2499 /// Constructs a new `RandomState` that is initialized with random keys.
2504 /// use std::collections::hash_map::RandomState;
2506 /// let s = RandomState::new();
2509 #[allow(deprecated)]
2511 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2512 pub fn new() -> RandomState {
2513 // Historically this function did not cache keys from the OS and instead
2514 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2515 // was discovered, however, that because we re-seed the thread-local RNG
2516 // from the OS periodically that this can cause excessive slowdown when
2517 // many hash maps are created on a thread. To solve this performance
2518 // trap we cache the first set of randomly generated keys per-thread.
2520 // Later in #36481 it was discovered that exposing a deterministic
2521 // iteration order allows a form of DOS attack. To counter that we
2522 // increment one of the seeds on every RandomState creation, giving
2523 // every corresponding HashMap a different iteration order.
2524 thread_local!(static KEYS: Cell<(u64, u64)> = {
2525 Cell::new(sys::hashmap_random_keys())
2529 let (k0, k1) = keys.get();
2530 keys.set((k0.wrapping_add(1), k1));
2531 RandomState { k0, k1 }
2536 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2537 impl BuildHasher for RandomState {
2538 type Hasher = DefaultHasher;
2540 #[allow(deprecated)]
2541 fn build_hasher(&self) -> DefaultHasher {
2542 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2546 /// The default [`Hasher`] used by [`RandomState`].
2548 /// The internal algorithm is not specified, and so it and its hashes should
2549 /// not be relied upon over releases.
2551 /// [`RandomState`]: struct.RandomState.html
2552 /// [`Hasher`]: ../../hash/trait.Hasher.html
2553 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2554 #[allow(deprecated)]
2555 #[derive(Clone, Debug)]
2556 pub struct DefaultHasher(SipHasher13);
2558 impl DefaultHasher {
2559 /// Creates a new `DefaultHasher`.
2561 /// This hasher is not guaranteed to be the same as all other
2562 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2563 /// instances created through `new` or `default`.
2564 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2565 #[allow(deprecated)]
2566 pub fn new() -> DefaultHasher {
2567 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2571 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2572 impl Default for DefaultHasher {
2573 // FIXME: here should link `new` to [DefaultHasher::new], but it occurs intra-doc link
2574 // resolution failure when re-exporting libstd items. When #56922 fixed,
2575 // link `new` to [DefaultHasher::new] again.
2576 /// Creates a new `DefaultHasher` using `new`.
2577 /// See its documentation for more.
2578 fn default() -> DefaultHasher {
2579 DefaultHasher::new()
2583 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2584 impl Hasher for DefaultHasher {
2586 fn write(&mut self, msg: &[u8]) {
2591 fn finish(&self) -> u64 {
2596 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2597 impl Default for RandomState {
2598 /// Constructs a new `RandomState`.
2600 fn default() -> RandomState {
2605 #[stable(feature = "std_debug", since = "1.16.0")]
2606 impl fmt::Debug for RandomState {
2607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2608 f.pad("RandomState { .. }")
2613 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2615 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2616 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2621 fn map_collection_alloc_err(err: hashbrown::CollectionAllocErr) -> TryReserveError {
2623 hashbrown::CollectionAllocErr::CapacityOverflow => TryReserveError::CapacityOverflow,
2624 hashbrown::CollectionAllocErr::AllocErr { layout } => {
2625 TryReserveError::AllocError { layout, non_exhaustive: () }
2631 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
2632 raw: base::RawEntryMut<'a, K, V, S>,
2633 ) -> RawEntryMut<'a, K, V, S> {
2635 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
2636 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
2641 fn assert_covariance() {
2642 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2645 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2648 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2651 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2654 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2657 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2660 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2663 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2666 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2669 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2673 d: Drain<'static, &'static str, &'static str>,
2674 ) -> Drain<'new, &'new str, &'new str> {
2681 use super::Entry::{Occupied, Vacant};
2683 use super::RandomState;
2684 use crate::cell::RefCell;
2685 use rand::{thread_rng, Rng};
2686 use realstd::collections::TryReserveError::*;
2688 // https://github.com/rust-lang/rust/issues/62301
2689 fn _assert_hashmap_is_unwind_safe() {
2690 fn assert_unwind_safe<T: crate::panic::UnwindSafe>() {}
2691 assert_unwind_safe::<HashMap<(), crate::cell::UnsafeCell<()>>>();
2695 fn test_zero_capacities() {
2696 type HM = HashMap<i32, i32>;
2699 assert_eq!(m.capacity(), 0);
2701 let m = HM::default();
2702 assert_eq!(m.capacity(), 0);
2704 let m = HM::with_hasher(RandomState::new());
2705 assert_eq!(m.capacity(), 0);
2707 let m = HM::with_capacity(0);
2708 assert_eq!(m.capacity(), 0);
2710 let m = HM::with_capacity_and_hasher(0, RandomState::new());
2711 assert_eq!(m.capacity(), 0);
2713 let mut m = HM::new();
2719 assert_eq!(m.capacity(), 0);
2721 let mut m = HM::new();
2723 assert_eq!(m.capacity(), 0);
2727 fn test_create_capacity_zero() {
2728 let mut m = HashMap::with_capacity(0);
2730 assert!(m.insert(1, 1).is_none());
2732 assert!(m.contains_key(&1));
2733 assert!(!m.contains_key(&0));
2738 let mut m = HashMap::new();
2739 assert_eq!(m.len(), 0);
2740 assert!(m.insert(1, 2).is_none());
2741 assert_eq!(m.len(), 1);
2742 assert!(m.insert(2, 4).is_none());
2743 assert_eq!(m.len(), 2);
2744 assert_eq!(*m.get(&1).unwrap(), 2);
2745 assert_eq!(*m.get(&2).unwrap(), 4);
2750 let mut m = HashMap::new();
2751 assert_eq!(m.len(), 0);
2752 assert!(m.insert(1, 2).is_none());
2753 assert_eq!(m.len(), 1);
2754 assert!(m.insert(2, 4).is_none());
2755 assert_eq!(m.len(), 2);
2757 assert_eq!(*m2.get(&1).unwrap(), 2);
2758 assert_eq!(*m2.get(&2).unwrap(), 4);
2759 assert_eq!(m2.len(), 2);
2762 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
2764 #[derive(Hash, PartialEq, Eq)]
2770 fn new(k: usize) -> Droppable {
2771 DROP_VECTOR.with(|slot| {
2772 slot.borrow_mut()[k] += 1;
2779 impl Drop for Droppable {
2780 fn drop(&mut self) {
2781 DROP_VECTOR.with(|slot| {
2782 slot.borrow_mut()[self.k] -= 1;
2787 impl Clone for Droppable {
2788 fn clone(&self) -> Droppable {
2789 Droppable::new(self.k)
2795 DROP_VECTOR.with(|slot| {
2796 *slot.borrow_mut() = vec![0; 200];
2800 let mut m = HashMap::new();
2802 DROP_VECTOR.with(|v| {
2804 assert_eq!(v.borrow()[i], 0);
2809 let d1 = Droppable::new(i);
2810 let d2 = Droppable::new(i + 100);
2814 DROP_VECTOR.with(|v| {
2816 assert_eq!(v.borrow()[i], 1);
2821 let k = Droppable::new(i);
2822 let v = m.remove(&k);
2824 assert!(v.is_some());
2826 DROP_VECTOR.with(|v| {
2827 assert_eq!(v.borrow()[i], 1);
2828 assert_eq!(v.borrow()[i + 100], 1);
2832 DROP_VECTOR.with(|v| {
2834 assert_eq!(v.borrow()[i], 0);
2835 assert_eq!(v.borrow()[i + 100], 0);
2839 assert_eq!(v.borrow()[i], 1);
2840 assert_eq!(v.borrow()[i + 100], 1);
2845 DROP_VECTOR.with(|v| {
2847 assert_eq!(v.borrow()[i], 0);
2853 fn test_into_iter_drops() {
2854 DROP_VECTOR.with(|v| {
2855 *v.borrow_mut() = vec![0; 200];
2859 let mut hm = HashMap::new();
2861 DROP_VECTOR.with(|v| {
2863 assert_eq!(v.borrow()[i], 0);
2868 let d1 = Droppable::new(i);
2869 let d2 = Droppable::new(i + 100);
2873 DROP_VECTOR.with(|v| {
2875 assert_eq!(v.borrow()[i], 1);
2882 // By the way, ensure that cloning doesn't screw up the dropping.
2886 let mut half = hm.into_iter().take(50);
2888 DROP_VECTOR.with(|v| {
2890 assert_eq!(v.borrow()[i], 1);
2894 for _ in half.by_ref() {}
2896 DROP_VECTOR.with(|v| {
2897 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
2899 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
2906 DROP_VECTOR.with(|v| {
2908 assert_eq!(v.borrow()[i], 0);
2914 fn test_empty_remove() {
2915 let mut m: HashMap<i32, bool> = HashMap::new();
2916 assert_eq!(m.remove(&0), None);
2920 fn test_empty_entry() {
2921 let mut m: HashMap<i32, bool> = HashMap::new();
2923 Occupied(_) => panic!(),
2926 assert!(*m.entry(0).or_insert(true));
2927 assert_eq!(m.len(), 1);
2931 fn test_empty_iter() {
2932 let mut m: HashMap<i32, bool> = HashMap::new();
2933 assert_eq!(m.drain().next(), None);
2934 assert_eq!(m.keys().next(), None);
2935 assert_eq!(m.values().next(), None);
2936 assert_eq!(m.values_mut().next(), None);
2937 assert_eq!(m.iter().next(), None);
2938 assert_eq!(m.iter_mut().next(), None);
2939 assert_eq!(m.len(), 0);
2940 assert!(m.is_empty());
2941 assert_eq!(m.into_iter().next(), None);
2945 fn test_lots_of_insertions() {
2946 let mut m = HashMap::new();
2948 // Try this a few times to make sure we never screw up the hashmap's
2951 assert!(m.is_empty());
2954 assert!(m.insert(i, i).is_none());
2958 assert_eq!(r, Some(&j));
2961 for j in i + 1..1001 {
2963 assert_eq!(r, None);
2967 for i in 1001..2001 {
2968 assert!(!m.contains_key(&i));
2973 assert!(m.remove(&i).is_some());
2976 assert!(!m.contains_key(&j));
2979 for j in i + 1..1001 {
2980 assert!(m.contains_key(&j));
2985 assert!(!m.contains_key(&i));
2989 assert!(m.insert(i, i).is_none());
2993 for i in (1..1001).rev() {
2994 assert!(m.remove(&i).is_some());
2997 assert!(!m.contains_key(&j));
3001 assert!(m.contains_key(&j));
3008 fn test_find_mut() {
3009 let mut m = HashMap::new();
3010 assert!(m.insert(1, 12).is_none());
3011 assert!(m.insert(2, 8).is_none());
3012 assert!(m.insert(5, 14).is_none());
3014 match m.get_mut(&5) {
3016 Some(x) => *x = new,
3018 assert_eq!(m.get(&5), Some(&new));
3022 fn test_insert_overwrite() {
3023 let mut m = HashMap::new();
3024 assert!(m.insert(1, 2).is_none());
3025 assert_eq!(*m.get(&1).unwrap(), 2);
3026 assert!(!m.insert(1, 3).is_none());
3027 assert_eq!(*m.get(&1).unwrap(), 3);
3031 fn test_insert_conflicts() {
3032 let mut m = HashMap::with_capacity(4);
3033 assert!(m.insert(1, 2).is_none());
3034 assert!(m.insert(5, 3).is_none());
3035 assert!(m.insert(9, 4).is_none());
3036 assert_eq!(*m.get(&9).unwrap(), 4);
3037 assert_eq!(*m.get(&5).unwrap(), 3);
3038 assert_eq!(*m.get(&1).unwrap(), 2);
3042 fn test_conflict_remove() {
3043 let mut m = HashMap::with_capacity(4);
3044 assert!(m.insert(1, 2).is_none());
3045 assert_eq!(*m.get(&1).unwrap(), 2);
3046 assert!(m.insert(5, 3).is_none());
3047 assert_eq!(*m.get(&1).unwrap(), 2);
3048 assert_eq!(*m.get(&5).unwrap(), 3);
3049 assert!(m.insert(9, 4).is_none());
3050 assert_eq!(*m.get(&1).unwrap(), 2);
3051 assert_eq!(*m.get(&5).unwrap(), 3);
3052 assert_eq!(*m.get(&9).unwrap(), 4);
3053 assert!(m.remove(&1).is_some());
3054 assert_eq!(*m.get(&9).unwrap(), 4);
3055 assert_eq!(*m.get(&5).unwrap(), 3);
3059 fn test_is_empty() {
3060 let mut m = HashMap::with_capacity(4);
3061 assert!(m.insert(1, 2).is_none());
3062 assert!(!m.is_empty());
3063 assert!(m.remove(&1).is_some());
3064 assert!(m.is_empty());
3069 let mut m = HashMap::new();
3071 assert_eq!(m.remove(&1), Some(2));
3072 assert_eq!(m.remove(&1), None);
3076 fn test_remove_entry() {
3077 let mut m = HashMap::new();
3079 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3080 assert_eq!(m.remove(&1), None);
3085 let mut m = HashMap::with_capacity(4);
3087 assert!(m.insert(i, i * 2).is_none());
3089 assert_eq!(m.len(), 32);
3091 let mut observed: u32 = 0;
3094 assert_eq!(*v, *k * 2);
3095 observed |= 1 << *k;
3097 assert_eq!(observed, 0xFFFF_FFFF);
3102 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3103 let map: HashMap<_, _> = vec.into_iter().collect();
3104 let keys: Vec<_> = map.keys().cloned().collect();
3105 assert_eq!(keys.len(), 3);
3106 assert!(keys.contains(&1));
3107 assert!(keys.contains(&2));
3108 assert!(keys.contains(&3));
3113 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3114 let map: HashMap<_, _> = vec.into_iter().collect();
3115 let values: Vec<_> = map.values().cloned().collect();
3116 assert_eq!(values.len(), 3);
3117 assert!(values.contains(&'a'));
3118 assert!(values.contains(&'b'));
3119 assert!(values.contains(&'c'));
3123 fn test_values_mut() {
3124 let vec = vec![(1, 1), (2, 2), (3, 3)];
3125 let mut map: HashMap<_, _> = vec.into_iter().collect();
3126 for value in map.values_mut() {
3127 *value = (*value) * 2
3129 let values: Vec<_> = map.values().cloned().collect();
3130 assert_eq!(values.len(), 3);
3131 assert!(values.contains(&2));
3132 assert!(values.contains(&4));
3133 assert!(values.contains(&6));
3138 let mut m = HashMap::new();
3139 assert!(m.get(&1).is_none());
3143 Some(v) => assert_eq!(*v, 2),
3149 let mut m1 = HashMap::new();
3154 let mut m2 = HashMap::new();
3167 let mut map = HashMap::new();
3168 let empty: HashMap<i32, i32> = HashMap::new();
3173 let map_str = format!("{:?}", map);
3175 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
3176 assert_eq!(format!("{:?}", empty), "{}");
3180 fn test_reserve_shrink_to_fit() {
3181 let mut m = HashMap::new();
3184 assert!(m.capacity() >= m.len());
3190 let usable_cap = m.capacity();
3191 for i in 128..(128 + 256) {
3193 assert_eq!(m.capacity(), usable_cap);
3196 for i in 100..(128 + 256) {
3197 assert_eq!(m.remove(&i), Some(i));
3201 assert_eq!(m.len(), 100);
3202 assert!(!m.is_empty());
3203 assert!(m.capacity() >= m.len());
3206 assert_eq!(m.remove(&i), Some(i));
3211 assert_eq!(m.len(), 1);
3212 assert!(m.capacity() >= m.len());
3213 assert_eq!(m.remove(&0), Some(0));
3217 fn test_from_iter() {
3218 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3220 let map: HashMap<_, _> = xs.iter().cloned().collect();
3222 for &(k, v) in &xs {
3223 assert_eq!(map.get(&k), Some(&v));
3226 assert_eq!(map.iter().len(), xs.len() - 1);
3230 fn test_size_hint() {
3231 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3233 let map: HashMap<_, _> = xs.iter().cloned().collect();
3235 let mut iter = map.iter();
3237 for _ in iter.by_ref().take(3) {}
3239 assert_eq!(iter.size_hint(), (3, Some(3)));
3243 fn test_iter_len() {
3244 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3246 let map: HashMap<_, _> = xs.iter().cloned().collect();
3248 let mut iter = map.iter();
3250 for _ in iter.by_ref().take(3) {}
3252 assert_eq!(iter.len(), 3);
3256 fn test_mut_size_hint() {
3257 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3259 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3261 let mut iter = map.iter_mut();
3263 for _ in iter.by_ref().take(3) {}
3265 assert_eq!(iter.size_hint(), (3, Some(3)));
3269 fn test_iter_mut_len() {
3270 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3272 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3274 let mut iter = map.iter_mut();
3276 for _ in iter.by_ref().take(3) {}
3278 assert_eq!(iter.len(), 3);
3283 let mut map = HashMap::new();
3289 assert_eq!(map[&2], 1);
3294 fn test_index_nonexistent() {
3295 let mut map = HashMap::new();
3306 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3308 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3310 // Existing key (insert)
3311 match map.entry(1) {
3312 Vacant(_) => unreachable!(),
3313 Occupied(mut view) => {
3314 assert_eq!(view.get(), &10);
3315 assert_eq!(view.insert(100), 10);
3318 assert_eq!(map.get(&1).unwrap(), &100);
3319 assert_eq!(map.len(), 6);
3321 // Existing key (update)
3322 match map.entry(2) {
3323 Vacant(_) => unreachable!(),
3324 Occupied(mut view) => {
3325 let v = view.get_mut();
3326 let new_v = (*v) * 10;
3330 assert_eq!(map.get(&2).unwrap(), &200);
3331 assert_eq!(map.len(), 6);
3333 // Existing key (take)
3334 match map.entry(3) {
3335 Vacant(_) => unreachable!(),
3337 assert_eq!(view.remove(), 30);
3340 assert_eq!(map.get(&3), None);
3341 assert_eq!(map.len(), 5);
3343 // Inexistent key (insert)
3344 match map.entry(10) {
3345 Occupied(_) => unreachable!(),
3347 assert_eq!(*view.insert(1000), 1000);
3350 assert_eq!(map.get(&10).unwrap(), &1000);
3351 assert_eq!(map.len(), 6);
3355 fn test_entry_take_doesnt_corrupt() {
3356 #![allow(deprecated)] //rand
3358 fn check(m: &HashMap<i32, ()>) {
3360 assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
3364 let mut m = HashMap::new();
3365 let mut rng = thread_rng();
3367 // Populate the map with some items.
3369 let x = rng.gen_range(-10, 10);
3374 let x = rng.gen_range(-10, 10);
3387 fn test_extend_ref() {
3388 let mut a = HashMap::new();
3390 let mut b = HashMap::new();
3392 b.insert(3, "three");
3396 assert_eq!(a.len(), 3);
3397 assert_eq!(a[&1], "one");
3398 assert_eq!(a[&2], "two");
3399 assert_eq!(a[&3], "three");
3403 fn test_capacity_not_less_than_len() {
3404 let mut a = HashMap::new();
3412 assert!(a.capacity() > a.len());
3414 let free = a.capacity() - a.len();
3420 assert_eq!(a.len(), a.capacity());
3422 // Insert at capacity should cause allocation.
3424 assert!(a.capacity() > a.len());
3428 fn test_occupied_entry_key() {
3429 let mut a = HashMap::new();
3430 let key = "hello there";
3431 let value = "value goes here";
3432 assert!(a.is_empty());
3433 a.insert(key.clone(), value.clone());
3434 assert_eq!(a.len(), 1);
3435 assert_eq!(a[key], value);
3437 match a.entry(key.clone()) {
3438 Vacant(_) => panic!(),
3439 Occupied(e) => assert_eq!(key, *e.key()),
3441 assert_eq!(a.len(), 1);
3442 assert_eq!(a[key], value);
3446 fn test_vacant_entry_key() {
3447 let mut a = HashMap::new();
3448 let key = "hello there";
3449 let value = "value goes here";
3451 assert!(a.is_empty());
3452 match a.entry(key.clone()) {
3453 Occupied(_) => panic!(),
3455 assert_eq!(key, *e.key());
3456 e.insert(value.clone());
3459 assert_eq!(a.len(), 1);
3460 assert_eq!(a[key], value);
3465 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
3467 map.retain(|&k, _| k % 2 == 0);
3468 assert_eq!(map.len(), 50);
3469 assert_eq!(map[&2], 20);
3470 assert_eq!(map[&4], 40);
3471 assert_eq!(map[&6], 60);
3475 fn test_try_reserve() {
3476 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
3478 const MAX_USIZE: usize = usize::MAX;
3480 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
3482 panic!("usize::MAX should trigger an overflow!");
3485 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE / 8) {
3487 panic!("usize::MAX / 8 should trigger an OOM!")
3492 fn test_raw_entry() {
3493 use super::RawEntryMut::{Occupied, Vacant};
3495 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3497 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3499 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
3500 use core::hash::{BuildHasher, Hash, Hasher};
3502 let mut hasher = map.hasher().build_hasher();
3503 k.hash(&mut hasher);
3507 // Existing key (insert)
3508 match map.raw_entry_mut().from_key(&1) {
3509 Vacant(_) => unreachable!(),
3510 Occupied(mut view) => {
3511 assert_eq!(view.get(), &10);
3512 assert_eq!(view.insert(100), 10);
3515 let hash1 = compute_hash(&map, 1);
3516 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
3517 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
3518 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
3519 assert_eq!(map.len(), 6);
3521 // Existing key (update)
3522 match map.raw_entry_mut().from_key(&2) {
3523 Vacant(_) => unreachable!(),
3524 Occupied(mut view) => {
3525 let v = view.get_mut();
3526 let new_v = (*v) * 10;
3530 let hash2 = compute_hash(&map, 2);
3531 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
3532 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
3533 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
3534 assert_eq!(map.len(), 6);
3536 // Existing key (take)
3537 let hash3 = compute_hash(&map, 3);
3538 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
3539 Vacant(_) => unreachable!(),
3541 assert_eq!(view.remove_entry(), (3, 30));
3544 assert_eq!(map.raw_entry().from_key(&3), None);
3545 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
3546 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
3547 assert_eq!(map.len(), 5);
3549 // Nonexistent key (insert)
3550 match map.raw_entry_mut().from_key(&10) {
3551 Occupied(_) => unreachable!(),
3553 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
3556 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
3557 assert_eq!(map.len(), 6);
3559 // Ensure all lookup methods produce equivalent results.
3561 let hash = compute_hash(&map, k);
3562 let v = map.get(&k).cloned();
3563 let kv = v.as_ref().map(|v| (&k, v));
3565 assert_eq!(map.raw_entry().from_key(&k), kv);
3566 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
3567 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
3569 match map.raw_entry_mut().from_key(&k) {
3570 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3571 Vacant(_) => assert_eq!(v, None),
3573 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
3574 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3575 Vacant(_) => assert_eq!(v, None),
3577 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
3578 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
3579 Vacant(_) => assert_eq!(v, None),