std/collections/hash/map.rs
1#[cfg(test)]
2mod tests;
3
4use hashbrown::hash_map as base;
5
6use self::Entry::*;
7use crate::alloc::{Allocator, Global};
8use crate::borrow::Borrow;
9use crate::collections::{TryReserveError, TryReserveErrorKind};
10use crate::error::Error;
11use crate::fmt::{self, Debug};
12use crate::hash::{BuildHasher, Hash, RandomState};
13use crate::iter::FusedIterator;
14use crate::ops::Index;
15
16/// A [hash map] implemented with quadratic probing and SIMD lookup.
17///
18/// By default, `HashMap` uses a hashing algorithm selected to provide
19/// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
20/// reasonable best-effort is made to generate this seed from a high quality,
21/// secure source of randomness provided by the host without blocking the
22/// program. Because of this, the randomness of the seed depends on the output
23/// quality of the system's random number coroutine when the seed is created.
24/// In particular, seeds generated when the system's entropy pool is abnormally
25/// low such as during system boot may be of a lower quality.
26///
27/// The default hashing algorithm is currently SipHash 1-3, though this is
28/// subject to change at any point in the future. While its performance is very
29/// competitive for medium sized keys, other hashing algorithms will outperform
30/// it for small keys such as integers as well as large keys such as long
31/// strings, though those algorithms will typically *not* protect against
32/// attacks such as HashDoS.
33///
34/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
35/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods.
36/// There are many alternative [hashing algorithms available on crates.io].
37///
38/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
39/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
40/// If you implement these yourself, it is important that the following
41/// property holds:
42///
43/// ```text
44/// k1 == k2 -> hash(k1) == hash(k2)
45/// ```
46///
47/// In other words, if two keys are equal, their hashes must be equal.
48/// Violating this property is a logic error.
49///
50/// It is also a logic error for a key to be modified in such a way that the key's
51/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
52/// the [`Eq`] trait, changes while it is in the map. This is normally only
53/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
54///
55/// The behavior resulting from either logic error is not specified, but will
56/// be encapsulated to the `HashMap` that observed the logic error and not
57/// result in undefined behavior. This could include panics, incorrect results,
58/// aborts, memory leaks, and non-termination.
59///
60/// The hash table implementation is a Rust port of Google's [SwissTable].
61/// The original C++ version of SwissTable can be found [here], and this
62/// [CppCon talk] gives an overview of how the algorithm works.
63///
64/// [hash map]: crate::collections#use-a-hashmap-when
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
69///
70/// # Examples
71///
72/// ```
73/// use std::collections::HashMap;
74///
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();
78///
79/// // Review some books.
80/// book_reviews.insert(
81/// "Adventures of Huckleberry Finn".to_string(),
82/// "My favorite book.".to_string(),
83/// );
84/// book_reviews.insert(
85/// "Grimms' Fairy Tales".to_string(),
86/// "Masterpiece.".to_string(),
87/// );
88/// book_reviews.insert(
89/// "Pride and Prejudice".to_string(),
90/// "Very enjoyable.".to_string(),
91/// );
92/// book_reviews.insert(
93/// "The Adventures of Sherlock Holmes".to_string(),
94/// "Eye lyked it alot.".to_string(),
95/// );
96///
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());
103/// }
104///
105/// // oops, this review has a lot of spelling mistakes, let's delete it.
106/// book_reviews.remove("The Adventures of Sherlock Holmes");
107///
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!("{book} is unreviewed.")
114/// }
115/// }
116///
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"]);
119///
120/// // Iterate over everything.
121/// for (book, review) in &book_reviews {
122/// println!("{book}: \"{review}\"");
123/// }
124/// ```
125///
126/// A `HashMap` with a known list of items can be initialized from an array:
127///
128/// ```
129/// use std::collections::HashMap;
130///
131/// let solar_distance = HashMap::from([
132/// ("Mercury", 0.4),
133/// ("Venus", 0.7),
134/// ("Earth", 1.0),
135/// ("Mars", 1.5),
136/// ]);
137/// ```
138///
139/// ## `Entry` API
140///
141/// `HashMap` implements an [`Entry` API](#method.entry), which allows
142/// for complex methods of getting, setting, updating and removing keys and
143/// their values:
144///
145/// ```
146/// use std::collections::HashMap;
147///
148/// // type inference lets us omit an explicit type signature (which
149/// // would be `HashMap<&str, u8>` in this example).
150/// let mut player_stats = HashMap::new();
151///
152/// fn random_stat_buff() -> u8 {
153/// // could actually return some random value here - let's just return
154/// // some fixed value for now
155/// 42
156/// }
157///
158/// // insert a key only if it doesn't already exist
159/// player_stats.entry("health").or_insert(100);
160///
161/// // insert a key using a function that provides a new value only if it
162/// // doesn't already exist
163/// player_stats.entry("defence").or_insert_with(random_stat_buff);
164///
165/// // update a key, guarding against the key possibly not being set
166/// let stat = player_stats.entry("attack").or_insert(100);
167/// *stat += random_stat_buff();
168///
169/// // modify an entry before an insert with in-place mutation
170/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
171/// ```
172///
173/// ## Usage with custom key types
174///
175/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
176/// We must also derive [`PartialEq`].
177///
178/// [`RefCell`]: crate::cell::RefCell
179/// [`Cell`]: crate::cell::Cell
180/// [`default`]: Default::default
181/// [`with_hasher`]: Self::with_hasher
182/// [`with_capacity_and_hasher`]: Self::with_capacity_and_hasher
183///
184/// ```
185/// use std::collections::HashMap;
186///
187/// #[derive(Hash, Eq, PartialEq, Debug)]
188/// struct Viking {
189/// name: String,
190/// country: String,
191/// }
192///
193/// impl Viking {
194/// /// Creates a new Viking.
195/// fn new(name: &str, country: &str) -> Viking {
196/// Viking { name: name.to_string(), country: country.to_string() }
197/// }
198/// }
199///
200/// // Use a HashMap to store the vikings' health points.
201/// let vikings = HashMap::from([
202/// (Viking::new("Einar", "Norway"), 25),
203/// (Viking::new("Olaf", "Denmark"), 24),
204/// (Viking::new("Harald", "Iceland"), 12),
205/// ]);
206///
207/// // Use derived implementation to print the status of the vikings.
208/// for (viking, health) in &vikings {
209/// println!("{viking:?} has {health} hp");
210/// }
211/// ```
212///
213/// # Usage in `const` and `static`
214///
215/// As explained above, `HashMap` is randomly seeded: each `HashMap` instance uses a different seed,
216/// which means that `HashMap::new` normally cannot be used in a `const` or `static` initializer.
217///
218/// However, if you need to use a `HashMap` in a `const` or `static` initializer while retaining
219/// random seed generation, you can wrap the `HashMap` in [`LazyLock`].
220///
221/// Alternatively, you can construct a `HashMap` in a `const` or `static` initializer using a different
222/// hasher that does not rely on a random seed. **Be aware that a `HashMap` created this way is not
223/// resistant to HashDoS attacks!**
224///
225/// [`LazyLock`]: crate::sync::LazyLock
226/// ```rust
227/// use std::collections::HashMap;
228/// use std::hash::{BuildHasherDefault, DefaultHasher};
229/// use std::sync::{LazyLock, Mutex};
230///
231/// // HashMaps with a fixed, non-random hasher
232/// const NONRANDOM_EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> =
233/// HashMap::with_hasher(BuildHasherDefault::new());
234/// static NONRANDOM_MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> =
235/// Mutex::new(HashMap::with_hasher(BuildHasherDefault::new()));
236///
237/// // HashMaps using LazyLock to retain random seeding
238/// const RANDOM_EMPTY_MAP: LazyLock<HashMap<String, Vec<i32>>> =
239/// LazyLock::new(HashMap::new);
240/// static RANDOM_MAP: LazyLock<Mutex<HashMap<String, Vec<i32>>>> =
241/// LazyLock::new(|| Mutex::new(HashMap::new()));
242/// ```
243
244#[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]
245#[stable(feature = "rust1", since = "1.0.0")]
246#[rustc_insignificant_dtor]
247pub struct HashMap<
248 K,
249 V,
250 S = RandomState,
251 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
252> {
253 base: base::HashMap<K, V, S, A>,
254}
255
256impl<K, V> HashMap<K, V, RandomState> {
257 /// Creates an empty `HashMap`.
258 ///
259 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
260 /// is first inserted into.
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use std::collections::HashMap;
266 /// let mut map: HashMap<&str, i32> = HashMap::new();
267 /// ```
268 #[inline]
269 #[must_use]
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn new() -> HashMap<K, V, RandomState> {
272 Default::default()
273 }
274
275 /// Creates an empty `HashMap` with at least the specified capacity.
276 ///
277 /// The hash map will be able to hold at least `capacity` elements without
278 /// reallocating. This method is allowed to allocate for more elements than
279 /// `capacity`. If `capacity` is zero, the hash map will not allocate.
280 ///
281 /// # Examples
282 ///
283 /// ```
284 /// use std::collections::HashMap;
285 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
286 /// ```
287 #[inline]
288 #[must_use]
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
291 HashMap::with_capacity_and_hasher(capacity, Default::default())
292 }
293}
294
295impl<K, V, A: Allocator> HashMap<K, V, RandomState, A> {
296 /// Creates an empty `HashMap` using the given allocator.
297 ///
298 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
299 /// is first inserted into.
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// # #![feature(allocator_api)]
305 /// use std::collections::HashMap;
306 /// use std::alloc::Global;
307 ///
308 /// let map: HashMap<i32, i32> = HashMap::new_in(Global);
309 /// ```
310 #[inline]
311 #[must_use]
312 #[unstable(feature = "allocator_api", issue = "32838")]
313 pub fn new_in(alloc: A) -> Self {
314 HashMap::with_hasher_in(Default::default(), alloc)
315 }
316
317 /// Creates an empty `HashMap` with at least the specified capacity using
318 /// the given allocator.
319 ///
320 /// The hash map will be able to hold at least `capacity` elements without
321 /// reallocating. This method is allowed to allocate for more elements than
322 /// `capacity`. If `capacity` is zero, the hash map will not allocate.
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// # #![feature(allocator_api)]
328 /// use std::collections::HashMap;
329 /// use std::alloc::Global;
330 ///
331 /// let map: HashMap<i32, i32> = HashMap::with_capacity_in(10, Global);
332 /// ```
333 #[inline]
334 #[must_use]
335 #[unstable(feature = "allocator_api", issue = "32838")]
336 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
337 HashMap::with_capacity_and_hasher_in(capacity, Default::default(), alloc)
338 }
339}
340
341impl<K, V, S> HashMap<K, V, S> {
342 /// Creates an empty `HashMap` which will use the given hash builder to hash
343 /// keys.
344 ///
345 /// The created map has the default initial capacity.
346 ///
347 /// Warning: `hash_builder` is normally randomly generated, and
348 /// is designed to allow HashMaps to be resistant to attacks that
349 /// cause many collisions and very poor performance. Setting it
350 /// manually using this function can expose a DoS attack vector.
351 ///
352 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
353 /// the `HashMap` to be useful, see its documentation for details.
354 ///
355 /// # Examples
356 ///
357 /// ```
358 /// use std::collections::HashMap;
359 /// use std::hash::RandomState;
360 ///
361 /// let s = RandomState::new();
362 /// let mut map = HashMap::with_hasher(s);
363 /// map.insert(1, 2);
364 /// ```
365 #[inline]
366 #[must_use]
367 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
368 #[rustc_const_stable(feature = "const_collections_with_hasher", since = "1.85.0")]
369 pub const fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
370 HashMap { base: base::HashMap::with_hasher(hash_builder) }
371 }
372
373 /// Creates an empty `HashMap` with at least the specified capacity, using
374 /// `hasher` to hash the keys.
375 ///
376 /// The hash map will be able to hold at least `capacity` elements without
377 /// reallocating. This method is allowed to allocate for more elements than
378 /// `capacity`. If `capacity` is zero, the hash map will not allocate.
379 ///
380 /// Warning: `hasher` is normally randomly generated, and
381 /// is designed to allow HashMaps to be resistant to attacks that
382 /// cause many collisions and very poor performance. Setting it
383 /// manually using this function can expose a DoS attack vector.
384 ///
385 /// The `hasher` passed should implement the [`BuildHasher`] trait for
386 /// the `HashMap` to be useful, see its documentation for details.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use std::collections::HashMap;
392 /// use std::hash::RandomState;
393 ///
394 /// let s = RandomState::new();
395 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
396 /// map.insert(1, 2);
397 /// ```
398 #[inline]
399 #[must_use]
400 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
401 pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashMap<K, V, S> {
402 HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hasher) }
403 }
404}
405
406impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
407 /// Creates an empty `HashMap` which will use the given hash builder and
408 /// allocator.
409 ///
410 /// The created map has the default initial capacity.
411 ///
412 /// Warning: `hash_builder` is normally randomly generated, and
413 /// is designed to allow HashMaps to be resistant to attacks that
414 /// cause many collisions and very poor performance. Setting it
415 /// manually using this function can expose a DoS attack vector.
416 ///
417 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
418 /// the `HashMap` to be useful, see its documentation for details.
419 ///
420 /// # Examples
421 ///
422 /// ```
423 /// #![feature(allocator_api)]
424 /// use std::alloc::Global;
425 /// use std::collections::HashMap;
426 /// use std::hash::RandomState;
427 ///
428 /// let s = RandomState::new();
429 /// let map: HashMap<i32, i32> = HashMap::with_hasher_in(s, Global);
430 /// ```
431 #[inline]
432 #[must_use]
433 #[unstable(feature = "allocator_api", issue = "32838")]
434 pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
435 HashMap { base: base::HashMap::with_hasher_in(hash_builder, alloc) }
436 }
437
438 /// Creates an empty `HashMap` with at least the specified capacity, using
439 /// `hasher` to hash the keys and `alloc` to allocate memory.
440 ///
441 /// The hash map will be able to hold at least `capacity` elements without
442 /// reallocating. This method is allowed to allocate for more elements than
443 /// `capacity`. If `capacity` is zero, the hash map will not allocate.
444 ///
445 /// Warning: `hasher` is normally randomly generated, and
446 /// is designed to allow HashMaps to be resistant to attacks that
447 /// cause many collisions and very poor performance. Setting it
448 /// manually using this function can expose a DoS attack vector.
449 ///
450 /// The `hasher` passed should implement the [`BuildHasher`] trait for
451 /// the `HashMap` to be useful, see its documentation for details.
452 ///
453 /// # Examples
454 ///
455 /// ```
456 /// #![feature(allocator_api)]
457 /// use std::alloc::Global;
458 /// use std::collections::HashMap;
459 /// use std::hash::RandomState;
460 ///
461 /// let s = RandomState::new();
462 /// let map: HashMap<i32, i32> = HashMap::with_capacity_and_hasher_in(10, s, Global);
463 /// ```
464 #[inline]
465 #[must_use]
466 #[unstable(feature = "allocator_api", issue = "32838")]
467 pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self {
468 HashMap { base: base::HashMap::with_capacity_and_hasher_in(capacity, hash_builder, alloc) }
469 }
470
471 /// Returns the number of elements the map can hold without reallocating.
472 ///
473 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
474 /// more, but is guaranteed to be able to hold at least this many.
475 ///
476 /// # Examples
477 ///
478 /// ```
479 /// use std::collections::HashMap;
480 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
481 /// assert!(map.capacity() >= 100);
482 /// ```
483 #[inline]
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn capacity(&self) -> usize {
486 self.base.capacity()
487 }
488
489 /// An iterator visiting all keys in arbitrary order.
490 /// The iterator element type is `&'a K`.
491 ///
492 /// # Examples
493 ///
494 /// ```
495 /// use std::collections::HashMap;
496 ///
497 /// let map = HashMap::from([
498 /// ("a", 1),
499 /// ("b", 2),
500 /// ("c", 3),
501 /// ]);
502 ///
503 /// for key in map.keys() {
504 /// println!("{key}");
505 /// }
506 /// ```
507 ///
508 /// # Performance
509 ///
510 /// In the current implementation, iterating over keys takes O(capacity) time
511 /// instead of O(len) because it internally visits empty buckets too.
512 #[rustc_lint_query_instability]
513 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn keys(&self) -> Keys<'_, K, V> {
515 Keys { inner: self.iter() }
516 }
517
518 /// Creates a consuming iterator visiting all the keys in arbitrary order.
519 /// The map cannot be used after calling this.
520 /// The iterator element type is `K`.
521 ///
522 /// # Examples
523 ///
524 /// ```
525 /// use std::collections::HashMap;
526 ///
527 /// let map = HashMap::from([
528 /// ("a", 1),
529 /// ("b", 2),
530 /// ("c", 3),
531 /// ]);
532 ///
533 /// let mut vec: Vec<&str> = map.into_keys().collect();
534 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
535 /// // keys must be sorted to test them against a sorted array.
536 /// vec.sort_unstable();
537 /// assert_eq!(vec, ["a", "b", "c"]);
538 /// ```
539 ///
540 /// # Performance
541 ///
542 /// In the current implementation, iterating over keys takes O(capacity) time
543 /// instead of O(len) because it internally visits empty buckets too.
544 #[inline]
545 #[rustc_lint_query_instability]
546 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
547 pub fn into_keys(self) -> IntoKeys<K, V, A> {
548 IntoKeys { inner: self.into_iter() }
549 }
550
551 /// An iterator visiting all values in arbitrary order.
552 /// The iterator element type is `&'a V`.
553 ///
554 /// # Examples
555 ///
556 /// ```
557 /// use std::collections::HashMap;
558 ///
559 /// let map = HashMap::from([
560 /// ("a", 1),
561 /// ("b", 2),
562 /// ("c", 3),
563 /// ]);
564 ///
565 /// for val in map.values() {
566 /// println!("{val}");
567 /// }
568 /// ```
569 ///
570 /// # Performance
571 ///
572 /// In the current implementation, iterating over values takes O(capacity) time
573 /// instead of O(len) because it internally visits empty buckets too.
574 #[rustc_lint_query_instability]
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn values(&self) -> Values<'_, K, V> {
577 Values { inner: self.iter() }
578 }
579
580 /// An iterator visiting all values mutably in arbitrary order.
581 /// The iterator element type is `&'a mut V`.
582 ///
583 /// # Examples
584 ///
585 /// ```
586 /// use std::collections::HashMap;
587 ///
588 /// let mut map = HashMap::from([
589 /// ("a", 1),
590 /// ("b", 2),
591 /// ("c", 3),
592 /// ]);
593 ///
594 /// for val in map.values_mut() {
595 /// *val = *val + 10;
596 /// }
597 ///
598 /// for val in map.values() {
599 /// println!("{val}");
600 /// }
601 /// ```
602 ///
603 /// # Performance
604 ///
605 /// In the current implementation, iterating over values takes O(capacity) time
606 /// instead of O(len) because it internally visits empty buckets too.
607 #[rustc_lint_query_instability]
608 #[stable(feature = "map_values_mut", since = "1.10.0")]
609 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
610 ValuesMut { inner: self.iter_mut() }
611 }
612
613 /// Creates a consuming iterator visiting all the values in arbitrary order.
614 /// The map cannot be used after calling this.
615 /// The iterator element type is `V`.
616 ///
617 /// # Examples
618 ///
619 /// ```
620 /// use std::collections::HashMap;
621 ///
622 /// let map = HashMap::from([
623 /// ("a", 1),
624 /// ("b", 2),
625 /// ("c", 3),
626 /// ]);
627 ///
628 /// let mut vec: Vec<i32> = map.into_values().collect();
629 /// // The `IntoValues` iterator produces values in arbitrary order, so
630 /// // the values must be sorted to test them against a sorted array.
631 /// vec.sort_unstable();
632 /// assert_eq!(vec, [1, 2, 3]);
633 /// ```
634 ///
635 /// # Performance
636 ///
637 /// In the current implementation, iterating over values takes O(capacity) time
638 /// instead of O(len) because it internally visits empty buckets too.
639 #[inline]
640 #[rustc_lint_query_instability]
641 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
642 pub fn into_values(self) -> IntoValues<K, V, A> {
643 IntoValues { inner: self.into_iter() }
644 }
645
646 /// An iterator visiting all key-value pairs in arbitrary order.
647 /// The iterator element type is `(&'a K, &'a V)`.
648 ///
649 /// # Examples
650 ///
651 /// ```
652 /// use std::collections::HashMap;
653 ///
654 /// let map = HashMap::from([
655 /// ("a", 1),
656 /// ("b", 2),
657 /// ("c", 3),
658 /// ]);
659 ///
660 /// for (key, val) in map.iter() {
661 /// println!("key: {key} val: {val}");
662 /// }
663 /// ```
664 ///
665 /// # Performance
666 ///
667 /// In the current implementation, iterating over map takes O(capacity) time
668 /// instead of O(len) because it internally visits empty buckets too.
669 #[rustc_lint_query_instability]
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn iter(&self) -> Iter<'_, K, V> {
672 Iter { base: self.base.iter() }
673 }
674
675 /// An iterator visiting all key-value pairs in arbitrary order,
676 /// with mutable references to the values.
677 /// The iterator element type is `(&'a K, &'a mut V)`.
678 ///
679 /// # Examples
680 ///
681 /// ```
682 /// use std::collections::HashMap;
683 ///
684 /// let mut map = HashMap::from([
685 /// ("a", 1),
686 /// ("b", 2),
687 /// ("c", 3),
688 /// ]);
689 ///
690 /// // Update all values
691 /// for (_, val) in map.iter_mut() {
692 /// *val *= 2;
693 /// }
694 ///
695 /// for (key, val) in &map {
696 /// println!("key: {key} val: {val}");
697 /// }
698 /// ```
699 ///
700 /// # Performance
701 ///
702 /// In the current implementation, iterating over map takes O(capacity) time
703 /// instead of O(len) because it internally visits empty buckets too.
704 #[rustc_lint_query_instability]
705 #[stable(feature = "rust1", since = "1.0.0")]
706 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
707 IterMut { base: self.base.iter_mut() }
708 }
709
710 /// Returns the number of elements in the map.
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// use std::collections::HashMap;
716 ///
717 /// let mut a = HashMap::new();
718 /// assert_eq!(a.len(), 0);
719 /// a.insert(1, "a");
720 /// assert_eq!(a.len(), 1);
721 /// ```
722 #[stable(feature = "rust1", since = "1.0.0")]
723 pub fn len(&self) -> usize {
724 self.base.len()
725 }
726
727 /// Returns `true` if the map contains no elements.
728 ///
729 /// # Examples
730 ///
731 /// ```
732 /// use std::collections::HashMap;
733 ///
734 /// let mut a = HashMap::new();
735 /// assert!(a.is_empty());
736 /// a.insert(1, "a");
737 /// assert!(!a.is_empty());
738 /// ```
739 #[inline]
740 #[stable(feature = "rust1", since = "1.0.0")]
741 pub fn is_empty(&self) -> bool {
742 self.base.is_empty()
743 }
744
745 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
746 /// allocated memory for reuse.
747 ///
748 /// If the returned iterator is dropped before being fully consumed, it
749 /// drops the remaining key-value pairs. The returned iterator keeps a
750 /// mutable borrow on the map to optimize its implementation.
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// use std::collections::HashMap;
756 ///
757 /// let mut a = HashMap::new();
758 /// a.insert(1, "a");
759 /// a.insert(2, "b");
760 ///
761 /// for (k, v) in a.drain().take(1) {
762 /// assert!(k == 1 || k == 2);
763 /// assert!(v == "a" || v == "b");
764 /// }
765 ///
766 /// assert!(a.is_empty());
767 /// ```
768 #[inline]
769 #[rustc_lint_query_instability]
770 #[stable(feature = "drain", since = "1.6.0")]
771 pub fn drain(&mut self) -> Drain<'_, K, V, A> {
772 Drain { base: self.base.drain() }
773 }
774
775 /// Creates an iterator which uses a closure to determine if an element (key-value pair) should be removed.
776 ///
777 /// If the closure returns `true`, the element is removed from the map and
778 /// yielded. If the closure returns `false`, or panics, the element remains
779 /// in the map and will not be yielded.
780 ///
781 /// The iterator also lets you mutate the value of each element in the
782 /// closure, regardless of whether you choose to keep or remove it.
783 ///
784 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
785 /// or the iteration short-circuits, then the remaining elements will be retained.
786 /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
787 ///
788 /// [`retain`]: HashMap::retain
789 ///
790 /// # Examples
791 ///
792 /// Splitting a map into even and odd keys, reusing the original map:
793 ///
794 /// ```
795 /// use std::collections::HashMap;
796 ///
797 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
798 /// let extracted: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
799 ///
800 /// let mut evens = extracted.keys().copied().collect::<Vec<_>>();
801 /// let mut odds = map.keys().copied().collect::<Vec<_>>();
802 /// evens.sort();
803 /// odds.sort();
804 ///
805 /// assert_eq!(evens, vec![0, 2, 4, 6]);
806 /// assert_eq!(odds, vec![1, 3, 5, 7]);
807 /// ```
808 #[inline]
809 #[rustc_lint_query_instability]
810 #[stable(feature = "hash_extract_if", since = "1.88.0")]
811 pub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, K, V, F, A>
812 where
813 F: FnMut(&K, &mut V) -> bool,
814 {
815 ExtractIf { base: self.base.extract_if(pred) }
816 }
817
818 /// Retains only the elements specified by the predicate.
819 ///
820 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
821 /// The elements are visited in unsorted (and unspecified) order.
822 ///
823 /// # Examples
824 ///
825 /// ```
826 /// use std::collections::HashMap;
827 ///
828 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
829 /// map.retain(|&k, _| k % 2 == 0);
830 /// assert_eq!(map.len(), 4);
831 /// ```
832 ///
833 /// # Performance
834 ///
835 /// In the current implementation, this operation takes O(capacity) time
836 /// instead of O(len) because it internally visits empty buckets too.
837 #[inline]
838 #[rustc_lint_query_instability]
839 #[stable(feature = "retain_hash_collection", since = "1.18.0")]
840 pub fn retain<F>(&mut self, f: F)
841 where
842 F: FnMut(&K, &mut V) -> bool,
843 {
844 self.base.retain(f)
845 }
846
847 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
848 /// for reuse.
849 ///
850 /// # Examples
851 ///
852 /// ```
853 /// use std::collections::HashMap;
854 ///
855 /// let mut a = HashMap::new();
856 /// a.insert(1, "a");
857 /// a.clear();
858 /// assert!(a.is_empty());
859 /// ```
860 #[inline]
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn clear(&mut self) {
863 self.base.clear();
864 }
865
866 /// Returns a reference to the map's [`BuildHasher`].
867 ///
868 /// # Examples
869 ///
870 /// ```
871 /// use std::collections::HashMap;
872 /// use std::hash::RandomState;
873 ///
874 /// let hasher = RandomState::new();
875 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
876 /// let hasher: &RandomState = map.hasher();
877 /// ```
878 #[inline]
879 #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
880 pub fn hasher(&self) -> &S {
881 self.base.hasher()
882 }
883}
884
885impl<K, V, S, A> HashMap<K, V, S, A>
886where
887 K: Eq + Hash,
888 S: BuildHasher,
889 A: Allocator,
890{
891 /// Reserves capacity for at least `additional` more elements to be inserted
892 /// in the `HashMap`. The collection may reserve more space to speculatively
893 /// avoid frequent reallocations. After calling `reserve`,
894 /// capacity will be greater than or equal to `self.len() + additional`.
895 /// Does nothing if capacity is already sufficient.
896 ///
897 /// # Panics
898 ///
899 /// Panics if the new allocation size overflows [`usize`].
900 ///
901 /// # Examples
902 ///
903 /// ```
904 /// use std::collections::HashMap;
905 /// let mut map: HashMap<&str, i32> = HashMap::new();
906 /// map.reserve(10);
907 /// ```
908 #[inline]
909 #[stable(feature = "rust1", since = "1.0.0")]
910 pub fn reserve(&mut self, additional: usize) {
911 self.base.reserve(additional)
912 }
913
914 /// Tries to reserve capacity for at least `additional` more elements to be inserted
915 /// in the `HashMap`. The collection may reserve more space to speculatively
916 /// avoid frequent reallocations. After calling `try_reserve`,
917 /// capacity will be greater than or equal to `self.len() + additional` if
918 /// it returns `Ok(())`.
919 /// Does nothing if capacity is already sufficient.
920 ///
921 /// # Errors
922 ///
923 /// If the capacity overflows, or the allocator reports a failure, then an error
924 /// is returned.
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// use std::collections::HashMap;
930 ///
931 /// let mut map: HashMap<&str, isize> = HashMap::new();
932 /// map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?");
933 /// ```
934 #[inline]
935 #[stable(feature = "try_reserve", since = "1.57.0")]
936 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
937 self.base.try_reserve(additional).map_err(map_try_reserve_error)
938 }
939
940 /// Shrinks the capacity of the map as much as possible. It will drop
941 /// down as much as possible while maintaining the internal rules
942 /// and possibly leaving some space in accordance with the resize policy.
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// use std::collections::HashMap;
948 ///
949 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
950 /// map.insert(1, 2);
951 /// map.insert(3, 4);
952 /// assert!(map.capacity() >= 100);
953 /// map.shrink_to_fit();
954 /// assert!(map.capacity() >= 2);
955 /// ```
956 #[inline]
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn shrink_to_fit(&mut self) {
959 self.base.shrink_to_fit();
960 }
961
962 /// Shrinks the capacity of the map with a lower limit. It will drop
963 /// down no lower than the supplied limit while maintaining the internal rules
964 /// and possibly leaving some space in accordance with the resize policy.
965 ///
966 /// If the current capacity is less than the lower limit, this is a no-op.
967 ///
968 /// # Examples
969 ///
970 /// ```
971 /// use std::collections::HashMap;
972 ///
973 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
974 /// map.insert(1, 2);
975 /// map.insert(3, 4);
976 /// assert!(map.capacity() >= 100);
977 /// map.shrink_to(10);
978 /// assert!(map.capacity() >= 10);
979 /// map.shrink_to(0);
980 /// assert!(map.capacity() >= 2);
981 /// ```
982 #[inline]
983 #[stable(feature = "shrink_to", since = "1.56.0")]
984 pub fn shrink_to(&mut self, min_capacity: usize) {
985 self.base.shrink_to(min_capacity);
986 }
987
988 /// Gets the given key's corresponding entry in the map for in-place manipulation.
989 ///
990 /// # Examples
991 ///
992 /// ```
993 /// use std::collections::HashMap;
994 ///
995 /// let mut letters = HashMap::new();
996 ///
997 /// for ch in "a short treatise on fungi".chars() {
998 /// letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
999 /// }
1000 ///
1001 /// assert_eq!(letters[&'s'], 2);
1002 /// assert_eq!(letters[&'t'], 3);
1003 /// assert_eq!(letters[&'u'], 1);
1004 /// assert_eq!(letters.get(&'y'), None);
1005 /// ```
1006 #[inline]
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A> {
1009 map_entry(self.base.rustc_entry(key))
1010 }
1011
1012 /// Returns a reference to the value corresponding to the key.
1013 ///
1014 /// The key may be any borrowed form of the map's key type, but
1015 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1016 /// the key type.
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// use std::collections::HashMap;
1022 ///
1023 /// let mut map = HashMap::new();
1024 /// map.insert(1, "a");
1025 /// assert_eq!(map.get(&1), Some(&"a"));
1026 /// assert_eq!(map.get(&2), None);
1027 /// ```
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 #[inline]
1030 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1031 where
1032 K: Borrow<Q>,
1033 Q: Hash + Eq,
1034 {
1035 self.base.get(k)
1036 }
1037
1038 /// Returns the key-value pair corresponding to the supplied key. This is
1039 /// potentially useful:
1040 /// - for key types where non-identical keys can be considered equal;
1041 /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
1042 /// - for getting a reference to a key with the same lifetime as the collection.
1043 ///
1044 /// The supplied key may be any borrowed form of the map's key type, but
1045 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1046 /// the key type.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// use std::collections::HashMap;
1052 /// use std::hash::{Hash, Hasher};
1053 ///
1054 /// #[derive(Clone, Copy, Debug)]
1055 /// struct S {
1056 /// id: u32,
1057 /// # #[allow(unused)] // prevents a "field `name` is never read" error
1058 /// name: &'static str, // ignored by equality and hashing operations
1059 /// }
1060 ///
1061 /// impl PartialEq for S {
1062 /// fn eq(&self, other: &S) -> bool {
1063 /// self.id == other.id
1064 /// }
1065 /// }
1066 ///
1067 /// impl Eq for S {}
1068 ///
1069 /// impl Hash for S {
1070 /// fn hash<H: Hasher>(&self, state: &mut H) {
1071 /// self.id.hash(state);
1072 /// }
1073 /// }
1074 ///
1075 /// let j_a = S { id: 1, name: "Jessica" };
1076 /// let j_b = S { id: 1, name: "Jess" };
1077 /// let p = S { id: 2, name: "Paul" };
1078 /// assert_eq!(j_a, j_b);
1079 ///
1080 /// let mut map = HashMap::new();
1081 /// map.insert(j_a, "Paris");
1082 /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
1083 /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
1084 /// assert_eq!(map.get_key_value(&p), None);
1085 /// ```
1086 #[inline]
1087 #[stable(feature = "map_get_key_value", since = "1.40.0")]
1088 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1089 where
1090 K: Borrow<Q>,
1091 Q: Hash + Eq,
1092 {
1093 self.base.get_key_value(k)
1094 }
1095
1096 /// Attempts to get mutable references to `N` values in the map at once.
1097 ///
1098 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1099 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1100 ///
1101 /// This method performs a check to ensure there are no duplicate keys, which currently has a time-complexity of O(n^2),
1102 /// so be careful when passing many keys.
1103 ///
1104 /// # Panics
1105 ///
1106 /// Panics if any keys are overlapping.
1107 ///
1108 /// # Examples
1109 ///
1110 /// ```
1111 /// use std::collections::HashMap;
1112 ///
1113 /// let mut libraries = HashMap::new();
1114 /// libraries.insert("Bodleian Library".to_string(), 1602);
1115 /// libraries.insert("Athenæum".to_string(), 1807);
1116 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1117 /// libraries.insert("Library of Congress".to_string(), 1800);
1118 ///
1119 /// // Get Athenæum and Bodleian Library
1120 /// let [Some(a), Some(b)] = libraries.get_disjoint_mut([
1121 /// "Athenæum",
1122 /// "Bodleian Library",
1123 /// ]) else { panic!() };
1124 ///
1125 /// // Assert values of Athenæum and Library of Congress
1126 /// let got = libraries.get_disjoint_mut([
1127 /// "Athenæum",
1128 /// "Library of Congress",
1129 /// ]);
1130 /// assert_eq!(
1131 /// got,
1132 /// [
1133 /// Some(&mut 1807),
1134 /// Some(&mut 1800),
1135 /// ],
1136 /// );
1137 ///
1138 /// // Missing keys result in None
1139 /// let got = libraries.get_disjoint_mut([
1140 /// "Athenæum",
1141 /// "New York Public Library",
1142 /// ]);
1143 /// assert_eq!(
1144 /// got,
1145 /// [
1146 /// Some(&mut 1807),
1147 /// None
1148 /// ]
1149 /// );
1150 /// ```
1151 ///
1152 /// ```should_panic
1153 /// use std::collections::HashMap;
1154 ///
1155 /// let mut libraries = HashMap::new();
1156 /// libraries.insert("Athenæum".to_string(), 1807);
1157 ///
1158 /// // Duplicate keys panic!
1159 /// let got = libraries.get_disjoint_mut([
1160 /// "Athenæum",
1161 /// "Athenæum",
1162 /// ]);
1163 /// ```
1164 #[inline]
1165 #[doc(alias = "get_many_mut")]
1166 #[stable(feature = "map_many_mut", since = "1.86.0")]
1167 pub fn get_disjoint_mut<Q: ?Sized, const N: usize>(
1168 &mut self,
1169 ks: [&Q; N],
1170 ) -> [Option<&'_ mut V>; N]
1171 where
1172 K: Borrow<Q>,
1173 Q: Hash + Eq,
1174 {
1175 self.base.get_disjoint_mut(ks)
1176 }
1177
1178 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1179 /// the values are unique.
1180 ///
1181 /// Returns an array of length `N` with the results of each query. `None` will be used if
1182 /// the key is missing.
1183 ///
1184 /// For a safe alternative see [`get_disjoint_mut`](`HashMap::get_disjoint_mut`).
1185 ///
1186 /// # Safety
1187 ///
1188 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1189 /// references are not used.
1190 ///
1191 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1192 ///
1193 /// # Examples
1194 ///
1195 /// ```
1196 /// use std::collections::HashMap;
1197 ///
1198 /// let mut libraries = HashMap::new();
1199 /// libraries.insert("Bodleian Library".to_string(), 1602);
1200 /// libraries.insert("Athenæum".to_string(), 1807);
1201 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1202 /// libraries.insert("Library of Congress".to_string(), 1800);
1203 ///
1204 /// // SAFETY: The keys do not overlap.
1205 /// let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([
1206 /// "Athenæum",
1207 /// "Bodleian Library",
1208 /// ]) }) else { panic!() };
1209 ///
1210 /// // SAFETY: The keys do not overlap.
1211 /// let got = unsafe { libraries.get_disjoint_unchecked_mut([
1212 /// "Athenæum",
1213 /// "Library of Congress",
1214 /// ]) };
1215 /// assert_eq!(
1216 /// got,
1217 /// [
1218 /// Some(&mut 1807),
1219 /// Some(&mut 1800),
1220 /// ],
1221 /// );
1222 ///
1223 /// // SAFETY: The keys do not overlap.
1224 /// let got = unsafe { libraries.get_disjoint_unchecked_mut([
1225 /// "Athenæum",
1226 /// "New York Public Library",
1227 /// ]) };
1228 /// // Missing keys result in None
1229 /// assert_eq!(got, [Some(&mut 1807), None]);
1230 /// ```
1231 #[inline]
1232 #[doc(alias = "get_many_unchecked_mut")]
1233 #[stable(feature = "map_many_mut", since = "1.86.0")]
1234 pub unsafe fn get_disjoint_unchecked_mut<Q: ?Sized, const N: usize>(
1235 &mut self,
1236 ks: [&Q; N],
1237 ) -> [Option<&'_ mut V>; N]
1238 where
1239 K: Borrow<Q>,
1240 Q: Hash + Eq,
1241 {
1242 unsafe { self.base.get_disjoint_unchecked_mut(ks) }
1243 }
1244
1245 /// Returns `true` if the map contains a value for the specified key.
1246 ///
1247 /// The key may be any borrowed form of the map's key type, but
1248 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1249 /// the key type.
1250 ///
1251 /// # Examples
1252 ///
1253 /// ```
1254 /// use std::collections::HashMap;
1255 ///
1256 /// let mut map = HashMap::new();
1257 /// map.insert(1, "a");
1258 /// assert_eq!(map.contains_key(&1), true);
1259 /// assert_eq!(map.contains_key(&2), false);
1260 /// ```
1261 #[inline]
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_contains_key")]
1264 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1265 where
1266 K: Borrow<Q>,
1267 Q: Hash + Eq,
1268 {
1269 self.base.contains_key(k)
1270 }
1271
1272 /// Returns a mutable reference to the value corresponding to the key.
1273 ///
1274 /// The key may be any borrowed form of the map's key type, but
1275 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1276 /// the key type.
1277 ///
1278 /// # Examples
1279 ///
1280 /// ```
1281 /// use std::collections::HashMap;
1282 ///
1283 /// let mut map = HashMap::new();
1284 /// map.insert(1, "a");
1285 /// if let Some(x) = map.get_mut(&1) {
1286 /// *x = "b";
1287 /// }
1288 /// assert_eq!(map[&1], "b");
1289 /// ```
1290 #[inline]
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1293 where
1294 K: Borrow<Q>,
1295 Q: Hash + Eq,
1296 {
1297 self.base.get_mut(k)
1298 }
1299
1300 /// Inserts a key-value pair into the map.
1301 ///
1302 /// If the map did not have this key present, [`None`] is returned.
1303 ///
1304 /// If the map did have this key present, the value is updated, and the old
1305 /// value is returned. The key is not updated, though; this matters for
1306 /// types that can be `==` without being identical. See the [module-level
1307 /// documentation] for more.
1308 ///
1309 /// [module-level documentation]: crate::collections#insert-and-complex-keys
1310 ///
1311 /// # Examples
1312 ///
1313 /// ```
1314 /// use std::collections::HashMap;
1315 ///
1316 /// let mut map = HashMap::new();
1317 /// assert_eq!(map.insert(37, "a"), None);
1318 /// assert_eq!(map.is_empty(), false);
1319 ///
1320 /// map.insert(37, "b");
1321 /// assert_eq!(map.insert(37, "c"), Some("b"));
1322 /// assert_eq!(map[&37], "c");
1323 /// ```
1324 #[inline]
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 #[rustc_confusables("push", "append", "put")]
1327 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_insert")]
1328 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1329 self.base.insert(k, v)
1330 }
1331
1332 /// Tries to insert a key-value pair into the map, and returns
1333 /// a mutable reference to the value in the entry.
1334 ///
1335 /// If the map already had this key present, nothing is updated, and
1336 /// an error containing the occupied entry and the value is returned.
1337 ///
1338 /// # Examples
1339 ///
1340 /// Basic usage:
1341 ///
1342 /// ```
1343 /// #![feature(map_try_insert)]
1344 ///
1345 /// use std::collections::HashMap;
1346 ///
1347 /// let mut map = HashMap::new();
1348 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1349 ///
1350 /// let err = map.try_insert(37, "b").unwrap_err();
1351 /// assert_eq!(err.entry.key(), &37);
1352 /// assert_eq!(err.entry.get(), &"a");
1353 /// assert_eq!(err.value, "b");
1354 /// ```
1355 #[unstable(feature = "map_try_insert", issue = "82766")]
1356 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>> {
1357 match self.entry(key) {
1358 Occupied(entry) => Err(OccupiedError { entry, value }),
1359 Vacant(entry) => Ok(entry.insert(value)),
1360 }
1361 }
1362
1363 /// Removes a key from the map, returning the value at the key if the key
1364 /// was previously in the map.
1365 ///
1366 /// The key may be any borrowed form of the map's key type, but
1367 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1368 /// the key type.
1369 ///
1370 /// # Examples
1371 ///
1372 /// ```
1373 /// use std::collections::HashMap;
1374 ///
1375 /// let mut map = HashMap::new();
1376 /// map.insert(1, "a");
1377 /// assert_eq!(map.remove(&1), Some("a"));
1378 /// assert_eq!(map.remove(&1), None);
1379 /// ```
1380 #[inline]
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 #[rustc_confusables("delete", "take")]
1383 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1384 where
1385 K: Borrow<Q>,
1386 Q: Hash + Eq,
1387 {
1388 self.base.remove(k)
1389 }
1390
1391 /// Removes a key from the map, returning the stored key and value if the
1392 /// key was previously in the map.
1393 ///
1394 /// The key may be any borrowed form of the map's key type, but
1395 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1396 /// the key type.
1397 ///
1398 /// # Examples
1399 ///
1400 /// ```
1401 /// use std::collections::HashMap;
1402 ///
1403 /// # fn main() {
1404 /// let mut map = HashMap::new();
1405 /// map.insert(1, "a");
1406 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1407 /// assert_eq!(map.remove(&1), None);
1408 /// # }
1409 /// ```
1410 #[inline]
1411 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1412 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1413 where
1414 K: Borrow<Q>,
1415 Q: Hash + Eq,
1416 {
1417 self.base.remove_entry(k)
1418 }
1419}
1420
1421#[stable(feature = "rust1", since = "1.0.0")]
1422impl<K, V, S, A> Clone for HashMap<K, V, S, A>
1423where
1424 K: Clone,
1425 V: Clone,
1426 S: Clone,
1427 A: Allocator + Clone,
1428{
1429 #[inline]
1430 fn clone(&self) -> Self {
1431 Self { base: self.base.clone() }
1432 }
1433
1434 #[inline]
1435 fn clone_from(&mut self, source: &Self) {
1436 self.base.clone_from(&source.base);
1437 }
1438}
1439
1440#[stable(feature = "rust1", since = "1.0.0")]
1441impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
1442where
1443 K: Eq + Hash,
1444 V: PartialEq,
1445 S: BuildHasher,
1446 A: Allocator,
1447{
1448 fn eq(&self, other: &HashMap<K, V, S, A>) -> bool {
1449 if self.len() != other.len() {
1450 return false;
1451 }
1452
1453 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1454 }
1455}
1456
1457#[stable(feature = "rust1", since = "1.0.0")]
1458impl<K, V, S, A> Eq for HashMap<K, V, S, A>
1459where
1460 K: Eq + Hash,
1461 V: Eq,
1462 S: BuildHasher,
1463 A: Allocator,
1464{
1465}
1466
1467#[stable(feature = "rust1", since = "1.0.0")]
1468impl<K, V, S, A> Debug for HashMap<K, V, S, A>
1469where
1470 K: Debug,
1471 V: Debug,
1472 A: Allocator,
1473{
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 f.debug_map().entries(self.iter()).finish()
1476 }
1477}
1478
1479#[stable(feature = "rust1", since = "1.0.0")]
1480#[rustc_const_unstable(feature = "const_default", issue = "143894")]
1481impl<K, V, S> const Default for HashMap<K, V, S>
1482where
1483 S: [const] Default,
1484{
1485 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1486 #[inline]
1487 fn default() -> HashMap<K, V, S> {
1488 HashMap::with_hasher(Default::default())
1489 }
1490}
1491
1492#[stable(feature = "rust1", since = "1.0.0")]
1493impl<K, Q: ?Sized, V, S, A> Index<&Q> for HashMap<K, V, S, A>
1494where
1495 K: Eq + Hash + Borrow<Q>,
1496 Q: Eq + Hash,
1497 S: BuildHasher,
1498 A: Allocator,
1499{
1500 type Output = V;
1501
1502 /// Returns a reference to the value corresponding to the supplied key.
1503 ///
1504 /// # Panics
1505 ///
1506 /// Panics if the key is not present in the `HashMap`.
1507 #[inline]
1508 fn index(&self, key: &Q) -> &V {
1509 self.get(key).expect("no entry found for key")
1510 }
1511}
1512
1513#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1514// Note: as what is currently the most convenient built-in way to construct
1515// a HashMap, a simple usage of this function must not *require* the user
1516// to provide a type annotation in order to infer the third type parameter
1517// (the hasher parameter, conventionally "S").
1518// To that end, this impl is defined using RandomState as the concrete
1519// type of S, rather than being generic over `S: BuildHasher + Default`.
1520// It is expected that users who want to specify a hasher will manually use
1521// `with_capacity_and_hasher`.
1522// If type parameter defaults worked on impls, and if type parameter
1523// defaults could be mixed with const generics, then perhaps
1524// this could be generalized.
1525// See also the equivalent impl on HashSet.
1526impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
1527where
1528 K: Eq + Hash,
1529{
1530 /// Converts a `[(K, V); N]` into a `HashMap<K, V>`.
1531 ///
1532 /// If any entries in the array have equal keys,
1533 /// all but one of the corresponding values will be dropped.
1534 ///
1535 /// # Examples
1536 ///
1537 /// ```
1538 /// use std::collections::HashMap;
1539 ///
1540 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1541 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1542 /// assert_eq!(map1, map2);
1543 /// ```
1544 fn from(arr: [(K, V); N]) -> Self {
1545 Self::from_iter(arr)
1546 }
1547}
1548
1549/// An iterator over the entries of a `HashMap`.
1550///
1551/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1552/// documentation for more.
1553///
1554/// [`iter`]: HashMap::iter
1555///
1556/// # Example
1557///
1558/// ```
1559/// use std::collections::HashMap;
1560///
1561/// let map = HashMap::from([
1562/// ("a", 1),
1563/// ]);
1564/// let iter = map.iter();
1565/// ```
1566#[stable(feature = "rust1", since = "1.0.0")]
1567#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_iter_ty")]
1568pub struct Iter<'a, K: 'a, V: 'a> {
1569 base: base::Iter<'a, K, V>,
1570}
1571
1572// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1573#[stable(feature = "rust1", since = "1.0.0")]
1574impl<K, V> Clone for Iter<'_, K, V> {
1575 #[inline]
1576 fn clone(&self) -> Self {
1577 Iter { base: self.base.clone() }
1578 }
1579}
1580
1581#[stable(feature = "default_iters_hash", since = "1.83.0")]
1582impl<K, V> Default for Iter<'_, K, V> {
1583 #[inline]
1584 fn default() -> Self {
1585 Iter { base: Default::default() }
1586 }
1587}
1588
1589#[stable(feature = "std_debug", since = "1.16.0")]
1590impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592 f.debug_list().entries(self.clone()).finish()
1593 }
1594}
1595
1596/// A mutable iterator over the entries of a `HashMap`.
1597///
1598/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1599/// documentation for more.
1600///
1601/// [`iter_mut`]: HashMap::iter_mut
1602///
1603/// # Example
1604///
1605/// ```
1606/// use std::collections::HashMap;
1607///
1608/// let mut map = HashMap::from([
1609/// ("a", 1),
1610/// ]);
1611/// let iter = map.iter_mut();
1612/// ```
1613#[stable(feature = "rust1", since = "1.0.0")]
1614#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_iter_mut_ty")]
1615pub struct IterMut<'a, K: 'a, V: 'a> {
1616 base: base::IterMut<'a, K, V>,
1617}
1618
1619impl<'a, K, V> IterMut<'a, K, V> {
1620 /// Returns an iterator of references over the remaining items.
1621 #[inline]
1622 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1623 Iter { base: self.base.rustc_iter() }
1624 }
1625}
1626
1627#[stable(feature = "default_iters_hash", since = "1.83.0")]
1628impl<K, V> Default for IterMut<'_, K, V> {
1629 #[inline]
1630 fn default() -> Self {
1631 IterMut { base: Default::default() }
1632 }
1633}
1634
1635/// An owning iterator over the entries of a `HashMap`.
1636///
1637/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1638/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1639///
1640/// [`into_iter`]: IntoIterator::into_iter
1641///
1642/// # Example
1643///
1644/// ```
1645/// use std::collections::HashMap;
1646///
1647/// let map = HashMap::from([
1648/// ("a", 1),
1649/// ]);
1650/// let iter = map.into_iter();
1651/// ```
1652#[stable(feature = "rust1", since = "1.0.0")]
1653pub struct IntoIter<
1654 K,
1655 V,
1656 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1657> {
1658 base: base::IntoIter<K, V, A>,
1659}
1660
1661impl<K, V, A: Allocator> IntoIter<K, V, A> {
1662 /// Returns an iterator of references over the remaining items.
1663 #[inline]
1664 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1665 Iter { base: self.base.rustc_iter() }
1666 }
1667}
1668
1669#[stable(feature = "default_iters_hash", since = "1.83.0")]
1670impl<K, V> Default for IntoIter<K, V> {
1671 #[inline]
1672 fn default() -> Self {
1673 IntoIter { base: Default::default() }
1674 }
1675}
1676
1677/// An iterator over the keys of a `HashMap`.
1678///
1679/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1680/// documentation for more.
1681///
1682/// [`keys`]: HashMap::keys
1683///
1684/// # Example
1685///
1686/// ```
1687/// use std::collections::HashMap;
1688///
1689/// let map = HashMap::from([
1690/// ("a", 1),
1691/// ]);
1692/// let iter_keys = map.keys();
1693/// ```
1694#[stable(feature = "rust1", since = "1.0.0")]
1695#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_keys_ty")]
1696pub struct Keys<'a, K: 'a, V: 'a> {
1697 inner: Iter<'a, K, V>,
1698}
1699
1700// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1701#[stable(feature = "rust1", since = "1.0.0")]
1702impl<K, V> Clone for Keys<'_, K, V> {
1703 #[inline]
1704 fn clone(&self) -> Self {
1705 Keys { inner: self.inner.clone() }
1706 }
1707}
1708
1709#[stable(feature = "default_iters_hash", since = "1.83.0")]
1710impl<K, V> Default for Keys<'_, K, V> {
1711 #[inline]
1712 fn default() -> Self {
1713 Keys { inner: Default::default() }
1714 }
1715}
1716
1717#[stable(feature = "std_debug", since = "1.16.0")]
1718impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1720 f.debug_list().entries(self.clone()).finish()
1721 }
1722}
1723
1724/// An iterator over the values of a `HashMap`.
1725///
1726/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1727/// documentation for more.
1728///
1729/// [`values`]: HashMap::values
1730///
1731/// # Example
1732///
1733/// ```
1734/// use std::collections::HashMap;
1735///
1736/// let map = HashMap::from([
1737/// ("a", 1),
1738/// ]);
1739/// let iter_values = map.values();
1740/// ```
1741#[stable(feature = "rust1", since = "1.0.0")]
1742#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_values_ty")]
1743pub struct Values<'a, K: 'a, V: 'a> {
1744 inner: Iter<'a, K, V>,
1745}
1746
1747// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1748#[stable(feature = "rust1", since = "1.0.0")]
1749impl<K, V> Clone for Values<'_, K, V> {
1750 #[inline]
1751 fn clone(&self) -> Self {
1752 Values { inner: self.inner.clone() }
1753 }
1754}
1755
1756#[stable(feature = "default_iters_hash", since = "1.83.0")]
1757impl<K, V> Default for Values<'_, K, V> {
1758 #[inline]
1759 fn default() -> Self {
1760 Values { inner: Default::default() }
1761 }
1762}
1763
1764#[stable(feature = "std_debug", since = "1.16.0")]
1765impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1766 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1767 f.debug_list().entries(self.clone()).finish()
1768 }
1769}
1770
1771/// A draining iterator over the entries of a `HashMap`.
1772///
1773/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1774/// documentation for more.
1775///
1776/// [`drain`]: HashMap::drain
1777///
1778/// # Example
1779///
1780/// ```
1781/// use std::collections::HashMap;
1782///
1783/// let mut map = HashMap::from([
1784/// ("a", 1),
1785/// ]);
1786/// let iter = map.drain();
1787/// ```
1788#[stable(feature = "drain", since = "1.6.0")]
1789#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_drain_ty")]
1790pub struct Drain<
1791 'a,
1792 K: 'a,
1793 V: 'a,
1794 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1795> {
1796 base: base::Drain<'a, K, V, A>,
1797}
1798
1799impl<'a, K, V, A: Allocator> Drain<'a, K, V, A> {
1800 /// Returns an iterator of references over the remaining items.
1801 #[inline]
1802 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1803 Iter { base: self.base.rustc_iter() }
1804 }
1805}
1806
1807/// A draining, filtering iterator over the entries of a `HashMap`.
1808///
1809/// This `struct` is created by the [`extract_if`] method on [`HashMap`].
1810///
1811/// [`extract_if`]: HashMap::extract_if
1812///
1813/// # Example
1814///
1815/// ```
1816/// use std::collections::HashMap;
1817///
1818/// let mut map = HashMap::from([
1819/// ("a", 1),
1820/// ]);
1821/// let iter = map.extract_if(|_k, v| *v % 2 == 0);
1822/// ```
1823#[stable(feature = "hash_extract_if", since = "1.88.0")]
1824#[must_use = "iterators are lazy and do nothing unless consumed; \
1825 use `retain` to remove and discard elements"]
1826pub struct ExtractIf<
1827 'a,
1828 K,
1829 V,
1830 F,
1831 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1832> {
1833 base: base::ExtractIf<'a, K, V, F, A>,
1834}
1835
1836/// A mutable iterator over the values of a `HashMap`.
1837///
1838/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1839/// documentation for more.
1840///
1841/// [`values_mut`]: HashMap::values_mut
1842///
1843/// # Example
1844///
1845/// ```
1846/// use std::collections::HashMap;
1847///
1848/// let mut map = HashMap::from([
1849/// ("a", 1),
1850/// ]);
1851/// let iter_values = map.values_mut();
1852/// ```
1853#[stable(feature = "map_values_mut", since = "1.10.0")]
1854#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_values_mut_ty")]
1855pub struct ValuesMut<'a, K: 'a, V: 'a> {
1856 inner: IterMut<'a, K, V>,
1857}
1858
1859#[stable(feature = "default_iters_hash", since = "1.83.0")]
1860impl<K, V> Default for ValuesMut<'_, K, V> {
1861 #[inline]
1862 fn default() -> Self {
1863 ValuesMut { inner: Default::default() }
1864 }
1865}
1866
1867/// An owning iterator over the keys of a `HashMap`.
1868///
1869/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1870/// See its documentation for more.
1871///
1872/// [`into_keys`]: HashMap::into_keys
1873///
1874/// # Example
1875///
1876/// ```
1877/// use std::collections::HashMap;
1878///
1879/// let map = HashMap::from([
1880/// ("a", 1),
1881/// ]);
1882/// let iter_keys = map.into_keys();
1883/// ```
1884#[stable(feature = "map_into_keys_values", since = "1.54.0")]
1885pub struct IntoKeys<
1886 K,
1887 V,
1888 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1889> {
1890 inner: IntoIter<K, V, A>,
1891}
1892
1893#[stable(feature = "default_iters_hash", since = "1.83.0")]
1894impl<K, V> Default for IntoKeys<K, V> {
1895 #[inline]
1896 fn default() -> Self {
1897 IntoKeys { inner: Default::default() }
1898 }
1899}
1900
1901/// An owning iterator over the values of a `HashMap`.
1902///
1903/// This `struct` is created by the [`into_values`] method on [`HashMap`].
1904/// See its documentation for more.
1905///
1906/// [`into_values`]: HashMap::into_values
1907///
1908/// # Example
1909///
1910/// ```
1911/// use std::collections::HashMap;
1912///
1913/// let map = HashMap::from([
1914/// ("a", 1),
1915/// ]);
1916/// let iter_keys = map.into_values();
1917/// ```
1918#[stable(feature = "map_into_keys_values", since = "1.54.0")]
1919pub struct IntoValues<
1920 K,
1921 V,
1922 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1923> {
1924 inner: IntoIter<K, V, A>,
1925}
1926
1927#[stable(feature = "default_iters_hash", since = "1.83.0")]
1928impl<K, V> Default for IntoValues<K, V> {
1929 #[inline]
1930 fn default() -> Self {
1931 IntoValues { inner: Default::default() }
1932 }
1933}
1934
1935/// A view into a single entry in a map, which may either be vacant or occupied.
1936///
1937/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1938///
1939/// [`entry`]: HashMap::entry
1940#[stable(feature = "rust1", since = "1.0.0")]
1941#[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
1942pub enum Entry<
1943 'a,
1944 K: 'a,
1945 V: 'a,
1946 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1947> {
1948 /// An occupied entry.
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V, A>),
1951
1952 /// A vacant entry.
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V, A>),
1955}
1956
1957#[stable(feature = "debug_hash_map", since = "1.12.0")]
1958impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1960 match *self {
1961 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1962 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1963 }
1964 }
1965}
1966
1967/// A view into an occupied entry in a `HashMap`.
1968/// It is part of the [`Entry`] enum.
1969#[stable(feature = "rust1", since = "1.0.0")]
1970pub struct OccupiedEntry<
1971 'a,
1972 K: 'a,
1973 V: 'a,
1974 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1975> {
1976 base: base::RustcOccupiedEntry<'a, K, V, A>,
1977}
1978
1979#[stable(feature = "debug_hash_map", since = "1.12.0")]
1980impl<K: Debug, V: Debug, A: Allocator> Debug for OccupiedEntry<'_, K, V, A> {
1981 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1982 f.debug_struct("OccupiedEntry")
1983 .field("key", self.key())
1984 .field("value", self.get())
1985 .finish_non_exhaustive()
1986 }
1987}
1988
1989/// A view into a vacant entry in a `HashMap`.
1990/// It is part of the [`Entry`] enum.
1991#[stable(feature = "rust1", since = "1.0.0")]
1992pub struct VacantEntry<
1993 'a,
1994 K: 'a,
1995 V: 'a,
1996 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1997> {
1998 base: base::RustcVacantEntry<'a, K, V, A>,
1999}
2000
2001#[stable(feature = "debug_hash_map", since = "1.12.0")]
2002impl<K: Debug, V, A: Allocator> Debug for VacantEntry<'_, K, V, A> {
2003 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2004 f.debug_tuple("VacantEntry").field(self.key()).finish()
2005 }
2006}
2007
2008/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
2009///
2010/// Contains the occupied entry, and the value that was not inserted.
2011#[unstable(feature = "map_try_insert", issue = "82766")]
2012pub struct OccupiedError<
2013 'a,
2014 K: 'a,
2015 V: 'a,
2016 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
2017> {
2018 /// The entry in the map that was already occupied.
2019 pub entry: OccupiedEntry<'a, K, V, A>,
2020 /// The value which was not inserted, because the entry was already occupied.
2021 pub value: V,
2022}
2023
2024#[unstable(feature = "map_try_insert", issue = "82766")]
2025impl<K: Debug, V: Debug, A: Allocator> Debug for OccupiedError<'_, K, V, A> {
2026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2027 f.debug_struct("OccupiedError")
2028 .field("key", self.entry.key())
2029 .field("old_value", self.entry.get())
2030 .field("new_value", &self.value)
2031 .finish_non_exhaustive()
2032 }
2033}
2034
2035#[unstable(feature = "map_try_insert", issue = "82766")]
2036impl<'a, K: Debug, V: Debug, A: Allocator> fmt::Display for OccupiedError<'a, K, V, A> {
2037 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2038 write!(
2039 f,
2040 "failed to insert {:?}, key {:?} already exists with value {:?}",
2041 self.value,
2042 self.entry.key(),
2043 self.entry.get(),
2044 )
2045 }
2046}
2047
2048#[unstable(feature = "map_try_insert", issue = "82766")]
2049impl<'a, K: Debug, V: Debug, A: Allocator> Error for OccupiedError<'a, K, V, A> {}
2050
2051#[stable(feature = "rust1", since = "1.0.0")]
2052impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
2053 type Item = (&'a K, &'a V);
2054 type IntoIter = Iter<'a, K, V>;
2055
2056 #[inline]
2057 #[rustc_lint_query_instability]
2058 fn into_iter(self) -> Iter<'a, K, V> {
2059 self.iter()
2060 }
2061}
2062
2063#[stable(feature = "rust1", since = "1.0.0")]
2064impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
2065 type Item = (&'a K, &'a mut V);
2066 type IntoIter = IterMut<'a, K, V>;
2067
2068 #[inline]
2069 #[rustc_lint_query_instability]
2070 fn into_iter(self) -> IterMut<'a, K, V> {
2071 self.iter_mut()
2072 }
2073}
2074
2075#[stable(feature = "rust1", since = "1.0.0")]
2076impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
2077 type Item = (K, V);
2078 type IntoIter = IntoIter<K, V, A>;
2079
2080 /// Creates a consuming iterator, that is, one that moves each key-value
2081 /// pair out of the map in arbitrary order. The map cannot be used after
2082 /// calling this.
2083 ///
2084 /// # Examples
2085 ///
2086 /// ```
2087 /// use std::collections::HashMap;
2088 ///
2089 /// let map = HashMap::from([
2090 /// ("a", 1),
2091 /// ("b", 2),
2092 /// ("c", 3),
2093 /// ]);
2094 ///
2095 /// // Not possible with .iter()
2096 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2097 /// ```
2098 #[inline]
2099 #[rustc_lint_query_instability]
2100 fn into_iter(self) -> IntoIter<K, V, A> {
2101 IntoIter { base: self.base.into_iter() }
2102 }
2103}
2104
2105#[stable(feature = "rust1", since = "1.0.0")]
2106impl<'a, K, V> Iterator for Iter<'a, K, V> {
2107 type Item = (&'a K, &'a V);
2108
2109 #[inline]
2110 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2111 self.base.next()
2112 }
2113 #[inline]
2114 fn size_hint(&self) -> (usize, Option<usize>) {
2115 self.base.size_hint()
2116 }
2117 #[inline]
2118 fn count(self) -> usize {
2119 self.base.len()
2120 }
2121 #[inline]
2122 fn fold<B, F>(self, init: B, f: F) -> B
2123 where
2124 Self: Sized,
2125 F: FnMut(B, Self::Item) -> B,
2126 {
2127 self.base.fold(init, f)
2128 }
2129}
2130#[stable(feature = "rust1", since = "1.0.0")]
2131impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
2132 #[inline]
2133 fn len(&self) -> usize {
2134 self.base.len()
2135 }
2136}
2137
2138#[stable(feature = "fused", since = "1.26.0")]
2139impl<K, V> FusedIterator for Iter<'_, K, V> {}
2140
2141#[stable(feature = "rust1", since = "1.0.0")]
2142impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2143 type Item = (&'a K, &'a mut V);
2144
2145 #[inline]
2146 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2147 self.base.next()
2148 }
2149 #[inline]
2150 fn size_hint(&self) -> (usize, Option<usize>) {
2151 self.base.size_hint()
2152 }
2153 #[inline]
2154 fn count(self) -> usize {
2155 self.base.len()
2156 }
2157 #[inline]
2158 fn fold<B, F>(self, init: B, f: F) -> B
2159 where
2160 Self: Sized,
2161 F: FnMut(B, Self::Item) -> B,
2162 {
2163 self.base.fold(init, f)
2164 }
2165}
2166#[stable(feature = "rust1", since = "1.0.0")]
2167impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2168 #[inline]
2169 fn len(&self) -> usize {
2170 self.base.len()
2171 }
2172}
2173#[stable(feature = "fused", since = "1.26.0")]
2174impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2175
2176#[stable(feature = "std_debug", since = "1.16.0")]
2177impl<K, V> fmt::Debug for IterMut<'_, K, V>
2178where
2179 K: fmt::Debug,
2180 V: fmt::Debug,
2181{
2182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2183 f.debug_list().entries(self.iter()).finish()
2184 }
2185}
2186
2187#[stable(feature = "rust1", since = "1.0.0")]
2188impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
2189 type Item = (K, V);
2190
2191 #[inline]
2192 fn next(&mut self) -> Option<(K, V)> {
2193 self.base.next()
2194 }
2195 #[inline]
2196 fn size_hint(&self) -> (usize, Option<usize>) {
2197 self.base.size_hint()
2198 }
2199 #[inline]
2200 fn count(self) -> usize {
2201 self.base.len()
2202 }
2203 #[inline]
2204 fn fold<B, F>(self, init: B, f: F) -> B
2205 where
2206 Self: Sized,
2207 F: FnMut(B, Self::Item) -> B,
2208 {
2209 self.base.fold(init, f)
2210 }
2211}
2212#[stable(feature = "rust1", since = "1.0.0")]
2213impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
2214 #[inline]
2215 fn len(&self) -> usize {
2216 self.base.len()
2217 }
2218}
2219#[stable(feature = "fused", since = "1.26.0")]
2220impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
2221
2222#[stable(feature = "std_debug", since = "1.16.0")]
2223impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
2224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2225 f.debug_list().entries(self.iter()).finish()
2226 }
2227}
2228
2229#[stable(feature = "rust1", since = "1.0.0")]
2230impl<'a, K, V> Iterator for Keys<'a, K, V> {
2231 type Item = &'a K;
2232
2233 #[inline]
2234 fn next(&mut self) -> Option<&'a K> {
2235 self.inner.next().map(|(k, _)| k)
2236 }
2237 #[inline]
2238 fn size_hint(&self) -> (usize, Option<usize>) {
2239 self.inner.size_hint()
2240 }
2241 #[inline]
2242 fn count(self) -> usize {
2243 self.inner.len()
2244 }
2245 #[inline]
2246 fn fold<B, F>(self, init: B, mut f: F) -> B
2247 where
2248 Self: Sized,
2249 F: FnMut(B, Self::Item) -> B,
2250 {
2251 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2252 }
2253}
2254#[stable(feature = "rust1", since = "1.0.0")]
2255impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2256 #[inline]
2257 fn len(&self) -> usize {
2258 self.inner.len()
2259 }
2260}
2261#[stable(feature = "fused", since = "1.26.0")]
2262impl<K, V> FusedIterator for Keys<'_, K, V> {}
2263
2264#[stable(feature = "rust1", since = "1.0.0")]
2265impl<'a, K, V> Iterator for Values<'a, K, V> {
2266 type Item = &'a V;
2267
2268 #[inline]
2269 fn next(&mut self) -> Option<&'a V> {
2270 self.inner.next().map(|(_, v)| v)
2271 }
2272 #[inline]
2273 fn size_hint(&self) -> (usize, Option<usize>) {
2274 self.inner.size_hint()
2275 }
2276 #[inline]
2277 fn count(self) -> usize {
2278 self.inner.len()
2279 }
2280 #[inline]
2281 fn fold<B, F>(self, init: B, mut f: F) -> B
2282 where
2283 Self: Sized,
2284 F: FnMut(B, Self::Item) -> B,
2285 {
2286 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2287 }
2288}
2289#[stable(feature = "rust1", since = "1.0.0")]
2290impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2291 #[inline]
2292 fn len(&self) -> usize {
2293 self.inner.len()
2294 }
2295}
2296#[stable(feature = "fused", since = "1.26.0")]
2297impl<K, V> FusedIterator for Values<'_, K, V> {}
2298
2299#[stable(feature = "map_values_mut", since = "1.10.0")]
2300impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2301 type Item = &'a mut V;
2302
2303 #[inline]
2304 fn next(&mut self) -> Option<&'a mut V> {
2305 self.inner.next().map(|(_, v)| v)
2306 }
2307 #[inline]
2308 fn size_hint(&self) -> (usize, Option<usize>) {
2309 self.inner.size_hint()
2310 }
2311 #[inline]
2312 fn count(self) -> usize {
2313 self.inner.len()
2314 }
2315 #[inline]
2316 fn fold<B, F>(self, init: B, mut f: F) -> B
2317 where
2318 Self: Sized,
2319 F: FnMut(B, Self::Item) -> B,
2320 {
2321 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2322 }
2323}
2324#[stable(feature = "map_values_mut", since = "1.10.0")]
2325impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2326 #[inline]
2327 fn len(&self) -> usize {
2328 self.inner.len()
2329 }
2330}
2331#[stable(feature = "fused", since = "1.26.0")]
2332impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2333
2334#[stable(feature = "std_debug", since = "1.16.0")]
2335impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2337 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2338 }
2339}
2340
2341#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2342impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
2343 type Item = K;
2344
2345 #[inline]
2346 fn next(&mut self) -> Option<K> {
2347 self.inner.next().map(|(k, _)| k)
2348 }
2349 #[inline]
2350 fn size_hint(&self) -> (usize, Option<usize>) {
2351 self.inner.size_hint()
2352 }
2353 #[inline]
2354 fn count(self) -> usize {
2355 self.inner.len()
2356 }
2357 #[inline]
2358 fn fold<B, F>(self, init: B, mut f: F) -> B
2359 where
2360 Self: Sized,
2361 F: FnMut(B, Self::Item) -> B,
2362 {
2363 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2364 }
2365}
2366#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2367impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
2368 #[inline]
2369 fn len(&self) -> usize {
2370 self.inner.len()
2371 }
2372}
2373#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2374impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
2375
2376#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2377impl<K: Debug, V, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
2378 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2379 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2380 }
2381}
2382
2383#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2384impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
2385 type Item = V;
2386
2387 #[inline]
2388 fn next(&mut self) -> Option<V> {
2389 self.inner.next().map(|(_, v)| v)
2390 }
2391 #[inline]
2392 fn size_hint(&self) -> (usize, Option<usize>) {
2393 self.inner.size_hint()
2394 }
2395 #[inline]
2396 fn count(self) -> usize {
2397 self.inner.len()
2398 }
2399 #[inline]
2400 fn fold<B, F>(self, init: B, mut f: F) -> B
2401 where
2402 Self: Sized,
2403 F: FnMut(B, Self::Item) -> B,
2404 {
2405 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2406 }
2407}
2408#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2409impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2410 #[inline]
2411 fn len(&self) -> usize {
2412 self.inner.len()
2413 }
2414}
2415#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2416impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2417
2418#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2419impl<K, V: Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
2420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2421 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2422 }
2423}
2424
2425#[stable(feature = "drain", since = "1.6.0")]
2426impl<'a, K, V, A: Allocator> Iterator for Drain<'a, K, V, A> {
2427 type Item = (K, V);
2428
2429 #[inline]
2430 fn next(&mut self) -> Option<(K, V)> {
2431 self.base.next()
2432 }
2433 #[inline]
2434 fn size_hint(&self) -> (usize, Option<usize>) {
2435 self.base.size_hint()
2436 }
2437 #[inline]
2438 fn fold<B, F>(self, init: B, f: F) -> B
2439 where
2440 Self: Sized,
2441 F: FnMut(B, Self::Item) -> B,
2442 {
2443 self.base.fold(init, f)
2444 }
2445}
2446#[stable(feature = "drain", since = "1.6.0")]
2447impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
2448 #[inline]
2449 fn len(&self) -> usize {
2450 self.base.len()
2451 }
2452}
2453#[stable(feature = "fused", since = "1.26.0")]
2454impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
2455
2456#[stable(feature = "std_debug", since = "1.16.0")]
2457impl<K, V, A: Allocator> fmt::Debug for Drain<'_, K, V, A>
2458where
2459 K: fmt::Debug,
2460 V: fmt::Debug,
2461{
2462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2463 f.debug_list().entries(self.iter()).finish()
2464 }
2465}
2466
2467#[stable(feature = "hash_extract_if", since = "1.88.0")]
2468impl<K, V, F, A: Allocator> Iterator for ExtractIf<'_, K, V, F, A>
2469where
2470 F: FnMut(&K, &mut V) -> bool,
2471{
2472 type Item = (K, V);
2473
2474 #[inline]
2475 fn next(&mut self) -> Option<(K, V)> {
2476 self.base.next()
2477 }
2478 #[inline]
2479 fn size_hint(&self) -> (usize, Option<usize>) {
2480 self.base.size_hint()
2481 }
2482}
2483
2484#[stable(feature = "hash_extract_if", since = "1.88.0")]
2485impl<K, V, F, A: Allocator> FusedIterator for ExtractIf<'_, K, V, F, A> where
2486 F: FnMut(&K, &mut V) -> bool
2487{
2488}
2489
2490#[stable(feature = "hash_extract_if", since = "1.88.0")]
2491impl<K, V, F, A: Allocator> fmt::Debug for ExtractIf<'_, K, V, F, A>
2492where
2493 K: fmt::Debug,
2494 V: fmt::Debug,
2495{
2496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2497 f.debug_struct("ExtractIf").finish_non_exhaustive()
2498 }
2499}
2500
2501impl<'a, K, V, A: Allocator> Entry<'a, K, V, A> {
2502 /// Ensures a value is in the entry by inserting the default if empty, and returns
2503 /// a mutable reference to the value in the entry.
2504 ///
2505 /// # Examples
2506 ///
2507 /// ```
2508 /// use std::collections::HashMap;
2509 ///
2510 /// let mut map: HashMap<&str, u32> = HashMap::new();
2511 ///
2512 /// map.entry("poneyland").or_insert(3);
2513 /// assert_eq!(map["poneyland"], 3);
2514 ///
2515 /// *map.entry("poneyland").or_insert(10) *= 2;
2516 /// assert_eq!(map["poneyland"], 6);
2517 /// ```
2518 #[inline]
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 pub fn or_insert(self, default: V) -> &'a mut V {
2521 match self {
2522 Occupied(entry) => entry.into_mut(),
2523 Vacant(entry) => entry.insert(default),
2524 }
2525 }
2526
2527 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2528 /// and returns a mutable reference to the value in the entry.
2529 ///
2530 /// # Examples
2531 ///
2532 /// ```
2533 /// use std::collections::HashMap;
2534 ///
2535 /// let mut map = HashMap::new();
2536 /// let value = "hoho";
2537 ///
2538 /// map.entry("poneyland").or_insert_with(|| value);
2539 ///
2540 /// assert_eq!(map["poneyland"], "hoho");
2541 /// ```
2542 #[inline]
2543 #[stable(feature = "rust1", since = "1.0.0")]
2544 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2545 match self {
2546 Occupied(entry) => entry.into_mut(),
2547 Vacant(entry) => entry.insert(default()),
2548 }
2549 }
2550
2551 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2552 /// This method allows for generating key-derived values for insertion by providing the default
2553 /// function a reference to the key that was moved during the `.entry(key)` method call.
2554 ///
2555 /// The reference to the moved key is provided so that cloning or copying the key is
2556 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2557 ///
2558 /// # Examples
2559 ///
2560 /// ```
2561 /// use std::collections::HashMap;
2562 ///
2563 /// let mut map: HashMap<&str, usize> = HashMap::new();
2564 ///
2565 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2566 ///
2567 /// assert_eq!(map["poneyland"], 9);
2568 /// ```
2569 #[inline]
2570 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2571 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2572 match self {
2573 Occupied(entry) => entry.into_mut(),
2574 Vacant(entry) => {
2575 let value = default(entry.key());
2576 entry.insert(value)
2577 }
2578 }
2579 }
2580
2581 /// Returns a reference to this entry's key.
2582 ///
2583 /// # Examples
2584 ///
2585 /// ```
2586 /// use std::collections::HashMap;
2587 ///
2588 /// let mut map: HashMap<&str, u32> = HashMap::new();
2589 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2590 /// ```
2591 #[inline]
2592 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2593 pub fn key(&self) -> &K {
2594 match *self {
2595 Occupied(ref entry) => entry.key(),
2596 Vacant(ref entry) => entry.key(),
2597 }
2598 }
2599
2600 /// Provides in-place mutable access to an occupied entry before any
2601 /// potential inserts into the map.
2602 ///
2603 /// # Examples
2604 ///
2605 /// ```
2606 /// use std::collections::HashMap;
2607 ///
2608 /// let mut map: HashMap<&str, u32> = HashMap::new();
2609 ///
2610 /// map.entry("poneyland")
2611 /// .and_modify(|e| { *e += 1 })
2612 /// .or_insert(42);
2613 /// assert_eq!(map["poneyland"], 42);
2614 ///
2615 /// map.entry("poneyland")
2616 /// .and_modify(|e| { *e += 1 })
2617 /// .or_insert(42);
2618 /// assert_eq!(map["poneyland"], 43);
2619 /// ```
2620 #[inline]
2621 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2622 pub fn and_modify<F>(self, f: F) -> Self
2623 where
2624 F: FnOnce(&mut V),
2625 {
2626 match self {
2627 Occupied(mut entry) => {
2628 f(entry.get_mut());
2629 Occupied(entry)
2630 }
2631 Vacant(entry) => Vacant(entry),
2632 }
2633 }
2634
2635 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2636 ///
2637 /// # Examples
2638 ///
2639 /// ```
2640 /// use std::collections::HashMap;
2641 ///
2642 /// let mut map: HashMap<&str, String> = HashMap::new();
2643 /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2644 ///
2645 /// assert_eq!(entry.key(), &"poneyland");
2646 /// ```
2647 #[inline]
2648 #[stable(feature = "entry_insert", since = "1.83.0")]
2649 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, A> {
2650 match self {
2651 Occupied(mut entry) => {
2652 entry.insert(value);
2653 entry
2654 }
2655 Vacant(entry) => entry.insert_entry(value),
2656 }
2657 }
2658}
2659
2660impl<'a, K, V: Default> Entry<'a, K, V> {
2661 /// Ensures a value is in the entry by inserting the default value if empty,
2662 /// and returns a mutable reference to the value in the entry.
2663 ///
2664 /// # Examples
2665 ///
2666 /// ```
2667 /// # fn main() {
2668 /// use std::collections::HashMap;
2669 ///
2670 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2671 /// map.entry("poneyland").or_default();
2672 ///
2673 /// assert_eq!(map["poneyland"], None);
2674 /// # }
2675 /// ```
2676 #[inline]
2677 #[stable(feature = "entry_or_default", since = "1.28.0")]
2678 pub fn or_default(self) -> &'a mut V {
2679 match self {
2680 Occupied(entry) => entry.into_mut(),
2681 Vacant(entry) => entry.insert(Default::default()),
2682 }
2683 }
2684}
2685
2686impl<'a, K, V, A: Allocator> OccupiedEntry<'a, K, V, A> {
2687 /// Gets a reference to the key in the entry.
2688 ///
2689 /// # Examples
2690 ///
2691 /// ```
2692 /// use std::collections::HashMap;
2693 ///
2694 /// let mut map: HashMap<&str, u32> = HashMap::new();
2695 /// map.entry("poneyland").or_insert(12);
2696 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2697 /// ```
2698 #[inline]
2699 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2700 pub fn key(&self) -> &K {
2701 self.base.key()
2702 }
2703
2704 /// Take the ownership of the key and value from the map.
2705 ///
2706 /// # Examples
2707 ///
2708 /// ```
2709 /// use std::collections::HashMap;
2710 /// use std::collections::hash_map::Entry;
2711 ///
2712 /// let mut map: HashMap<&str, u32> = HashMap::new();
2713 /// map.entry("poneyland").or_insert(12);
2714 ///
2715 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2716 /// // We delete the entry from the map.
2717 /// o.remove_entry();
2718 /// }
2719 ///
2720 /// assert_eq!(map.contains_key("poneyland"), false);
2721 /// ```
2722 #[inline]
2723 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2724 pub fn remove_entry(self) -> (K, V) {
2725 self.base.remove_entry()
2726 }
2727
2728 /// Gets a reference to the value in the entry.
2729 ///
2730 /// # Examples
2731 ///
2732 /// ```
2733 /// use std::collections::HashMap;
2734 /// use std::collections::hash_map::Entry;
2735 ///
2736 /// let mut map: HashMap<&str, u32> = HashMap::new();
2737 /// map.entry("poneyland").or_insert(12);
2738 ///
2739 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2740 /// assert_eq!(o.get(), &12);
2741 /// }
2742 /// ```
2743 #[inline]
2744 #[stable(feature = "rust1", since = "1.0.0")]
2745 pub fn get(&self) -> &V {
2746 self.base.get()
2747 }
2748
2749 /// Gets a mutable reference to the value in the entry.
2750 ///
2751 /// If you need a reference to the `OccupiedEntry` which may outlive the
2752 /// destruction of the `Entry` value, see [`into_mut`].
2753 ///
2754 /// [`into_mut`]: Self::into_mut
2755 ///
2756 /// # Examples
2757 ///
2758 /// ```
2759 /// use std::collections::HashMap;
2760 /// use std::collections::hash_map::Entry;
2761 ///
2762 /// let mut map: HashMap<&str, u32> = HashMap::new();
2763 /// map.entry("poneyland").or_insert(12);
2764 ///
2765 /// assert_eq!(map["poneyland"], 12);
2766 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2767 /// *o.get_mut() += 10;
2768 /// assert_eq!(*o.get(), 22);
2769 ///
2770 /// // We can use the same Entry multiple times.
2771 /// *o.get_mut() += 2;
2772 /// }
2773 ///
2774 /// assert_eq!(map["poneyland"], 24);
2775 /// ```
2776 #[inline]
2777 #[stable(feature = "rust1", since = "1.0.0")]
2778 pub fn get_mut(&mut self) -> &mut V {
2779 self.base.get_mut()
2780 }
2781
2782 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2783 /// with a lifetime bound to the map itself.
2784 ///
2785 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2786 ///
2787 /// [`get_mut`]: Self::get_mut
2788 ///
2789 /// # Examples
2790 ///
2791 /// ```
2792 /// use std::collections::HashMap;
2793 /// use std::collections::hash_map::Entry;
2794 ///
2795 /// let mut map: HashMap<&str, u32> = HashMap::new();
2796 /// map.entry("poneyland").or_insert(12);
2797 ///
2798 /// assert_eq!(map["poneyland"], 12);
2799 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2800 /// *o.into_mut() += 10;
2801 /// }
2802 ///
2803 /// assert_eq!(map["poneyland"], 22);
2804 /// ```
2805 #[inline]
2806 #[stable(feature = "rust1", since = "1.0.0")]
2807 pub fn into_mut(self) -> &'a mut V {
2808 self.base.into_mut()
2809 }
2810
2811 /// Sets the value of the entry, and returns the entry's old value.
2812 ///
2813 /// # Examples
2814 ///
2815 /// ```
2816 /// use std::collections::HashMap;
2817 /// use std::collections::hash_map::Entry;
2818 ///
2819 /// let mut map: HashMap<&str, u32> = HashMap::new();
2820 /// map.entry("poneyland").or_insert(12);
2821 ///
2822 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2823 /// assert_eq!(o.insert(15), 12);
2824 /// }
2825 ///
2826 /// assert_eq!(map["poneyland"], 15);
2827 /// ```
2828 #[inline]
2829 #[stable(feature = "rust1", since = "1.0.0")]
2830 pub fn insert(&mut self, value: V) -> V {
2831 self.base.insert(value)
2832 }
2833
2834 /// Takes the value out of the entry, and returns it.
2835 ///
2836 /// # Examples
2837 ///
2838 /// ```
2839 /// use std::collections::HashMap;
2840 /// use std::collections::hash_map::Entry;
2841 ///
2842 /// let mut map: HashMap<&str, u32> = HashMap::new();
2843 /// map.entry("poneyland").or_insert(12);
2844 ///
2845 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2846 /// assert_eq!(o.remove(), 12);
2847 /// }
2848 ///
2849 /// assert_eq!(map.contains_key("poneyland"), false);
2850 /// ```
2851 #[inline]
2852 #[stable(feature = "rust1", since = "1.0.0")]
2853 pub fn remove(self) -> V {
2854 self.base.remove()
2855 }
2856}
2857
2858impl<'a, K: 'a, V: 'a, A: Allocator> VacantEntry<'a, K, V, A> {
2859 /// Gets a reference to the key that would be used when inserting a value
2860 /// through the `VacantEntry`.
2861 ///
2862 /// # Examples
2863 ///
2864 /// ```
2865 /// use std::collections::HashMap;
2866 ///
2867 /// let mut map: HashMap<&str, u32> = HashMap::new();
2868 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2869 /// ```
2870 #[inline]
2871 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2872 pub fn key(&self) -> &K {
2873 self.base.key()
2874 }
2875
2876 /// Take ownership of the key.
2877 ///
2878 /// # Examples
2879 ///
2880 /// ```
2881 /// use std::collections::HashMap;
2882 /// use std::collections::hash_map::Entry;
2883 ///
2884 /// let mut map: HashMap<&str, u32> = HashMap::new();
2885 ///
2886 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2887 /// v.into_key();
2888 /// }
2889 /// ```
2890 #[inline]
2891 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2892 pub fn into_key(self) -> K {
2893 self.base.into_key()
2894 }
2895
2896 /// Sets the value of the entry with the `VacantEntry`'s key,
2897 /// and returns a mutable reference to it.
2898 ///
2899 /// # Examples
2900 ///
2901 /// ```
2902 /// use std::collections::HashMap;
2903 /// use std::collections::hash_map::Entry;
2904 ///
2905 /// let mut map: HashMap<&str, u32> = HashMap::new();
2906 ///
2907 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2908 /// o.insert(37);
2909 /// }
2910 /// assert_eq!(map["poneyland"], 37);
2911 /// ```
2912 #[inline]
2913 #[stable(feature = "rust1", since = "1.0.0")]
2914 pub fn insert(self, value: V) -> &'a mut V {
2915 self.base.insert(value)
2916 }
2917
2918 /// Sets the value of the entry with the `VacantEntry`'s key,
2919 /// and returns an `OccupiedEntry`.
2920 ///
2921 /// # Examples
2922 ///
2923 /// ```
2924 /// use std::collections::HashMap;
2925 /// use std::collections::hash_map::Entry;
2926 ///
2927 /// let mut map: HashMap<&str, u32> = HashMap::new();
2928 ///
2929 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2930 /// o.insert_entry(37);
2931 /// }
2932 /// assert_eq!(map["poneyland"], 37);
2933 /// ```
2934 #[inline]
2935 #[stable(feature = "entry_insert", since = "1.83.0")]
2936 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, A> {
2937 let base = self.base.insert_entry(value);
2938 OccupiedEntry { base }
2939 }
2940}
2941
2942#[stable(feature = "rust1", since = "1.0.0")]
2943impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2944where
2945 K: Eq + Hash,
2946 S: BuildHasher + Default,
2947{
2948 /// Constructs a `HashMap<K, V>` from an iterator of key-value pairs.
2949 ///
2950 /// If the iterator produces any pairs with equal keys,
2951 /// all but one of the corresponding values will be dropped.
2952 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2953 let mut map = HashMap::with_hasher(Default::default());
2954 map.extend(iter);
2955 map
2956 }
2957}
2958
2959/// Inserts all new key-values from the iterator and replaces values with existing
2960/// keys with new values returned from the iterator.
2961#[stable(feature = "rust1", since = "1.0.0")]
2962impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
2963where
2964 K: Eq + Hash,
2965 S: BuildHasher,
2966 A: Allocator,
2967{
2968 #[inline]
2969 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2970 self.base.extend(iter)
2971 }
2972
2973 #[inline]
2974 fn extend_one(&mut self, (k, v): (K, V)) {
2975 self.base.insert(k, v);
2976 }
2977
2978 #[inline]
2979 fn extend_reserve(&mut self, additional: usize) {
2980 self.base.extend_reserve(additional);
2981 }
2982}
2983
2984#[stable(feature = "hash_extend_copy", since = "1.4.0")]
2985impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
2986where
2987 K: Eq + Hash + Copy,
2988 V: Copy,
2989 S: BuildHasher,
2990 A: Allocator,
2991{
2992 #[inline]
2993 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2994 self.base.extend(iter)
2995 }
2996
2997 #[inline]
2998 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2999 self.base.insert(k, v);
3000 }
3001
3002 #[inline]
3003 fn extend_reserve(&mut self, additional: usize) {
3004 Extend::<(K, V)>::extend_reserve(self, additional)
3005 }
3006}
3007
3008#[inline]
3009fn map_entry<'a, K: 'a, V: 'a, A: Allocator>(
3010 raw: base::RustcEntry<'a, K, V, A>,
3011) -> Entry<'a, K, V, A> {
3012 match raw {
3013 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
3014 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
3015 }
3016}
3017
3018#[inline]
3019pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
3020 match err {
3021 hashbrown::TryReserveError::CapacityOverflow => {
3022 TryReserveErrorKind::CapacityOverflow.into()
3023 }
3024 hashbrown::TryReserveError::AllocError { layout } => {
3025 TryReserveErrorKind::AllocError { layout, non_exhaustive: () }.into()
3026 }
3027 }
3028}
3029
3030#[allow(dead_code)]
3031fn assert_covariance() {
3032 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3033 v
3034 }
3035 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3036 v
3037 }
3038 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3039 v
3040 }
3041 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3042 v
3043 }
3044 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3045 v
3046 }
3047 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3048 v
3049 }
3050 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3051 v
3052 }
3053 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3054 v
3055 }
3056 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3057 v
3058 }
3059 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3060 v
3061 }
3062 fn drain<'new>(
3063 d: Drain<'static, &'static str, &'static str>,
3064 ) -> Drain<'new, &'new str, &'new str> {
3065 d
3066 }
3067}