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