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