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