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 = "CURRENT_RUSTC_VERSION")]
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 /// # Panics
977 ///
978 /// Panics if any keys are overlapping.
979 ///
980 /// # Examples
981 ///
982 /// ```
983 /// use std::collections::HashMap;
984 ///
985 /// let mut libraries = HashMap::new();
986 /// libraries.insert("Bodleian Library".to_string(), 1602);
987 /// libraries.insert("Athenæum".to_string(), 1807);
988 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
989 /// libraries.insert("Library of Congress".to_string(), 1800);
990 ///
991 /// // Get Athenæum and Bodleian Library
992 /// let [Some(a), Some(b)] = libraries.get_disjoint_mut([
993 /// "Athenæum",
994 /// "Bodleian Library",
995 /// ]) else { panic!() };
996 ///
997 /// // Assert values of Athenæum and Library of Congress
998 /// let got = libraries.get_disjoint_mut([
999 /// "Athenæum",
1000 /// "Library of Congress",
1001 /// ]);
1002 /// assert_eq!(
1003 /// got,
1004 /// [
1005 /// Some(&mut 1807),
1006 /// Some(&mut 1800),
1007 /// ],
1008 /// );
1009 ///
1010 /// // Missing keys result in None
1011 /// let got = libraries.get_disjoint_mut([
1012 /// "Athenæum",
1013 /// "New York Public Library",
1014 /// ]);
1015 /// assert_eq!(
1016 /// got,
1017 /// [
1018 /// Some(&mut 1807),
1019 /// None
1020 /// ]
1021 /// );
1022 /// ```
1023 ///
1024 /// ```should_panic
1025 /// use std::collections::HashMap;
1026 ///
1027 /// let mut libraries = HashMap::new();
1028 /// libraries.insert("Athenæum".to_string(), 1807);
1029 ///
1030 /// // Duplicate keys panic!
1031 /// let got = libraries.get_disjoint_mut([
1032 /// "Athenæum",
1033 /// "Athenæum",
1034 /// ]);
1035 /// ```
1036 #[inline]
1037 #[doc(alias = "get_many_mut")]
1038 #[stable(feature = "map_many_mut", since = "1.86.0")]
1039 pub fn get_disjoint_mut<Q: ?Sized, const N: usize>(
1040 &mut self,
1041 ks: [&Q; N],
1042 ) -> [Option<&'_ mut V>; N]
1043 where
1044 K: Borrow<Q>,
1045 Q: Hash + Eq,
1046 {
1047 self.base.get_many_mut(ks)
1048 }
1049
1050 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1051 /// the values are unique.
1052 ///
1053 /// Returns an array of length `N` with the results of each query. `None` will be used if
1054 /// the key is missing.
1055 ///
1056 /// For a safe alternative see [`get_disjoint_mut`](`HashMap::get_disjoint_mut`).
1057 ///
1058 /// # Safety
1059 ///
1060 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1061 /// references are not used.
1062 ///
1063 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1064 ///
1065 /// # Examples
1066 ///
1067 /// ```
1068 /// use std::collections::HashMap;
1069 ///
1070 /// let mut libraries = HashMap::new();
1071 /// libraries.insert("Bodleian Library".to_string(), 1602);
1072 /// libraries.insert("Athenæum".to_string(), 1807);
1073 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1074 /// libraries.insert("Library of Congress".to_string(), 1800);
1075 ///
1076 /// // SAFETY: The keys do not overlap.
1077 /// let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([
1078 /// "Athenæum",
1079 /// "Bodleian Library",
1080 /// ]) }) else { panic!() };
1081 ///
1082 /// // SAFETY: The keys do not overlap.
1083 /// let got = unsafe { libraries.get_disjoint_unchecked_mut([
1084 /// "Athenæum",
1085 /// "Library of Congress",
1086 /// ]) };
1087 /// assert_eq!(
1088 /// got,
1089 /// [
1090 /// Some(&mut 1807),
1091 /// Some(&mut 1800),
1092 /// ],
1093 /// );
1094 ///
1095 /// // SAFETY: The keys do not overlap.
1096 /// let got = unsafe { libraries.get_disjoint_unchecked_mut([
1097 /// "Athenæum",
1098 /// "New York Public Library",
1099 /// ]) };
1100 /// // Missing keys result in None
1101 /// assert_eq!(got, [Some(&mut 1807), None]);
1102 /// ```
1103 #[inline]
1104 #[doc(alias = "get_many_unchecked_mut")]
1105 #[stable(feature = "map_many_mut", since = "1.86.0")]
1106 pub unsafe fn get_disjoint_unchecked_mut<Q: ?Sized, const N: usize>(
1107 &mut self,
1108 ks: [&Q; N],
1109 ) -> [Option<&'_ mut V>; N]
1110 where
1111 K: Borrow<Q>,
1112 Q: Hash + Eq,
1113 {
1114 unsafe { self.base.get_many_unchecked_mut(ks) }
1115 }
1116
1117 /// Returns `true` if the map contains a value for the specified key.
1118 ///
1119 /// The key may be any borrowed form of the map's key type, but
1120 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1121 /// the key type.
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// use std::collections::HashMap;
1127 ///
1128 /// let mut map = HashMap::new();
1129 /// map.insert(1, "a");
1130 /// assert_eq!(map.contains_key(&1), true);
1131 /// assert_eq!(map.contains_key(&2), false);
1132 /// ```
1133 #[inline]
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_contains_key")]
1136 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1137 where
1138 K: Borrow<Q>,
1139 Q: Hash + Eq,
1140 {
1141 self.base.contains_key(k)
1142 }
1143
1144 /// Returns a mutable reference to the value corresponding to the key.
1145 ///
1146 /// The key may be any borrowed form of the map's key type, but
1147 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1148 /// the key type.
1149 ///
1150 /// # Examples
1151 ///
1152 /// ```
1153 /// use std::collections::HashMap;
1154 ///
1155 /// let mut map = HashMap::new();
1156 /// map.insert(1, "a");
1157 /// if let Some(x) = map.get_mut(&1) {
1158 /// *x = "b";
1159 /// }
1160 /// assert_eq!(map[&1], "b");
1161 /// ```
1162 #[inline]
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1165 where
1166 K: Borrow<Q>,
1167 Q: Hash + Eq,
1168 {
1169 self.base.get_mut(k)
1170 }
1171
1172 /// Inserts a key-value pair into the map.
1173 ///
1174 /// If the map did not have this key present, [`None`] is returned.
1175 ///
1176 /// If the map did have this key present, the value is updated, and the old
1177 /// value is returned. The key is not updated, though; this matters for
1178 /// types that can be `==` without being identical. See the [module-level
1179 /// documentation] for more.
1180 ///
1181 /// [module-level documentation]: crate::collections#insert-and-complex-keys
1182 ///
1183 /// # Examples
1184 ///
1185 /// ```
1186 /// use std::collections::HashMap;
1187 ///
1188 /// let mut map = HashMap::new();
1189 /// assert_eq!(map.insert(37, "a"), None);
1190 /// assert_eq!(map.is_empty(), false);
1191 ///
1192 /// map.insert(37, "b");
1193 /// assert_eq!(map.insert(37, "c"), Some("b"));
1194 /// assert_eq!(map[&37], "c");
1195 /// ```
1196 #[inline]
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 #[rustc_confusables("push", "append", "put")]
1199 #[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_insert")]
1200 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1201 self.base.insert(k, v)
1202 }
1203
1204 /// Tries to insert a key-value pair into the map, and returns
1205 /// a mutable reference to the value in the entry.
1206 ///
1207 /// If the map already had this key present, nothing is updated, and
1208 /// an error containing the occupied entry and the value is returned.
1209 ///
1210 /// # Examples
1211 ///
1212 /// Basic usage:
1213 ///
1214 /// ```
1215 /// #![feature(map_try_insert)]
1216 ///
1217 /// use std::collections::HashMap;
1218 ///
1219 /// let mut map = HashMap::new();
1220 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1221 ///
1222 /// let err = map.try_insert(37, "b").unwrap_err();
1223 /// assert_eq!(err.entry.key(), &37);
1224 /// assert_eq!(err.entry.get(), &"a");
1225 /// assert_eq!(err.value, "b");
1226 /// ```
1227 #[unstable(feature = "map_try_insert", issue = "82766")]
1228 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>> {
1229 match self.entry(key) {
1230 Occupied(entry) => Err(OccupiedError { entry, value }),
1231 Vacant(entry) => Ok(entry.insert(value)),
1232 }
1233 }
1234
1235 /// Removes a key from the map, returning the value at the key if the key
1236 /// was previously in the map.
1237 ///
1238 /// The key may be any borrowed form of the map's key type, but
1239 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1240 /// the key type.
1241 ///
1242 /// # Examples
1243 ///
1244 /// ```
1245 /// use std::collections::HashMap;
1246 ///
1247 /// let mut map = HashMap::new();
1248 /// map.insert(1, "a");
1249 /// assert_eq!(map.remove(&1), Some("a"));
1250 /// assert_eq!(map.remove(&1), None);
1251 /// ```
1252 #[inline]
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 #[rustc_confusables("delete", "take")]
1255 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1256 where
1257 K: Borrow<Q>,
1258 Q: Hash + Eq,
1259 {
1260 self.base.remove(k)
1261 }
1262
1263 /// Removes a key from the map, returning the stored key and value if the
1264 /// key was previously in the map.
1265 ///
1266 /// The key may be any borrowed form of the map's key type, but
1267 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1268 /// the key type.
1269 ///
1270 /// # Examples
1271 ///
1272 /// ```
1273 /// use std::collections::HashMap;
1274 ///
1275 /// # fn main() {
1276 /// let mut map = HashMap::new();
1277 /// map.insert(1, "a");
1278 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1279 /// assert_eq!(map.remove(&1), None);
1280 /// # }
1281 /// ```
1282 #[inline]
1283 #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1284 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1285 where
1286 K: Borrow<Q>,
1287 Q: Hash + Eq,
1288 {
1289 self.base.remove_entry(k)
1290 }
1291}
1292
1293#[stable(feature = "rust1", since = "1.0.0")]
1294impl<K, V, S> Clone for HashMap<K, V, S>
1295where
1296 K: Clone,
1297 V: Clone,
1298 S: Clone,
1299{
1300 #[inline]
1301 fn clone(&self) -> Self {
1302 Self { base: self.base.clone() }
1303 }
1304
1305 #[inline]
1306 fn clone_from(&mut self, source: &Self) {
1307 self.base.clone_from(&source.base);
1308 }
1309}
1310
1311#[stable(feature = "rust1", since = "1.0.0")]
1312impl<K, V, S> PartialEq for HashMap<K, V, S>
1313where
1314 K: Eq + Hash,
1315 V: PartialEq,
1316 S: BuildHasher,
1317{
1318 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1319 if self.len() != other.len() {
1320 return false;
1321 }
1322
1323 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1324 }
1325}
1326
1327#[stable(feature = "rust1", since = "1.0.0")]
1328impl<K, V, S> Eq for HashMap<K, V, S>
1329where
1330 K: Eq + Hash,
1331 V: Eq,
1332 S: BuildHasher,
1333{
1334}
1335
1336#[stable(feature = "rust1", since = "1.0.0")]
1337impl<K, V, S> Debug for HashMap<K, V, S>
1338where
1339 K: Debug,
1340 V: Debug,
1341{
1342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343 f.debug_map().entries(self.iter()).finish()
1344 }
1345}
1346
1347#[stable(feature = "rust1", since = "1.0.0")]
1348impl<K, V, S> Default for HashMap<K, V, S>
1349where
1350 S: Default,
1351{
1352 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1353 #[inline]
1354 fn default() -> HashMap<K, V, S> {
1355 HashMap::with_hasher(Default::default())
1356 }
1357}
1358
1359#[stable(feature = "rust1", since = "1.0.0")]
1360impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1361where
1362 K: Eq + Hash + Borrow<Q>,
1363 Q: Eq + Hash,
1364 S: BuildHasher,
1365{
1366 type Output = V;
1367
1368 /// Returns a reference to the value corresponding to the supplied key.
1369 ///
1370 /// # Panics
1371 ///
1372 /// Panics if the key is not present in the `HashMap`.
1373 #[inline]
1374 fn index(&self, key: &Q) -> &V {
1375 self.get(key).expect("no entry found for key")
1376 }
1377}
1378
1379#[stable(feature = "std_collections_from_array", since = "1.56.0")]
1380// Note: as what is currently the most convenient built-in way to construct
1381// a HashMap, a simple usage of this function must not *require* the user
1382// to provide a type annotation in order to infer the third type parameter
1383// (the hasher parameter, conventionally "S").
1384// To that end, this impl is defined using RandomState as the concrete
1385// type of S, rather than being generic over `S: BuildHasher + Default`.
1386// It is expected that users who want to specify a hasher will manually use
1387// `with_capacity_and_hasher`.
1388// If type parameter defaults worked on impls, and if type parameter
1389// defaults could be mixed with const generics, then perhaps
1390// this could be generalized.
1391// See also the equivalent impl on HashSet.
1392impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
1393where
1394 K: Eq + Hash,
1395{
1396 /// Converts a `[(K, V); N]` into a `HashMap<K, V>`.
1397 ///
1398 /// If any entries in the array have equal keys,
1399 /// all but one of the corresponding values will be dropped.
1400 ///
1401 /// # Examples
1402 ///
1403 /// ```
1404 /// use std::collections::HashMap;
1405 ///
1406 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
1407 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
1408 /// assert_eq!(map1, map2);
1409 /// ```
1410 fn from(arr: [(K, V); N]) -> Self {
1411 Self::from_iter(arr)
1412 }
1413}
1414
1415/// An iterator over the entries of a `HashMap`.
1416///
1417/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1418/// documentation for more.
1419///
1420/// [`iter`]: HashMap::iter
1421///
1422/// # Example
1423///
1424/// ```
1425/// use std::collections::HashMap;
1426///
1427/// let map = HashMap::from([
1428/// ("a", 1),
1429/// ]);
1430/// let iter = map.iter();
1431/// ```
1432#[stable(feature = "rust1", since = "1.0.0")]
1433#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_iter_ty")]
1434pub struct Iter<'a, K: 'a, V: 'a> {
1435 base: base::Iter<'a, K, V>,
1436}
1437
1438// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1439#[stable(feature = "rust1", since = "1.0.0")]
1440impl<K, V> Clone for Iter<'_, K, V> {
1441 #[inline]
1442 fn clone(&self) -> Self {
1443 Iter { base: self.base.clone() }
1444 }
1445}
1446
1447#[stable(feature = "default_iters_hash", since = "1.83.0")]
1448impl<K, V> Default for Iter<'_, K, V> {
1449 #[inline]
1450 fn default() -> Self {
1451 Iter { base: Default::default() }
1452 }
1453}
1454
1455#[stable(feature = "std_debug", since = "1.16.0")]
1456impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458 f.debug_list().entries(self.clone()).finish()
1459 }
1460}
1461
1462/// A mutable iterator over the entries of a `HashMap`.
1463///
1464/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1465/// documentation for more.
1466///
1467/// [`iter_mut`]: HashMap::iter_mut
1468///
1469/// # Example
1470///
1471/// ```
1472/// use std::collections::HashMap;
1473///
1474/// let mut map = HashMap::from([
1475/// ("a", 1),
1476/// ]);
1477/// let iter = map.iter_mut();
1478/// ```
1479#[stable(feature = "rust1", since = "1.0.0")]
1480#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_iter_mut_ty")]
1481pub struct IterMut<'a, K: 'a, V: 'a> {
1482 base: base::IterMut<'a, K, V>,
1483}
1484
1485impl<'a, K, V> IterMut<'a, K, V> {
1486 /// Returns an iterator of references over the remaining items.
1487 #[inline]
1488 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1489 Iter { base: self.base.rustc_iter() }
1490 }
1491}
1492
1493#[stable(feature = "default_iters_hash", since = "1.83.0")]
1494impl<K, V> Default for IterMut<'_, K, V> {
1495 #[inline]
1496 fn default() -> Self {
1497 IterMut { base: Default::default() }
1498 }
1499}
1500
1501/// An owning iterator over the entries of a `HashMap`.
1502///
1503/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
1504/// (provided by the [`IntoIterator`] trait). See its documentation for more.
1505///
1506/// [`into_iter`]: IntoIterator::into_iter
1507///
1508/// # Example
1509///
1510/// ```
1511/// use std::collections::HashMap;
1512///
1513/// let map = HashMap::from([
1514/// ("a", 1),
1515/// ]);
1516/// let iter = map.into_iter();
1517/// ```
1518#[stable(feature = "rust1", since = "1.0.0")]
1519pub struct IntoIter<K, V> {
1520 base: base::IntoIter<K, V>,
1521}
1522
1523impl<K, V> IntoIter<K, V> {
1524 /// Returns an iterator of references over the remaining items.
1525 #[inline]
1526 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1527 Iter { base: self.base.rustc_iter() }
1528 }
1529}
1530
1531#[stable(feature = "default_iters_hash", since = "1.83.0")]
1532impl<K, V> Default for IntoIter<K, V> {
1533 #[inline]
1534 fn default() -> Self {
1535 IntoIter { base: Default::default() }
1536 }
1537}
1538
1539/// An iterator over the keys of a `HashMap`.
1540///
1541/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1542/// documentation for more.
1543///
1544/// [`keys`]: HashMap::keys
1545///
1546/// # Example
1547///
1548/// ```
1549/// use std::collections::HashMap;
1550///
1551/// let map = HashMap::from([
1552/// ("a", 1),
1553/// ]);
1554/// let iter_keys = map.keys();
1555/// ```
1556#[stable(feature = "rust1", since = "1.0.0")]
1557#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_keys_ty")]
1558pub struct Keys<'a, K: 'a, V: 'a> {
1559 inner: Iter<'a, K, V>,
1560}
1561
1562// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1563#[stable(feature = "rust1", since = "1.0.0")]
1564impl<K, V> Clone for Keys<'_, K, V> {
1565 #[inline]
1566 fn clone(&self) -> Self {
1567 Keys { inner: self.inner.clone() }
1568 }
1569}
1570
1571#[stable(feature = "default_iters_hash", since = "1.83.0")]
1572impl<K, V> Default for Keys<'_, K, V> {
1573 #[inline]
1574 fn default() -> Self {
1575 Keys { inner: Default::default() }
1576 }
1577}
1578
1579#[stable(feature = "std_debug", since = "1.16.0")]
1580impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582 f.debug_list().entries(self.clone()).finish()
1583 }
1584}
1585
1586/// An iterator over the values of a `HashMap`.
1587///
1588/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1589/// documentation for more.
1590///
1591/// [`values`]: HashMap::values
1592///
1593/// # Example
1594///
1595/// ```
1596/// use std::collections::HashMap;
1597///
1598/// let map = HashMap::from([
1599/// ("a", 1),
1600/// ]);
1601/// let iter_values = map.values();
1602/// ```
1603#[stable(feature = "rust1", since = "1.0.0")]
1604#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_values_ty")]
1605pub struct Values<'a, K: 'a, V: 'a> {
1606 inner: Iter<'a, K, V>,
1607}
1608
1609// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1610#[stable(feature = "rust1", since = "1.0.0")]
1611impl<K, V> Clone for Values<'_, K, V> {
1612 #[inline]
1613 fn clone(&self) -> Self {
1614 Values { inner: self.inner.clone() }
1615 }
1616}
1617
1618#[stable(feature = "default_iters_hash", since = "1.83.0")]
1619impl<K, V> Default for Values<'_, K, V> {
1620 #[inline]
1621 fn default() -> Self {
1622 Values { inner: Default::default() }
1623 }
1624}
1625
1626#[stable(feature = "std_debug", since = "1.16.0")]
1627impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 f.debug_list().entries(self.clone()).finish()
1630 }
1631}
1632
1633/// A draining iterator over the entries of a `HashMap`.
1634///
1635/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1636/// documentation for more.
1637///
1638/// [`drain`]: HashMap::drain
1639///
1640/// # Example
1641///
1642/// ```
1643/// use std::collections::HashMap;
1644///
1645/// let mut map = HashMap::from([
1646/// ("a", 1),
1647/// ]);
1648/// let iter = map.drain();
1649/// ```
1650#[stable(feature = "drain", since = "1.6.0")]
1651#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_drain_ty")]
1652pub struct Drain<'a, K: 'a, V: 'a> {
1653 base: base::Drain<'a, K, V>,
1654}
1655
1656impl<'a, K, V> Drain<'a, K, V> {
1657 /// Returns an iterator of references over the remaining items.
1658 #[inline]
1659 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1660 Iter { base: self.base.rustc_iter() }
1661 }
1662}
1663
1664/// A draining, filtering iterator over the entries of a `HashMap`.
1665///
1666/// This `struct` is created by the [`extract_if`] method on [`HashMap`].
1667///
1668/// [`extract_if`]: HashMap::extract_if
1669///
1670/// # Example
1671///
1672/// ```
1673/// use std::collections::HashMap;
1674///
1675/// let mut map = HashMap::from([
1676/// ("a", 1),
1677/// ]);
1678/// let iter = map.extract_if(|_k, v| *v % 2 == 0);
1679/// ```
1680#[stable(feature = "hash_extract_if", since = "CURRENT_RUSTC_VERSION")]
1681#[must_use = "iterators are lazy and do nothing unless consumed"]
1682pub struct ExtractIf<'a, K, V, F>
1683where
1684 F: FnMut(&K, &mut V) -> bool,
1685{
1686 base: base::ExtractIf<'a, K, V, F>,
1687}
1688
1689/// A mutable iterator over the values of a `HashMap`.
1690///
1691/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1692/// documentation for more.
1693///
1694/// [`values_mut`]: HashMap::values_mut
1695///
1696/// # Example
1697///
1698/// ```
1699/// use std::collections::HashMap;
1700///
1701/// let mut map = HashMap::from([
1702/// ("a", 1),
1703/// ]);
1704/// let iter_values = map.values_mut();
1705/// ```
1706#[stable(feature = "map_values_mut", since = "1.10.0")]
1707#[cfg_attr(not(test), rustc_diagnostic_item = "hashmap_values_mut_ty")]
1708pub struct ValuesMut<'a, K: 'a, V: 'a> {
1709 inner: IterMut<'a, K, V>,
1710}
1711
1712#[stable(feature = "default_iters_hash", since = "1.83.0")]
1713impl<K, V> Default for ValuesMut<'_, K, V> {
1714 #[inline]
1715 fn default() -> Self {
1716 ValuesMut { inner: Default::default() }
1717 }
1718}
1719
1720/// An owning iterator over the keys of a `HashMap`.
1721///
1722/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
1723/// See its documentation for more.
1724///
1725/// [`into_keys`]: HashMap::into_keys
1726///
1727/// # Example
1728///
1729/// ```
1730/// use std::collections::HashMap;
1731///
1732/// let map = HashMap::from([
1733/// ("a", 1),
1734/// ]);
1735/// let iter_keys = map.into_keys();
1736/// ```
1737#[stable(feature = "map_into_keys_values", since = "1.54.0")]
1738pub struct IntoKeys<K, V> {
1739 inner: IntoIter<K, V>,
1740}
1741
1742#[stable(feature = "default_iters_hash", since = "1.83.0")]
1743impl<K, V> Default for IntoKeys<K, V> {
1744 #[inline]
1745 fn default() -> Self {
1746 IntoKeys { inner: Default::default() }
1747 }
1748}
1749
1750/// An owning iterator over the values of a `HashMap`.
1751///
1752/// This `struct` is created by the [`into_values`] method on [`HashMap`].
1753/// See its documentation for more.
1754///
1755/// [`into_values`]: HashMap::into_values
1756///
1757/// # Example
1758///
1759/// ```
1760/// use std::collections::HashMap;
1761///
1762/// let map = HashMap::from([
1763/// ("a", 1),
1764/// ]);
1765/// let iter_keys = map.into_values();
1766/// ```
1767#[stable(feature = "map_into_keys_values", since = "1.54.0")]
1768pub struct IntoValues<K, V> {
1769 inner: IntoIter<K, V>,
1770}
1771
1772#[stable(feature = "default_iters_hash", since = "1.83.0")]
1773impl<K, V> Default for IntoValues<K, V> {
1774 #[inline]
1775 fn default() -> Self {
1776 IntoValues { inner: Default::default() }
1777 }
1778}
1779
1780/// A view into a single entry in a map, which may either be vacant or occupied.
1781///
1782/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
1783///
1784/// [`entry`]: HashMap::entry
1785#[stable(feature = "rust1", since = "1.0.0")]
1786#[cfg_attr(not(test), rustc_diagnostic_item = "HashMapEntry")]
1787pub enum Entry<'a, K: 'a, V: 'a> {
1788 /// An occupied entry.
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
1791
1792 /// A vacant entry.
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
1795}
1796
1797#[stable(feature = "debug_hash_map", since = "1.12.0")]
1798impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
1799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800 match *self {
1801 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
1802 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
1803 }
1804 }
1805}
1806
1807/// A view into an occupied entry in a `HashMap`.
1808/// It is part of the [`Entry`] enum.
1809#[stable(feature = "rust1", since = "1.0.0")]
1810pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1811 base: base::RustcOccupiedEntry<'a, K, V>,
1812}
1813
1814#[stable(feature = "debug_hash_map", since = "1.12.0")]
1815impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
1816 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1817 f.debug_struct("OccupiedEntry")
1818 .field("key", self.key())
1819 .field("value", self.get())
1820 .finish_non_exhaustive()
1821 }
1822}
1823
1824/// A view into a vacant entry in a `HashMap`.
1825/// It is part of the [`Entry`] enum.
1826#[stable(feature = "rust1", since = "1.0.0")]
1827pub struct VacantEntry<'a, K: 'a, V: 'a> {
1828 base: base::RustcVacantEntry<'a, K, V>,
1829}
1830
1831#[stable(feature = "debug_hash_map", since = "1.12.0")]
1832impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
1833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1834 f.debug_tuple("VacantEntry").field(self.key()).finish()
1835 }
1836}
1837
1838/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
1839///
1840/// Contains the occupied entry, and the value that was not inserted.
1841#[unstable(feature = "map_try_insert", issue = "82766")]
1842pub struct OccupiedError<'a, K: 'a, V: 'a> {
1843 /// The entry in the map that was already occupied.
1844 pub entry: OccupiedEntry<'a, K, V>,
1845 /// The value which was not inserted, because the entry was already occupied.
1846 pub value: V,
1847}
1848
1849#[unstable(feature = "map_try_insert", issue = "82766")]
1850impl<K: Debug, V: Debug> Debug for OccupiedError<'_, K, V> {
1851 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1852 f.debug_struct("OccupiedError")
1853 .field("key", self.entry.key())
1854 .field("old_value", self.entry.get())
1855 .field("new_value", &self.value)
1856 .finish_non_exhaustive()
1857 }
1858}
1859
1860#[unstable(feature = "map_try_insert", issue = "82766")]
1861impl<'a, K: Debug, V: Debug> fmt::Display for OccupiedError<'a, K, V> {
1862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1863 write!(
1864 f,
1865 "failed to insert {:?}, key {:?} already exists with value {:?}",
1866 self.value,
1867 self.entry.key(),
1868 self.entry.get(),
1869 )
1870 }
1871}
1872
1873#[unstable(feature = "map_try_insert", issue = "82766")]
1874impl<'a, K: fmt::Debug, V: fmt::Debug> Error for OccupiedError<'a, K, V> {
1875 #[allow(deprecated)]
1876 fn description(&self) -> &str {
1877 "key already exists"
1878 }
1879}
1880
1881#[stable(feature = "rust1", since = "1.0.0")]
1882impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
1883 type Item = (&'a K, &'a V);
1884 type IntoIter = Iter<'a, K, V>;
1885
1886 #[inline]
1887 #[rustc_lint_query_instability]
1888 fn into_iter(self) -> Iter<'a, K, V> {
1889 self.iter()
1890 }
1891}
1892
1893#[stable(feature = "rust1", since = "1.0.0")]
1894impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
1895 type Item = (&'a K, &'a mut V);
1896 type IntoIter = IterMut<'a, K, V>;
1897
1898 #[inline]
1899 #[rustc_lint_query_instability]
1900 fn into_iter(self) -> IterMut<'a, K, V> {
1901 self.iter_mut()
1902 }
1903}
1904
1905#[stable(feature = "rust1", since = "1.0.0")]
1906impl<K, V, S> IntoIterator for HashMap<K, V, S> {
1907 type Item = (K, V);
1908 type IntoIter = IntoIter<K, V>;
1909
1910 /// Creates a consuming iterator, that is, one that moves each key-value
1911 /// pair out of the map in arbitrary order. The map cannot be used after
1912 /// calling this.
1913 ///
1914 /// # Examples
1915 ///
1916 /// ```
1917 /// use std::collections::HashMap;
1918 ///
1919 /// let map = HashMap::from([
1920 /// ("a", 1),
1921 /// ("b", 2),
1922 /// ("c", 3),
1923 /// ]);
1924 ///
1925 /// // Not possible with .iter()
1926 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
1927 /// ```
1928 #[inline]
1929 #[rustc_lint_query_instability]
1930 fn into_iter(self) -> IntoIter<K, V> {
1931 IntoIter { base: self.base.into_iter() }
1932 }
1933}
1934
1935#[stable(feature = "rust1", since = "1.0.0")]
1936impl<'a, K, V> Iterator for Iter<'a, K, V> {
1937 type Item = (&'a K, &'a V);
1938
1939 #[inline]
1940 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1941 self.base.next()
1942 }
1943 #[inline]
1944 fn size_hint(&self) -> (usize, Option<usize>) {
1945 self.base.size_hint()
1946 }
1947 #[inline]
1948 fn count(self) -> usize {
1949 self.base.len()
1950 }
1951 #[inline]
1952 fn fold<B, F>(self, init: B, f: F) -> B
1953 where
1954 Self: Sized,
1955 F: FnMut(B, Self::Item) -> B,
1956 {
1957 self.base.fold(init, f)
1958 }
1959}
1960#[stable(feature = "rust1", since = "1.0.0")]
1961impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1962 #[inline]
1963 fn len(&self) -> usize {
1964 self.base.len()
1965 }
1966}
1967
1968#[stable(feature = "fused", since = "1.26.0")]
1969impl<K, V> FusedIterator for Iter<'_, K, V> {}
1970
1971#[stable(feature = "rust1", since = "1.0.0")]
1972impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1973 type Item = (&'a K, &'a mut V);
1974
1975 #[inline]
1976 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1977 self.base.next()
1978 }
1979 #[inline]
1980 fn size_hint(&self) -> (usize, Option<usize>) {
1981 self.base.size_hint()
1982 }
1983 #[inline]
1984 fn count(self) -> usize {
1985 self.base.len()
1986 }
1987 #[inline]
1988 fn fold<B, F>(self, init: B, f: F) -> B
1989 where
1990 Self: Sized,
1991 F: FnMut(B, Self::Item) -> B,
1992 {
1993 self.base.fold(init, f)
1994 }
1995}
1996#[stable(feature = "rust1", since = "1.0.0")]
1997impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1998 #[inline]
1999 fn len(&self) -> usize {
2000 self.base.len()
2001 }
2002}
2003#[stable(feature = "fused", since = "1.26.0")]
2004impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2005
2006#[stable(feature = "std_debug", since = "1.16.0")]
2007impl<K, V> fmt::Debug for IterMut<'_, K, V>
2008where
2009 K: fmt::Debug,
2010 V: fmt::Debug,
2011{
2012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2013 f.debug_list().entries(self.iter()).finish()
2014 }
2015}
2016
2017#[stable(feature = "rust1", since = "1.0.0")]
2018impl<K, V> Iterator for IntoIter<K, V> {
2019 type Item = (K, V);
2020
2021 #[inline]
2022 fn next(&mut self) -> Option<(K, V)> {
2023 self.base.next()
2024 }
2025 #[inline]
2026 fn size_hint(&self) -> (usize, Option<usize>) {
2027 self.base.size_hint()
2028 }
2029 #[inline]
2030 fn count(self) -> usize {
2031 self.base.len()
2032 }
2033 #[inline]
2034 fn fold<B, F>(self, init: B, f: F) -> B
2035 where
2036 Self: Sized,
2037 F: FnMut(B, Self::Item) -> B,
2038 {
2039 self.base.fold(init, f)
2040 }
2041}
2042#[stable(feature = "rust1", since = "1.0.0")]
2043impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2044 #[inline]
2045 fn len(&self) -> usize {
2046 self.base.len()
2047 }
2048}
2049#[stable(feature = "fused", since = "1.26.0")]
2050impl<K, V> FusedIterator for IntoIter<K, V> {}
2051
2052#[stable(feature = "std_debug", since = "1.16.0")]
2053impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2054 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2055 f.debug_list().entries(self.iter()).finish()
2056 }
2057}
2058
2059#[stable(feature = "rust1", since = "1.0.0")]
2060impl<'a, K, V> Iterator for Keys<'a, K, V> {
2061 type Item = &'a K;
2062
2063 #[inline]
2064 fn next(&mut self) -> Option<&'a K> {
2065 self.inner.next().map(|(k, _)| k)
2066 }
2067 #[inline]
2068 fn size_hint(&self) -> (usize, Option<usize>) {
2069 self.inner.size_hint()
2070 }
2071 #[inline]
2072 fn count(self) -> usize {
2073 self.inner.len()
2074 }
2075 #[inline]
2076 fn fold<B, F>(self, init: B, mut f: F) -> B
2077 where
2078 Self: Sized,
2079 F: FnMut(B, Self::Item) -> B,
2080 {
2081 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2082 }
2083}
2084#[stable(feature = "rust1", since = "1.0.0")]
2085impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2086 #[inline]
2087 fn len(&self) -> usize {
2088 self.inner.len()
2089 }
2090}
2091#[stable(feature = "fused", since = "1.26.0")]
2092impl<K, V> FusedIterator for Keys<'_, K, V> {}
2093
2094#[stable(feature = "rust1", since = "1.0.0")]
2095impl<'a, K, V> Iterator for Values<'a, K, V> {
2096 type Item = &'a V;
2097
2098 #[inline]
2099 fn next(&mut self) -> Option<&'a V> {
2100 self.inner.next().map(|(_, v)| v)
2101 }
2102 #[inline]
2103 fn size_hint(&self) -> (usize, Option<usize>) {
2104 self.inner.size_hint()
2105 }
2106 #[inline]
2107 fn count(self) -> usize {
2108 self.inner.len()
2109 }
2110 #[inline]
2111 fn fold<B, F>(self, init: B, mut f: F) -> B
2112 where
2113 Self: Sized,
2114 F: FnMut(B, Self::Item) -> B,
2115 {
2116 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2117 }
2118}
2119#[stable(feature = "rust1", since = "1.0.0")]
2120impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2121 #[inline]
2122 fn len(&self) -> usize {
2123 self.inner.len()
2124 }
2125}
2126#[stable(feature = "fused", since = "1.26.0")]
2127impl<K, V> FusedIterator for Values<'_, K, V> {}
2128
2129#[stable(feature = "map_values_mut", since = "1.10.0")]
2130impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2131 type Item = &'a mut V;
2132
2133 #[inline]
2134 fn next(&mut self) -> Option<&'a mut V> {
2135 self.inner.next().map(|(_, v)| v)
2136 }
2137 #[inline]
2138 fn size_hint(&self) -> (usize, Option<usize>) {
2139 self.inner.size_hint()
2140 }
2141 #[inline]
2142 fn count(self) -> usize {
2143 self.inner.len()
2144 }
2145 #[inline]
2146 fn fold<B, F>(self, init: B, mut f: F) -> B
2147 where
2148 Self: Sized,
2149 F: FnMut(B, Self::Item) -> B,
2150 {
2151 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2152 }
2153}
2154#[stable(feature = "map_values_mut", since = "1.10.0")]
2155impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2156 #[inline]
2157 fn len(&self) -> usize {
2158 self.inner.len()
2159 }
2160}
2161#[stable(feature = "fused", since = "1.26.0")]
2162impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2163
2164#[stable(feature = "std_debug", since = "1.16.0")]
2165impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
2166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2167 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
2168 }
2169}
2170
2171#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2172impl<K, V> Iterator for IntoKeys<K, V> {
2173 type Item = K;
2174
2175 #[inline]
2176 fn next(&mut self) -> Option<K> {
2177 self.inner.next().map(|(k, _)| k)
2178 }
2179 #[inline]
2180 fn size_hint(&self) -> (usize, Option<usize>) {
2181 self.inner.size_hint()
2182 }
2183 #[inline]
2184 fn count(self) -> usize {
2185 self.inner.len()
2186 }
2187 #[inline]
2188 fn fold<B, F>(self, init: B, mut f: F) -> B
2189 where
2190 Self: Sized,
2191 F: FnMut(B, Self::Item) -> B,
2192 {
2193 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2194 }
2195}
2196#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2197impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2198 #[inline]
2199 fn len(&self) -> usize {
2200 self.inner.len()
2201 }
2202}
2203#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2204impl<K, V> FusedIterator for IntoKeys<K, V> {}
2205
2206#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2207impl<K: Debug, V> fmt::Debug for IntoKeys<K, V> {
2208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2209 f.debug_list().entries(self.inner.iter().map(|(k, _)| k)).finish()
2210 }
2211}
2212
2213#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2214impl<K, V> Iterator for IntoValues<K, V> {
2215 type Item = V;
2216
2217 #[inline]
2218 fn next(&mut self) -> Option<V> {
2219 self.inner.next().map(|(_, v)| v)
2220 }
2221 #[inline]
2222 fn size_hint(&self) -> (usize, Option<usize>) {
2223 self.inner.size_hint()
2224 }
2225 #[inline]
2226 fn count(self) -> usize {
2227 self.inner.len()
2228 }
2229 #[inline]
2230 fn fold<B, F>(self, init: B, mut f: F) -> B
2231 where
2232 Self: Sized,
2233 F: FnMut(B, Self::Item) -> B,
2234 {
2235 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2236 }
2237}
2238#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2239impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2240 #[inline]
2241 fn len(&self) -> usize {
2242 self.inner.len()
2243 }
2244}
2245#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2246impl<K, V> FusedIterator for IntoValues<K, V> {}
2247
2248#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2249impl<K, V: Debug> fmt::Debug for IntoValues<K, V> {
2250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2251 f.debug_list().entries(self.inner.iter().map(|(_, v)| v)).finish()
2252 }
2253}
2254
2255#[stable(feature = "drain", since = "1.6.0")]
2256impl<'a, K, V> Iterator for Drain<'a, K, V> {
2257 type Item = (K, V);
2258
2259 #[inline]
2260 fn next(&mut self) -> Option<(K, V)> {
2261 self.base.next()
2262 }
2263 #[inline]
2264 fn size_hint(&self) -> (usize, Option<usize>) {
2265 self.base.size_hint()
2266 }
2267 #[inline]
2268 fn fold<B, F>(self, init: B, f: F) -> B
2269 where
2270 Self: Sized,
2271 F: FnMut(B, Self::Item) -> B,
2272 {
2273 self.base.fold(init, f)
2274 }
2275}
2276#[stable(feature = "drain", since = "1.6.0")]
2277impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2278 #[inline]
2279 fn len(&self) -> usize {
2280 self.base.len()
2281 }
2282}
2283#[stable(feature = "fused", since = "1.26.0")]
2284impl<K, V> FusedIterator for Drain<'_, K, V> {}
2285
2286#[stable(feature = "std_debug", since = "1.16.0")]
2287impl<K, V> fmt::Debug for Drain<'_, K, V>
2288where
2289 K: fmt::Debug,
2290 V: fmt::Debug,
2291{
2292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2293 f.debug_list().entries(self.iter()).finish()
2294 }
2295}
2296
2297#[stable(feature = "hash_extract_if", since = "CURRENT_RUSTC_VERSION")]
2298impl<K, V, F> Iterator for ExtractIf<'_, K, V, F>
2299where
2300 F: FnMut(&K, &mut V) -> bool,
2301{
2302 type Item = (K, V);
2303
2304 #[inline]
2305 fn next(&mut self) -> Option<(K, V)> {
2306 self.base.next()
2307 }
2308 #[inline]
2309 fn size_hint(&self) -> (usize, Option<usize>) {
2310 self.base.size_hint()
2311 }
2312}
2313
2314#[stable(feature = "hash_extract_if", since = "CURRENT_RUSTC_VERSION")]
2315impl<K, V, F> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2316
2317#[stable(feature = "hash_extract_if", since = "CURRENT_RUSTC_VERSION")]
2318impl<'a, K, V, F> fmt::Debug for ExtractIf<'a, K, V, F>
2319where
2320 F: FnMut(&K, &mut V) -> bool,
2321{
2322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2323 f.debug_struct("ExtractIf").finish_non_exhaustive()
2324 }
2325}
2326
2327impl<'a, K, V> Entry<'a, K, V> {
2328 /// Ensures a value is in the entry by inserting the default if empty, and returns
2329 /// a mutable reference to the value in the entry.
2330 ///
2331 /// # Examples
2332 ///
2333 /// ```
2334 /// use std::collections::HashMap;
2335 ///
2336 /// let mut map: HashMap<&str, u32> = HashMap::new();
2337 ///
2338 /// map.entry("poneyland").or_insert(3);
2339 /// assert_eq!(map["poneyland"], 3);
2340 ///
2341 /// *map.entry("poneyland").or_insert(10) *= 2;
2342 /// assert_eq!(map["poneyland"], 6);
2343 /// ```
2344 #[inline]
2345 #[stable(feature = "rust1", since = "1.0.0")]
2346 pub fn or_insert(self, default: V) -> &'a mut V {
2347 match self {
2348 Occupied(entry) => entry.into_mut(),
2349 Vacant(entry) => entry.insert(default),
2350 }
2351 }
2352
2353 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2354 /// and returns a mutable reference to the value in the entry.
2355 ///
2356 /// # Examples
2357 ///
2358 /// ```
2359 /// use std::collections::HashMap;
2360 ///
2361 /// let mut map = HashMap::new();
2362 /// let value = "hoho";
2363 ///
2364 /// map.entry("poneyland").or_insert_with(|| value);
2365 ///
2366 /// assert_eq!(map["poneyland"], "hoho");
2367 /// ```
2368 #[inline]
2369 #[stable(feature = "rust1", since = "1.0.0")]
2370 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2371 match self {
2372 Occupied(entry) => entry.into_mut(),
2373 Vacant(entry) => entry.insert(default()),
2374 }
2375 }
2376
2377 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
2378 /// This method allows for generating key-derived values for insertion by providing the default
2379 /// function a reference to the key that was moved during the `.entry(key)` method call.
2380 ///
2381 /// The reference to the moved key is provided so that cloning or copying the key is
2382 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
2383 ///
2384 /// # Examples
2385 ///
2386 /// ```
2387 /// use std::collections::HashMap;
2388 ///
2389 /// let mut map: HashMap<&str, usize> = HashMap::new();
2390 ///
2391 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2392 ///
2393 /// assert_eq!(map["poneyland"], 9);
2394 /// ```
2395 #[inline]
2396 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
2397 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2398 match self {
2399 Occupied(entry) => entry.into_mut(),
2400 Vacant(entry) => {
2401 let value = default(entry.key());
2402 entry.insert(value)
2403 }
2404 }
2405 }
2406
2407 /// Returns a reference to this entry's key.
2408 ///
2409 /// # Examples
2410 ///
2411 /// ```
2412 /// use std::collections::HashMap;
2413 ///
2414 /// let mut map: HashMap<&str, u32> = HashMap::new();
2415 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2416 /// ```
2417 #[inline]
2418 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2419 pub fn key(&self) -> &K {
2420 match *self {
2421 Occupied(ref entry) => entry.key(),
2422 Vacant(ref entry) => entry.key(),
2423 }
2424 }
2425
2426 /// Provides in-place mutable access to an occupied entry before any
2427 /// potential inserts into the map.
2428 ///
2429 /// # Examples
2430 ///
2431 /// ```
2432 /// use std::collections::HashMap;
2433 ///
2434 /// let mut map: HashMap<&str, u32> = HashMap::new();
2435 ///
2436 /// map.entry("poneyland")
2437 /// .and_modify(|e| { *e += 1 })
2438 /// .or_insert(42);
2439 /// assert_eq!(map["poneyland"], 42);
2440 ///
2441 /// map.entry("poneyland")
2442 /// .and_modify(|e| { *e += 1 })
2443 /// .or_insert(42);
2444 /// assert_eq!(map["poneyland"], 43);
2445 /// ```
2446 #[inline]
2447 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2448 pub fn and_modify<F>(self, f: F) -> Self
2449 where
2450 F: FnOnce(&mut V),
2451 {
2452 match self {
2453 Occupied(mut entry) => {
2454 f(entry.get_mut());
2455 Occupied(entry)
2456 }
2457 Vacant(entry) => Vacant(entry),
2458 }
2459 }
2460
2461 /// Sets the value of the entry, and returns an `OccupiedEntry`.
2462 ///
2463 /// # Examples
2464 ///
2465 /// ```
2466 /// use std::collections::HashMap;
2467 ///
2468 /// let mut map: HashMap<&str, String> = HashMap::new();
2469 /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
2470 ///
2471 /// assert_eq!(entry.key(), &"poneyland");
2472 /// ```
2473 #[inline]
2474 #[stable(feature = "entry_insert", since = "1.83.0")]
2475 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2476 match self {
2477 Occupied(mut entry) => {
2478 entry.insert(value);
2479 entry
2480 }
2481 Vacant(entry) => entry.insert_entry(value),
2482 }
2483 }
2484}
2485
2486impl<'a, K, V: Default> Entry<'a, K, V> {
2487 /// Ensures a value is in the entry by inserting the default value if empty,
2488 /// and returns a mutable reference to the value in the entry.
2489 ///
2490 /// # Examples
2491 ///
2492 /// ```
2493 /// # fn main() {
2494 /// use std::collections::HashMap;
2495 ///
2496 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2497 /// map.entry("poneyland").or_default();
2498 ///
2499 /// assert_eq!(map["poneyland"], None);
2500 /// # }
2501 /// ```
2502 #[inline]
2503 #[stable(feature = "entry_or_default", since = "1.28.0")]
2504 pub fn or_default(self) -> &'a mut V {
2505 match self {
2506 Occupied(entry) => entry.into_mut(),
2507 Vacant(entry) => entry.insert(Default::default()),
2508 }
2509 }
2510}
2511
2512impl<'a, K, V> OccupiedEntry<'a, K, V> {
2513 /// Gets a reference to the key in the entry.
2514 ///
2515 /// # Examples
2516 ///
2517 /// ```
2518 /// use std::collections::HashMap;
2519 ///
2520 /// let mut map: HashMap<&str, u32> = HashMap::new();
2521 /// map.entry("poneyland").or_insert(12);
2522 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2523 /// ```
2524 #[inline]
2525 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2526 pub fn key(&self) -> &K {
2527 self.base.key()
2528 }
2529
2530 /// Take the ownership of the key and value from the map.
2531 ///
2532 /// # Examples
2533 ///
2534 /// ```
2535 /// use std::collections::HashMap;
2536 /// use std::collections::hash_map::Entry;
2537 ///
2538 /// let mut map: HashMap<&str, u32> = HashMap::new();
2539 /// map.entry("poneyland").or_insert(12);
2540 ///
2541 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2542 /// // We delete the entry from the map.
2543 /// o.remove_entry();
2544 /// }
2545 ///
2546 /// assert_eq!(map.contains_key("poneyland"), false);
2547 /// ```
2548 #[inline]
2549 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2550 pub fn remove_entry(self) -> (K, V) {
2551 self.base.remove_entry()
2552 }
2553
2554 /// Gets a reference to the value in the entry.
2555 ///
2556 /// # Examples
2557 ///
2558 /// ```
2559 /// use std::collections::HashMap;
2560 /// use std::collections::hash_map::Entry;
2561 ///
2562 /// let mut map: HashMap<&str, u32> = HashMap::new();
2563 /// map.entry("poneyland").or_insert(12);
2564 ///
2565 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2566 /// assert_eq!(o.get(), &12);
2567 /// }
2568 /// ```
2569 #[inline]
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 pub fn get(&self) -> &V {
2572 self.base.get()
2573 }
2574
2575 /// Gets a mutable reference to the value in the entry.
2576 ///
2577 /// If you need a reference to the `OccupiedEntry` which may outlive the
2578 /// destruction of the `Entry` value, see [`into_mut`].
2579 ///
2580 /// [`into_mut`]: Self::into_mut
2581 ///
2582 /// # Examples
2583 ///
2584 /// ```
2585 /// use std::collections::HashMap;
2586 /// use std::collections::hash_map::Entry;
2587 ///
2588 /// let mut map: HashMap<&str, u32> = HashMap::new();
2589 /// map.entry("poneyland").or_insert(12);
2590 ///
2591 /// assert_eq!(map["poneyland"], 12);
2592 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2593 /// *o.get_mut() += 10;
2594 /// assert_eq!(*o.get(), 22);
2595 ///
2596 /// // We can use the same Entry multiple times.
2597 /// *o.get_mut() += 2;
2598 /// }
2599 ///
2600 /// assert_eq!(map["poneyland"], 24);
2601 /// ```
2602 #[inline]
2603 #[stable(feature = "rust1", since = "1.0.0")]
2604 pub fn get_mut(&mut self) -> &mut V {
2605 self.base.get_mut()
2606 }
2607
2608 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
2609 /// with a lifetime bound to the map itself.
2610 ///
2611 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2612 ///
2613 /// [`get_mut`]: Self::get_mut
2614 ///
2615 /// # Examples
2616 ///
2617 /// ```
2618 /// use std::collections::HashMap;
2619 /// use std::collections::hash_map::Entry;
2620 ///
2621 /// let mut map: HashMap<&str, u32> = HashMap::new();
2622 /// map.entry("poneyland").or_insert(12);
2623 ///
2624 /// assert_eq!(map["poneyland"], 12);
2625 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2626 /// *o.into_mut() += 10;
2627 /// }
2628 ///
2629 /// assert_eq!(map["poneyland"], 22);
2630 /// ```
2631 #[inline]
2632 #[stable(feature = "rust1", since = "1.0.0")]
2633 pub fn into_mut(self) -> &'a mut V {
2634 self.base.into_mut()
2635 }
2636
2637 /// Sets the value of the entry, and returns the entry's old value.
2638 ///
2639 /// # Examples
2640 ///
2641 /// ```
2642 /// use std::collections::HashMap;
2643 /// use std::collections::hash_map::Entry;
2644 ///
2645 /// let mut map: HashMap<&str, u32> = HashMap::new();
2646 /// map.entry("poneyland").or_insert(12);
2647 ///
2648 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2649 /// assert_eq!(o.insert(15), 12);
2650 /// }
2651 ///
2652 /// assert_eq!(map["poneyland"], 15);
2653 /// ```
2654 #[inline]
2655 #[stable(feature = "rust1", since = "1.0.0")]
2656 pub fn insert(&mut self, value: V) -> V {
2657 self.base.insert(value)
2658 }
2659
2660 /// Takes the value out of the entry, and returns it.
2661 ///
2662 /// # Examples
2663 ///
2664 /// ```
2665 /// use std::collections::HashMap;
2666 /// use std::collections::hash_map::Entry;
2667 ///
2668 /// let mut map: HashMap<&str, u32> = HashMap::new();
2669 /// map.entry("poneyland").or_insert(12);
2670 ///
2671 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2672 /// assert_eq!(o.remove(), 12);
2673 /// }
2674 ///
2675 /// assert_eq!(map.contains_key("poneyland"), false);
2676 /// ```
2677 #[inline]
2678 #[stable(feature = "rust1", since = "1.0.0")]
2679 pub fn remove(self) -> V {
2680 self.base.remove()
2681 }
2682}
2683
2684impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2685 /// Gets a reference to the key that would be used when inserting a value
2686 /// through the `VacantEntry`.
2687 ///
2688 /// # Examples
2689 ///
2690 /// ```
2691 /// use std::collections::HashMap;
2692 ///
2693 /// let mut map: HashMap<&str, u32> = HashMap::new();
2694 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2695 /// ```
2696 #[inline]
2697 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2698 pub fn key(&self) -> &K {
2699 self.base.key()
2700 }
2701
2702 /// Take ownership of the key.
2703 ///
2704 /// # Examples
2705 ///
2706 /// ```
2707 /// use std::collections::HashMap;
2708 /// use std::collections::hash_map::Entry;
2709 ///
2710 /// let mut map: HashMap<&str, u32> = HashMap::new();
2711 ///
2712 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2713 /// v.into_key();
2714 /// }
2715 /// ```
2716 #[inline]
2717 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2718 pub fn into_key(self) -> K {
2719 self.base.into_key()
2720 }
2721
2722 /// Sets the value of the entry with the `VacantEntry`'s key,
2723 /// and returns a mutable reference to it.
2724 ///
2725 /// # Examples
2726 ///
2727 /// ```
2728 /// use std::collections::HashMap;
2729 /// use std::collections::hash_map::Entry;
2730 ///
2731 /// let mut map: HashMap<&str, u32> = HashMap::new();
2732 ///
2733 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2734 /// o.insert(37);
2735 /// }
2736 /// assert_eq!(map["poneyland"], 37);
2737 /// ```
2738 #[inline]
2739 #[stable(feature = "rust1", since = "1.0.0")]
2740 pub fn insert(self, value: V) -> &'a mut V {
2741 self.base.insert(value)
2742 }
2743
2744 /// Sets the value of the entry with the `VacantEntry`'s key,
2745 /// and returns an `OccupiedEntry`.
2746 ///
2747 /// # Examples
2748 ///
2749 /// ```
2750 /// use std::collections::HashMap;
2751 /// use std::collections::hash_map::Entry;
2752 ///
2753 /// let mut map: HashMap<&str, u32> = HashMap::new();
2754 ///
2755 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2756 /// o.insert_entry(37);
2757 /// }
2758 /// assert_eq!(map["poneyland"], 37);
2759 /// ```
2760 #[inline]
2761 #[stable(feature = "entry_insert", since = "1.83.0")]
2762 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V> {
2763 let base = self.base.insert_entry(value);
2764 OccupiedEntry { base }
2765 }
2766}
2767
2768#[stable(feature = "rust1", since = "1.0.0")]
2769impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2770where
2771 K: Eq + Hash,
2772 S: BuildHasher + Default,
2773{
2774 /// Constructs a `HashMap<K, V>` from an iterator of key-value pairs.
2775 ///
2776 /// If the iterator produces any pairs with equal keys,
2777 /// all but one of the corresponding values will be dropped.
2778 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2779 let mut map = HashMap::with_hasher(Default::default());
2780 map.extend(iter);
2781 map
2782 }
2783}
2784
2785/// Inserts all new key-values from the iterator and replaces values with existing
2786/// keys with new values returned from the iterator.
2787#[stable(feature = "rust1", since = "1.0.0")]
2788impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2789where
2790 K: Eq + Hash,
2791 S: BuildHasher,
2792{
2793 #[inline]
2794 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2795 self.base.extend(iter)
2796 }
2797
2798 #[inline]
2799 fn extend_one(&mut self, (k, v): (K, V)) {
2800 self.base.insert(k, v);
2801 }
2802
2803 #[inline]
2804 fn extend_reserve(&mut self, additional: usize) {
2805 self.base.extend_reserve(additional);
2806 }
2807}
2808
2809#[stable(feature = "hash_extend_copy", since = "1.4.0")]
2810impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2811where
2812 K: Eq + Hash + Copy,
2813 V: Copy,
2814 S: BuildHasher,
2815{
2816 #[inline]
2817 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2818 self.base.extend(iter)
2819 }
2820
2821 #[inline]
2822 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2823 self.base.insert(k, v);
2824 }
2825
2826 #[inline]
2827 fn extend_reserve(&mut self, additional: usize) {
2828 Extend::<(K, V)>::extend_reserve(self, additional)
2829 }
2830}
2831
2832#[inline]
2833fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> {
2834 match raw {
2835 base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }),
2836 base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }),
2837 }
2838}
2839
2840#[inline]
2841pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError {
2842 match err {
2843 hashbrown::TryReserveError::CapacityOverflow => {
2844 TryReserveErrorKind::CapacityOverflow.into()
2845 }
2846 hashbrown::TryReserveError::AllocError { layout } => {
2847 TryReserveErrorKind::AllocError { layout, non_exhaustive: () }.into()
2848 }
2849 }
2850}
2851
2852#[allow(dead_code)]
2853fn assert_covariance() {
2854 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2855 v
2856 }
2857 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2858 v
2859 }
2860 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2861 v
2862 }
2863 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2864 v
2865 }
2866 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2867 v
2868 }
2869 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2870 v
2871 }
2872 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2873 v
2874 }
2875 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2876 v
2877 }
2878 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2879 v
2880 }
2881 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2882 v
2883 }
2884 fn drain<'new>(
2885 d: Drain<'static, &'static str, &'static str>,
2886 ) -> Drain<'new, &'new str, &'new str> {
2887 d
2888 }
2889}