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