1 // ignore-tidy-filelength
8 use hashbrown::hash_map as base;
10 use crate::borrow::Borrow;
11 use crate::cell::Cell;
12 use crate::collections::TryReserveError;
13 use crate::fmt::{self, Debug};
15 use crate::hash::{BuildHasher, Hash, Hasher, SipHasher13};
16 use crate::iter::{FromIterator, FusedIterator};
17 use crate::ops::Index;
20 /// A hash map implemented with quadratic probing and SIMD lookup.
22 /// By default, `HashMap` uses a hashing algorithm selected to provide
23 /// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
24 /// reasonable best-effort is made to generate this seed from a high quality,
25 /// secure source of randomness provided by the host without blocking the
26 /// program. Because of this, the randomness of the seed depends on the output
27 /// quality of the system's random number generator when the seed is created.
28 /// In particular, seeds generated when the system's entropy pool is abnormally
29 /// low such as during system boot may be of a lower quality.
31 /// The default hashing algorithm is currently SipHash 1-3, though this is
32 /// subject to change at any point in the future. While its performance is very
33 /// competitive for medium sized keys, other hashing algorithms will outperform
34 /// it for small keys such as integers as well as large keys such as long
35 /// strings, though those algorithms will typically *not* protect against
36 /// attacks such as HashDoS.
38 /// The hashing algorithm can be replaced on a per-`HashMap` basis using the
39 /// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods.
40 /// There are many alternative [hashing algorithms available on crates.io].
42 /// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
43 /// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
44 /// If you implement these yourself, it is important that the following
48 /// k1 == k2 -> hash(k1) == hash(k2)
51 /// In other words, if two keys are equal, their hashes must be equal.
53 /// It is a logic error for a key to be modified in such a way that the key's
54 /// hash, as determined by the [`Hash`] trait, or its equality, as determined by
55 /// the [`Eq`] trait, changes while it is in the map. This is normally only
56 /// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
57 /// The behavior resulting from such a logic error is not specified, but will
58 /// not result in undefined behavior. This could include panics, incorrect results,
59 /// aborts, memory leaks, and non-termination.
61 /// The hash table implementation is a Rust port of Google's [SwissTable].
62 /// The original C++ version of SwissTable can be found [here], and this
63 /// [CppCon talk] gives an overview of how the algorithm works.
65 /// [hashing algorithms available on crates.io]: https://crates.io/keywords/hasher
66 /// [SwissTable]: https://abseil.io/blog/20180927-swisstables
67 /// [here]: https://github.com/abseil/abseil-cpp/blob/master/absl/container/internal/raw_hash_set.h
68 /// [CppCon talk]: https://www.youtube.com/watch?v=ncHmEUmJZf4
73 /// use std::collections::HashMap;
75 /// // Type inference lets us omit an explicit type signature (which
76 /// // would be `HashMap<String, String>` in this example).
77 /// let mut book_reviews = HashMap::new();
79 /// // Review some books.
80 /// book_reviews.insert(
81 /// "Adventures of Huckleberry Finn".to_string(),
82 /// "My favorite book.".to_string(),
84 /// book_reviews.insert(
85 /// "Grimms' Fairy Tales".to_string(),
86 /// "Masterpiece.".to_string(),
88 /// book_reviews.insert(
89 /// "Pride and Prejudice".to_string(),
90 /// "Very enjoyable.".to_string(),
92 /// book_reviews.insert(
93 /// "The Adventures of Sherlock Holmes".to_string(),
94 /// "Eye lyked it alot.".to_string(),
97 /// // Check for a specific one.
98 /// // When collections store owned values (String), they can still be
99 /// // queried using references (&str).
100 /// if !book_reviews.contains_key("Les Misérables") {
101 /// println!("We've got {} reviews, but Les Misérables ain't one.",
102 /// book_reviews.len());
105 /// // oops, this review has a lot of spelling mistakes, let's delete it.
106 /// book_reviews.remove("The Adventures of Sherlock Holmes");
108 /// // Look up the values associated with some keys.
109 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
110 /// for &book in &to_find {
111 /// match book_reviews.get(book) {
112 /// Some(review) => println!("{}: {}", book, review),
113 /// None => println!("{} is unreviewed.", book)
117 /// // Look up the value for a key (will panic if the key is not found).
118 /// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
120 /// // Iterate over everything.
121 /// for (book, review) in &book_reviews {
122 /// println!("{}: \"{}\"", book, review);
126 /// `HashMap` also implements an [`Entry API`](#method.entry), which allows
127 /// for more complex methods of getting, setting, updating and removing keys and
131 /// use std::collections::HashMap;
133 /// // type inference lets us omit an explicit type signature (which
134 /// // would be `HashMap<&str, u8>` in this example).
135 /// let mut player_stats = HashMap::new();
137 /// fn random_stat_buff() -> u8 {
138 /// // could actually return some random value here - let's just return
139 /// // some fixed value for now
143 /// // insert a key only if it doesn't already exist
144 /// player_stats.entry("health").or_insert(100);
146 /// // insert a key using a function that provides a new value only if it
147 /// // doesn't already exist
148 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
150 /// // update a key, guarding against the key possibly not being set
151 /// let stat = player_stats.entry("attack").or_insert(100);
152 /// *stat += random_stat_buff();
155 /// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
156 /// We must also derive [`PartialEq`].
158 /// [`RefCell`]: crate::cell::RefCell
159 /// [`Cell`]: crate::cell::Cell
160 /// [`default`]: Default::default
161 /// [`with_hasher`]: Self::with_hasher
162 /// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
165 /// use std::collections::HashMap;
167 /// #[derive(Hash, Eq, PartialEq, Debug)]
174 /// /// Creates a new Viking.
175 /// fn new(name: &str, country: &str) -> Viking {
176 /// Viking { name: name.to_string(), country: country.to_string() }
180 /// // Use a HashMap to store the vikings' health points.
181 /// let mut vikings = HashMap::new();
183 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
184 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
185 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
187 /// // Use derived implementation to print the status of the vikings.
188 /// for (viking, health) in &vikings {
189 /// println!("{:?} has {} hp", viking, health);
193 /// A `HashMap` with fixed list of elements can be initialized from an array:
196 /// use std::collections::HashMap;
198 /// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
199 /// .iter().cloned().collect();
200 /// // use the values stored in map
203 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_type")]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct HashMap<K, V, S = RandomState> {
206 base: base::HashMap<K, V, S>,
209 impl<K, V> HashMap<K, V, RandomState> {
210 /// Creates an empty `HashMap`.
212 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
213 /// is first inserted into.
218 /// use std::collections::HashMap;
219 /// let mut map: HashMap<&str, i32> = HashMap::new();
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn new() -> HashMap<K, V, RandomState> {
227 /// Creates an empty `HashMap` with the specified capacity.
229 /// The hash map will be able to hold at least `capacity` elements without
230 /// reallocating. If `capacity` is 0, the hash map will not allocate.
235 /// use std::collections::HashMap;
236 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
239 #[stable(feature = "rust1", since = "1.0.0")]
240 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
241 HashMap::with_capacity_and_hasher(capacity, Default::default())
245 impl<K, V, S> HashMap<K, V, S> {
246 /// Creates an empty `HashMap` which will use the given hash builder to hash
249 /// The created map has the default initial capacity.
251 /// Warning: `hash_builder` is normally randomly generated, and
252 /// is designed to allow HashMaps to be resistant to attacks that
253 /// cause many collisions and very poor performance. Setting it
254 /// manually using this function can expose a DoS attack vector.
256 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
257 /// the HashMap to be useful, see its documentation for details.
262 /// use std::collections::HashMap;
263 /// use std::collections::hash_map::RandomState;
265 /// let s = RandomState::new();
266 /// let mut map = HashMap::with_hasher(s);
267 /// map.insert(1, 2);
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 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
301 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
302 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) }
305 /// Returns the number of elements the map can hold without reallocating.
307 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
308 /// more, but is guaranteed to be able to hold at least this many.
313 /// use std::collections::HashMap;
314 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
315 /// assert!(map.capacity() >= 100);
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn capacity(&self) -> usize {
323 /// An iterator visiting all keys in arbitrary order.
324 /// The iterator element type is `&'a K`.
329 /// use std::collections::HashMap;
331 /// let mut map = HashMap::new();
332 /// map.insert("a", 1);
333 /// map.insert("b", 2);
334 /// map.insert("c", 3);
336 /// for key in map.keys() {
337 /// println!("{}", key);
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn keys(&self) -> Keys<'_, K, V> {
342 Keys { inner: self.iter() }
345 /// An iterator visiting all values in arbitrary order.
346 /// The iterator element type is `&'a V`.
351 /// use std::collections::HashMap;
353 /// let mut map = HashMap::new();
354 /// map.insert("a", 1);
355 /// map.insert("b", 2);
356 /// map.insert("c", 3);
358 /// for val in map.values() {
359 /// println!("{}", val);
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn values(&self) -> Values<'_, K, V> {
364 Values { inner: self.iter() }
367 /// An iterator visiting all values mutably in arbitrary order.
368 /// The iterator element type is `&'a mut V`.
373 /// use std::collections::HashMap;
375 /// let mut map = HashMap::new();
377 /// map.insert("a", 1);
378 /// map.insert("b", 2);
379 /// map.insert("c", 3);
381 /// for val in map.values_mut() {
382 /// *val = *val + 10;
385 /// for val in map.values() {
386 /// println!("{}", val);
389 #[stable(feature = "map_values_mut", since = "1.10.0")]
390 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
391 ValuesMut { inner: self.iter_mut() }
394 /// An iterator visiting all key-value pairs in arbitrary order.
395 /// The iterator element type is `(&'a K, &'a V)`.
400 /// use std::collections::HashMap;
402 /// let mut map = HashMap::new();
403 /// map.insert("a", 1);
404 /// map.insert("b", 2);
405 /// map.insert("c", 3);
407 /// for (key, val) in map.iter() {
408 /// println!("key: {} val: {}", key, val);
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn iter(&self) -> Iter<'_, K, V> {
413 Iter { base: self.base.iter() }
416 /// An iterator visiting all key-value pairs in arbitrary order,
417 /// with mutable references to the values.
418 /// The iterator element type is `(&'a K, &'a mut V)`.
423 /// use std::collections::HashMap;
425 /// let mut map = HashMap::new();
426 /// map.insert("a", 1);
427 /// map.insert("b", 2);
428 /// map.insert("c", 3);
430 /// // Update all values
431 /// for (_, val) in map.iter_mut() {
435 /// for (key, val) in &map {
436 /// println!("key: {} val: {}", key, val);
439 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
441 IterMut { base: self.base.iter_mut() }
444 /// Returns the number of elements in the map.
449 /// use std::collections::HashMap;
451 /// let mut a = HashMap::new();
452 /// assert_eq!(a.len(), 0);
453 /// a.insert(1, "a");
454 /// assert_eq!(a.len(), 1);
456 #[doc(alias = "length")]
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn len(&self) -> usize {
462 /// Returns `true` if the map contains no elements.
467 /// use std::collections::HashMap;
469 /// let mut a = HashMap::new();
470 /// assert!(a.is_empty());
471 /// a.insert(1, "a");
472 /// assert!(!a.is_empty());
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn is_empty(&self) -> bool {
480 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
481 /// allocated memory for reuse.
486 /// use std::collections::HashMap;
488 /// let mut a = HashMap::new();
489 /// a.insert(1, "a");
490 /// a.insert(2, "b");
492 /// for (k, v) in a.drain().take(1) {
493 /// assert!(k == 1 || k == 2);
494 /// assert!(v == "a" || v == "b");
497 /// assert!(a.is_empty());
500 #[stable(feature = "drain", since = "1.6.0")]
501 pub fn drain(&mut self) -> Drain<'_, K, V> {
502 Drain { base: self.base.drain() }
505 /// Creates an iterator which uses a closure to determine if an element should be removed.
507 /// If the closure returns true, the element is removed from the map and yielded.
508 /// If the closure returns false, or panics, the element remains in the map and will not be
511 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
512 /// whether you choose to keep or remove it.
514 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
515 /// elements will still be subjected to the closure and removed and dropped if it returns true.
517 /// It is unspecified how many more elements will be subjected to the closure
518 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
519 /// or if the `DrainFilter` value is leaked.
523 /// Splitting a map into even and odd keys, reusing the original map:
526 /// #![feature(hash_drain_filter)]
527 /// use std::collections::HashMap;
529 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
530 /// let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
532 /// let mut evens = drained.keys().copied().collect::<Vec<_>>();
533 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
537 /// assert_eq!(evens, vec![0, 2, 4, 6]);
538 /// assert_eq!(odds, vec![1, 3, 5, 7]);
541 #[unstable(feature = "hash_drain_filter", issue = "59618")]
542 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
544 F: FnMut(&K, &mut V) -> bool,
546 DrainFilter { base: self.base.drain_filter(pred) }
549 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
555 /// use std::collections::HashMap;
557 /// let mut a = HashMap::new();
558 /// a.insert(1, "a");
560 /// assert!(a.is_empty());
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn clear(&mut self) {
568 /// Returns a reference to the map's [`BuildHasher`].
573 /// use std::collections::HashMap;
574 /// use std::collections::hash_map::RandomState;
576 /// let hasher = RandomState::new();
577 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
578 /// let hasher: &RandomState = map.hasher();
581 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
582 pub fn hasher(&self) -> &S {
587 impl<K, V, S> HashMap<K, V, S>
592 /// Reserves capacity for at least `additional` more elements to be inserted
593 /// in the `HashMap`. The collection may reserve more space to avoid
594 /// frequent reallocations.
598 /// Panics if the new allocation size overflows [`usize`].
603 /// use std::collections::HashMap;
604 /// let mut map: HashMap<&str, i32> = HashMap::new();
608 #[stable(feature = "rust1", since = "1.0.0")]
609 pub fn reserve(&mut self, additional: usize) {
610 self.base.reserve(additional)
613 /// Tries to reserve capacity for at least `additional` more elements to be inserted
614 /// in the given `HashMap<K, V>`. The collection may reserve more space to avoid
615 /// frequent reallocations.
619 /// If the capacity overflows, or the allocator reports a failure, then an error
625 /// #![feature(try_reserve)]
626 /// use std::collections::HashMap;
628 /// let mut map: HashMap<&str, isize> = HashMap::new();
629 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
632 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
633 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
634 self.base.try_reserve(additional).map_err(map_try_reserve_error)
637 /// Shrinks the capacity of the map as much as possible. It will drop
638 /// down as much as possible while maintaining the internal rules
639 /// and possibly leaving some space in accordance with the resize policy.
644 /// use std::collections::HashMap;
646 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
647 /// map.insert(1, 2);
648 /// map.insert(3, 4);
649 /// assert!(map.capacity() >= 100);
650 /// map.shrink_to_fit();
651 /// assert!(map.capacity() >= 2);
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn shrink_to_fit(&mut self) {
656 self.base.shrink_to_fit();
659 /// Shrinks the capacity of the map with a lower limit. It will drop
660 /// down no lower than the supplied limit while maintaining the internal rules
661 /// and possibly leaving some space in accordance with the resize policy.
663 /// If the current capacity is less than the lower limit, this is a no-op.
668 /// #![feature(shrink_to)]
669 /// use std::collections::HashMap;
671 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
672 /// map.insert(1, 2);
673 /// map.insert(3, 4);
674 /// assert!(map.capacity() >= 100);
675 /// map.shrink_to(10);
676 /// assert!(map.capacity() >= 10);
677 /// map.shrink_to(0);
678 /// assert!(map.capacity() >= 2);
681 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
682 pub fn shrink_to(&mut self, min_capacity: usize) {
683 self.base.shrink_to(min_capacity);
686 /// Gets the given key's corresponding entry in the map for in-place manipulation.
691 /// use std::collections::HashMap;
693 /// let mut letters = HashMap::new();
695 /// for ch in "a short treatise on fungi".chars() {
696 /// let counter = letters.entry(ch).or_insert(0);
700 /// assert_eq!(letters[&'s'], 2);
701 /// assert_eq!(letters[&'t'], 3);
702 /// assert_eq!(letters[&'u'], 1);
703 /// assert_eq!(letters.get(&'y'), None);
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
708 map_entry(self.base.rustc_entry(key))
711 /// Returns a reference to the value corresponding to the key.
713 /// The key may be any borrowed form of the map's key type, but
714 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
720 /// use std::collections::HashMap;
722 /// let mut map = HashMap::new();
723 /// map.insert(1, "a");
724 /// assert_eq!(map.get(&1), Some(&"a"));
725 /// assert_eq!(map.get(&2), None);
727 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
737 /// Returns the key-value pair corresponding to the supplied key.
739 /// The supplied key may be any borrowed form of the map's key type, but
740 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
746 /// use std::collections::HashMap;
748 /// let mut map = HashMap::new();
749 /// map.insert(1, "a");
750 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
751 /// assert_eq!(map.get_key_value(&2), None);
754 #[stable(feature = "map_get_key_value", since = "1.40.0")]
755 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
760 self.base.get_key_value(k)
763 /// Returns `true` if the map contains a value for the specified key.
765 /// The key may be any borrowed form of the map's key type, but
766 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
772 /// use std::collections::HashMap;
774 /// let mut map = HashMap::new();
775 /// map.insert(1, "a");
776 /// assert_eq!(map.contains_key(&1), true);
777 /// assert_eq!(map.contains_key(&2), false);
780 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
786 self.base.contains_key(k)
789 /// Returns a mutable reference to the value corresponding to the key.
791 /// The key may be any borrowed form of the map's key type, but
792 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
798 /// use std::collections::HashMap;
800 /// let mut map = HashMap::new();
801 /// map.insert(1, "a");
802 /// if let Some(x) = map.get_mut(&1) {
805 /// assert_eq!(map[&1], "b");
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
817 /// Inserts a key-value pair into the map.
819 /// If the map did not have this key present, [`None`] is returned.
821 /// If the map did have this key present, the value is updated, and the old
822 /// value is returned. The key is not updated, though; this matters for
823 /// types that can be `==` without being identical. See the [module-level
824 /// documentation] for more.
826 /// [module-level documentation]: crate::collections#insert-and-complex-keys
831 /// use std::collections::HashMap;
833 /// let mut map = HashMap::new();
834 /// assert_eq!(map.insert(37, "a"), None);
835 /// assert_eq!(map.is_empty(), false);
837 /// map.insert(37, "b");
838 /// assert_eq!(map.insert(37, "c"), Some("b"));
839 /// assert_eq!(map[&37], "c");
842 #[stable(feature = "rust1", since = "1.0.0")]
843 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
844 self.base.insert(k, v)
847 /// Tries to insert a key-value pair into the map, and returns
848 /// a mutable reference to the value in the entry.
850 /// If the map already had this key present, nothing is updated, and
851 /// an error containing the occupied entry and the value is returned.
858 /// #![feature(map_try_insert)]
860 /// use std::collections::HashMap;
862 /// let mut map = HashMap::new();
863 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
865 /// let err = map.try_insert(37, "b").unwrap_err();
866 /// assert_eq!(err.entry.key(), &37);
867 /// assert_eq!(err.entry.get(), &"a");
868 /// assert_eq!(err.value, "b");
870 #[unstable(feature = "map_try_insert", issue = "82766")]
871 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>> {
872 match self.entry(key) {
873 Occupied(entry) => Err(OccupiedError { entry, value }),
874 Vacant(entry) => Ok(entry.insert(value)),
878 /// Removes a key from the map, returning the value at the key if the key
879 /// was previously in the map.
881 /// The key may be any borrowed form of the map's key type, but
882 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
888 /// use std::collections::HashMap;
890 /// let mut map = HashMap::new();
891 /// map.insert(1, "a");
892 /// assert_eq!(map.remove(&1), Some("a"));
893 /// assert_eq!(map.remove(&1), None);
895 #[doc(alias = "delete")]
897 #[stable(feature = "rust1", since = "1.0.0")]
898 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
906 /// Removes a key from the map, returning the stored key and value if the
907 /// key was previously in the map.
909 /// The key may be any borrowed form of the map's key type, but
910 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
916 /// use std::collections::HashMap;
919 /// let mut map = HashMap::new();
920 /// map.insert(1, "a");
921 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
922 /// assert_eq!(map.remove(&1), None);
926 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
927 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
932 self.base.remove_entry(k)
935 /// Retains only the elements specified by the predicate.
937 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
942 /// use std::collections::HashMap;
944 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
945 /// map.retain(|&k, _| k % 2 == 0);
946 /// assert_eq!(map.len(), 4);
949 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
950 pub fn retain<F>(&mut self, f: F)
952 F: FnMut(&K, &mut V) -> bool,
957 /// Creates a consuming iterator visiting all the keys in arbitrary order.
958 /// The map cannot be used after calling this.
959 /// The iterator element type is `K`.
964 /// #![feature(map_into_keys_values)]
965 /// use std::collections::HashMap;
967 /// let mut map = HashMap::new();
968 /// map.insert("a", 1);
969 /// map.insert("b", 2);
970 /// map.insert("c", 3);
972 /// let vec: Vec<&str> = map.into_keys().collect();
975 #[unstable(feature = "map_into_keys_values", issue = "75294")]
976 pub fn into_keys(self) -> IntoKeys<K, V> {
977 IntoKeys { inner: self.into_iter() }
980 /// Creates a consuming iterator visiting all the values in arbitrary order.
981 /// The map cannot be used after calling this.
982 /// The iterator element type is `V`.
987 /// #![feature(map_into_keys_values)]
988 /// use std::collections::HashMap;
990 /// let mut map = HashMap::new();
991 /// map.insert("a", 1);
992 /// map.insert("b", 2);
993 /// map.insert("c", 3);
995 /// let vec: Vec<i32> = map.into_values().collect();
998 #[unstable(feature = "map_into_keys_values", issue = "75294")]
999 pub fn into_values(self) -> IntoValues<K, V> {
1000 IntoValues { inner: self.into_iter() }
1004 impl<K, V, S> HashMap<K, V, S>
1008 /// Creates a raw entry builder for the HashMap.
1010 /// Raw entries provide the lowest level of control for searching and
1011 /// manipulating a map. They must be manually initialized with a hash and
1012 /// then manually searched. After this, insertions into a vacant entry
1013 /// still require an owned key to be provided.
1015 /// Raw entries are useful for such exotic situations as:
1017 /// * Hash memoization
1018 /// * Deferring the creation of an owned key until it is known to be required
1019 /// * Using a search key that doesn't work with the Borrow trait
1020 /// * Using custom comparison logic without newtype wrappers
1022 /// Because raw entries provide much more low-level control, it's much easier
1023 /// to put the HashMap into an inconsistent state which, while memory-safe,
1024 /// will cause the map to produce seemingly random results. Higher-level and
1025 /// more foolproof APIs like `entry` should be preferred when possible.
1027 /// In particular, the hash used to initialized the raw entry must still be
1028 /// consistent with the hash of the key that is ultimately stored in the entry.
1029 /// This is because implementations of HashMap may need to recompute hashes
1030 /// when resizing, at which point only the keys are available.
1032 /// Raw entries give mutable access to the keys. This must not be used
1033 /// to modify how the key would compare or hash, as the map will not re-evaluate
1034 /// where the key should go, meaning the keys may become "lost" if their
1035 /// location does not reflect their state. For instance, if you change a key
1036 /// so that the map now contains keys which compare equal, search may start
1037 /// acting erratically, with two keys randomly masking each other. Implementations
1038 /// are free to assume this doesn't happen (within the limits of memory-safety).
1040 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1041 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
1042 RawEntryBuilderMut { map: self }
1045 /// Creates a raw immutable entry builder for the HashMap.
1047 /// Raw entries provide the lowest level of control for searching and
1048 /// manipulating a map. They must be manually initialized with a hash and
1049 /// then manually searched.
1051 /// This is useful for
1052 /// * Hash memoization
1053 /// * Using a search key that doesn't work with the Borrow trait
1054 /// * Using custom comparison logic without newtype wrappers
1056 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1057 /// `get` should be preferred.
1059 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1061 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1062 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
1063 RawEntryBuilder { map: self }
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 impl<K, V, S> Clone for HashMap<K, V, S>
1075 fn clone(&self) -> Self {
1076 Self { base: self.base.clone() }
1080 fn clone_from(&mut self, other: &Self) {
1081 self.base.clone_from(&other.base);
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<K, V, S> PartialEq for HashMap<K, V, S>
1092 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1093 if self.len() != other.len() {
1097 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl<K, V, S> Eq for HashMap<K, V, S>
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<K, V, S> Debug for HashMap<K, V, S>
1116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1117 f.debug_map().entries(self.iter()).finish()
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 impl<K, V, S> Default for HashMap<K, V, S>
1126 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1128 fn default() -> HashMap<K, V, S> {
1129 HashMap::with_hasher(Default::default())
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1136 K: Eq + Hash + Borrow<Q>,
1142 /// Returns a reference to the value corresponding to the supplied key.
1146 /// Panics if the key is not present in the `HashMap`.
1148 fn index(&self, key: &Q) -> &V {
1149 self.get(key).expect("no entry found for key")
1153 /// An iterator over the entries of a `HashMap`.
1155 /// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1156 /// documentation for more.
1158 /// [`iter`]: HashMap::iter
1163 /// use std::collections::HashMap;
1165 /// let mut map = HashMap::new();
1166 /// map.insert("a", 1);
1167 /// let iter = map.iter();
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 pub struct Iter<'a, K: 'a, V: 'a> {
1171 base: base::Iter<'a, K, V>,
1174 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1175 #[stable(feature = "rust1", since = "1.0.0")]
1176 impl<K, V> Clone for Iter<'_, K, V> {
1178 fn clone(&self) -> Self {
1179 Iter { base: self.base.clone() }
1183 #[stable(feature = "std_debug", since = "1.16.0")]
1184 impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1186 f.debug_list().entries(self.clone()).finish()
1190 /// A mutable iterator over the entries of a `HashMap`.
1192 /// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1193 /// documentation for more.
1195 /// [`iter_mut`]: HashMap::iter_mut
1200 /// use std::collections::HashMap;
1202 /// let mut map = HashMap::new();
1203 /// map.insert("a", 1);
1204 /// let iter = map.iter_mut();
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 pub struct IterMut<'a, K: 'a, V: 'a> {
1208 base: base::IterMut<'a, K, V>,
1211 impl<'a, K, V> IterMut<'a, K, V> {
1212 /// Returns a iterator of references over the remaining items.
1214 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1215 Iter { base: self.base.rustc_iter() }
1219 /// An owning iterator over the entries of a `HashMap`.
1221 /// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1222 /// (provided by the `IntoIterator` trait). See its documentation for more.
1224 /// [`into_iter`]: IntoIterator::into_iter
1229 /// use std::collections::HashMap;
1231 /// let mut map = HashMap::new();
1232 /// map.insert("a", 1);
1233 /// let iter = map.into_iter();
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 pub struct IntoIter<K, V> {
1237 base: base::IntoIter<K, V>,
1240 impl<K, V> IntoIter<K, V> {
1241 /// Returns a iterator of references over the remaining items.
1243 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1244 Iter { base: self.base.rustc_iter() }
1248 /// An iterator over the keys of a `HashMap`.
1250 /// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1251 /// documentation for more.
1253 /// [`keys`]: HashMap::keys
1258 /// use std::collections::HashMap;
1260 /// let mut map = HashMap::new();
1261 /// map.insert("a", 1);
1262 /// let iter_keys = map.keys();
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub struct Keys<'a, K: 'a, V: 'a> {
1266 inner: Iter<'a, K, V>,
1269 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl<K, V> Clone for Keys<'_, K, V> {
1273 fn clone(&self) -> Self {
1274 Keys { inner: self.inner.clone() }
1278 #[stable(feature = "std_debug", since = "1.16.0")]
1279 impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1281 f.debug_list().entries(self.clone()).finish()
1285 /// An iterator over the values of a `HashMap`.
1287 /// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1288 /// documentation for more.
1290 /// [`values`]: HashMap::values
1295 /// use std::collections::HashMap;
1297 /// let mut map = HashMap::new();
1298 /// map.insert("a", 1);
1299 /// let iter_values = map.values();
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub struct Values<'a, K: 'a, V: 'a> {
1303 inner: Iter<'a, K, V>,
1306 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 impl<K, V> Clone for Values<'_, K, V> {
1310 fn clone(&self) -> Self {
1311 Values { inner: self.inner.clone() }
1315 #[stable(feature = "std_debug", since = "1.16.0")]
1316 impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1318 f.debug_list().entries(self.clone()).finish()
1322 /// A draining iterator over the entries of a `HashMap`.
1324 /// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1325 /// documentation for more.
1327 /// [`drain`]: HashMap::drain
1332 /// use std::collections::HashMap;
1334 /// let mut map = HashMap::new();
1335 /// map.insert("a", 1);
1336 /// let iter = map.drain();
1338 #[stable(feature = "drain", since = "1.6.0")]
1339 pub struct Drain<'a, K: 'a, V: 'a> {
1340 base: base::Drain<'a, K, V>,
1343 impl<'a, K, V> Drain<'a, K, V> {
1344 /// Returns a iterator of references over the remaining items.
1346 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1347 Iter { base: self.base.rustc_iter() }
1351 /// A draining, filtering iterator over the entries of a `HashMap`.
1353 /// This `struct` is created by the [`drain_filter`] method on [`HashMap`].
1355 /// [`drain_filter`]: HashMap::drain_filter
1360 /// #![feature(hash_drain_filter)]
1362 /// use std::collections::HashMap;
1364 /// let mut map = HashMap::new();
1365 /// map.insert("a", 1);
1366 /// let iter = map.drain_filter(|_k, v| *v % 2 == 0);
1368 #[unstable(feature = "hash_drain_filter", issue = "59618")]
1369 pub struct DrainFilter<'a, K, V, F>
1371 F: FnMut(&K, &mut V) -> bool,
1373 base: base::DrainFilter<'a, K, V, F>,
1376 /// A mutable iterator over the values of a `HashMap`.
1378 /// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1379 /// documentation for more.
1381 /// [`values_mut`]: HashMap::values_mut
1386 /// use std::collections::HashMap;
1388 /// let mut map = HashMap::new();
1389 /// map.insert("a", 1);
1390 /// let iter_values = map.values_mut();
1392 #[stable(feature = "map_values_mut", since = "1.10.0")]
1393 pub struct ValuesMut<'a, K: 'a, V: 'a> {
1394 inner: IterMut<'a, K, V>,
1397 /// An owning iterator over the keys of a `HashMap`.
1399 /// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1400 /// See its documentation for more.
1402 /// [`into_keys`]: HashMap::into_keys
1407 /// #![feature(map_into_keys_values)]
1409 /// use std::collections::HashMap;
1411 /// let mut map = HashMap::new();
1412 /// map.insert("a", 1);
1413 /// let iter_keys = map.into_keys();
1415 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1416 pub struct IntoKeys<K, V> {
1417 inner: IntoIter<K, V>,
1420 /// An owning iterator over the values of a `HashMap`.
1422 /// This `struct` is created by the [`into_values`] method on [`HashMap`].
1423 /// See its documentation for more.
1425 /// [`into_values`]: HashMap::into_values
1430 /// #![feature(map_into_keys_values)]
1432 /// use std::collections::HashMap;
1434 /// let mut map = HashMap::new();
1435 /// map.insert("a", 1);
1436 /// let iter_keys = map.into_values();
1438 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1439 pub struct IntoValues<K, V> {
1440 inner: IntoIter<K, V>,
1443 /// A builder for computing where in a HashMap a key-value pair would be stored.
1445 /// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1446 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1447 pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1448 map: &'a mut HashMap<K, V, S>,
1451 /// A view into a single entry in a map, which may either be vacant or occupied.
1453 /// This is a lower-level version of [`Entry`].
1455 /// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
1456 /// then calling one of the methods of that [`RawEntryBuilderMut`].
1458 /// [`raw_entry_mut`]: HashMap::raw_entry_mut
1459 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1460 pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1461 /// An occupied entry.
1462 Occupied(RawOccupiedEntryMut<'a, K, V, S>),
1464 Vacant(RawVacantEntryMut<'a, K, V, S>),
1467 /// A view into an occupied entry in a `HashMap`.
1468 /// It is part of the [`RawEntryMut`] enum.
1469 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1470 pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1471 base: base::RawOccupiedEntryMut<'a, K, V, S>,
1474 /// A view into a vacant entry in a `HashMap`.
1475 /// It is part of the [`RawEntryMut`] enum.
1476 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1477 pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1478 base: base::RawVacantEntryMut<'a, K, V, S>,
1481 /// A builder for computing where in a HashMap a key-value pair would be stored.
1483 /// See the [`HashMap::raw_entry`] docs for usage examples.
1484 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1485 pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1486 map: &'a HashMap<K, V, S>,
1489 impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1493 /// Creates a `RawEntryMut` from the given key.
1495 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1496 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1501 map_raw_entry(self.map.base.raw_entry_mut().from_key(k))
1504 /// Creates a `RawEntryMut` from the given key and its hash.
1506 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1507 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1512 map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k))
1515 /// Creates a `RawEntryMut` from the given hash.
1517 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1518 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1520 for<'b> F: FnMut(&'b K) -> bool,
1522 map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match))
1526 impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1530 /// Access an entry by key.
1532 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1533 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1538 self.map.base.raw_entry().from_key(k)
1541 /// Access an entry by a key and its hash.
1543 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1544 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1549 self.map.base.raw_entry().from_key_hashed_nocheck(hash, k)
1552 /// Access an entry by hash.
1554 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1555 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
1557 F: FnMut(&K) -> bool,
1559 self.map.base.raw_entry().from_hash(hash, is_match)
1563 impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
1564 /// Ensures a value is in the entry by inserting the default if empty, and returns
1565 /// mutable references to the key and value in the entry.
1570 /// #![feature(hash_raw_entry)]
1571 /// use std::collections::HashMap;
1573 /// let mut map: HashMap<&str, u32> = HashMap::new();
1575 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
1576 /// assert_eq!(map["poneyland"], 3);
1578 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
1579 /// assert_eq!(map["poneyland"], 6);
1582 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1583 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
1589 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1590 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
1594 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1595 /// and returns mutable references to the key and value in the entry.
1600 /// #![feature(hash_raw_entry)]
1601 /// use std::collections::HashMap;
1603 /// let mut map: HashMap<&str, String> = HashMap::new();
1605 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
1606 /// ("poneyland", "hoho".to_string())
1609 /// assert_eq!(map["poneyland"], "hoho".to_string());
1612 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1613 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
1615 F: FnOnce() -> (K, V),
1620 RawEntryMut::Occupied(entry) => entry.into_key_value(),
1621 RawEntryMut::Vacant(entry) => {
1622 let (k, v) = default();
1628 /// Provides in-place mutable access to an occupied entry before any
1629 /// potential inserts into the map.
1634 /// #![feature(hash_raw_entry)]
1635 /// use std::collections::HashMap;
1637 /// let mut map: HashMap<&str, u32> = HashMap::new();
1639 /// map.raw_entry_mut()
1640 /// .from_key("poneyland")
1641 /// .and_modify(|_k, v| { *v += 1 })
1642 /// .or_insert("poneyland", 42);
1643 /// assert_eq!(map["poneyland"], 42);
1645 /// map.raw_entry_mut()
1646 /// .from_key("poneyland")
1647 /// .and_modify(|_k, v| { *v += 1 })
1648 /// .or_insert("poneyland", 0);
1649 /// assert_eq!(map["poneyland"], 43);
1652 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1653 pub fn and_modify<F>(self, f: F) -> Self
1655 F: FnOnce(&mut K, &mut V),
1658 RawEntryMut::Occupied(mut entry) => {
1660 let (k, v) = entry.get_key_value_mut();
1663 RawEntryMut::Occupied(entry)
1665 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
1670 impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> {
1671 /// Gets a reference to the key in the entry.
1673 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1674 pub fn key(&self) -> &K {
1678 /// Gets a mutable reference to the key in the entry.
1680 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1681 pub fn key_mut(&mut self) -> &mut K {
1685 /// Converts the entry into a mutable reference to the key in the entry
1686 /// with a lifetime bound to the map itself.
1688 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1689 pub fn into_key(self) -> &'a mut K {
1690 self.base.into_key()
1693 /// Gets a reference to the value in the entry.
1695 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1696 pub fn get(&self) -> &V {
1700 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
1701 /// with a lifetime bound to the map itself.
1703 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1704 pub fn into_mut(self) -> &'a mut V {
1705 self.base.into_mut()
1708 /// Gets a mutable reference to the value in the entry.
1710 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1711 pub fn get_mut(&mut self) -> &mut V {
1715 /// Gets a reference to the key and value in the entry.
1717 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1718 pub fn get_key_value(&mut self) -> (&K, &V) {
1719 self.base.get_key_value()
1722 /// Gets a mutable reference to the key and value in the entry.
1724 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1725 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
1726 self.base.get_key_value_mut()
1729 /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry
1730 /// with a lifetime bound to the map itself.
1732 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1733 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
1734 self.base.into_key_value()
1737 /// Sets the value of the entry, and returns the entry's old value.
1739 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1740 pub fn insert(&mut self, value: V) -> V {
1741 self.base.insert(value)
1744 /// Sets the value of the entry, and returns the entry's old value.
1746 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1747 pub fn insert_key(&mut self, key: K) -> K {
1748 self.base.insert_key(key)
1751 /// Takes the value out of the entry, and returns it.
1753 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1754 pub fn remove(self) -> V {
1758 /// Take the ownership of the key and value from the map.
1760 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1761 pub fn remove_entry(self) -> (K, V) {
1762 self.base.remove_entry()
1766 impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
1767 /// Sets the value of the entry with the `VacantEntry`'s key,
1768 /// and returns a mutable reference to it.
1770 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1771 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
1776 self.base.insert(key, value)
1779 /// Sets the value of the entry with the VacantEntry's key,
1780 /// and returns a mutable reference to it.
1782 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1783 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
1788 self.base.insert_hashed_nocheck(hash, key, value)
1792 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1793 impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
1794 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1795 f.debug_struct("RawEntryBuilder").finish()
1799 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1800 impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
1801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1803 RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(),
1804 RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(),
1809 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1810 impl<K: Debug, V: Debug, S> Debug for RawOccupiedEntryMut<'_, K, V, S> {
1811 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1812 f.debug_struct("RawOccupiedEntryMut")
1813 .field("key", self.key())
1814 .field("value", self.get())
1819 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1820 impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
1821 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1822 f.debug_struct("RawVacantEntryMut").finish()
1826 #[unstable(feature = "hash_raw_entry", issue = "56167")]
1827 impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
1828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1829 f.debug_struct("RawEntryBuilder").finish()
1833 /// A view into a single entry in a map, which may either be vacant or occupied.
1835 /// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1837 /// [`entry`]: HashMap::entry
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 pub enum Entry<'a, K: 'a, V: 'a> {
1840 /// An occupied entry.
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1849 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1850 impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1851 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1853 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1854 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1859 /// A view into an occupied entry in a `HashMap`.
1860 /// It is part of the [`Entry`] enum.
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1863 base: base::RustcOccupiedEntry<'a, K, V>,
1866 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1867 impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1869 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
1873 /// A view into a vacant entry in a `HashMap`.
1874 /// It is part of the [`Entry`] enum.
1875 #[stable(feature = "rust1", since = "1.0.0")]
1876 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1877 base: base::RustcVacantEntry<'a, K, V>,
1880 #[stable(feature = "debug_hash_map", since = "1.12.0")]
1881 impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883 f.debug_tuple("VacantEntry").field(self.key()).finish()
1887 /// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1889 /// Contains the occupied entry, and the value that was not inserted.
1890 #[unstable(feature = "map_try_insert", issue = "82766")]
1891 pub struct OccupiedError<'a, K: 'a, V: 'a> {
1892 /// The entry in the map that was already occupied.
1893 pub entry: OccupiedEntry<'a, K, V>,
1894 /// The value which was not inserted, because the entry was already occupied.
1898 #[unstable(feature = "map_try_insert", issue = "82766")]
1899 impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V> {
1900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1901 f.debug_struct("OccupiedError")
1902 .field("key", self.entry.key())
1903 .field("old_value", self.entry.get())
1904 .field("new_value", &self.value)
1909 #[unstable(feature = "map_try_insert", issue = "82766")]
1910 impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> {
1911 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1914 "failed to insert {:?}, key {:?} already exists with value {:?}",
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1924 type Item = (&'a K, &'a V);
1925 type IntoIter = Iter<'a, K, V>;
1928 fn into_iter(self) -> Iter<'a, K, V> {
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1935 type Item = (&'a K, &'a mut V);
1936 type IntoIter = IterMut<'a, K, V>;
1939 fn into_iter(self) -> IterMut<'a, K, V> {
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1947 type IntoIter = IntoIter<K, V>;
1949 /// Creates a consuming iterator, that is, one that moves each key-value
1950 /// pair out of the map in arbitrary order. The map cannot be used after
1956 /// use std::collections::HashMap;
1958 /// let mut map = HashMap::new();
1959 /// map.insert("a", 1);
1960 /// map.insert("b", 2);
1961 /// map.insert("c", 3);
1963 /// // Not possible with .iter()
1964 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1967 fn into_iter(self) -> IntoIter<K, V> {
1968 IntoIter { base: self.base.into_iter() }
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1974 type Item = (&'a K, &'a V);
1977 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1981 fn size_hint(&self) -> (usize, Option<usize>) {
1982 self.base.size_hint()
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1988 fn len(&self) -> usize {
1993 #[stable(feature = "fused", since = "1.26.0")]
1994 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1998 type Item = (&'a K, &'a mut V);
2001 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2005 fn size_hint(&self) -> (usize, Option<usize>) {
2006 self.base.size_hint()
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2012 fn len(&self) -> usize {
2016 #[stable(feature = "fused", since = "1.26.0")]
2017 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2019 #[stable(feature = "std_debug", since = "1.16.0")]
2020 impl<K, V> fmt::Debug for IterMut<'_, K, V>
2025 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2026 f.debug_list().entries(self.iter()).finish()
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 impl<K, V> Iterator for IntoIter<K, V> {
2035 fn next(&mut self) -> Option<(K, V)> {
2039 fn size_hint(&self) -> (usize, Option<usize>) {
2040 self.base.size_hint()
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2046 fn len(&self) -> usize {
2050 #[stable(feature = "fused", since = "1.26.0")]
2051 impl<K, V> FusedIterator for IntoIter<K, V> {}
2053 #[stable(feature = "std_debug", since = "1.16.0")]
2054 impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2056 f.debug_list().entries(self.iter()).finish()
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<'a, K, V> Iterator for Keys<'a, K, V> {
2065 fn next(&mut self) -> Option<&'a K> {
2066 self.inner.next().map(|(k, _)| k)
2069 fn size_hint(&self) -> (usize, Option<usize>) {
2070 self.inner.size_hint()
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2076 fn len(&self) -> usize {
2080 #[stable(feature = "fused", since = "1.26.0")]
2081 impl<K, V> FusedIterator for Keys<'_, K, V> {}
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 impl<'a, K, V> Iterator for Values<'a, K, V> {
2088 fn next(&mut self) -> Option<&'a V> {
2089 self.inner.next().map(|(_, v)| v)
2092 fn size_hint(&self) -> (usize, Option<usize>) {
2093 self.inner.size_hint()
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2099 fn len(&self) -> usize {
2103 #[stable(feature = "fused", since = "1.26.0")]
2104 impl<K, V> FusedIterator for Values<'_, K, V> {}
2106 #[stable(feature = "map_values_mut", since = "1.10.0")]
2107 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2108 type Item = &'a mut V;
2111 fn next(&mut self) -> Option<&'a mut V> {
2112 self.inner.next().map(|(_, v)| v)
2115 fn size_hint(&self) -> (usize, Option<usize>) {
2116 self.inner.size_hint()
2119 #[stable(feature = "map_values_mut", since = "1.10.0")]
2120 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2122 fn len(&self) -> usize {
2126 #[stable(feature = "fused", since = "1.26.0")]
2127 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2129 #[stable(feature = "std_debug", since = "1.16.0")]
2130 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2132 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2136 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2137 impl<K, V> Iterator for IntoKeys<K, V> {
2141 fn next(&mut self) -> Option<K> {
2142 self.inner.next().map(|(k, _)| k)
2145 fn size_hint(&self) -> (usize, Option<usize>) {
2146 self.inner.size_hint()
2149 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2150 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2152 fn len(&self) -> usize {
2156 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2157 impl<K, V> FusedIterator for IntoKeys<K, V> {}
2159 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2160 impl<K: Debug, V> fmt::Debug for IntoKeys<K, V> {
2161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2162 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2166 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2167 impl<K, V> Iterator for IntoValues<K, V> {
2171 fn next(&mut self) -> Option<V> {
2172 self.inner.next().map(|(_, v)| v)
2175 fn size_hint(&self) -> (usize, Option<usize>) {
2176 self.inner.size_hint()
2179 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2180 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2182 fn len(&self) -> usize {
2186 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2187 impl<K, V> FusedIterator for IntoValues<K, V> {}
2189 #[unstable(feature = "map_into_keys_values", issue = "75294")]
2190 impl<K, V: Debug> fmt::Debug for IntoValues<K, V> {
2191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2192 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2196 #[stable(feature = "drain", since = "1.6.0")]
2197 impl<'a, K, V> Iterator for Drain<'a, K, V> {
2201 fn next(&mut self) -> Option<(K, V)> {
2205 fn size_hint(&self) -> (usize, Option<usize>) {
2206 self.base.size_hint()
2209 #[stable(feature = "drain", since = "1.6.0")]
2210 impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2212 fn len(&self) -> usize {
2216 #[stable(feature = "fused", since = "1.26.0")]
2217 impl<K, V> FusedIterator for Drain<'_, K, V> {}
2219 #[stable(feature = "std_debug", since = "1.16.0")]
2220 impl<K, V> fmt::Debug for Drain<'_, K, V>
2225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 f.debug_list().entries(self.iter()).finish()
2230 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2231 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
2233 F: FnMut(&K, &mut V) -> bool,
2238 fn next(&mut self) -> Option<(K, V)> {
2242 fn size_hint(&self) -> (usize, Option<usize>) {
2243 self.base.size_hint()
2247 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2248 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2250 #[unstable(feature = "hash_drain_filter", issue = "59618")]
2251 impl<'a, K, V, F> fmt::Debug for DrainFilter<'a, K, V, F>
2253 F: FnMut(&K, &mut V) -> bool,
2255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2256 f.pad("DrainFilter { .. }")
2260 impl<'a, K, V> Entry<'a, K, V> {
2261 /// Ensures a value is in the entry by inserting the default if empty, and returns
2262 /// a mutable reference to the value in the entry.
2267 /// use std::collections::HashMap;
2269 /// let mut map: HashMap<&str, u32> = HashMap::new();
2271 /// map.entry("poneyland").or_insert(3);
2272 /// assert_eq!(map["poneyland"], 3);
2274 /// *map.entry("poneyland").or_insert(10) *= 2;
2275 /// assert_eq!(map["poneyland"], 6);
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 pub fn or_insert(self, default: V) -> &'a mut V {
2281 Occupied(entry) => entry.into_mut(),
2282 Vacant(entry) => entry.insert(default),
2286 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2287 /// and returns a mutable reference to the value in the entry.
2292 /// use std::collections::HashMap;
2294 /// let mut map: HashMap<&str, String> = HashMap::new();
2295 /// let s = "hoho".to_string();
2297 /// map.entry("poneyland").or_insert_with(|| s);
2299 /// assert_eq!(map["poneyland"], "hoho".to_string());
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2305 Occupied(entry) => entry.into_mut(),
2306 Vacant(entry) => entry.insert(default()),
2310 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2311 /// This method allows for generating key-derived values for insertion by providing the default
2312 /// function a reference to the key that was moved during the `.entry(key)` method call.
2314 /// The reference to the moved key is provided so that cloning or copying the key is
2315 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2320 /// use std::collections::HashMap;
2322 /// let mut map: HashMap<&str, usize> = HashMap::new();
2324 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2326 /// assert_eq!(map["poneyland"], 9);
2329 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2330 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2332 Occupied(entry) => entry.into_mut(),
2334 let value = default(entry.key());
2340 /// Returns a reference to this entry's key.
2345 /// use std::collections::HashMap;
2347 /// let mut map: HashMap<&str, u32> = HashMap::new();
2348 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2351 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2352 pub fn key(&self) -> &K {
2354 Occupied(ref entry) => entry.key(),
2355 Vacant(ref entry) => entry.key(),
2359 /// Provides in-place mutable access to an occupied entry before any
2360 /// potential inserts into the map.
2365 /// use std::collections::HashMap;
2367 /// let mut map: HashMap<&str, u32> = HashMap::new();
2369 /// map.entry("poneyland")
2370 /// .and_modify(|e| { *e += 1 })
2372 /// assert_eq!(map["poneyland"], 42);
2374 /// map.entry("poneyland")
2375 /// .and_modify(|e| { *e += 1 })
2377 /// assert_eq!(map["poneyland"], 43);
2380 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2381 pub fn and_modify<F>(self, f: F) -> Self
2386 Occupied(mut entry) => {
2390 Vacant(entry) => Vacant(entry),
2394 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2399 /// #![feature(entry_insert)]
2400 /// use std::collections::HashMap;
2402 /// let mut map: HashMap<&str, String> = HashMap::new();
2403 /// let entry = map.entry("poneyland").insert("hoho".to_string());
2405 /// assert_eq!(entry.key(), &"poneyland");
2408 #[unstable(feature = "entry_insert", issue = "65225")]
2409 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V> {
2411 Occupied(mut entry) => {
2412 entry.insert(value);
2415 Vacant(entry) => entry.insert_entry(value),
2420 impl<'a, K, V: Default> Entry<'a, K, V> {
2421 /// Ensures a value is in the entry by inserting the default value if empty,
2422 /// and returns a mutable reference to the value in the entry.
2428 /// use std::collections::HashMap;
2430 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2431 /// map.entry("poneyland").or_default();
2433 /// assert_eq!(map["poneyland"], None);
2437 #[stable(feature = "entry_or_default", since = "1.28.0")]
2438 pub fn or_default(self) -> &'a mut V {
2440 Occupied(entry) => entry.into_mut(),
2441 Vacant(entry) => entry.insert(Default::default()),
2446 impl<'a, K, V> OccupiedEntry<'a, K, V> {
2447 /// Gets a reference to the key in the entry.
2452 /// use std::collections::HashMap;
2454 /// let mut map: HashMap<&str, u32> = HashMap::new();
2455 /// map.entry("poneyland").or_insert(12);
2456 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2459 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2460 pub fn key(&self) -> &K {
2464 /// Take the ownership of the key and value from the map.
2469 /// use std::collections::HashMap;
2470 /// use std::collections::hash_map::Entry;
2472 /// let mut map: HashMap<&str, u32> = HashMap::new();
2473 /// map.entry("poneyland").or_insert(12);
2475 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2476 /// // We delete the entry from the map.
2477 /// o.remove_entry();
2480 /// assert_eq!(map.contains_key("poneyland"), false);
2483 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2484 pub fn remove_entry(self) -> (K, V) {
2485 self.base.remove_entry()
2488 /// Gets a reference to the value in the entry.
2493 /// use std::collections::HashMap;
2494 /// use std::collections::hash_map::Entry;
2496 /// let mut map: HashMap<&str, u32> = HashMap::new();
2497 /// map.entry("poneyland").or_insert(12);
2499 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2500 /// assert_eq!(o.get(), &12);
2504 #[stable(feature = "rust1", since = "1.0.0")]
2505 pub fn get(&self) -> &V {
2509 /// Gets a mutable reference to the value in the entry.
2511 /// If you need a reference to the `OccupiedEntry` which may outlive the
2512 /// destruction of the `Entry` value, see [`into_mut`].
2514 /// [`into_mut`]: Self::into_mut
2519 /// use std::collections::HashMap;
2520 /// use std::collections::hash_map::Entry;
2522 /// let mut map: HashMap<&str, u32> = HashMap::new();
2523 /// map.entry("poneyland").or_insert(12);
2525 /// assert_eq!(map["poneyland"], 12);
2526 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2527 /// *o.get_mut() += 10;
2528 /// assert_eq!(*o.get(), 22);
2530 /// // We can use the same Entry multiple times.
2531 /// *o.get_mut() += 2;
2534 /// assert_eq!(map["poneyland"], 24);
2537 #[stable(feature = "rust1", since = "1.0.0")]
2538 pub fn get_mut(&mut self) -> &mut V {
2542 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2543 /// with a lifetime bound to the map itself.
2545 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2547 /// [`get_mut`]: Self::get_mut
2552 /// use std::collections::HashMap;
2553 /// use std::collections::hash_map::Entry;
2555 /// let mut map: HashMap<&str, u32> = HashMap::new();
2556 /// map.entry("poneyland").or_insert(12);
2558 /// assert_eq!(map["poneyland"], 12);
2559 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2560 /// *o.into_mut() += 10;
2563 /// assert_eq!(map["poneyland"], 22);
2566 #[stable(feature = "rust1", since = "1.0.0")]
2567 pub fn into_mut(self) -> &'a mut V {
2568 self.base.into_mut()
2571 /// Sets the value of the entry, and returns the entry's old value.
2576 /// use std::collections::HashMap;
2577 /// use std::collections::hash_map::Entry;
2579 /// let mut map: HashMap<&str, u32> = HashMap::new();
2580 /// map.entry("poneyland").or_insert(12);
2582 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2583 /// assert_eq!(o.insert(15), 12);
2586 /// assert_eq!(map["poneyland"], 15);
2589 #[stable(feature = "rust1", since = "1.0.0")]
2590 pub fn insert(&mut self, value: V) -> V {
2591 self.base.insert(value)
2594 /// Takes the value out of the entry, and returns it.
2599 /// use std::collections::HashMap;
2600 /// use std::collections::hash_map::Entry;
2602 /// let mut map: HashMap<&str, u32> = HashMap::new();
2603 /// map.entry("poneyland").or_insert(12);
2605 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2606 /// assert_eq!(o.remove(), 12);
2609 /// assert_eq!(map.contains_key("poneyland"), false);
2612 #[stable(feature = "rust1", since = "1.0.0")]
2613 pub fn remove(self) -> V {
2617 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2618 /// the key used to create this entry.
2623 /// #![feature(map_entry_replace)]
2624 /// use std::collections::hash_map::{Entry, HashMap};
2625 /// use std::rc::Rc;
2627 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2628 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2630 /// let my_key = Rc::new("Stringthing".to_string());
2632 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2633 /// // Also replace the key with a handle to our other key.
2634 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2639 #[unstable(feature = "map_entry_replace", issue = "44286")]
2640 pub fn replace_entry(self, value: V) -> (K, V) {
2641 self.base.replace_entry(value)
2644 /// Replaces the key in the hash map with the key used to create this entry.
2649 /// #![feature(map_entry_replace)]
2650 /// use std::collections::hash_map::{Entry, HashMap};
2651 /// use std::rc::Rc;
2653 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2654 /// let known_strings: Vec<Rc<String>> = Vec::new();
2656 /// // Initialise known strings, run program, etc.
2658 /// reclaim_memory(&mut map, &known_strings);
2660 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2661 /// for s in known_strings {
2662 /// if let Entry::Occupied(entry) = map.entry(Rc::clone(s)) {
2663 /// // Replaces the entry's key with our version of it in `known_strings`.
2664 /// entry.replace_key();
2670 #[unstable(feature = "map_entry_replace", issue = "44286")]
2671 pub fn replace_key(self) -> K {
2672 self.base.replace_key()
2676 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2677 /// Gets a reference to the key that would be used when inserting a value
2678 /// through the `VacantEntry`.
2683 /// use std::collections::HashMap;
2685 /// let mut map: HashMap<&str, u32> = HashMap::new();
2686 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2689 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2690 pub fn key(&self) -> &K {
2694 /// Take ownership of the key.
2699 /// use std::collections::HashMap;
2700 /// use std::collections::hash_map::Entry;
2702 /// let mut map: HashMap<&str, u32> = HashMap::new();
2704 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2709 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2710 pub fn into_key(self) -> K {
2711 self.base.into_key()
2714 /// Sets the value of the entry with the `VacantEntry`'s key,
2715 /// and returns a mutable reference to it.
2720 /// use std::collections::HashMap;
2721 /// use std::collections::hash_map::Entry;
2723 /// let mut map: HashMap<&str, u32> = HashMap::new();
2725 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2728 /// assert_eq!(map["poneyland"], 37);
2731 #[stable(feature = "rust1", since = "1.0.0")]
2732 pub fn insert(self, value: V) -> &'a mut V {
2733 self.base.insert(value)
2736 /// Sets the value of the entry with the `VacantEntry`'s key,
2737 /// and returns an `OccupiedEntry`.
2742 /// use std::collections::HashMap;
2743 /// use std::collections::hash_map::Entry;
2745 /// let mut map: HashMap<&str, u32> = HashMap::new();
2747 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2750 /// assert_eq!(map["poneyland"], 37);
2753 fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2754 let base = self.base.insert_entry(value);
2755 OccupiedEntry { base }
2759 #[stable(feature = "rust1", since = "1.0.0")]
2760 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2763 S: BuildHasher + Default,
2765 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2766 let mut map = HashMap::with_hasher(Default::default());
2772 /// Inserts all new key-values from the iterator and replaces values with existing
2773 /// keys with new values returned from the iterator.
2774 #[stable(feature = "rust1", since = "1.0.0")]
2775 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2781 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2782 self.base.extend(iter)
2786 fn extend_one(&mut self, (k, v): (K, V)) {
2787 self.base.insert(k, v);
2791 fn extend_reserve(&mut self, additional: usize) {
2792 // self.base.extend_reserve(additional);
2793 // FIXME: hashbrown should implement this method.
2794 // But until then, use the same reservation logic:
2796 // Reserve the entire hint lower bound if the map is empty.
2797 // Otherwise reserve half the hint (rounded up), so the map
2798 // will only resize twice in the worst case.
2799 let reserve = if self.is_empty() { additional } else { (additional + 1) / 2 };
2800 self.base.reserve(reserve);
2804 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2805 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2807 K: Eq + Hash + Copy,
2812 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2813 self.base.extend(iter)
2817 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2818 self.base.insert(k, v);
2822 fn extend_reserve(&mut self, additional: usize) {
2823 Extend::<(K, V)>::extend_reserve(self, additional)
2827 /// `RandomState` is the default state for [`HashMap`] types.
2829 /// A particular instance `RandomState` will create the same instances of
2830 /// [`Hasher`], but the hashers created by two different `RandomState`
2831 /// instances are unlikely to produce the same result for the same values.
2836 /// use std::collections::HashMap;
2837 /// use std::collections::hash_map::RandomState;
2839 /// let s = RandomState::new();
2840 /// let mut map = HashMap::with_hasher(s);
2841 /// map.insert(1, 2);
2844 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2845 pub struct RandomState {
2851 /// Constructs a new `RandomState` that is initialized with random keys.
2856 /// use std::collections::hash_map::RandomState;
2858 /// let s = RandomState::new();
2861 #[allow(deprecated)]
2863 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2864 pub fn new() -> RandomState {
2865 // Historically this function did not cache keys from the OS and instead
2866 // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2867 // was discovered, however, that because we re-seed the thread-local RNG
2868 // from the OS periodically that this can cause excessive slowdown when
2869 // many hash maps are created on a thread. To solve this performance
2870 // trap we cache the first set of randomly generated keys per-thread.
2872 // Later in #36481 it was discovered that exposing a deterministic
2873 // iteration order allows a form of DOS attack. To counter that we
2874 // increment one of the seeds on every RandomState creation, giving
2875 // every corresponding HashMap a different iteration order.
2876 thread_local!(static KEYS: Cell<(u64, u64)> = {
2877 Cell::new(sys::hashmap_random_keys())
2881 let (k0, k1) = keys.get();
2882 keys.set((k0.wrapping_add(1), k1));
2883 RandomState { k0, k1 }
2888 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2889 impl BuildHasher for RandomState {
2890 type Hasher = DefaultHasher;
2892 #[allow(deprecated)]
2893 fn build_hasher(&self) -> DefaultHasher {
2894 DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2898 /// The default [`Hasher`] used by [`RandomState`].
2900 /// The internal algorithm is not specified, and so it and its hashes should
2901 /// not be relied upon over releases.
2902 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2903 #[allow(deprecated)]
2904 #[derive(Clone, Debug)]
2905 pub struct DefaultHasher(SipHasher13);
2907 impl DefaultHasher {
2908 /// Creates a new `DefaultHasher`.
2910 /// This hasher is not guaranteed to be the same as all other
2911 /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2912 /// instances created through `new` or `default`.
2913 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2914 #[allow(deprecated)]
2915 pub fn new() -> DefaultHasher {
2916 DefaultHasher(SipHasher13::new_with_keys(0, 0))
2920 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2921 impl Default for DefaultHasher {
2922 /// Creates a new `DefaultHasher` using [`new`].
2923 /// See its documentation for more.
2925 /// [`new`]: DefaultHasher::new
2926 fn default() -> DefaultHasher {
2927 DefaultHasher::new()
2931 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2932 impl Hasher for DefaultHasher {
2934 fn write(&mut self, msg: &[u8]) {
2939 fn finish(&self) -> u64 {
2944 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2945 impl Default for RandomState {
2946 /// Constructs a new `RandomState`.
2948 fn default() -> RandomState {
2953 #[stable(feature = "std_debug", since = "1.16.0")]
2954 impl fmt::Debug for RandomState {
2955 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2956 f.pad("RandomState { .. }")
2961 fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2963 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2964 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2969 pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
2971 hashbrown::TryReserveError::CapacityOverflow => TryReserveError::CapacityOverflow,
2972 hashbrown::TryReserveError::AllocError { layout } => {
2973 TryReserveError::AllocError { layout, non_exhaustive: () }
2979 fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>(
2980 raw: base::RawEntryMut<'a, K, V, S>,
2981 ) -> RawEntryMut<'a, K, V, S> {
2983 base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }),
2984 base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }),
2989 fn assert_covariance() {
2990 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2993 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2996 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2999 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3002 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3005 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3008 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3011 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3014 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3017 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3021 d: Drain<'static, &'static str, &'static str>,
3022 ) -> Drain<'new, &'new str, &'new str> {