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