6 use hashbrown::hash_map as base;
8 use crate::borrow::Borrow;
10 use crate::collections::TryReserveError;
11 use crate::fmt::{self, Debug};
13 use crate::hash::{BuildHasher, Hash, Hasher, SipHasher13};
14 use crate::iter::{FromIterator, FusedIterator};
15 use crate::ops::Index;
18 /// A hash map implemented with quadratic probing and SIMD lookup.
20 /// By default, `HashMap` uses a hashing algorithm selected to provide
21 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
22 /// reasonable best-effort is made to generate this seed from a high quality,
23 /// secure source of randomness provided by the host without blocking the
24 /// program. Because of this, the randomness of the seed depends on the output
25 /// quality of the system's random number generator when the seed is created.
26 /// In particular, seeds generated when the system's entropy pool is abnormally
27 /// low such as during system boot may be of a lower quality.
29 /// The default hashing algorithm is currently SipHash 1-3, though this is
30 /// subject to change at any point in the future. While its performance is very
31 /// competitive for medium sized keys, other hashing algorithms will outperform
32 /// it for small keys such as integers as well as large keys such as long
33 /// strings, though those algorithms will typically *not* protect against
34 /// attacks such as HashDoS.
36 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
37 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
38 /// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
40 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
41 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
42 /// If you implement these yourself, it is important that the following
46 /// k1 == k2 -> hash(k1) == hash(k2)
49 /// In other words, if two keys are equal, their hashes must be equal.
51 /// It is a logic error for a key to be modified in such a way that the key's
52 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
53 /// the [`Eq`] trait, changes while it is in the map. This is normally only
54 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56 /// The hash table implementation is a Rust port of Google's [SwissTable].
57 /// The original C++ version of SwissTable can be found [here], and this
58 /// [CppCon talk] gives an overview of how the algorithm works.
60 /// [SwissTable]: https://abseil.io/blog/20180927-swisstables
61 /// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
62 /// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
67 /// use std::collections::HashMap;
69 /// // Type inference lets us omit an explicit type signature (which
70 /// // would be `HashMap<String, String>` in this example).
71 /// let mut book_reviews = HashMap::new();
73 /// // Review some books.
74 /// book_reviews.insert(
75 /// "Adventures of Huckleberry Finn".to_string(),
76 /// "My favorite book.".to_string(),
78 /// book_reviews.insert(
79 /// "Grimms' Fairy Tales".to_string(),
80 /// "Masterpiece.".to_string(),
82 /// book_reviews.insert(
83 /// "Pride and Prejudice".to_string(),
84 /// "Very enjoyable.".to_string(),
86 /// book_reviews.insert(
87 /// "The Adventures of Sherlock Holmes".to_string(),
88 /// "Eye lyked it alot.".to_string(),
91 /// // Check for a specific one.
92 /// // When collections store owned values (String), they can still be
93 /// // queried using references (&str).
94 /// if !book_reviews.contains_key("Les Misérables") {
95 /// println!("We've got {} reviews, but Les Misérables ain't one.",
96 /// book_reviews.len());
99 /// // oops, this review has a lot of spelling mistakes, let's delete it.
100 /// book_reviews.remove("The Adventures of Sherlock Holmes");
102 /// // Look up the values associated with some keys.
103 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
104 /// for &book in &to_find {
105 /// match book_reviews.get(book) {
106 /// Some(review) => println!("{}: {}", book, review),
107 /// None => println!("{} is unreviewed.", book)
111 /// // Look up the value for a key (will panic if the key is not found).
112 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
114 /// // Iterate over everything.
115 /// for (book, review) in &book_reviews {
116 /// println!("{}: \"{}\"", book, review);
120 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
121 /// for more complex methods of getting, setting, updating and removing keys and
125 /// use std::collections::HashMap;
127 /// // type inference lets us omit an explicit type signature (which
128 /// // would be `HashMap<&str, u8>` in this example).
129 /// let mut player_stats = HashMap::new();
131 /// fn random_stat_buff() -> u8 {
132 /// // could actually return some random value here - let's just return
133 /// // some fixed value for now
137 /// // insert a key only if it doesn't already exist
138 /// player_stats.entry("health").or_insert(100);
140 /// // insert a key using a function that provides a new value only if it
141 /// // doesn't already exist
142 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
144 /// // update a key, guarding against the key possibly not being set
145 /// let stat = player_stats.entry("attack").or_insert(100);
146 /// *stat += random_stat_buff();
149 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
150 /// We must also derive [`PartialEq`].
152 /// [`RefCell`]: crate::cell::RefCell
153 /// [`Cell`]: crate::cell::Cell
154 /// [`default`]: Default::default
155 /// [`with_hasher`]: Self::with_hasher
156 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
157 /// [`fnv`]: https://crates.io/crates/fnv
160 /// use std::collections::HashMap;
162 /// #[derive(Hash, Eq, PartialEq, Debug)]
169 /// /// Creates a new Viking.
170 /// fn new(name: &str, country: &str) -> Viking {
171 /// Viking { name: name.to_string(), country: country.to_string() }
175 /// // Use a HashMap to store the vikings' health points.
176 /// let mut vikings = HashMap::new();
178 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
179 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
180 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
182 /// // Use derived implementation to print the status of the vikings.
183 /// for (viking, health) in &vikings {
184 /// println!("{:?} has {} hp", viking, health);
188 /// A `HashMap` with fixed list of elements can be initialized from an array:
191 /// use std::collections::HashMap;
193 /// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
194 /// .iter().cloned().collect();
195 /// // use the values stored in map
199 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_type")]
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub struct HashMap<K, V, S = RandomState> {
202 base: base::HashMap<K, V, S>,
205 impl<K, V> HashMap<K, V, RandomState> {
206 /// Creates an empty `HashMap`.
208 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
209 /// is first inserted into.
214 /// use std::collections::HashMap;
215 /// let mut map: HashMap<&str, i32> = HashMap::new();
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn new() -> HashMap<K, V, RandomState> {
223 /// Creates an empty `HashMap` with the specified capacity.
225 /// The hash map will be able to hold at least `capacity` elements without
226 /// reallocating. If `capacity` is 0, the hash map will not allocate.
231 /// use std::collections::HashMap;
232 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
237 HashMap::with_capacity_and_hasher(capacity, Default::default())
241 impl<K, V, S> HashMap<K, V, S> {
242 /// Creates an empty `HashMap` which will use the given hash builder to hash
245 /// The created map has the default initial capacity.
247 /// Warning: `hash_builder` is normally randomly generated, and
248 /// is designed to allow HashMaps to be resistant to attacks that
249 /// cause many collisions and very poor performance. Setting it
250 /// manually using this function can expose a DoS attack vector.
252 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
253 /// the HashMap to be useful, see its documentation for details.
258 /// use std::collections::HashMap;
259 /// use std::collections::hash_map::RandomState;
261 /// let s = RandomState::new();
262 /// let mut map = HashMap::with_hasher(s);
263 /// map.insert(1, 2);
266 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
267 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
268 HashMap { base: base::HashMap::with_hasher(hash_builder) }
271 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
272 /// to hash the keys.
274 /// The hash map will be able to hold at least `capacity` elements without
275 /// reallocating. If `capacity` is 0, the hash map will not allocate.
277 /// Warning: `hash_builder` is normally randomly generated, and
278 /// is designed to allow HashMaps to be resistant to attacks that
279 /// cause many collisions and very poor performance. Setting it
280 /// manually using this function can expose a DoS attack vector.
282 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
283 /// the HashMap to be useful, see its documentation for details.
288 /// use std::collections::HashMap;
289 /// use std::collections::hash_map::RandomState;
291 /// let s = RandomState::new();
292 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
293 /// map.insert(1, 2);
296 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
297 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
298 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
301 /// Returns the number of elements the map can hold without reallocating.
303 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
304 /// more, but is guaranteed to be able to hold at least this many.
309 /// use std::collections::HashMap;
310 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
311 /// assert!(map.capacity() >= 100);
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn capacity(&self) -> usize {
319 /// An iterator visiting all keys in arbitrary order.
320 /// The iterator element type is `&'a K`.
325 /// use std::collections::HashMap;
327 /// let mut map = HashMap::new();
328 /// map.insert("a", 1);
329 /// map.insert("b", 2);
330 /// map.insert("c", 3);
332 /// for key in map.keys() {
333 /// println!("{}", key);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn keys(&self) -> Keys<'_, K, V> {
338 Keys { inner: self.iter() }
341 /// An iterator visiting all values in arbitrary order.
342 /// The iterator element type is `&'a V`.
347 /// use std::collections::HashMap;
349 /// let mut map = HashMap::new();
350 /// map.insert("a", 1);
351 /// map.insert("b", 2);
352 /// map.insert("c", 3);
354 /// for val in map.values() {
355 /// println!("{}", val);
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn values(&self) -> Values<'_, K, V> {
360 Values { inner: self.iter() }
363 /// An iterator visiting all values mutably in arbitrary order.
364 /// The iterator element type is `&'a mut V`.
369 /// use std::collections::HashMap;
371 /// let mut map = HashMap::new();
373 /// map.insert("a", 1);
374 /// map.insert("b", 2);
375 /// map.insert("c", 3);
377 /// for val in map.values_mut() {
378 /// *val = *val + 10;
381 /// for val in map.values() {
382 /// println!("{}", val);
385 #[stable(feature = "map_values_mut", since = "1.10.0")]
386 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
387 ValuesMut { inner: self.iter_mut() }
390 /// An iterator visiting all key-value pairs in arbitrary order.
391 /// The iterator element type is `(&'a K, &'a V)`.
396 /// use std::collections::HashMap;
398 /// let mut map = HashMap::new();
399 /// map.insert("a", 1);
400 /// map.insert("b", 2);
401 /// map.insert("c", 3);
403 /// for (key, val) in map.iter() {
404 /// println!("key: {} val: {}", key, val);
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn iter(&self) -> Iter<'_, K, V> {
409 Iter { base: self.base.iter() }
412 /// An iterator visiting all key-value pairs in arbitrary order,
413 /// with mutable references to the values.
414 /// The iterator element type is `(&'a K, &'a mut V)`.
419 /// use std::collections::HashMap;
421 /// let mut map = HashMap::new();
422 /// map.insert("a", 1);
423 /// map.insert("b", 2);
424 /// map.insert("c", 3);
426 /// // Update all values
427 /// for (_, val) in map.iter_mut() {
431 /// for (key, val) in &map {
432 /// println!("key: {} val: {}", key, val);
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
437 IterMut { base: self.base.iter_mut() }
440 /// Returns the number of elements in the map.
445 /// use std::collections::HashMap;
447 /// let mut a = HashMap::new();
448 /// assert_eq!(a.len(), 0);
449 /// a.insert(1, "a");
450 /// assert_eq!(a.len(), 1);
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn len(&self) -> usize {
457 /// Returns `true` if the map contains no elements.
462 /// use std::collections::HashMap;
464 /// let mut a = HashMap::new();
465 /// assert!(a.is_empty());
466 /// a.insert(1, "a");
467 /// assert!(!a.is_empty());
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub fn is_empty(&self) -> bool {
475 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
476 /// allocated memory for reuse.
481 /// use std::collections::HashMap;
483 /// let mut a = HashMap::new();
484 /// a.insert(1, "a");
485 /// a.insert(2, "b");
487 /// for (k, v) in a.drain().take(1) {
488 /// assert!(k == 1 || k == 2);
489 /// assert!(v == "a" || v == "b");
492 /// assert!(a.is_empty());
495 #[stable(feature = "drain", since = "1.6.0")]
496 pub fn drain(&mut self) -> Drain<'_, K, V> {
497 Drain { base: self.base.drain() }
500 /// Creates an iterator which uses a closure to determine if an element should be removed.
502 /// If the closure returns true, the element is removed from the map and yielded.
503 /// If the closure returns false, or panics, the element remains in the map and will not be
506 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
507 /// whether you choose to keep or remove it.
509 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
510 /// elements will still be subjected to the closure and removed and dropped if it returns true.
512 /// It is unspecified how many more elements will be subjected to the closure
513 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
514 /// or if the `DrainFilter` value is leaked.
518 /// Splitting a map into even and odd keys, reusing the original map:
521 /// #![feature(hash_drain_filter)]
522 /// use std::collections::HashMap;
524 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
525 /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
527 /// let mut evens = drained.keys().copied().collect::<Vec<_>>();
528 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
532 /// assert_eq!(evens, vec![0, 2, 4, 6]);
533 /// assert_eq!(odds, vec![1, 3, 5, 7]);
536 #[unstable(feature = "hash_drain_filter", issue = "59618")]
537 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
539 F: FnMut(&K, &mut V) -> bool,
541 DrainFilter { base: self.base.drain_filter(pred) }
544 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
550 /// use std::collections::HashMap;
552 /// let mut a = HashMap::new();
553 /// a.insert(1, "a");
555 /// assert!(a.is_empty());
557 #[stable(feature = "rust1", since = "1.0.0")]
559 pub fn clear(&mut self) {
563 /// Returns a reference to the map's [`BuildHasher`].
568 /// use std::collections::HashMap;
569 /// use std::collections::hash_map::RandomState;
571 /// let hasher = RandomState::new();
572 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
573 /// let hasher: &RandomState = map.hasher();
576 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
577 pub fn hasher(&self) -> &S {
582 impl<K, V, S> HashMap<K, V, S>
587 /// Reserves capacity for at least `additional` more elements to be inserted
588 /// in the `HashMap`. The collection may reserve more space to avoid
589 /// frequent reallocations.
593 /// Panics if the new allocation size overflows [`usize`].
598 /// use std::collections::HashMap;
599 /// let mut map: HashMap<&str, i32> = HashMap::new();
603 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn reserve(&mut self, additional: usize) {
605 self.base.reserve(additional)
608 /// Tries to reserve capacity for at least `additional` more elements to be inserted
609 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
610 /// frequent reallocations.
614 /// If the capacity overflows, or the allocator reports a failure, then an error
620 /// #![feature(try_reserve)]
621 /// use std::collections::HashMap;
622 /// let mut map: HashMap<&str, isize> = HashMap::new();
623 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
626 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
627 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
628 self.base.try_reserve(additional).map_err(map_try_reserve_error)
631 /// Shrinks the capacity of the map as much as possible. It will drop
632 /// down as much as possible while maintaining the internal rules
633 /// and possibly leaving some space in accordance with the resize policy.
638 /// use std::collections::HashMap;
640 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
641 /// map.insert(1, 2);
642 /// map.insert(3, 4);
643 /// assert!(map.capacity() >= 100);
644 /// map.shrink_to_fit();
645 /// assert!(map.capacity() >= 2);
648 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn shrink_to_fit(&mut self) {
650 self.base.shrink_to_fit();
653 /// Shrinks the capacity of the map with a lower limit. It will drop
654 /// down no lower than the supplied limit while maintaining the internal rules
655 /// and possibly leaving some space in accordance with the resize policy.
657 /// Panics if the current capacity is smaller than the supplied
658 /// minimum capacity.
663 /// #![feature(shrink_to)]
664 /// use std::collections::HashMap;
666 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
667 /// map.insert(1, 2);
668 /// map.insert(3, 4);
669 /// assert!(map.capacity() >= 100);
670 /// map.shrink_to(10);
671 /// assert!(map.capacity() >= 10);
672 /// map.shrink_to(0);
673 /// assert!(map.capacity() >= 2);
676 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
677 pub fn shrink_to(&mut self, min_capacity: usize) {
678 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
679 self.base.shrink_to(min_capacity);
682 /// Gets the given key's corresponding entry in the map for in-place manipulation.
687 /// use std::collections::HashMap;
689 /// let mut letters = HashMap::new();
691 /// for ch in "a short treatise on fungi".chars() {
692 /// let counter = letters.entry(ch).or_insert(0);
696 /// assert_eq!(letters[&'s'], 2);
697 /// assert_eq!(letters[&'t'], 3);
698 /// assert_eq!(letters[&'u'], 1);
699 /// assert_eq!(letters.get(&'y'), None);
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
704 map_entry(self.base.rustc_entry(key))
707 /// Returns a reference to the value corresponding to the key.
709 /// The key may be any borrowed form of the map's key type, but
710 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
716 /// use std::collections::HashMap;
718 /// let mut map = HashMap::new();
719 /// map.insert(1, "a");
720 /// assert_eq!(map.get(&1), Some(&"a"));
721 /// assert_eq!(map.get(&2), None);
723 #[stable(feature = "rust1", since = "1.0.0")]
725 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
733 /// Returns the key-value pair corresponding to the supplied key.
735 /// The supplied key may be any borrowed form of the map's key type, but
736 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
742 /// use std::collections::HashMap;
744 /// let mut map = HashMap::new();
745 /// map.insert(1, "a");
746 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
747 /// assert_eq!(map.get_key_value(&2), None);
749 #[stable(feature = "map_get_key_value", since = "1.40.0")]
751 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
756 self.base.get_key_value(k)
759 /// Returns `true` if the map contains a value for the specified key.
761 /// The key may be any borrowed form of the map's key type, but
762 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
768 /// use std::collections::HashMap;
770 /// let mut map = HashMap::new();
771 /// map.insert(1, "a");
772 /// assert_eq!(map.contains_key(&1), true);
773 /// assert_eq!(map.contains_key(&2), false);
775 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
782 self.base.contains_key(k)
785 /// Returns a mutable reference to the value corresponding to the key.
787 /// The key may be any borrowed form of the map's key type, but
788 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
794 /// use std::collections::HashMap;
796 /// let mut map = HashMap::new();
797 /// map.insert(1, "a");
798 /// if let Some(x) = map.get_mut(&1) {
801 /// assert_eq!(map[&1], "b");
803 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
813 /// Inserts a key-value pair into the map.
815 /// If the map did not have this key present, [`None`] is returned.
817 /// If the map did have this key present, the value is updated, and the old
818 /// value is returned. The key is not updated, though; this matters for
819 /// types that can be `==` without being identical. See the [module-level
820 /// documentation] for more.
822 /// [module-level documentation]: crate::collections#insert-and-complex-keys
827 /// use std::collections::HashMap;
829 /// let mut map = HashMap::new();
830 /// assert_eq!(map.insert(37, "a"), None);
831 /// assert_eq!(map.is_empty(), false);
833 /// map.insert(37, "b");
834 /// assert_eq!(map.insert(37, "c"), Some("b"));
835 /// assert_eq!(map[&37], "c");
837 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
840 self.base.insert(k, v)
843 /// Removes a key from the map, returning the value at the key if the key
844 /// was previously in the map.
846 /// The key may be any borrowed form of the map's key type, but
847 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
853 /// use std::collections::HashMap;
855 /// let mut map = HashMap::new();
856 /// map.insert(1, "a");
857 /// assert_eq!(map.remove(&1), Some("a"));
858 /// assert_eq!(map.remove(&1), None);
860 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
870 /// Removes a key from the map, returning the stored key and value if the
871 /// key was previously in the map.
873 /// The key may be any borrowed form of the map's key type, but
874 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
880 /// use std::collections::HashMap;
883 /// let mut map = HashMap::new();
884 /// map.insert(1, "a");
885 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
886 /// assert_eq!(map.remove(&1), None);
889 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
891 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
896 self.base.remove_entry(k)
899 /// Retains only the elements specified by the predicate.
901 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
906 /// use std::collections::HashMap;
908 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
909 /// map.retain(|&k, _| k % 2 == 0);
910 /// assert_eq!(map.len(), 4);
912 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
914 pub fn retain<F>(&mut self, f: F)
916 F: FnMut(&K, &mut V) -> bool,
921 /// Creates a consuming iterator visiting all the keys in arbitrary order.
922 /// The map cannot be used after calling this.
923 /// The iterator element type is `K`.
928 /// #![feature(map_into_keys_values)]
929 /// use std::collections::HashMap;
931 /// let mut map = HashMap::new();
932 /// map.insert("a", 1);
933 /// map.insert("b", 2);
934 /// map.insert("c", 3);
936 /// let vec: Vec<&str> = map.into_keys().collect();
939 #[unstable(feature = "map_into_keys_values", issue = "75294")]
940 pub fn into_keys(self) -> IntoKeys<K, V> {
941 IntoKeys { inner: self.into_iter() }
944 /// Creates a consuming iterator visiting all the values in arbitrary order.
945 /// The map cannot be used after calling this.
946 /// The iterator element type is `V`.
951 /// #![feature(map_into_keys_values)]
952 /// use std::collections::HashMap;
954 /// let mut map = HashMap::new();
955 /// map.insert("a", 1);
956 /// map.insert("b", 2);
957 /// map.insert("c", 3);
959 /// let vec: Vec<i32> = map.into_values().collect();
962 #[unstable(feature = "map_into_keys_values", issue = "75294")]
963 pub fn into_values(self) -> IntoValues<K, V> {
964 IntoValues { inner: self.into_iter() }
968 impl<K, V, S> HashMap<K, V, S>
972 /// Creates a raw entry builder for the HashMap.
974 /// Raw entries provide the lowest level of control for searching and
975 /// manipulating a map. They must be manually initialized with a hash and
976 /// then manually searched. After this, insertions into a vacant entry
977 /// still require an owned key to be provided.
979 /// Raw entries are useful for such exotic situations as:
981 /// * Hash memoization
982 /// * Deferring the creation of an owned key until it is known to be required
983 /// * Using a search key that doesn't work with the Borrow trait
984 /// * Using custom comparison logic without newtype wrappers
986 /// Because raw entries provide much more low-level control, it's much easier
987 /// to put the HashMap into an inconsistent state which, while memory-safe,
988 /// will cause the map to produce seemingly random results. Higher-level and
989 /// more foolproof APIs like `entry` should be preferred when possible.
991 /// In particular, the hash used to initialized the raw entry must still be
992 /// consistent with the hash of the key that is ultimately stored in the entry.
993 /// This is because implementations of HashMap may need to recompute hashes
994 /// when resizing, at which point only the keys are available.
996 /// Raw entries give mutable access to the keys. This must not be used
997 /// to modify how the key would compare or hash, as the map will not re-evaluate
998 /// where the key should go, meaning the keys may become "lost" if their
999 /// location does not reflect their state. For instance, if you change a key
1000 /// so that the map now contains keys which compare equal, search may start
1001 /// acting erratically, with two keys randomly masking each other. Implementations
1002 /// are free to assume this doesn't happen (within the limits of memory-safety).
1004 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1005 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
1006 RawEntryBuilderMut { map: self }
1009 /// Creates a raw immutable entry builder for the HashMap.
1011 /// Raw entries provide the lowest level of control for searching and
1012 /// manipulating a map. They must be manually initialized with a hash and
1013 /// then manually searched.
1015 /// This is useful for
1016 /// * Hash memoization
1017 /// * Using a search key that doesn't work with the Borrow trait
1018 /// * Using custom comparison logic without newtype wrappers
1020 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1021 /// `get` should be preferred.
1023 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1025 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1026 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
1027 RawEntryBuilder { map: self }
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl<K, V, S> PartialEq for HashMap<K, V, S>
1038 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1039 if self.len() != other.len() {
1043 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 impl<K, V, S> Eq for HashMap<K, V, S>
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<K, V, S> Debug for HashMap<K, V, S>
1062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1063 f.debug_map().entries(self.iter()).finish()
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 impl<K, V, S> Default for HashMap<K, V, S>
1072 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1074 fn default() -> HashMap<K, V, S> {
1075 HashMap::with_hasher(Default::default())
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1082 K: Eq + Hash + Borrow<Q>,
1088 /// Returns a reference to the value corresponding to the supplied key.
1092 /// Panics if the key is not present in the `HashMap`.
1094 fn index(&self, key: &Q) -> &V {
1095 self.get(key).expect("no entry found for key")
1099 /// An iterator over the entries of a `HashMap`.
1101 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1102 /// documentation for more.
1104 /// [`iter`]: HashMap::iter
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 pub struct Iter<'a, K: 'a, V: 'a> {
1107 base: base::Iter<'a, K, V>,
1110 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<K, V> Clone for Iter<'_, K, V> {
1114 fn clone(&self) -> Self {
1115 Iter { base: self.base.clone() }
1119 #[stable(feature = "std_debug", since = "1.16.0")]
1120 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122 f.debug_list().entries(self.clone()).finish()
1126 /// A mutable iterator over the entries of a `HashMap`.
1128 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1129 /// documentation for more.
1131 /// [`iter_mut`]: HashMap::iter_mut
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 pub struct IterMut<'a, K: 'a, V: 'a> {
1134 base: base::IterMut<'a, K, V>,
1137 impl<'a, K, V> IterMut<'a, K, V> {
1138 /// Returns a iterator of references over the remaining items.
1140 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1141 Iter { base: self.base.rustc_iter() }
1145 /// An owning iterator over the entries of a `HashMap`.
1147 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1148 /// (provided by the `IntoIterator` trait). See its documentation for more.
1150 /// [`into_iter`]: IntoIterator::into_iter
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 pub struct IntoIter<K, V> {
1153 base: base::IntoIter<K, V>,
1156 impl<K, V> IntoIter<K, V> {
1157 /// Returns a iterator of references over the remaining items.
1159 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1160 Iter { base: self.base.rustc_iter() }
1164 /// An iterator over the keys of a `HashMap`.
1166 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1167 /// documentation for more.
1169 /// [`keys`]: HashMap::keys
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub struct Keys<'a, K: 'a, V: 'a> {
1172 inner: Iter<'a, K, V>,
1175 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<K, V> Clone for Keys<'_, K, V> {
1179 fn clone(&self) -> Self {
1180 Keys { inner: self.inner.clone() }
1184 #[stable(feature = "std_debug", since = "1.16.0")]
1185 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187 f.debug_list().entries(self.clone()).finish()
1191 /// An iterator over the values of a `HashMap`.
1193 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1194 /// documentation for more.
1196 /// [`values`]: HashMap::values
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub struct Values<'a, K: 'a, V: 'a> {
1199 inner: Iter<'a, K, V>,
1202 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 impl<K, V> Clone for Values<'_, K, V> {
1206 fn clone(&self) -> Self {
1207 Values { inner: self.inner.clone() }
1211 #[stable(feature = "std_debug", since = "1.16.0")]
1212 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214 f.debug_list().entries(self.clone()).finish()
1218 /// A draining iterator over the entries of a `HashMap`.
1220 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1221 /// documentation for more.
1223 /// [`drain`]: HashMap::drain
1224 #[stable(feature = "drain", since = "1.6.0")]
1225 pub struct Drain<'a, K: 'a, V: 'a> {
1226 base: base::Drain<'a, K, V>,
1229 impl<'a, K, V> Drain<'a, K, V> {
1230 /// Returns a iterator of references over the remaining items.
1232 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1233 Iter { base: self.base.rustc_iter() }
1237 /// A draining, filtering iterator over the entries of a `HashMap`.
1239 /// This `struct` is created by the [`drain_filter`] method on [`HashMap`].
1241 /// [`drain_filter`]: HashMap::drain_filter
1242 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1243 pub struct DrainFilter<'a, K, V, F>
1245 F: FnMut(&K, &mut V) -> bool,
1247 base: base::DrainFilter<'a, K, V, F>,
1250 /// A mutable iterator over the values of a `HashMap`.
1252 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1253 /// documentation for more.
1255 /// [`values_mut`]: HashMap::values_mut
1256 #[stable(feature = "map_values_mut", since = "1.10.0")]
1257 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1258 inner: IterMut<'a, K, V>,
1261 /// An owning iterator over the keys of a `HashMap`.
1263 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1264 /// See its documentation for more.
1266 /// [`into_keys`]: HashMap::into_keys
1267 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1268 pub struct IntoKeys<K, V> {
1269 inner: IntoIter<K, V>,
1272 /// An owning iterator over the values of a `HashMap`.
1274 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1275 /// See its documentation for more.
1277 /// [`into_values`]: HashMap::into_values
1278 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1279 pub struct IntoValues<K, V> {
1280 inner: IntoIter<K, V>,
1283 /// A builder for computing where in a HashMap a key-value pair would be stored.
1285 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1287 /// [`HashMap::raw_entry_mut`]: HashMap::raw_entry_mut
1289 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1290 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1291 map: &'a mut HashMap<K, V, S>,
1294 /// A view into a single entry in a map, which may either be vacant or occupied.
1296 /// This is a lower-level version of [`Entry`].
1298 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1299 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1301 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1302 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1303 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1304 /// An occupied entry.
1305 Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1307 Vacant(RawVacantEntryMut<'a, K, V, S>),
1310 /// A view into an occupied entry in a `HashMap`.
1311 /// It is part of the [`RawEntryMut`] enum.
1312 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1313 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1314 base: base::RawOccupiedEntryMut<'a, K, V, S>,
1317 /// A view into a vacant entry in a `HashMap`.
1318 /// It is part of the [`RawEntryMut`] enum.
1319 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1320 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1321 base: base::RawVacantEntryMut<'a, K, V, S>,
1324 /// A builder for computing where in a HashMap a key-value pair would be stored.
1326 /// See the [`HashMap::raw_entry`] docs for usage examples.
1328 /// [`HashMap::raw_entry`]: HashMap::raw_entry
1329 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1330 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1331 map: &'a HashMap<K, V, S>,
1334 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1338 /// Creates a `RawEntryMut` from the given key.
1340 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1341 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1346 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1349 /// Creates a `RawEntryMut` from the given key and its hash.
1351 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1352 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1357 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1360 /// Creates a `RawEntryMut` from the given hash.
1362 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1363 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1365 for<'b> F: FnMut(&'b K) -> bool,
1367 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1371 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1375 /// Access an entry by key.
1377 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1378 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1383 self.map.base.raw_entry().from_key(k)
1386 /// Access an entry by a key and its hash.
1388 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1389 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1394 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1397 /// Access an entry by hash.
1399 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1400 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1402 F: FnMut(&K) -> bool,
1404 self.map.base.raw_entry().from_hash(hash, is_match)
1408 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1409 /// Ensures a value is in the entry by inserting the default if empty, and returns
1410 /// mutable references to the key and value in the entry.
1415 /// #![feature(hash_raw_entry)]
1416 /// use std::collections::HashMap;
1418 /// let mut map: HashMap<&str, u32> = HashMap::new();
1420 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1421 /// assert_eq!(map["poneyland"], 3);
1423 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1424 /// assert_eq!(map["poneyland"], 6);
1427 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1428 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1434 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1435 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1439 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1440 /// and returns mutable references to the key and value in the entry.
1445 /// #![feature(hash_raw_entry)]
1446 /// use std::collections::HashMap;
1448 /// let mut map: HashMap<&str, String> = HashMap::new();
1450 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1451 /// ("poneyland", "hoho".to_string())
1454 /// assert_eq!(map["poneyland"], "hoho".to_string());
1457 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1458 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1460 F: FnOnce() -> (K, V),
1465 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1466 RawEntryMut::Vacant(entry) => {
1467 let (k, v) = default();
1473 /// Provides in-place mutable access to an occupied entry before any
1474 /// potential inserts into the map.
1479 /// #![feature(hash_raw_entry)]
1480 /// use std::collections::HashMap;
1482 /// let mut map: HashMap<&str, u32> = HashMap::new();
1484 /// map.raw_entry_mut()
1485 /// .from_key("poneyland")
1486 /// .and_modify(|_k, v| { *v += 1 })
1487 /// .or_insert("poneyland", 42);
1488 /// assert_eq!(map["poneyland"], 42);
1490 /// map.raw_entry_mut()
1491 /// .from_key("poneyland")
1492 /// .and_modify(|_k, v| { *v += 1 })
1493 /// .or_insert("poneyland", 0);
1494 /// assert_eq!(map["poneyland"], 43);
1497 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1498 pub fn and_modify<F>(self, f: F) -> Self
1500 F: FnOnce(&mut K, &mut V),
1503 RawEntryMut::Occupied(mut entry) => {
1505 let (k, v) = entry.get_key_value_mut();
1508 RawEntryMut::Occupied(entry)
1510 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1515 impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1516 /// Gets a reference to the key in the entry.
1518 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1519 pub fn key(&self) -> &K {
1523 /// Gets a mutable reference to the key in the entry.
1525 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1526 pub fn key_mut(&mut self) -> &mut K {
1530 /// Converts the entry into a mutable reference to the key in the entry
1531 /// with a lifetime bound to the map itself.
1533 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1534 pub fn into_key(self) -> &'a mut K {
1535 self.base.into_key()
1538 /// Gets a reference to the value in the entry.
1540 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1541 pub fn get(&self) -> &V {
1545 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1546 /// with a lifetime bound to the map itself.
1548 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1549 pub fn into_mut(self) -> &'a mut V {
1550 self.base.into_mut()
1553 /// Gets a mutable reference to the value in the entry.
1555 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1556 pub fn get_mut(&mut self) -> &mut V {
1560 /// Gets a reference to the key and value in the entry.
1562 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1563 pub fn get_key_value(&mut self) -> (&K, &V) {
1564 self.base.get_key_value()
1567 /// Gets a mutable reference to the key and value in the entry.
1569 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1570 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1571 self.base.get_key_value_mut()
1574 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
1575 /// with a lifetime bound to the map itself.
1577 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1578 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1579 self.base.into_key_value()
1582 /// Sets the value of the entry, and returns the entry's old value.
1584 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1585 pub fn insert(&mut self, value: V) -> V {
1586 self.base.insert(value)
1589 /// Sets the value of the entry, and returns the entry's old value.
1591 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1592 pub fn insert_key(&mut self, key: K) -> K {
1593 self.base.insert_key(key)
1596 /// Takes the value out of the entry, and returns it.
1598 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1599 pub fn remove(self) -> V {
1603 /// Take the ownership of the key and value from the map.
1605 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1606 pub fn remove_entry(self) -> (K, V) {
1607 self.base.remove_entry()
1611 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1612 /// Sets the value of the entry with the VacantEntry's key,
1613 /// and returns a mutable reference to it.
1615 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1616 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1621 self.base.insert(key, value)
1624 /// Sets the value of the entry with the VacantEntry's key,
1625 /// and returns a mutable reference to it.
1627 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1628 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1633 self.base.insert_hashed_nocheck(hash, key, value)
1637 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1638 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1640 f.debug_struct("RawEntryBuilder").finish()
1644 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1645 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1649 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1654 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1655 impl<K: Debug, V: Debug, S> Debug for RawOccupiedEntryMut<'_, K, V, S> {
1656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1657 f.debug_struct("RawOccupiedEntryMut")
1658 .field("key", self.key())
1659 .field("value", self.get())
1664 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1665 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1667 f.debug_struct("RawVacantEntryMut").finish()
1671 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1672 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1674 f.debug_struct("RawEntryBuilder").finish()
1678 /// A view into a single entry in a map, which may either be vacant or occupied.
1680 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1682 /// [`entry`]: HashMap::entry
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 pub enum Entry<'a, K: 'a, V: 'a> {
1685 /// An occupied entry.
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1694 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1695 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1696 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1698 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1699 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1704 /// A view into an occupied entry in a `HashMap`.
1705 /// It is part of the [`Entry`] enum.
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1708 base: base::RustcOccupiedEntry<'a, K, V>,
1711 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1712 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1714 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
1718 /// A view into a vacant entry in a `HashMap`.
1719 /// It is part of the [`Entry`] enum.
1720 #[stable(feature = "rust1", since = "1.0.0")]
1721 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1722 base: base::RustcVacantEntry<'a, K, V>,
1725 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1726 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1727 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1728 f.debug_tuple("VacantEntry").field(self.key()).finish()
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1734 type Item = (&'a K, &'a V);
1735 type IntoIter = Iter<'a, K, V>;
1738 fn into_iter(self) -> Iter<'a, K, V> {
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1745 type Item = (&'a K, &'a mut V);
1746 type IntoIter = IterMut<'a, K, V>;
1749 fn into_iter(self) -> IterMut<'a, K, V> {
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1757 type IntoIter = IntoIter<K, V>;
1759 /// Creates a consuming iterator, that is, one that moves each key-value
1760 /// pair out of the map in arbitrary order. The map cannot be used after
1766 /// use std::collections::HashMap;
1768 /// let mut map = HashMap::new();
1769 /// map.insert("a", 1);
1770 /// map.insert("b", 2);
1771 /// map.insert("c", 3);
1773 /// // Not possible with .iter()
1774 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1777 fn into_iter(self) -> IntoIter<K, V> {
1778 IntoIter { base: self.base.into_iter() }
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1784 type Item = (&'a K, &'a V);
1787 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1791 fn size_hint(&self) -> (usize, Option<usize>) {
1792 self.base.size_hint()
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1798 fn len(&self) -> usize {
1803 #[stable(feature = "fused", since = "1.26.0")]
1804 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1808 type Item = (&'a K, &'a mut V);
1811 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1815 fn size_hint(&self) -> (usize, Option<usize>) {
1816 self.base.size_hint()
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1822 fn len(&self) -> usize {
1826 #[stable(feature = "fused", since = "1.26.0")]
1827 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1829 #[stable(feature = "std_debug", since = "1.16.0")]
1830 impl<K, V> fmt::Debug for IterMut<'_, K, V>
1835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1836 f.debug_list().entries(self.iter()).finish()
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 impl<K, V> Iterator for IntoIter<K, V> {
1845 fn next(&mut self) -> Option<(K, V)> {
1849 fn size_hint(&self) -> (usize, Option<usize>) {
1850 self.base.size_hint()
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1856 fn len(&self) -> usize {
1860 #[stable(feature = "fused", since = "1.26.0")]
1861 impl<K, V> FusedIterator for IntoIter<K, V> {}
1863 #[stable(feature = "std_debug", since = "1.16.0")]
1864 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
1865 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1866 f.debug_list().entries(self.iter()).finish()
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1875 fn next(&mut self) -> Option<&'a K> {
1876 self.inner.next().map(|(k, _)| k)
1879 fn size_hint(&self) -> (usize, Option<usize>) {
1880 self.inner.size_hint()
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1886 fn len(&self) -> usize {
1890 #[stable(feature = "fused", since = "1.26.0")]
1891 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<'a, K, V> Iterator for Values<'a, K, V> {
1898 fn next(&mut self) -> Option<&'a V> {
1899 self.inner.next().map(|(_, v)| v)
1902 fn size_hint(&self) -> (usize, Option<usize>) {
1903 self.inner.size_hint()
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1909 fn len(&self) -> usize {
1913 #[stable(feature = "fused", since = "1.26.0")]
1914 impl<K, V> FusedIterator for Values<'_, K, V> {}
1916 #[stable(feature = "map_values_mut", since = "1.10.0")]
1917 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1918 type Item = &'a mut V;
1921 fn next(&mut self) -> Option<&'a mut V> {
1922 self.inner.next().map(|(_, v)| v)
1925 fn size_hint(&self) -> (usize, Option<usize>) {
1926 self.inner.size_hint()
1929 #[stable(feature = "map_values_mut", since = "1.10.0")]
1930 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1932 fn len(&self) -> usize {
1936 #[stable(feature = "fused", since = "1.26.0")]
1937 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1939 #[stable(feature = "std_debug", since = "1.16.0")]
1940 impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 f.debug_list().entries(self.inner.iter()).finish()
1950 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1951 impl<K, V> Iterator for IntoKeys<K, V> {
1955 fn next(&mut self) -> Option<K> {
1956 self.inner.next().map(|(k, _)| k)
1959 fn size_hint(&self) -> (usize, Option<usize>) {
1960 self.inner.size_hint()
1963 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1964 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1966 fn len(&self) -> usize {
1970 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1971 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1973 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1974 impl<K: Debug, V: Debug> fmt::Debug for IntoKeys<K, V> {
1975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1976 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
1980 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1981 impl<K, V> Iterator for IntoValues<K, V> {
1985 fn next(&mut self) -> Option<V> {
1986 self.inner.next().map(|(_, v)| v)
1989 fn size_hint(&self) -> (usize, Option<usize>) {
1990 self.inner.size_hint()
1993 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1994 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1996 fn len(&self) -> usize {
2000 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2001 impl<K, V> FusedIterator for IntoValues<K, V> {}
2003 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2004 impl<K: Debug, V: Debug> fmt::Debug for IntoValues<K, V> {
2005 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2006 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2010 #[stable(feature = "drain", since = "1.6.0")]
2011 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2015 fn next(&mut self) -> Option<(K, V)> {
2019 fn size_hint(&self) -> (usize, Option<usize>) {
2020 self.base.size_hint()
2023 #[stable(feature = "drain", since = "1.6.0")]
2024 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2026 fn len(&self) -> usize {
2030 #[stable(feature = "fused", since = "1.26.0")]
2031 impl<K, V> FusedIterator for Drain<'_, K, V> {}
2033 #[stable(feature = "std_debug", since = "1.16.0")]
2034 impl<K, V> fmt::Debug for Drain<'_, K, V>
2039 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2040 f.debug_list().entries(self.iter()).finish()
2044 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2045 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
2047 F: FnMut(&K, &mut V) -> bool,
2052 fn next(&mut self) -> Option<(K, V)> {
2056 fn size_hint(&self) -> (usize, Option<usize>) {
2057 self.base.size_hint()
2061 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2062 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2064 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2065 impl<'a, K, V, F> fmt::Debug for DrainFilter<'a, K, V, F>
2067 F: FnMut(&K, &mut V) -> bool,
2069 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2070 f.pad("DrainFilter { .. }")
2074 impl<'a, K, V> Entry<'a, K, V> {
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 /// Ensures a value is in the entry by inserting the default if empty, and returns
2077 /// a mutable reference to the value in the entry.
2082 /// use std::collections::HashMap;
2084 /// let mut map: HashMap<&str, u32> = HashMap::new();
2086 /// map.entry("poneyland").or_insert(3);
2087 /// assert_eq!(map["poneyland"], 3);
2089 /// *map.entry("poneyland").or_insert(10) *= 2;
2090 /// assert_eq!(map["poneyland"], 6);
2093 pub fn or_insert(self, default: V) -> &'a mut V {
2095 Occupied(entry) => entry.into_mut(),
2096 Vacant(entry) => entry.insert(default),
2100 #[stable(feature = "rust1", since = "1.0.0")]
2101 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2102 /// and returns a mutable reference to the value in the entry.
2107 /// use std::collections::HashMap;
2109 /// let mut map: HashMap<&str, String> = HashMap::new();
2110 /// let s = "hoho".to_string();
2112 /// map.entry("poneyland").or_insert_with(|| s);
2114 /// assert_eq!(map["poneyland"], "hoho".to_string());
2117 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2119 Occupied(entry) => entry.into_mut(),
2120 Vacant(entry) => entry.insert(default()),
2124 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2125 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2126 /// which takes the key as its argument, and returns a mutable reference to the value in the
2132 /// #![feature(or_insert_with_key)]
2133 /// use std::collections::HashMap;
2135 /// let mut map: HashMap<&str, usize> = HashMap::new();
2137 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2139 /// assert_eq!(map["poneyland"], 9);
2142 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2144 Occupied(entry) => entry.into_mut(),
2146 let value = default(entry.key());
2152 /// Returns a reference to this entry's key.
2157 /// use std::collections::HashMap;
2159 /// let mut map: HashMap<&str, u32> = HashMap::new();
2160 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2163 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2164 pub fn key(&self) -> &K {
2166 Occupied(ref entry) => entry.key(),
2167 Vacant(ref entry) => entry.key(),
2171 /// Provides in-place mutable access to an occupied entry before any
2172 /// potential inserts into the map.
2177 /// use std::collections::HashMap;
2179 /// let mut map: HashMap<&str, u32> = HashMap::new();
2181 /// map.entry("poneyland")
2182 /// .and_modify(|e| { *e += 1 })
2184 /// assert_eq!(map["poneyland"], 42);
2186 /// map.entry("poneyland")
2187 /// .and_modify(|e| { *e += 1 })
2189 /// assert_eq!(map["poneyland"], 43);
2192 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2193 pub fn and_modify<F>(self, f: F) -> Self
2198 Occupied(mut entry) => {
2202 Vacant(entry) => Vacant(entry),
2206 /// Sets the value of the entry, and returns an OccupiedEntry.
2211 /// #![feature(entry_insert)]
2212 /// use std::collections::HashMap;
2214 /// let mut map: HashMap<&str, String> = HashMap::new();
2215 /// let entry = map.entry("poneyland").insert("hoho".to_string());
2217 /// assert_eq!(entry.key(), &"poneyland");
2220 #[unstable(feature = "entry_insert", issue = "65225")]
2221 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
2223 Occupied(mut entry) => {
2224 entry.insert(value);
2227 Vacant(entry) => entry.insert_entry(value),
2232 impl<'a, K, V: Default> Entry<'a, K, V> {
2233 #[stable(feature = "entry_or_default", since = "1.28.0")]
2234 /// Ensures a value is in the entry by inserting the default value if empty,
2235 /// and returns a mutable reference to the value in the entry.
2241 /// use std::collections::HashMap;
2243 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2244 /// map.entry("poneyland").or_default();
2246 /// assert_eq!(map["poneyland"], None);
2250 pub fn or_default(self) -> &'a mut V {
2252 Occupied(entry) => entry.into_mut(),
2253 Vacant(entry) => entry.insert(Default::default()),
2258 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2259 /// Gets a reference to the key in the entry.
2264 /// use std::collections::HashMap;
2266 /// let mut map: HashMap<&str, u32> = HashMap::new();
2267 /// map.entry("poneyland").or_insert(12);
2268 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2271 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2272 pub fn key(&self) -> &K {
2276 /// Take the ownership of the key and value from the map.
2281 /// use std::collections::HashMap;
2282 /// use std::collections::hash_map::Entry;
2284 /// let mut map: HashMap<&str, u32> = HashMap::new();
2285 /// map.entry("poneyland").or_insert(12);
2287 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2288 /// // We delete the entry from the map.
2289 /// o.remove_entry();
2292 /// assert_eq!(map.contains_key("poneyland"), false);
2295 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2296 pub fn remove_entry(self) -> (K, V) {
2297 self.base.remove_entry()
2300 /// Gets a reference to the value in the entry.
2305 /// use std::collections::HashMap;
2306 /// use std::collections::hash_map::Entry;
2308 /// let mut map: HashMap<&str, u32> = HashMap::new();
2309 /// map.entry("poneyland").or_insert(12);
2311 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2312 /// assert_eq!(o.get(), &12);
2316 #[stable(feature = "rust1", since = "1.0.0")]
2317 pub fn get(&self) -> &V {
2321 /// Gets a mutable reference to the value in the entry.
2323 /// If you need a reference to the `OccupiedEntry` which may outlive the
2324 /// destruction of the `Entry` value, see [`into_mut`].
2326 /// [`into_mut`]: Self::into_mut
2331 /// use std::collections::HashMap;
2332 /// use std::collections::hash_map::Entry;
2334 /// let mut map: HashMap<&str, u32> = HashMap::new();
2335 /// map.entry("poneyland").or_insert(12);
2337 /// assert_eq!(map["poneyland"], 12);
2338 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2339 /// *o.get_mut() += 10;
2340 /// assert_eq!(*o.get(), 22);
2342 /// // We can use the same Entry multiple times.
2343 /// *o.get_mut() += 2;
2346 /// assert_eq!(map["poneyland"], 24);
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 pub fn get_mut(&mut self) -> &mut V {
2354 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2355 /// with a lifetime bound to the map itself.
2357 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2359 /// [`get_mut`]: Self::get_mut
2364 /// use std::collections::HashMap;
2365 /// use std::collections::hash_map::Entry;
2367 /// let mut map: HashMap<&str, u32> = HashMap::new();
2368 /// map.entry("poneyland").or_insert(12);
2370 /// assert_eq!(map["poneyland"], 12);
2371 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2372 /// *o.into_mut() += 10;
2375 /// assert_eq!(map["poneyland"], 22);
2378 #[stable(feature = "rust1", since = "1.0.0")]
2379 pub fn into_mut(self) -> &'a mut V {
2380 self.base.into_mut()
2383 /// Sets the value of the entry, and returns the entry's old value.
2388 /// use std::collections::HashMap;
2389 /// use std::collections::hash_map::Entry;
2391 /// let mut map: HashMap<&str, u32> = HashMap::new();
2392 /// map.entry("poneyland").or_insert(12);
2394 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2395 /// assert_eq!(o.insert(15), 12);
2398 /// assert_eq!(map["poneyland"], 15);
2401 #[stable(feature = "rust1", since = "1.0.0")]
2402 pub fn insert(&mut self, value: V) -> V {
2403 self.base.insert(value)
2406 /// Takes the value out of the entry, and returns it.
2411 /// use std::collections::HashMap;
2412 /// use std::collections::hash_map::Entry;
2414 /// let mut map: HashMap<&str, u32> = HashMap::new();
2415 /// map.entry("poneyland").or_insert(12);
2417 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2418 /// assert_eq!(o.remove(), 12);
2421 /// assert_eq!(map.contains_key("poneyland"), false);
2424 #[stable(feature = "rust1", since = "1.0.0")]
2425 pub fn remove(self) -> V {
2429 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2430 /// the key used to create this entry.
2435 /// #![feature(map_entry_replace)]
2436 /// use std::collections::hash_map::{Entry, HashMap};
2437 /// use std::rc::Rc;
2439 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2440 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2442 /// let my_key = Rc::new("Stringthing".to_string());
2444 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2445 /// // Also replace the key with a handle to our other key.
2446 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2451 #[unstable(feature = "map_entry_replace", issue = "44286")]
2452 pub fn replace_entry(self, value: V) -> (K, V) {
2453 self.base.replace_entry(value)
2456 /// Replaces the key in the hash map with the key used to create this entry.
2461 /// #![feature(map_entry_replace)]
2462 /// use std::collections::hash_map::{Entry, HashMap};
2463 /// use std::rc::Rc;
2465 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2466 /// let known_strings: Vec<Rc<String>> = Vec::new();
2468 /// // Initialise known strings, run program, etc.
2470 /// reclaim_memory(&mut map, &known_strings);
2472 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2473 /// for s in known_strings {
2474 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2475 /// // Replaces the entry's key with our version of it in `known_strings`.
2476 /// entry.replace_key();
2482 #[unstable(feature = "map_entry_replace", issue = "44286")]
2483 pub fn replace_key(self) -> K {
2484 self.base.replace_key()
2488 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2489 /// Gets a reference to the key that would be used when inserting a value
2490 /// through the `VacantEntry`.
2495 /// use std::collections::HashMap;
2497 /// let mut map: HashMap<&str, u32> = HashMap::new();
2498 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2501 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2502 pub fn key(&self) -> &K {
2506 /// Take ownership of the key.
2511 /// use std::collections::HashMap;
2512 /// use std::collections::hash_map::Entry;
2514 /// let mut map: HashMap<&str, u32> = HashMap::new();
2516 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2521 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2522 pub fn into_key(self) -> K {
2523 self.base.into_key()
2526 /// Sets the value of the entry with the VacantEntry's key,
2527 /// and returns a mutable reference to it.
2532 /// use std::collections::HashMap;
2533 /// use std::collections::hash_map::Entry;
2535 /// let mut map: HashMap<&str, u32> = HashMap::new();
2537 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2540 /// assert_eq!(map["poneyland"], 37);
2543 #[stable(feature = "rust1", since = "1.0.0")]
2544 pub fn insert(self, value: V) -> &'a mut V {
2545 self.base.insert(value)
2548 /// Sets the value of the entry with the VacantEntry's key,
2549 /// and returns an OccupiedEntry.
2554 /// use std::collections::HashMap;
2555 /// use std::collections::hash_map::Entry;
2557 /// let mut map: HashMap<&str, u32> = HashMap::new();
2559 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2562 /// assert_eq!(map["poneyland"], 37);
2565 fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2566 let base = self.base.insert_entry(value);
2567 OccupiedEntry { base }
2571 #[stable(feature = "rust1", since = "1.0.0")]
2572 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2575 S: BuildHasher + Default,
2577 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2578 let mut map = HashMap::with_hasher(Default::default());
2584 /// Inserts all new key-values from the iterator and replaces values with existing
2585 /// keys with new values returned from the iterator.
2586 #[stable(feature = "rust1", since = "1.0.0")]
2587 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2593 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2594 self.base.extend(iter)
2598 fn extend_one(&mut self, (k, v): (K, V)) {
2599 self.base.insert(k, v);
2603 fn extend_reserve(&mut self, additional: usize) {
2604 // self.base.extend_reserve(additional);
2605 // FIXME: hashbrown should implement this method.
2606 // But until then, use the same reservation logic:
2608 // Reserve the entire hint lower bound if the map is empty.
2609 // Otherwise reserve half the hint (rounded up), so the map
2610 // will only resize twice in the worst case.
2611 let reserve = if self.is_empty() { additional } else { (additional + 1) / 2 };
2612 self.base.reserve(reserve);
2616 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2617 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2619 K: Eq + Hash + Copy,
2624 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2625 self.base.extend(iter)
2629 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2630 self.base.insert(k, v);
2634 fn extend_reserve(&mut self, additional: usize) {
2635 Extend::<(K, V)>::extend_reserve(self, additional)
2639 /// `RandomState` is the default state for [`HashMap`] types.
2641 /// A particular instance `RandomState` will create the same instances of
2642 /// [`Hasher`], but the hashers created by two different `RandomState`
2643 /// instances are unlikely to produce the same result for the same values.
2648 /// use std::collections::HashMap;
2649 /// use std::collections::hash_map::RandomState;
2651 /// let s = RandomState::new();
2652 /// let mut map = HashMap::with_hasher(s);
2653 /// map.insert(1, 2);
2656 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2657 pub struct RandomState {
2663 /// Constructs a new `RandomState` that is initialized with random keys.
2668 /// use std::collections::hash_map::RandomState;
2670 /// let s = RandomState::new();
2673 #[allow(deprecated)]
2675 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2676 pub fn new() -> RandomState {
2677 // Historically this function did not cache keys from the OS and instead
2678 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2679 // was discovered, however, that because we re-seed the thread-local RNG
2680 // from the OS periodically that this can cause excessive slowdown when
2681 // many hash maps are created on a thread. To solve this performance
2682 // trap we cache the first set of randomly generated keys per-thread.
2684 // Later in #36481 it was discovered that exposing a deterministic
2685 // iteration order allows a form of DOS attack. To counter that we
2686 // increment one of the seeds on every RandomState creation, giving
2687 // every corresponding HashMap a different iteration order.
2688 thread_local!(static KEYS: Cell<(u64, u64)> = {
2689 Cell::new(sys::hashmap_random_keys())
2693 let (k0, k1) = keys.get();
2694 keys.set((k0.wrapping_add(1), k1));
2695 RandomState { k0, k1 }
2700 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2701 impl BuildHasher for RandomState {
2702 type Hasher = DefaultHasher;
2704 #[allow(deprecated)]
2705 fn build_hasher(&self) -> DefaultHasher {
2706 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2710 /// The default [`Hasher`] used by [`RandomState`].
2712 /// The internal algorithm is not specified, and so it and its hashes should
2713 /// not be relied upon over releases.
2714 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2715 #[allow(deprecated)]
2716 #[derive(Clone, Debug)]
2717 pub struct DefaultHasher(SipHasher13);
2719 impl DefaultHasher {
2720 /// Creates a new `DefaultHasher`.
2722 /// This hasher is not guaranteed to be the same as all other
2723 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2724 /// instances created through `new` or `default`.
2725 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2726 #[allow(deprecated)]
2727 pub fn new() -> DefaultHasher {
2728 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2732 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2733 impl Default for DefaultHasher {
2734 // FIXME: here should link `new` to [DefaultHasher::new], but it occurs intra-doc link
2735 // resolution failure when re-exporting libstd items. When #56922 fixed,
2736 // link `new` to [DefaultHasher::new] again.
2737 /// Creates a new `DefaultHasher` using `new`.
2738 /// See its documentation for more.
2739 fn default() -> DefaultHasher {
2740 DefaultHasher::new()
2744 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2745 impl Hasher for DefaultHasher {
2747 fn write(&mut self, msg: &[u8]) {
2752 fn finish(&self) -> u64 {
2757 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2758 impl Default for RandomState {
2759 /// Constructs a new `RandomState`.
2761 fn default() -> RandomState {
2766 #[stable(feature = "std_debug", since = "1.16.0")]
2767 impl fmt::Debug for RandomState {
2768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2769 f.pad("RandomState { .. }")
2774 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2776 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2777 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2782 pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
2784 hashbrown::TryReserveError::CapacityOverflow => TryReserveError::CapacityOverflow,
2785 hashbrown::TryReserveError::AllocError { layout } => {
2786 TryReserveError::AllocError { layout, non_exhaustive: () }
2792 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
2793 raw: base::RawEntryMut<'a, K, V, S>,
2794 ) -> RawEntryMut<'a, K, V, S> {
2796 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
2797 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
2802 fn assert_covariance() {
2803 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2806 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2809 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2812 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2815 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2818 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2821 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2824 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2827 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2830 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2834 d: Drain<'static, &'static str, &'static str>,
2835 ) -> Drain<'new, &'new str, &'new str> {