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