hashbrown/map.rs
1use crate::raw::{
2 Allocator, Bucket, Global, RawDrain, RawExtractIf, RawIntoIter, RawIter, RawTable,
3};
4use crate::{DefaultHashBuilder, Equivalent, TryReserveError};
5use core::borrow::Borrow;
6use core::fmt::{self, Debug};
7use core::hash::{BuildHasher, Hash};
8use core::iter::FusedIterator;
9use core::marker::PhantomData;
10use core::mem;
11use core::ops::Index;
12
13#[cfg(feature = "raw-entry")]
14pub use crate::raw_entry::*;
15
16/// A hash map implemented with quadratic probing and SIMD lookup.
17///
18/// The default hashing algorithm is currently [`foldhash`], though this is
19/// subject to change at any point in the future. This hash function is very
20/// fast for all types of keys, but this algorithm will typically *not* protect
21/// against attacks such as HashDoS.
22///
23/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
24/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
25/// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
26///
27/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
28/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
29/// If you implement these yourself, it is important that the following
30/// property holds:
31///
32/// ```text
33/// k1 == k2 -> hash(k1) == hash(k2)
34/// ```
35///
36/// In other words, if two keys are equal, their hashes must be equal.
37///
38/// It is a logic error for a key to be modified in such a way that the key's
39/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
40/// the [`Eq`] trait, changes while it is in the map. This is normally only
41/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
42///
43/// It is also a logic error for the [`Hash`] implementation of a key to panic.
44/// This is generally only possible if the trait is implemented manually. If a
45/// panic does occur then the contents of the `HashMap` may become corrupted and
46/// some items may be dropped from the table.
47///
48/// # Examples
49///
50/// ```
51/// use hashbrown::HashMap;
52///
53/// // Type inference lets us omit an explicit type signature (which
54/// // would be `HashMap<String, String>` in this example).
55/// let mut book_reviews = HashMap::new();
56///
57/// // Review some books.
58/// book_reviews.insert(
59/// "Adventures of Huckleberry Finn".to_string(),
60/// "My favorite book.".to_string(),
61/// );
62/// book_reviews.insert(
63/// "Grimms' Fairy Tales".to_string(),
64/// "Masterpiece.".to_string(),
65/// );
66/// book_reviews.insert(
67/// "Pride and Prejudice".to_string(),
68/// "Very enjoyable.".to_string(),
69/// );
70/// book_reviews.insert(
71/// "The Adventures of Sherlock Holmes".to_string(),
72/// "Eye lyked it alot.".to_string(),
73/// );
74///
75/// // Check for a specific one.
76/// // When collections store owned values (String), they can still be
77/// // queried using references (&str).
78/// if !book_reviews.contains_key("Les Misérables") {
79/// println!("We've got {} reviews, but Les Misérables ain't one.",
80/// book_reviews.len());
81/// }
82///
83/// // oops, this review has a lot of spelling mistakes, let's delete it.
84/// book_reviews.remove("The Adventures of Sherlock Holmes");
85///
86/// // Look up the values associated with some keys.
87/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
88/// for &book in &to_find {
89/// match book_reviews.get(book) {
90/// Some(review) => println!("{}: {}", book, review),
91/// None => println!("{} is unreviewed.", book)
92/// }
93/// }
94///
95/// // Look up the value for a key (will panic if the key is not found).
96/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
97///
98/// // Iterate over everything.
99/// for (book, review) in &book_reviews {
100/// println!("{}: \"{}\"", book, review);
101/// }
102/// ```
103///
104/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
105/// for more complex methods of getting, setting, updating and removing keys and
106/// their values:
107///
108/// ```
109/// use hashbrown::HashMap;
110///
111/// // type inference lets us omit an explicit type signature (which
112/// // would be `HashMap<&str, u8>` in this example).
113/// let mut player_stats = HashMap::new();
114///
115/// fn random_stat_buff() -> u8 {
116/// // could actually return some random value here - let's just return
117/// // some fixed value for now
118/// 42
119/// }
120///
121/// // insert a key only if it doesn't already exist
122/// player_stats.entry("health").or_insert(100);
123///
124/// // insert a key using a function that provides a new value only if it
125/// // doesn't already exist
126/// player_stats.entry("defence").or_insert_with(random_stat_buff);
127///
128/// // update a key, guarding against the key possibly not being set
129/// let stat = player_stats.entry("attack").or_insert(100);
130/// *stat += random_stat_buff();
131/// ```
132///
133/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
134/// We must also derive [`PartialEq`].
135///
136/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
137/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
138/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
139/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
140/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
141/// [`default`]: #method.default
142/// [`with_hasher`]: #method.with_hasher
143/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
144/// [`fnv`]: https://crates.io/crates/fnv
145/// [`foldhash`]: https://crates.io/crates/foldhash
146///
147/// ```
148/// use hashbrown::HashMap;
149///
150/// #[derive(Hash, Eq, PartialEq, Debug)]
151/// struct Viking {
152/// name: String,
153/// country: String,
154/// }
155///
156/// impl Viking {
157/// /// Creates a new Viking.
158/// fn new(name: &str, country: &str) -> Viking {
159/// Viking { name: name.to_string(), country: country.to_string() }
160/// }
161/// }
162///
163/// // Use a HashMap to store the vikings' health points.
164/// let mut vikings = HashMap::new();
165///
166/// vikings.insert(Viking::new("Einar", "Norway"), 25);
167/// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
168/// vikings.insert(Viking::new("Harald", "Iceland"), 12);
169///
170/// // Use derived implementation to print the status of the vikings.
171/// for (viking, health) in &vikings {
172/// println!("{:?} has {} hp", viking, health);
173/// }
174/// ```
175///
176/// A `HashMap` with fixed list of elements can be initialized from an array:
177///
178/// ```
179/// use hashbrown::HashMap;
180///
181/// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
182/// .into_iter().collect();
183/// // use the values stored in map
184/// ```
185pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator = Global> {
186 pub(crate) hash_builder: S,
187 pub(crate) table: RawTable<(K, V), A>,
188}
189
190impl<K: Clone, V: Clone, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A> {
191 fn clone(&self) -> Self {
192 HashMap {
193 hash_builder: self.hash_builder.clone(),
194 table: self.table.clone(),
195 }
196 }
197
198 fn clone_from(&mut self, source: &Self) {
199 self.table.clone_from(&source.table);
200
201 // Update hash_builder only if we successfully cloned all elements.
202 self.hash_builder.clone_from(&source.hash_builder);
203 }
204}
205
206/// Ensures that a single closure type across uses of this which, in turn prevents multiple
207/// instances of any functions like `RawTable::reserve` from being generated
208#[cfg_attr(feature = "inline-more", inline)]
209pub(crate) fn make_hasher<Q, V, S>(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_
210where
211 Q: Hash,
212 S: BuildHasher,
213{
214 move |val| make_hash::<Q, S>(hash_builder, &val.0)
215}
216
217/// Ensures that a single closure type across uses of this which, in turn prevents multiple
218/// instances of any functions like `RawTable::reserve` from being generated
219#[cfg_attr(feature = "inline-more", inline)]
220pub(crate) fn equivalent_key<Q, K, V>(k: &Q) -> impl Fn(&(K, V)) -> bool + '_
221where
222 Q: Equivalent<K> + ?Sized,
223{
224 move |x| k.equivalent(&x.0)
225}
226
227/// Ensures that a single closure type across uses of this which, in turn prevents multiple
228/// instances of any functions like `RawTable::reserve` from being generated
229#[cfg_attr(feature = "inline-more", inline)]
230#[allow(dead_code)]
231pub(crate) fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_
232where
233 Q: Equivalent<K> + ?Sized,
234{
235 move |x| k.equivalent(x)
236}
237
238#[cfg(not(feature = "nightly"))]
239#[cfg_attr(feature = "inline-more", inline)]
240pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
241where
242 Q: Hash + ?Sized,
243 S: BuildHasher,
244{
245 use core::hash::Hasher;
246 let mut state = hash_builder.build_hasher();
247 val.hash(&mut state);
248 state.finish()
249}
250
251#[cfg(feature = "nightly")]
252#[cfg_attr(feature = "inline-more", inline)]
253pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
254where
255 Q: Hash + ?Sized,
256 S: BuildHasher,
257{
258 hash_builder.hash_one(val)
259}
260
261#[cfg(feature = "default-hasher")]
262impl<K, V> HashMap<K, V, DefaultHashBuilder> {
263 /// Creates an empty `HashMap`.
264 ///
265 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
266 /// is first inserted into.
267 ///
268 /// # HashDoS resistance
269 ///
270 /// The `hash_builder` normally use a fixed key by default and that does
271 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
272 /// Users who require HashDoS resistance should explicitly use
273 /// [`std::collections::hash_map::RandomState`]
274 /// as the hasher when creating a [`HashMap`], for example with
275 /// [`with_hasher`](HashMap::with_hasher) method.
276 ///
277 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
278 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
279 ///
280 /// # Examples
281 ///
282 /// ```
283 /// use hashbrown::HashMap;
284 /// let mut map: HashMap<&str, i32> = HashMap::new();
285 /// assert_eq!(map.len(), 0);
286 /// assert_eq!(map.capacity(), 0);
287 /// ```
288 #[cfg_attr(feature = "inline-more", inline)]
289 pub fn new() -> Self {
290 Self::default()
291 }
292
293 /// Creates an empty `HashMap` with the specified capacity.
294 ///
295 /// The hash map will be able to hold at least `capacity` elements without
296 /// reallocating. If `capacity` is 0, the hash map will not allocate.
297 ///
298 /// # HashDoS resistance
299 ///
300 /// The `hash_builder` normally use a fixed key by default and that does
301 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
302 /// Users who require HashDoS resistance should explicitly use
303 /// [`std::collections::hash_map::RandomState`]
304 /// as the hasher when creating a [`HashMap`], for example with
305 /// [`with_capacity_and_hasher`](HashMap::with_capacity_and_hasher) method.
306 ///
307 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
308 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
309 ///
310 /// # Examples
311 ///
312 /// ```
313 /// use hashbrown::HashMap;
314 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
315 /// assert_eq!(map.len(), 0);
316 /// assert!(map.capacity() >= 10);
317 /// ```
318 #[cfg_attr(feature = "inline-more", inline)]
319 pub fn with_capacity(capacity: usize) -> Self {
320 Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default())
321 }
322}
323
324#[cfg(feature = "default-hasher")]
325impl<K, V, A: Allocator> HashMap<K, V, DefaultHashBuilder, A> {
326 /// Creates an empty `HashMap` using the given allocator.
327 ///
328 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
329 /// is first inserted into.
330 ///
331 /// # HashDoS resistance
332 ///
333 /// The `hash_builder` normally use a fixed key by default and that does
334 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
335 /// Users who require HashDoS resistance should explicitly use
336 /// [`std::collections::hash_map::RandomState`]
337 /// as the hasher when creating a [`HashMap`], for example with
338 /// [`with_hasher_in`](HashMap::with_hasher_in) method.
339 ///
340 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
341 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// use hashbrown::HashMap;
347 /// use bumpalo::Bump;
348 ///
349 /// let bump = Bump::new();
350 /// let mut map = HashMap::new_in(&bump);
351 ///
352 /// // The created HashMap holds none elements
353 /// assert_eq!(map.len(), 0);
354 ///
355 /// // The created HashMap also doesn't allocate memory
356 /// assert_eq!(map.capacity(), 0);
357 ///
358 /// // Now we insert element inside created HashMap
359 /// map.insert("One", 1);
360 /// // We can see that the HashMap holds 1 element
361 /// assert_eq!(map.len(), 1);
362 /// // And it also allocates some capacity
363 /// assert!(map.capacity() > 1);
364 /// ```
365 #[cfg_attr(feature = "inline-more", inline)]
366 pub fn new_in(alloc: A) -> Self {
367 Self::with_hasher_in(DefaultHashBuilder::default(), alloc)
368 }
369
370 /// Creates an empty `HashMap` with the specified capacity using the given allocator.
371 ///
372 /// The hash map will be able to hold at least `capacity` elements without
373 /// reallocating. If `capacity` is 0, the hash map will not allocate.
374 ///
375 /// # HashDoS resistance
376 ///
377 /// The `hash_builder` normally use a fixed key by default and that does
378 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
379 /// Users who require HashDoS resistance should explicitly use
380 /// [`std::collections::hash_map::RandomState`]
381 /// as the hasher when creating a [`HashMap`], for example with
382 /// [`with_capacity_and_hasher_in`](HashMap::with_capacity_and_hasher_in) method.
383 ///
384 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
385 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
386 ///
387 /// # Examples
388 ///
389 /// ```
390 /// use hashbrown::HashMap;
391 /// use bumpalo::Bump;
392 ///
393 /// let bump = Bump::new();
394 /// let mut map = HashMap::with_capacity_in(5, &bump);
395 ///
396 /// // The created HashMap holds none elements
397 /// assert_eq!(map.len(), 0);
398 /// // But it can hold at least 5 elements without reallocating
399 /// let empty_map_capacity = map.capacity();
400 /// assert!(empty_map_capacity >= 5);
401 ///
402 /// // Now we insert some 5 elements inside created HashMap
403 /// map.insert("One", 1);
404 /// map.insert("Two", 2);
405 /// map.insert("Three", 3);
406 /// map.insert("Four", 4);
407 /// map.insert("Five", 5);
408 ///
409 /// // We can see that the HashMap holds 5 elements
410 /// assert_eq!(map.len(), 5);
411 /// // But its capacity isn't changed
412 /// assert_eq!(map.capacity(), empty_map_capacity)
413 /// ```
414 #[cfg_attr(feature = "inline-more", inline)]
415 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
416 Self::with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc)
417 }
418}
419
420impl<K, V, S> HashMap<K, V, S> {
421 /// Creates an empty `HashMap` which will use the given hash builder to hash
422 /// keys.
423 ///
424 /// The hash map is initially created with a capacity of 0, so it will not
425 /// allocate until it is first inserted into.
426 ///
427 /// # HashDoS resistance
428 ///
429 /// The `hash_builder` normally use a fixed key by default and that does
430 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
431 /// Users who require HashDoS resistance should explicitly use
432 /// [`std::collections::hash_map::RandomState`]
433 /// as the hasher when creating a [`HashMap`].
434 ///
435 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
436 /// the `HashMap` to be useful, see its documentation for details.
437 ///
438 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
439 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
440 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
441 ///
442 /// # Examples
443 ///
444 /// ```
445 /// use hashbrown::HashMap;
446 /// use hashbrown::DefaultHashBuilder;
447 ///
448 /// let s = DefaultHashBuilder::default();
449 /// let mut map = HashMap::with_hasher(s);
450 /// assert_eq!(map.len(), 0);
451 /// assert_eq!(map.capacity(), 0);
452 ///
453 /// map.insert(1, 2);
454 /// ```
455 #[cfg_attr(feature = "inline-more", inline)]
456 #[cfg_attr(feature = "rustc-dep-of-std", rustc_const_stable_indirect)]
457 pub const fn with_hasher(hash_builder: S) -> Self {
458 Self {
459 hash_builder,
460 table: RawTable::new(),
461 }
462 }
463
464 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
465 /// to hash the keys.
466 ///
467 /// The hash map will be able to hold at least `capacity` elements without
468 /// reallocating. If `capacity` is 0, the hash map will not allocate.
469 ///
470 /// # HashDoS resistance
471 ///
472 /// The `hash_builder` normally use a fixed key by default and that does
473 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
474 /// Users who require HashDoS resistance should explicitly use
475 /// [`std::collections::hash_map::RandomState`]
476 /// as the hasher when creating a [`HashMap`].
477 ///
478 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
479 /// the `HashMap` to be useful, see its documentation for details.
480 ///
481 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
482 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
483 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use hashbrown::HashMap;
489 /// use hashbrown::DefaultHashBuilder;
490 ///
491 /// let s = DefaultHashBuilder::default();
492 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
493 /// assert_eq!(map.len(), 0);
494 /// assert!(map.capacity() >= 10);
495 ///
496 /// map.insert(1, 2);
497 /// ```
498 #[cfg_attr(feature = "inline-more", inline)]
499 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
500 Self {
501 hash_builder,
502 table: RawTable::with_capacity(capacity),
503 }
504 }
505}
506
507impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
508 /// Returns a reference to the underlying allocator.
509 #[inline]
510 pub fn allocator(&self) -> &A {
511 self.table.allocator()
512 }
513
514 /// Creates an empty `HashMap` which will use the given hash builder to hash
515 /// keys. It will be allocated with the given allocator.
516 ///
517 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
518 /// is first inserted into.
519 ///
520 /// # HashDoS resistance
521 ///
522 /// The `hash_builder` normally use a fixed key by default and that does
523 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
524 /// Users who require HashDoS resistance should explicitly use
525 /// [`std::collections::hash_map::RandomState`]
526 /// as the hasher when creating a [`HashMap`].
527 ///
528 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
529 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
530 ///
531 /// # Examples
532 ///
533 /// ```
534 /// use hashbrown::HashMap;
535 /// use hashbrown::DefaultHashBuilder;
536 ///
537 /// let s = DefaultHashBuilder::default();
538 /// let mut map = HashMap::with_hasher(s);
539 /// map.insert(1, 2);
540 /// ```
541 #[cfg_attr(feature = "inline-more", inline)]
542 #[cfg_attr(feature = "rustc-dep-of-std", rustc_const_stable_indirect)]
543 pub const fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
544 Self {
545 hash_builder,
546 table: RawTable::new_in(alloc),
547 }
548 }
549
550 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
551 /// to hash the keys. It will be allocated with the given allocator.
552 ///
553 /// The hash map will be able to hold at least `capacity` elements without
554 /// reallocating. If `capacity` is 0, the hash map will not allocate.
555 ///
556 /// # HashDoS resistance
557 ///
558 /// The `hash_builder` normally use a fixed key by default and that does
559 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
560 /// Users who require HashDoS resistance should explicitly use
561 /// [`std::collections::hash_map::RandomState`]
562 /// as the hasher when creating a [`HashMap`].
563 ///
564 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
565 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
566 ///
567 /// # Examples
568 ///
569 /// ```
570 /// use hashbrown::HashMap;
571 /// use hashbrown::DefaultHashBuilder;
572 ///
573 /// let s = DefaultHashBuilder::default();
574 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
575 /// map.insert(1, 2);
576 /// ```
577 #[cfg_attr(feature = "inline-more", inline)]
578 pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self {
579 Self {
580 hash_builder,
581 table: RawTable::with_capacity_in(capacity, alloc),
582 }
583 }
584
585 /// Returns a reference to the map's [`BuildHasher`].
586 ///
587 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// use hashbrown::HashMap;
593 /// use hashbrown::DefaultHashBuilder;
594 ///
595 /// let hasher = DefaultHashBuilder::default();
596 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
597 /// let hasher: &DefaultHashBuilder = map.hasher();
598 /// ```
599 #[cfg_attr(feature = "inline-more", inline)]
600 pub fn hasher(&self) -> &S {
601 &self.hash_builder
602 }
603
604 /// Returns the number of elements the map can hold without reallocating.
605 ///
606 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
607 /// more, but is guaranteed to be able to hold at least this many.
608 ///
609 /// # Examples
610 ///
611 /// ```
612 /// use hashbrown::HashMap;
613 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
614 /// assert_eq!(map.len(), 0);
615 /// assert!(map.capacity() >= 100);
616 /// ```
617 #[cfg_attr(feature = "inline-more", inline)]
618 pub fn capacity(&self) -> usize {
619 self.table.capacity()
620 }
621
622 /// An iterator visiting all keys in arbitrary order.
623 /// The iterator element type is `&'a K`.
624 ///
625 /// # Examples
626 ///
627 /// ```
628 /// use hashbrown::HashMap;
629 ///
630 /// let mut map = HashMap::new();
631 /// map.insert("a", 1);
632 /// map.insert("b", 2);
633 /// map.insert("c", 3);
634 /// assert_eq!(map.len(), 3);
635 /// let mut vec: Vec<&str> = Vec::new();
636 ///
637 /// for key in map.keys() {
638 /// println!("{}", key);
639 /// vec.push(*key);
640 /// }
641 ///
642 /// // The `Keys` iterator produces keys in arbitrary order, so the
643 /// // keys must be sorted to test them against a sorted array.
644 /// vec.sort_unstable();
645 /// assert_eq!(vec, ["a", "b", "c"]);
646 ///
647 /// assert_eq!(map.len(), 3);
648 /// ```
649 #[cfg_attr(feature = "inline-more", inline)]
650 pub fn keys(&self) -> Keys<'_, K, V> {
651 Keys { inner: self.iter() }
652 }
653
654 /// An iterator visiting all values in arbitrary order.
655 /// The iterator element type is `&'a V`.
656 ///
657 /// # Examples
658 ///
659 /// ```
660 /// use hashbrown::HashMap;
661 ///
662 /// let mut map = HashMap::new();
663 /// map.insert("a", 1);
664 /// map.insert("b", 2);
665 /// map.insert("c", 3);
666 /// assert_eq!(map.len(), 3);
667 /// let mut vec: Vec<i32> = Vec::new();
668 ///
669 /// for val in map.values() {
670 /// println!("{}", val);
671 /// vec.push(*val);
672 /// }
673 ///
674 /// // The `Values` iterator produces values in arbitrary order, so the
675 /// // values must be sorted to test them against a sorted array.
676 /// vec.sort_unstable();
677 /// assert_eq!(vec, [1, 2, 3]);
678 ///
679 /// assert_eq!(map.len(), 3);
680 /// ```
681 #[cfg_attr(feature = "inline-more", inline)]
682 pub fn values(&self) -> Values<'_, K, V> {
683 Values { inner: self.iter() }
684 }
685
686 /// An iterator visiting all values mutably in arbitrary order.
687 /// The iterator element type is `&'a mut V`.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// use hashbrown::HashMap;
693 ///
694 /// let mut map = HashMap::new();
695 ///
696 /// map.insert("a", 1);
697 /// map.insert("b", 2);
698 /// map.insert("c", 3);
699 ///
700 /// for val in map.values_mut() {
701 /// *val = *val + 10;
702 /// }
703 ///
704 /// assert_eq!(map.len(), 3);
705 /// let mut vec: Vec<i32> = Vec::new();
706 ///
707 /// for val in map.values() {
708 /// println!("{}", val);
709 /// vec.push(*val);
710 /// }
711 ///
712 /// // The `Values` iterator produces values in arbitrary order, so the
713 /// // values must be sorted to test them against a sorted array.
714 /// vec.sort_unstable();
715 /// assert_eq!(vec, [11, 12, 13]);
716 ///
717 /// assert_eq!(map.len(), 3);
718 /// ```
719 #[cfg_attr(feature = "inline-more", inline)]
720 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
721 ValuesMut {
722 inner: self.iter_mut(),
723 }
724 }
725
726 /// An iterator visiting all key-value pairs in arbitrary order.
727 /// The iterator element type is `(&'a K, &'a V)`.
728 ///
729 /// # Examples
730 ///
731 /// ```
732 /// use hashbrown::HashMap;
733 ///
734 /// let mut map = HashMap::new();
735 /// map.insert("a", 1);
736 /// map.insert("b", 2);
737 /// map.insert("c", 3);
738 /// assert_eq!(map.len(), 3);
739 /// let mut vec: Vec<(&str, i32)> = Vec::new();
740 ///
741 /// for (key, val) in map.iter() {
742 /// println!("key: {} val: {}", key, val);
743 /// vec.push((*key, *val));
744 /// }
745 ///
746 /// // The `Iter` iterator produces items in arbitrary order, so the
747 /// // items must be sorted to test them against a sorted array.
748 /// vec.sort_unstable();
749 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
750 ///
751 /// assert_eq!(map.len(), 3);
752 /// ```
753 #[cfg_attr(feature = "inline-more", inline)]
754 pub fn iter(&self) -> Iter<'_, K, V> {
755 // Here we tie the lifetime of self to the iter.
756 unsafe {
757 Iter {
758 inner: self.table.iter(),
759 marker: PhantomData,
760 }
761 }
762 }
763
764 /// An iterator visiting all key-value pairs in arbitrary order,
765 /// with mutable references to the values.
766 /// The iterator element type is `(&'a K, &'a mut V)`.
767 ///
768 /// # Examples
769 ///
770 /// ```
771 /// use hashbrown::HashMap;
772 ///
773 /// let mut map = HashMap::new();
774 /// map.insert("a", 1);
775 /// map.insert("b", 2);
776 /// map.insert("c", 3);
777 ///
778 /// // Update all values
779 /// for (_, val) in map.iter_mut() {
780 /// *val *= 2;
781 /// }
782 ///
783 /// assert_eq!(map.len(), 3);
784 /// let mut vec: Vec<(&str, i32)> = Vec::new();
785 ///
786 /// for (key, val) in &map {
787 /// println!("key: {} val: {}", key, val);
788 /// vec.push((*key, *val));
789 /// }
790 ///
791 /// // The `Iter` iterator produces items in arbitrary order, so the
792 /// // items must be sorted to test them against a sorted array.
793 /// vec.sort_unstable();
794 /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
795 ///
796 /// assert_eq!(map.len(), 3);
797 /// ```
798 #[cfg_attr(feature = "inline-more", inline)]
799 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
800 // Here we tie the lifetime of self to the iter.
801 unsafe {
802 IterMut {
803 inner: self.table.iter(),
804 marker: PhantomData,
805 }
806 }
807 }
808
809 #[cfg(test)]
810 #[cfg_attr(feature = "inline-more", inline)]
811 fn raw_capacity(&self) -> usize {
812 self.table.buckets()
813 }
814
815 /// Returns the number of elements in the map.
816 ///
817 /// # Examples
818 ///
819 /// ```
820 /// use hashbrown::HashMap;
821 ///
822 /// let mut a = HashMap::new();
823 /// assert_eq!(a.len(), 0);
824 /// a.insert(1, "a");
825 /// assert_eq!(a.len(), 1);
826 /// ```
827 #[cfg_attr(feature = "inline-more", inline)]
828 pub fn len(&self) -> usize {
829 self.table.len()
830 }
831
832 /// Returns `true` if the map contains no elements.
833 ///
834 /// # Examples
835 ///
836 /// ```
837 /// use hashbrown::HashMap;
838 ///
839 /// let mut a = HashMap::new();
840 /// assert!(a.is_empty());
841 /// a.insert(1, "a");
842 /// assert!(!a.is_empty());
843 /// ```
844 #[cfg_attr(feature = "inline-more", inline)]
845 pub fn is_empty(&self) -> bool {
846 self.len() == 0
847 }
848
849 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
850 /// allocated memory for reuse.
851 ///
852 /// If the returned iterator is dropped before being fully consumed, it
853 /// drops the remaining key-value pairs. The returned iterator keeps a
854 /// mutable borrow on the vector to optimize its implementation.
855 ///
856 /// # Examples
857 ///
858 /// ```
859 /// use hashbrown::HashMap;
860 ///
861 /// let mut a = HashMap::new();
862 /// a.insert(1, "a");
863 /// a.insert(2, "b");
864 /// let capacity_before_drain = a.capacity();
865 ///
866 /// for (k, v) in a.drain().take(1) {
867 /// assert!(k == 1 || k == 2);
868 /// assert!(v == "a" || v == "b");
869 /// }
870 ///
871 /// // As we can see, the map is empty and contains no element.
872 /// assert!(a.is_empty() && a.len() == 0);
873 /// // But map capacity is equal to old one.
874 /// assert_eq!(a.capacity(), capacity_before_drain);
875 ///
876 /// let mut a = HashMap::new();
877 /// a.insert(1, "a");
878 /// a.insert(2, "b");
879 ///
880 /// { // Iterator is dropped without being consumed.
881 /// let d = a.drain();
882 /// }
883 ///
884 /// // But the map is empty even if we do not use Drain iterator.
885 /// assert!(a.is_empty());
886 /// ```
887 #[cfg_attr(feature = "inline-more", inline)]
888 pub fn drain(&mut self) -> Drain<'_, K, V, A> {
889 Drain {
890 inner: self.table.drain(),
891 }
892 }
893
894 /// Retains only the elements specified by the predicate. Keeps the
895 /// allocated memory for reuse.
896 ///
897 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
898 /// The elements are visited in unsorted (and unspecified) order.
899 ///
900 /// # Examples
901 ///
902 /// ```
903 /// use hashbrown::HashMap;
904 ///
905 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
906 /// assert_eq!(map.len(), 8);
907 ///
908 /// map.retain(|&k, _| k % 2 == 0);
909 ///
910 /// // We can see, that the number of elements inside map is changed.
911 /// assert_eq!(map.len(), 4);
912 ///
913 /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
914 /// vec.sort_unstable();
915 /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
916 /// ```
917 pub fn retain<F>(&mut self, mut f: F)
918 where
919 F: FnMut(&K, &mut V) -> bool,
920 {
921 // Here we only use `iter` as a temporary, preventing use-after-free
922 unsafe {
923 for item in self.table.iter() {
924 let &mut (ref key, ref mut value) = item.as_mut();
925 if !f(key, value) {
926 self.table.erase(item);
927 }
928 }
929 }
930 }
931
932 /// Drains elements which are true under the given predicate,
933 /// and returns an iterator over the removed items.
934 ///
935 /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out
936 /// into another iterator.
937 ///
938 /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of
939 /// whether you choose to keep or remove it.
940 ///
941 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
942 /// or the iteration short-circuits, then the remaining elements will be retained.
943 /// Use [`retain()`] with a negated predicate if you do not need the returned iterator.
944 ///
945 /// Keeps the allocated memory for reuse.
946 ///
947 /// [`retain()`]: HashMap::retain
948 ///
949 /// # Examples
950 ///
951 /// ```
952 /// use hashbrown::HashMap;
953 ///
954 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
955 ///
956 /// let drained: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
957 ///
958 /// let mut evens = drained.keys().cloned().collect::<Vec<_>>();
959 /// let mut odds = map.keys().cloned().collect::<Vec<_>>();
960 /// evens.sort();
961 /// odds.sort();
962 ///
963 /// assert_eq!(evens, vec![0, 2, 4, 6]);
964 /// assert_eq!(odds, vec![1, 3, 5, 7]);
965 ///
966 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
967 ///
968 /// { // Iterator is dropped without being consumed.
969 /// let d = map.extract_if(|k, _v| k % 2 != 0);
970 /// }
971 ///
972 /// // ExtractIf was not exhausted, therefore no elements were drained.
973 /// assert_eq!(map.len(), 8);
974 /// ```
975 #[cfg_attr(feature = "inline-more", inline)]
976 pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F, A>
977 where
978 F: FnMut(&K, &mut V) -> bool,
979 {
980 ExtractIf {
981 f,
982 inner: RawExtractIf {
983 iter: unsafe { self.table.iter() },
984 table: &mut self.table,
985 },
986 }
987 }
988
989 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
990 /// for reuse.
991 ///
992 /// # Examples
993 ///
994 /// ```
995 /// use hashbrown::HashMap;
996 ///
997 /// let mut a = HashMap::new();
998 /// a.insert(1, "a");
999 /// let capacity_before_clear = a.capacity();
1000 ///
1001 /// a.clear();
1002 ///
1003 /// // Map is empty.
1004 /// assert!(a.is_empty());
1005 /// // But map capacity is equal to old one.
1006 /// assert_eq!(a.capacity(), capacity_before_clear);
1007 /// ```
1008 #[cfg_attr(feature = "inline-more", inline)]
1009 pub fn clear(&mut self) {
1010 self.table.clear();
1011 }
1012
1013 /// Creates a consuming iterator visiting all the keys in arbitrary order.
1014 /// The map cannot be used after calling this.
1015 /// The iterator element type is `K`.
1016 ///
1017 /// # Examples
1018 ///
1019 /// ```
1020 /// use hashbrown::HashMap;
1021 ///
1022 /// let mut map = HashMap::new();
1023 /// map.insert("a", 1);
1024 /// map.insert("b", 2);
1025 /// map.insert("c", 3);
1026 ///
1027 /// let mut vec: Vec<&str> = map.into_keys().collect();
1028 ///
1029 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
1030 /// // keys must be sorted to test them against a sorted array.
1031 /// vec.sort_unstable();
1032 /// assert_eq!(vec, ["a", "b", "c"]);
1033 /// ```
1034 #[inline]
1035 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1036 IntoKeys {
1037 inner: self.into_iter(),
1038 }
1039 }
1040
1041 /// Creates a consuming iterator visiting all the values in arbitrary order.
1042 /// The map cannot be used after calling this.
1043 /// The iterator element type is `V`.
1044 ///
1045 /// # Examples
1046 ///
1047 /// ```
1048 /// use hashbrown::HashMap;
1049 ///
1050 /// let mut map = HashMap::new();
1051 /// map.insert("a", 1);
1052 /// map.insert("b", 2);
1053 /// map.insert("c", 3);
1054 ///
1055 /// let mut vec: Vec<i32> = map.into_values().collect();
1056 ///
1057 /// // The `IntoValues` iterator produces values in arbitrary order, so
1058 /// // the values must be sorted to test them against a sorted array.
1059 /// vec.sort_unstable();
1060 /// assert_eq!(vec, [1, 2, 3]);
1061 /// ```
1062 #[inline]
1063 pub fn into_values(self) -> IntoValues<K, V, A> {
1064 IntoValues {
1065 inner: self.into_iter(),
1066 }
1067 }
1068}
1069
1070impl<K, V, S, A> HashMap<K, V, S, A>
1071where
1072 K: Eq + Hash,
1073 S: BuildHasher,
1074 A: Allocator,
1075{
1076 /// Reserves capacity for at least `additional` more elements to be inserted
1077 /// in the `HashMap`. The collection may reserve more space to avoid
1078 /// frequent reallocations.
1079 ///
1080 /// # Panics
1081 ///
1082 /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
1083 /// in case of allocation error. Use [`try_reserve`](HashMap::try_reserve) instead
1084 /// if you want to handle memory allocation failure.
1085 ///
1086 /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html
1087 /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```
1092 /// use hashbrown::HashMap;
1093 /// let mut map: HashMap<&str, i32> = HashMap::new();
1094 /// // Map is empty and doesn't allocate memory
1095 /// assert_eq!(map.capacity(), 0);
1096 ///
1097 /// map.reserve(10);
1098 ///
1099 /// // And now map can hold at least 10 elements
1100 /// assert!(map.capacity() >= 10);
1101 /// ```
1102 #[cfg_attr(feature = "inline-more", inline)]
1103 pub fn reserve(&mut self, additional: usize) {
1104 self.table
1105 .reserve(additional, make_hasher::<_, V, S>(&self.hash_builder));
1106 }
1107
1108 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1109 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
1110 /// frequent reallocations.
1111 ///
1112 /// # Errors
1113 ///
1114 /// If the capacity overflows, or the allocator reports a failure, then an error
1115 /// is returned.
1116 ///
1117 /// # Examples
1118 ///
1119 /// ```
1120 /// use hashbrown::HashMap;
1121 ///
1122 /// let mut map: HashMap<&str, isize> = HashMap::new();
1123 /// // Map is empty and doesn't allocate memory
1124 /// assert_eq!(map.capacity(), 0);
1125 ///
1126 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
1127 ///
1128 /// // And now map can hold at least 10 elements
1129 /// assert!(map.capacity() >= 10);
1130 /// ```
1131 /// If the capacity overflows, or the allocator reports a failure, then an error
1132 /// is returned:
1133 /// ```
1134 /// # fn test() {
1135 /// use hashbrown::HashMap;
1136 /// use hashbrown::TryReserveError;
1137 /// let mut map: HashMap<i32, i32> = HashMap::new();
1138 ///
1139 /// match map.try_reserve(usize::MAX) {
1140 /// Err(error) => match error {
1141 /// TryReserveError::CapacityOverflow => {}
1142 /// _ => panic!("TryReserveError::AllocError ?"),
1143 /// },
1144 /// _ => panic!(),
1145 /// }
1146 /// # }
1147 /// # fn main() {
1148 /// # #[cfg(not(miri))]
1149 /// # test()
1150 /// # }
1151 /// ```
1152 #[cfg_attr(feature = "inline-more", inline)]
1153 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1154 self.table
1155 .try_reserve(additional, make_hasher::<_, V, S>(&self.hash_builder))
1156 }
1157
1158 /// Shrinks the capacity of the map as much as possible. It will drop
1159 /// down as much as possible while maintaining the internal rules
1160 /// and possibly leaving some space in accordance with the resize policy.
1161 ///
1162 /// # Examples
1163 ///
1164 /// ```
1165 /// use hashbrown::HashMap;
1166 ///
1167 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1168 /// map.insert(1, 2);
1169 /// map.insert(3, 4);
1170 /// assert!(map.capacity() >= 100);
1171 /// map.shrink_to_fit();
1172 /// assert!(map.capacity() >= 2);
1173 /// ```
1174 #[cfg_attr(feature = "inline-more", inline)]
1175 pub fn shrink_to_fit(&mut self) {
1176 self.table
1177 .shrink_to(0, make_hasher::<_, V, S>(&self.hash_builder));
1178 }
1179
1180 /// Shrinks the capacity of the map with a lower limit. It will drop
1181 /// down no lower than the supplied limit while maintaining the internal rules
1182 /// and possibly leaving some space in accordance with the resize policy.
1183 ///
1184 /// This function does nothing if the current capacity is smaller than the
1185 /// supplied minimum capacity.
1186 ///
1187 /// # Examples
1188 ///
1189 /// ```
1190 /// use hashbrown::HashMap;
1191 ///
1192 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1193 /// map.insert(1, 2);
1194 /// map.insert(3, 4);
1195 /// assert!(map.capacity() >= 100);
1196 /// map.shrink_to(10);
1197 /// assert!(map.capacity() >= 10);
1198 /// map.shrink_to(0);
1199 /// assert!(map.capacity() >= 2);
1200 /// map.shrink_to(10);
1201 /// assert!(map.capacity() >= 2);
1202 /// ```
1203 #[cfg_attr(feature = "inline-more", inline)]
1204 pub fn shrink_to(&mut self, min_capacity: usize) {
1205 self.table
1206 .shrink_to(min_capacity, make_hasher::<_, V, S>(&self.hash_builder));
1207 }
1208
1209 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1210 ///
1211 /// # Examples
1212 ///
1213 /// ```
1214 /// use hashbrown::HashMap;
1215 ///
1216 /// let mut letters = HashMap::new();
1217 ///
1218 /// for ch in "a short treatise on fungi".chars() {
1219 /// let counter = letters.entry(ch).or_insert(0);
1220 /// *counter += 1;
1221 /// }
1222 ///
1223 /// assert_eq!(letters[&'s'], 2);
1224 /// assert_eq!(letters[&'t'], 3);
1225 /// assert_eq!(letters[&'u'], 1);
1226 /// assert_eq!(letters.get(&'y'), None);
1227 /// ```
1228 #[cfg_attr(feature = "inline-more", inline)]
1229 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> {
1230 let hash = make_hash::<K, S>(&self.hash_builder, &key);
1231 if let Some(elem) = self.table.find(hash, equivalent_key(&key)) {
1232 Entry::Occupied(OccupiedEntry {
1233 hash,
1234 elem,
1235 table: self,
1236 })
1237 } else {
1238 Entry::Vacant(VacantEntry {
1239 hash,
1240 key,
1241 table: self,
1242 })
1243 }
1244 }
1245
1246 /// Gets the given key's corresponding entry by reference in the map for in-place manipulation.
1247 ///
1248 /// # Examples
1249 ///
1250 /// ```
1251 /// use hashbrown::HashMap;
1252 ///
1253 /// let mut words: HashMap<String, usize> = HashMap::new();
1254 /// let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
1255 /// for (i, &s) in source.iter().enumerate() {
1256 /// let counter = words.entry_ref(s).or_insert(0);
1257 /// *counter += 1;
1258 /// }
1259 ///
1260 /// assert_eq!(words["poneyland"], 3);
1261 /// assert_eq!(words["horseyland"], 1);
1262 /// ```
1263 #[cfg_attr(feature = "inline-more", inline)]
1264 pub fn entry_ref<'a, 'b, Q>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A>
1265 where
1266 Q: Hash + Equivalent<K> + ?Sized,
1267 {
1268 let hash = make_hash::<Q, S>(&self.hash_builder, key);
1269 if let Some(elem) = self.table.find(hash, equivalent_key(key)) {
1270 EntryRef::Occupied(OccupiedEntry {
1271 hash,
1272 elem,
1273 table: self,
1274 })
1275 } else {
1276 EntryRef::Vacant(VacantEntryRef {
1277 hash,
1278 key,
1279 table: self,
1280 })
1281 }
1282 }
1283
1284 /// Returns a reference to the value corresponding to the key.
1285 ///
1286 /// The key may be any borrowed form of the map's key type, but
1287 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1288 /// the key type.
1289 ///
1290 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1291 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1292 ///
1293 /// # Examples
1294 ///
1295 /// ```
1296 /// use hashbrown::HashMap;
1297 ///
1298 /// let mut map = HashMap::new();
1299 /// map.insert(1, "a");
1300 /// assert_eq!(map.get(&1), Some(&"a"));
1301 /// assert_eq!(map.get(&2), None);
1302 /// ```
1303 #[inline]
1304 pub fn get<Q>(&self, k: &Q) -> Option<&V>
1305 where
1306 Q: Hash + Equivalent<K> + ?Sized,
1307 {
1308 // Avoid `Option::map` because it bloats LLVM IR.
1309 match self.get_inner(k) {
1310 Some((_, v)) => Some(v),
1311 None => None,
1312 }
1313 }
1314
1315 /// Returns the key-value pair corresponding to the supplied key.
1316 ///
1317 /// The supplied key may be any borrowed form of the map's key type, but
1318 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1319 /// the key type.
1320 ///
1321 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1322 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1323 ///
1324 /// # Examples
1325 ///
1326 /// ```
1327 /// use hashbrown::HashMap;
1328 ///
1329 /// let mut map = HashMap::new();
1330 /// map.insert(1, "a");
1331 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1332 /// assert_eq!(map.get_key_value(&2), None);
1333 /// ```
1334 #[inline]
1335 pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
1336 where
1337 Q: Hash + Equivalent<K> + ?Sized,
1338 {
1339 // Avoid `Option::map` because it bloats LLVM IR.
1340 match self.get_inner(k) {
1341 Some((key, value)) => Some((key, value)),
1342 None => None,
1343 }
1344 }
1345
1346 #[inline]
1347 fn get_inner<Q>(&self, k: &Q) -> Option<&(K, V)>
1348 where
1349 Q: Hash + Equivalent<K> + ?Sized,
1350 {
1351 if self.table.is_empty() {
1352 None
1353 } else {
1354 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1355 self.table.get(hash, equivalent_key(k))
1356 }
1357 }
1358
1359 /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
1360 ///
1361 /// The supplied key may be any borrowed form of the map's key type, but
1362 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1363 /// the key type.
1364 ///
1365 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1366 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1367 ///
1368 /// # Examples
1369 ///
1370 /// ```
1371 /// use hashbrown::HashMap;
1372 ///
1373 /// let mut map = HashMap::new();
1374 /// map.insert(1, "a");
1375 /// let (k, v) = map.get_key_value_mut(&1).unwrap();
1376 /// assert_eq!(k, &1);
1377 /// assert_eq!(v, &mut "a");
1378 /// *v = "b";
1379 /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
1380 /// assert_eq!(map.get_key_value_mut(&2), None);
1381 /// ```
1382 #[inline]
1383 pub fn get_key_value_mut<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
1384 where
1385 Q: Hash + Equivalent<K> + ?Sized,
1386 {
1387 // Avoid `Option::map` because it bloats LLVM IR.
1388 match self.get_inner_mut(k) {
1389 Some(&mut (ref key, ref mut value)) => Some((key, value)),
1390 None => None,
1391 }
1392 }
1393
1394 /// Returns `true` if the map contains a value for the specified key.
1395 ///
1396 /// The key may be any borrowed form of the map's key type, but
1397 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1398 /// the key type.
1399 ///
1400 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1401 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1402 ///
1403 /// # Examples
1404 ///
1405 /// ```
1406 /// use hashbrown::HashMap;
1407 ///
1408 /// let mut map = HashMap::new();
1409 /// map.insert(1, "a");
1410 /// assert_eq!(map.contains_key(&1), true);
1411 /// assert_eq!(map.contains_key(&2), false);
1412 /// ```
1413 #[cfg_attr(feature = "inline-more", inline)]
1414 pub fn contains_key<Q>(&self, k: &Q) -> bool
1415 where
1416 Q: Hash + Equivalent<K> + ?Sized,
1417 {
1418 self.get_inner(k).is_some()
1419 }
1420
1421 /// Returns a mutable reference to the value corresponding to the key.
1422 ///
1423 /// The key may be any borrowed form of the map's key type, but
1424 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1425 /// the key type.
1426 ///
1427 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1428 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1429 ///
1430 /// # Examples
1431 ///
1432 /// ```
1433 /// use hashbrown::HashMap;
1434 ///
1435 /// let mut map = HashMap::new();
1436 /// map.insert(1, "a");
1437 /// if let Some(x) = map.get_mut(&1) {
1438 /// *x = "b";
1439 /// }
1440 /// assert_eq!(map[&1], "b");
1441 ///
1442 /// assert_eq!(map.get_mut(&2), None);
1443 /// ```
1444 #[cfg_attr(feature = "inline-more", inline)]
1445 pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
1446 where
1447 Q: Hash + Equivalent<K> + ?Sized,
1448 {
1449 // Avoid `Option::map` because it bloats LLVM IR.
1450 match self.get_inner_mut(k) {
1451 Some(&mut (_, ref mut v)) => Some(v),
1452 None => None,
1453 }
1454 }
1455
1456 #[inline]
1457 fn get_inner_mut<Q>(&mut self, k: &Q) -> Option<&mut (K, V)>
1458 where
1459 Q: Hash + Equivalent<K> + ?Sized,
1460 {
1461 if self.table.is_empty() {
1462 None
1463 } else {
1464 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1465 self.table.get_mut(hash, equivalent_key(k))
1466 }
1467 }
1468
1469 /// Attempts to get mutable references to `N` values in the map at once.
1470 ///
1471 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1472 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1473 ///
1474 /// # Panics
1475 ///
1476 /// Panics if any keys are overlapping.
1477 ///
1478 /// # Examples
1479 ///
1480 /// ```
1481 /// use hashbrown::HashMap;
1482 ///
1483 /// let mut libraries = HashMap::new();
1484 /// libraries.insert("Bodleian Library".to_string(), 1602);
1485 /// libraries.insert("Athenæum".to_string(), 1807);
1486 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1487 /// libraries.insert("Library of Congress".to_string(), 1800);
1488 ///
1489 /// // Get Athenæum and Bodleian Library
1490 /// let [Some(a), Some(b)] = libraries.get_many_mut([
1491 /// "Athenæum",
1492 /// "Bodleian Library",
1493 /// ]) else { panic!() };
1494 ///
1495 /// // Assert values of Athenæum and Library of Congress
1496 /// let got = libraries.get_many_mut([
1497 /// "Athenæum",
1498 /// "Library of Congress",
1499 /// ]);
1500 /// assert_eq!(
1501 /// got,
1502 /// [
1503 /// Some(&mut 1807),
1504 /// Some(&mut 1800),
1505 /// ],
1506 /// );
1507 ///
1508 /// // Missing keys result in None
1509 /// let got = libraries.get_many_mut([
1510 /// "Athenæum",
1511 /// "New York Public Library",
1512 /// ]);
1513 /// assert_eq!(
1514 /// got,
1515 /// [
1516 /// Some(&mut 1807),
1517 /// None
1518 /// ]
1519 /// );
1520 /// ```
1521 ///
1522 /// ```should_panic
1523 /// use hashbrown::HashMap;
1524 ///
1525 /// let mut libraries = HashMap::new();
1526 /// libraries.insert("Athenæum".to_string(), 1807);
1527 ///
1528 /// // Duplicate keys panic!
1529 /// let got = libraries.get_many_mut([
1530 /// "Athenæum",
1531 /// "Athenæum",
1532 /// ]);
1533 /// ```
1534 pub fn get_many_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut V>; N]
1535 where
1536 Q: Hash + Equivalent<K> + ?Sized,
1537 {
1538 self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v))
1539 }
1540
1541 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1542 /// the values are unique.
1543 ///
1544 /// Returns an array of length `N` with the results of each query. `None` will be used if
1545 /// the key is missing.
1546 ///
1547 /// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`).
1548 ///
1549 /// # Safety
1550 ///
1551 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1552 /// references are not used.
1553 ///
1554 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```
1559 /// use hashbrown::HashMap;
1560 ///
1561 /// let mut libraries = HashMap::new();
1562 /// libraries.insert("Bodleian Library".to_string(), 1602);
1563 /// libraries.insert("Athenæum".to_string(), 1807);
1564 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1565 /// libraries.insert("Library of Congress".to_string(), 1800);
1566 ///
1567 /// // SAFETY: The keys do not overlap.
1568 /// let [Some(a), Some(b)] = (unsafe { libraries.get_many_unchecked_mut([
1569 /// "Athenæum",
1570 /// "Bodleian Library",
1571 /// ]) }) else { panic!() };
1572 ///
1573 /// // SAFETY: The keys do not overlap.
1574 /// let got = unsafe { libraries.get_many_unchecked_mut([
1575 /// "Athenæum",
1576 /// "Library of Congress",
1577 /// ]) };
1578 /// assert_eq!(
1579 /// got,
1580 /// [
1581 /// Some(&mut 1807),
1582 /// Some(&mut 1800),
1583 /// ],
1584 /// );
1585 ///
1586 /// // SAFETY: The keys do not overlap.
1587 /// let got = unsafe { libraries.get_many_unchecked_mut([
1588 /// "Athenæum",
1589 /// "New York Public Library",
1590 /// ]) };
1591 /// // Missing keys result in None
1592 /// assert_eq!(got, [Some(&mut 1807), None]);
1593 /// ```
1594 pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
1595 &mut self,
1596 ks: [&Q; N],
1597 ) -> [Option<&'_ mut V>; N]
1598 where
1599 Q: Hash + Equivalent<K> + ?Sized,
1600 {
1601 self.get_many_unchecked_mut_inner(ks)
1602 .map(|res| res.map(|(_, v)| v))
1603 }
1604
1605 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1606 /// references to the corresponding keys.
1607 ///
1608 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1609 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1610 ///
1611 /// # Panics
1612 ///
1613 /// Panics if any keys are overlapping.
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```
1618 /// use hashbrown::HashMap;
1619 ///
1620 /// let mut libraries = HashMap::new();
1621 /// libraries.insert("Bodleian Library".to_string(), 1602);
1622 /// libraries.insert("Athenæum".to_string(), 1807);
1623 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1624 /// libraries.insert("Library of Congress".to_string(), 1800);
1625 ///
1626 /// let got = libraries.get_many_key_value_mut([
1627 /// "Bodleian Library",
1628 /// "Herzogin-Anna-Amalia-Bibliothek",
1629 /// ]);
1630 /// assert_eq!(
1631 /// got,
1632 /// [
1633 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1634 /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
1635 /// ],
1636 /// );
1637 /// // Missing keys result in None
1638 /// let got = libraries.get_many_key_value_mut([
1639 /// "Bodleian Library",
1640 /// "Gewandhaus",
1641 /// ]);
1642 /// assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]);
1643 /// ```
1644 ///
1645 /// ```should_panic
1646 /// use hashbrown::HashMap;
1647 ///
1648 /// let mut libraries = HashMap::new();
1649 /// libraries.insert("Bodleian Library".to_string(), 1602);
1650 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1651 ///
1652 /// // Duplicate keys result in panic!
1653 /// let got = libraries.get_many_key_value_mut([
1654 /// "Bodleian Library",
1655 /// "Herzogin-Anna-Amalia-Bibliothek",
1656 /// "Herzogin-Anna-Amalia-Bibliothek",
1657 /// ]);
1658 /// ```
1659 pub fn get_many_key_value_mut<Q, const N: usize>(
1660 &mut self,
1661 ks: [&Q; N],
1662 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1663 where
1664 Q: Hash + Equivalent<K> + ?Sized,
1665 {
1666 self.get_many_mut_inner(ks)
1667 .map(|res| res.map(|(k, v)| (&*k, v)))
1668 }
1669
1670 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1671 /// references to the corresponding keys, without validating that the values are unique.
1672 ///
1673 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1674 /// any of the keys are missing.
1675 ///
1676 /// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`).
1677 ///
1678 /// # Safety
1679 ///
1680 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1681 /// references are not used.
1682 ///
1683 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1684 ///
1685 /// # Examples
1686 ///
1687 /// ```
1688 /// use hashbrown::HashMap;
1689 ///
1690 /// let mut libraries = HashMap::new();
1691 /// libraries.insert("Bodleian Library".to_string(), 1602);
1692 /// libraries.insert("Athenæum".to_string(), 1807);
1693 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1694 /// libraries.insert("Library of Congress".to_string(), 1800);
1695 ///
1696 /// let got = libraries.get_many_key_value_mut([
1697 /// "Bodleian Library",
1698 /// "Herzogin-Anna-Amalia-Bibliothek",
1699 /// ]);
1700 /// assert_eq!(
1701 /// got,
1702 /// [
1703 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1704 /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
1705 /// ],
1706 /// );
1707 /// // Missing keys result in None
1708 /// let got = libraries.get_many_key_value_mut([
1709 /// "Bodleian Library",
1710 /// "Gewandhaus",
1711 /// ]);
1712 /// assert_eq!(
1713 /// got,
1714 /// [
1715 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1716 /// None,
1717 /// ],
1718 /// );
1719 /// ```
1720 pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>(
1721 &mut self,
1722 ks: [&Q; N],
1723 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1724 where
1725 Q: Hash + Equivalent<K> + ?Sized,
1726 {
1727 self.get_many_unchecked_mut_inner(ks)
1728 .map(|res| res.map(|(k, v)| (&*k, v)))
1729 }
1730
1731 fn get_many_mut_inner<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut (K, V)>; N]
1732 where
1733 Q: Hash + Equivalent<K> + ?Sized,
1734 {
1735 let hashes = self.build_hashes_inner(ks);
1736 self.table
1737 .get_many_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1738 }
1739
1740 unsafe fn get_many_unchecked_mut_inner<Q, const N: usize>(
1741 &mut self,
1742 ks: [&Q; N],
1743 ) -> [Option<&'_ mut (K, V)>; N]
1744 where
1745 Q: Hash + Equivalent<K> + ?Sized,
1746 {
1747 let hashes = self.build_hashes_inner(ks);
1748 self.table
1749 .get_many_unchecked_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1750 }
1751
1752 fn build_hashes_inner<Q, const N: usize>(&self, ks: [&Q; N]) -> [u64; N]
1753 where
1754 Q: Hash + Equivalent<K> + ?Sized,
1755 {
1756 let mut hashes = [0_u64; N];
1757 for i in 0..N {
1758 hashes[i] = make_hash::<Q, S>(&self.hash_builder, ks[i]);
1759 }
1760 hashes
1761 }
1762
1763 /// Inserts a key-value pair into the map.
1764 ///
1765 /// If the map did not have this key present, [`None`] is returned.
1766 ///
1767 /// If the map did have this key present, the value is updated, and the old
1768 /// value is returned. The key is not updated, though; this matters for
1769 /// types that can be `==` without being identical. See the [`std::collections`]
1770 /// [module-level documentation] for more.
1771 ///
1772 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
1773 /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html
1774 /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys
1775 ///
1776 /// # Examples
1777 ///
1778 /// ```
1779 /// use hashbrown::HashMap;
1780 ///
1781 /// let mut map = HashMap::new();
1782 /// assert_eq!(map.insert(37, "a"), None);
1783 /// assert_eq!(map.is_empty(), false);
1784 ///
1785 /// map.insert(37, "b");
1786 /// assert_eq!(map.insert(37, "c"), Some("b"));
1787 /// assert_eq!(map[&37], "c");
1788 /// ```
1789 #[cfg_attr(feature = "inline-more", inline)]
1790 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1791 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1792 match self.find_or_find_insert_slot(hash, &k) {
1793 Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
1794 Err(slot) => {
1795 unsafe {
1796 self.table.insert_in_slot(hash, slot, (k, v));
1797 }
1798 None
1799 }
1800 }
1801 }
1802
1803 #[cfg_attr(feature = "inline-more", inline)]
1804 pub(crate) fn find_or_find_insert_slot<Q>(
1805 &mut self,
1806 hash: u64,
1807 key: &Q,
1808 ) -> Result<Bucket<(K, V)>, crate::raw::InsertSlot>
1809 where
1810 Q: Equivalent<K> + ?Sized,
1811 {
1812 self.table.find_or_find_insert_slot(
1813 hash,
1814 equivalent_key(key),
1815 make_hasher(&self.hash_builder),
1816 )
1817 }
1818
1819 /// Insert a key-value pair into the map without checking
1820 /// if the key already exists in the map.
1821 ///
1822 /// This operation is faster than regular insert, because it does not perform
1823 /// lookup before insertion.
1824 ///
1825 /// This operation is useful during initial population of the map.
1826 /// For example, when constructing a map from another map, we know
1827 /// that keys are unique.
1828 ///
1829 /// Returns a reference to the key and value just inserted.
1830 ///
1831 /// # Safety
1832 ///
1833 /// This operation is safe if a key does not exist in the map.
1834 ///
1835 /// However, if a key exists in the map already, the behavior is unspecified:
1836 /// this operation may panic, loop forever, or any following operation with the map
1837 /// may panic, loop forever or return arbitrary result.
1838 ///
1839 /// That said, this operation (and following operations) are guaranteed to
1840 /// not violate memory safety.
1841 ///
1842 /// However this operation is still unsafe because the resulting `HashMap`
1843 /// may be passed to unsafe code which does expect the map to behave
1844 /// correctly, and would cause unsoundness as a result.
1845 ///
1846 /// # Examples
1847 ///
1848 /// ```
1849 /// use hashbrown::HashMap;
1850 ///
1851 /// let mut map1 = HashMap::new();
1852 /// assert_eq!(map1.insert(1, "a"), None);
1853 /// assert_eq!(map1.insert(2, "b"), None);
1854 /// assert_eq!(map1.insert(3, "c"), None);
1855 /// assert_eq!(map1.len(), 3);
1856 ///
1857 /// let mut map2 = HashMap::new();
1858 ///
1859 /// for (key, value) in map1.into_iter() {
1860 /// unsafe {
1861 /// map2.insert_unique_unchecked(key, value);
1862 /// }
1863 /// }
1864 ///
1865 /// let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") };
1866 /// assert_eq!(key, &4);
1867 /// assert_eq!(value, &mut "d");
1868 /// *value = "e";
1869 ///
1870 /// assert_eq!(map2[&1], "a");
1871 /// assert_eq!(map2[&2], "b");
1872 /// assert_eq!(map2[&3], "c");
1873 /// assert_eq!(map2[&4], "e");
1874 /// assert_eq!(map2.len(), 4);
1875 /// ```
1876 #[cfg_attr(feature = "inline-more", inline)]
1877 pub unsafe fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
1878 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1879 let bucket = self
1880 .table
1881 .insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder));
1882 let (k_ref, v_ref) = unsafe { bucket.as_mut() };
1883 (k_ref, v_ref)
1884 }
1885
1886 /// Tries to insert a key-value pair into the map, and returns
1887 /// a mutable reference to the value in the entry.
1888 ///
1889 /// # Errors
1890 ///
1891 /// If the map already had this key present, nothing is updated, and
1892 /// an error containing the occupied entry and the value is returned.
1893 ///
1894 /// # Examples
1895 ///
1896 /// Basic usage:
1897 ///
1898 /// ```
1899 /// use hashbrown::HashMap;
1900 /// use hashbrown::hash_map::OccupiedError;
1901 ///
1902 /// let mut map = HashMap::new();
1903 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1904 ///
1905 /// match map.try_insert(37, "b") {
1906 /// Err(OccupiedError { entry, value }) => {
1907 /// assert_eq!(entry.key(), &37);
1908 /// assert_eq!(entry.get(), &"a");
1909 /// assert_eq!(value, "b");
1910 /// }
1911 /// _ => panic!()
1912 /// }
1913 /// ```
1914 #[cfg_attr(feature = "inline-more", inline)]
1915 pub fn try_insert(
1916 &mut self,
1917 key: K,
1918 value: V,
1919 ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> {
1920 match self.entry(key) {
1921 Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
1922 Entry::Vacant(entry) => Ok(entry.insert(value)),
1923 }
1924 }
1925
1926 /// Removes a key from the map, returning the value at the key if the key
1927 /// was previously in the map. Keeps the allocated memory for reuse.
1928 ///
1929 /// The key may be any borrowed form of the map's key type, but
1930 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1931 /// the key type.
1932 ///
1933 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1934 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1935 ///
1936 /// # Examples
1937 ///
1938 /// ```
1939 /// use hashbrown::HashMap;
1940 ///
1941 /// let mut map = HashMap::new();
1942 /// // The map is empty
1943 /// assert!(map.is_empty() && map.capacity() == 0);
1944 ///
1945 /// map.insert(1, "a");
1946 ///
1947 /// assert_eq!(map.remove(&1), Some("a"));
1948 /// assert_eq!(map.remove(&1), None);
1949 ///
1950 /// // Now map holds none elements
1951 /// assert!(map.is_empty());
1952 /// ```
1953 #[cfg_attr(feature = "inline-more", inline)]
1954 pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
1955 where
1956 Q: Hash + Equivalent<K> + ?Sized,
1957 {
1958 // Avoid `Option::map` because it bloats LLVM IR.
1959 match self.remove_entry(k) {
1960 Some((_, v)) => Some(v),
1961 None => None,
1962 }
1963 }
1964
1965 /// Removes a key from the map, returning the stored key and value if the
1966 /// key was previously in the map. Keeps the allocated memory for reuse.
1967 ///
1968 /// The key may be any borrowed form of the map's key type, but
1969 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1970 /// the key type.
1971 ///
1972 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1973 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1974 ///
1975 /// # Examples
1976 ///
1977 /// ```
1978 /// use hashbrown::HashMap;
1979 ///
1980 /// let mut map = HashMap::new();
1981 /// // The map is empty
1982 /// assert!(map.is_empty() && map.capacity() == 0);
1983 ///
1984 /// map.insert(1, "a");
1985 ///
1986 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1987 /// assert_eq!(map.remove(&1), None);
1988 ///
1989 /// // Now map hold none elements
1990 /// assert!(map.is_empty());
1991 /// ```
1992 #[cfg_attr(feature = "inline-more", inline)]
1993 pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
1994 where
1995 Q: Hash + Equivalent<K> + ?Sized,
1996 {
1997 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1998 self.table.remove_entry(hash, equivalent_key(k))
1999 }
2000
2001 /// Returns the total amount of memory allocated internally by the hash
2002 /// set, in bytes.
2003 ///
2004 /// The returned number is informational only. It is intended to be
2005 /// primarily used for memory profiling.
2006 #[inline]
2007 pub fn allocation_size(&self) -> usize {
2008 self.table.allocation_size()
2009 }
2010}
2011
2012impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
2013where
2014 K: Eq + Hash,
2015 V: PartialEq,
2016 S: BuildHasher,
2017 A: Allocator,
2018{
2019 fn eq(&self, other: &Self) -> bool {
2020 if self.len() != other.len() {
2021 return false;
2022 }
2023
2024 self.iter()
2025 .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
2026 }
2027}
2028
2029impl<K, V, S, A> Eq for HashMap<K, V, S, A>
2030where
2031 K: Eq + Hash,
2032 V: Eq,
2033 S: BuildHasher,
2034 A: Allocator,
2035{
2036}
2037
2038impl<K, V, S, A> Debug for HashMap<K, V, S, A>
2039where
2040 K: Debug,
2041 V: Debug,
2042 A: Allocator,
2043{
2044 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2045 f.debug_map().entries(self.iter()).finish()
2046 }
2047}
2048
2049impl<K, V, S, A> Default for HashMap<K, V, S, A>
2050where
2051 S: Default,
2052 A: Default + Allocator,
2053{
2054 /// Creates an empty `HashMap<K, V, S, A>`, with the `Default` value for the hasher and allocator.
2055 ///
2056 /// # Examples
2057 ///
2058 /// ```
2059 /// use hashbrown::HashMap;
2060 /// use std::collections::hash_map::RandomState;
2061 ///
2062 /// // You can specify all types of HashMap, including hasher and allocator.
2063 /// // Created map is empty and don't allocate memory
2064 /// let map: HashMap<u32, String> = Default::default();
2065 /// assert_eq!(map.capacity(), 0);
2066 /// let map: HashMap<u32, String, RandomState> = HashMap::default();
2067 /// assert_eq!(map.capacity(), 0);
2068 /// ```
2069 #[cfg_attr(feature = "inline-more", inline)]
2070 fn default() -> Self {
2071 Self::with_hasher_in(Default::default(), Default::default())
2072 }
2073}
2074
2075impl<K, Q, V, S, A> Index<&Q> for HashMap<K, V, S, A>
2076where
2077 K: Eq + Hash,
2078 Q: Hash + Equivalent<K> + ?Sized,
2079 S: BuildHasher,
2080 A: Allocator,
2081{
2082 type Output = V;
2083
2084 /// Returns a reference to the value corresponding to the supplied key.
2085 ///
2086 /// # Panics
2087 ///
2088 /// Panics if the key is not present in the `HashMap`.
2089 ///
2090 /// # Examples
2091 ///
2092 /// ```
2093 /// use hashbrown::HashMap;
2094 ///
2095 /// let map: HashMap<_, _> = [("a", "One"), ("b", "Two")].into();
2096 ///
2097 /// assert_eq!(map[&"a"], "One");
2098 /// assert_eq!(map[&"b"], "Two");
2099 /// ```
2100 #[cfg_attr(feature = "inline-more", inline)]
2101 fn index(&self, key: &Q) -> &V {
2102 self.get(key).expect("no entry found for key")
2103 }
2104}
2105
2106// The default hasher is used to match the std implementation signature
2107#[cfg(feature = "default-hasher")]
2108impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
2109where
2110 K: Eq + Hash,
2111 A: Default + Allocator,
2112{
2113 /// # Examples
2114 ///
2115 /// ```
2116 /// use hashbrown::HashMap;
2117 ///
2118 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
2119 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
2120 /// assert_eq!(map1, map2);
2121 /// ```
2122 fn from(arr: [(K, V); N]) -> Self {
2123 arr.into_iter().collect()
2124 }
2125}
2126
2127/// An iterator over the entries of a `HashMap` in arbitrary order.
2128/// The iterator element type is `(&'a K, &'a V)`.
2129///
2130/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
2131/// documentation for more.
2132///
2133/// [`iter`]: struct.HashMap.html#method.iter
2134/// [`HashMap`]: struct.HashMap.html
2135///
2136/// # Examples
2137///
2138/// ```
2139/// use hashbrown::HashMap;
2140///
2141/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2142///
2143/// let mut iter = map.iter();
2144/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2145///
2146/// // The `Iter` iterator produces items in arbitrary order, so the
2147/// // items must be sorted to test them against a sorted array.
2148/// vec.sort_unstable();
2149/// assert_eq!(vec, [Some((&1, &"a")), Some((&2, &"b")), Some((&3, &"c"))]);
2150///
2151/// // It is fused iterator
2152/// assert_eq!(iter.next(), None);
2153/// assert_eq!(iter.next(), None);
2154/// ```
2155pub struct Iter<'a, K, V> {
2156 inner: RawIter<(K, V)>,
2157 marker: PhantomData<(&'a K, &'a V)>,
2158}
2159
2160// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2161impl<K, V> Clone for Iter<'_, K, V> {
2162 #[cfg_attr(feature = "inline-more", inline)]
2163 fn clone(&self) -> Self {
2164 Iter {
2165 inner: self.inner.clone(),
2166 marker: PhantomData,
2167 }
2168 }
2169}
2170
2171impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
2172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2173 f.debug_list().entries(self.clone()).finish()
2174 }
2175}
2176
2177/// A mutable iterator over the entries of a `HashMap` in arbitrary order.
2178/// The iterator element type is `(&'a K, &'a mut V)`.
2179///
2180/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
2181/// documentation for more.
2182///
2183/// [`iter_mut`]: struct.HashMap.html#method.iter_mut
2184/// [`HashMap`]: struct.HashMap.html
2185///
2186/// # Examples
2187///
2188/// ```
2189/// use hashbrown::HashMap;
2190///
2191/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2192///
2193/// let mut iter = map.iter_mut();
2194/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2195/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2196///
2197/// // It is fused iterator
2198/// assert_eq!(iter.next(), None);
2199/// assert_eq!(iter.next(), None);
2200///
2201/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2202/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2203/// ```
2204pub struct IterMut<'a, K, V> {
2205 inner: RawIter<(K, V)>,
2206 // To ensure invariance with respect to V
2207 marker: PhantomData<(&'a K, &'a mut V)>,
2208}
2209
2210// We override the default Send impl which has K: Sync instead of K: Send. Both
2211// are correct, but this one is more general since it allows keys which
2212// implement Send but not Sync.
2213unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {}
2214
2215impl<K, V> IterMut<'_, K, V> {
2216 /// Returns a iterator of references over the remaining items.
2217 #[cfg_attr(feature = "inline-more", inline)]
2218 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2219 Iter {
2220 inner: self.inner.clone(),
2221 marker: PhantomData,
2222 }
2223 }
2224}
2225
2226/// An owning iterator over the entries of a `HashMap` in arbitrary order.
2227/// The iterator element type is `(K, V)`.
2228///
2229/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
2230/// (provided by the [`IntoIterator`] trait). See its documentation for more.
2231/// The map cannot be used after calling that method.
2232///
2233/// [`into_iter`]: struct.HashMap.html#method.into_iter
2234/// [`HashMap`]: struct.HashMap.html
2235/// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html
2236///
2237/// # Examples
2238///
2239/// ```
2240/// use hashbrown::HashMap;
2241///
2242/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2243///
2244/// let mut iter = map.into_iter();
2245/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2246///
2247/// // The `IntoIter` iterator produces items in arbitrary order, so the
2248/// // items must be sorted to test them against a sorted array.
2249/// vec.sort_unstable();
2250/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2251///
2252/// // It is fused iterator
2253/// assert_eq!(iter.next(), None);
2254/// assert_eq!(iter.next(), None);
2255/// ```
2256pub struct IntoIter<K, V, A: Allocator = Global> {
2257 inner: RawIntoIter<(K, V), A>,
2258}
2259
2260impl<K, V, A: Allocator> IntoIter<K, V, A> {
2261 /// Returns a iterator of references over the remaining items.
2262 #[cfg_attr(feature = "inline-more", inline)]
2263 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2264 Iter {
2265 inner: self.inner.iter(),
2266 marker: PhantomData,
2267 }
2268 }
2269}
2270
2271/// An owning iterator over the keys of a `HashMap` in arbitrary order.
2272/// The iterator element type is `K`.
2273///
2274/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
2275/// See its documentation for more.
2276/// The map cannot be used after calling that method.
2277///
2278/// [`into_keys`]: struct.HashMap.html#method.into_keys
2279/// [`HashMap`]: struct.HashMap.html
2280///
2281/// # Examples
2282///
2283/// ```
2284/// use hashbrown::HashMap;
2285///
2286/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2287///
2288/// let mut keys = map.into_keys();
2289/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2290///
2291/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
2292/// // keys must be sorted to test them against a sorted array.
2293/// vec.sort_unstable();
2294/// assert_eq!(vec, [Some(1), Some(2), Some(3)]);
2295///
2296/// // It is fused iterator
2297/// assert_eq!(keys.next(), None);
2298/// assert_eq!(keys.next(), None);
2299/// ```
2300pub struct IntoKeys<K, V, A: Allocator = Global> {
2301 inner: IntoIter<K, V, A>,
2302}
2303
2304impl<K, V, A: Allocator> Default for IntoKeys<K, V, A> {
2305 #[cfg_attr(feature = "inline-more", inline)]
2306 fn default() -> Self {
2307 Self {
2308 inner: Default::default(),
2309 }
2310 }
2311}
2312impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
2313 type Item = K;
2314
2315 #[inline]
2316 fn next(&mut self) -> Option<K> {
2317 self.inner.next().map(|(k, _)| k)
2318 }
2319 #[inline]
2320 fn size_hint(&self) -> (usize, Option<usize>) {
2321 self.inner.size_hint()
2322 }
2323 #[inline]
2324 fn fold<B, F>(self, init: B, mut f: F) -> B
2325 where
2326 Self: Sized,
2327 F: FnMut(B, Self::Item) -> B,
2328 {
2329 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2330 }
2331}
2332
2333impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
2334 #[inline]
2335 fn len(&self) -> usize {
2336 self.inner.len()
2337 }
2338}
2339
2340impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
2341
2342impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
2343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2344 f.debug_list()
2345 .entries(self.inner.iter().map(|(k, _)| k))
2346 .finish()
2347 }
2348}
2349
2350/// An owning iterator over the values of a `HashMap` in arbitrary order.
2351/// The iterator element type is `V`.
2352///
2353/// This `struct` is created by the [`into_values`] method on [`HashMap`].
2354/// See its documentation for more. The map cannot be used after calling that method.
2355///
2356/// [`into_values`]: struct.HashMap.html#method.into_values
2357/// [`HashMap`]: struct.HashMap.html
2358///
2359/// # Examples
2360///
2361/// ```
2362/// use hashbrown::HashMap;
2363///
2364/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2365///
2366/// let mut values = map.into_values();
2367/// let mut vec = vec![values.next(), values.next(), values.next()];
2368///
2369/// // The `IntoValues` iterator produces values in arbitrary order, so
2370/// // the values must be sorted to test them against a sorted array.
2371/// vec.sort_unstable();
2372/// assert_eq!(vec, [Some("a"), Some("b"), Some("c")]);
2373///
2374/// // It is fused iterator
2375/// assert_eq!(values.next(), None);
2376/// assert_eq!(values.next(), None);
2377/// ```
2378pub struct IntoValues<K, V, A: Allocator = Global> {
2379 inner: IntoIter<K, V, A>,
2380}
2381
2382impl<K, V, A: Allocator> Default for IntoValues<K, V, A> {
2383 #[cfg_attr(feature = "inline-more", inline)]
2384 fn default() -> Self {
2385 Self {
2386 inner: Default::default(),
2387 }
2388 }
2389}
2390impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
2391 type Item = V;
2392
2393 #[inline]
2394 fn next(&mut self) -> Option<V> {
2395 self.inner.next().map(|(_, v)| v)
2396 }
2397 #[inline]
2398 fn size_hint(&self) -> (usize, Option<usize>) {
2399 self.inner.size_hint()
2400 }
2401 #[inline]
2402 fn fold<B, F>(self, init: B, mut f: F) -> B
2403 where
2404 Self: Sized,
2405 F: FnMut(B, Self::Item) -> B,
2406 {
2407 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2408 }
2409}
2410
2411impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2412 #[inline]
2413 fn len(&self) -> usize {
2414 self.inner.len()
2415 }
2416}
2417
2418impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2419
2420impl<K, V: Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
2421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2422 f.debug_list()
2423 .entries(self.inner.iter().map(|(_, v)| v))
2424 .finish()
2425 }
2426}
2427
2428/// An iterator over the keys of a `HashMap` in arbitrary order.
2429/// The iterator element type is `&'a K`.
2430///
2431/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
2432/// documentation for more.
2433///
2434/// [`keys`]: struct.HashMap.html#method.keys
2435/// [`HashMap`]: struct.HashMap.html
2436///
2437/// # Examples
2438///
2439/// ```
2440/// use hashbrown::HashMap;
2441///
2442/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2443///
2444/// let mut keys = map.keys();
2445/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2446///
2447/// // The `Keys` iterator produces keys in arbitrary order, so the
2448/// // keys must be sorted to test them against a sorted array.
2449/// vec.sort_unstable();
2450/// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]);
2451///
2452/// // It is fused iterator
2453/// assert_eq!(keys.next(), None);
2454/// assert_eq!(keys.next(), None);
2455/// ```
2456pub struct Keys<'a, K, V> {
2457 inner: Iter<'a, K, V>,
2458}
2459
2460// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2461impl<K, V> Clone for Keys<'_, K, V> {
2462 #[cfg_attr(feature = "inline-more", inline)]
2463 fn clone(&self) -> Self {
2464 Keys {
2465 inner: self.inner.clone(),
2466 }
2467 }
2468}
2469
2470impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
2471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2472 f.debug_list().entries(self.clone()).finish()
2473 }
2474}
2475
2476/// An iterator over the values of a `HashMap` in arbitrary order.
2477/// The iterator element type is `&'a V`.
2478///
2479/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
2480/// documentation for more.
2481///
2482/// [`values`]: struct.HashMap.html#method.values
2483/// [`HashMap`]: struct.HashMap.html
2484///
2485/// # Examples
2486///
2487/// ```
2488/// use hashbrown::HashMap;
2489///
2490/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2491///
2492/// let mut values = map.values();
2493/// let mut vec = vec![values.next(), values.next(), values.next()];
2494///
2495/// // The `Values` iterator produces values in arbitrary order, so the
2496/// // values must be sorted to test them against a sorted array.
2497/// vec.sort_unstable();
2498/// assert_eq!(vec, [Some(&"a"), Some(&"b"), Some(&"c")]);
2499///
2500/// // It is fused iterator
2501/// assert_eq!(values.next(), None);
2502/// assert_eq!(values.next(), None);
2503/// ```
2504pub struct Values<'a, K, V> {
2505 inner: Iter<'a, K, V>,
2506}
2507
2508// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2509impl<K, V> Clone for Values<'_, K, V> {
2510 #[cfg_attr(feature = "inline-more", inline)]
2511 fn clone(&self) -> Self {
2512 Values {
2513 inner: self.inner.clone(),
2514 }
2515 }
2516}
2517
2518impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
2519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2520 f.debug_list().entries(self.clone()).finish()
2521 }
2522}
2523
2524/// A draining iterator over the entries of a `HashMap` in arbitrary
2525/// order. The iterator element type is `(K, V)`.
2526///
2527/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
2528/// documentation for more.
2529///
2530/// [`drain`]: struct.HashMap.html#method.drain
2531/// [`HashMap`]: struct.HashMap.html
2532///
2533/// # Examples
2534///
2535/// ```
2536/// use hashbrown::HashMap;
2537///
2538/// let mut map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2539///
2540/// let mut drain_iter = map.drain();
2541/// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()];
2542///
2543/// // The `Drain` iterator produces items in arbitrary order, so the
2544/// // items must be sorted to test them against a sorted array.
2545/// vec.sort_unstable();
2546/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2547///
2548/// // It is fused iterator
2549/// assert_eq!(drain_iter.next(), None);
2550/// assert_eq!(drain_iter.next(), None);
2551/// ```
2552pub struct Drain<'a, K, V, A: Allocator = Global> {
2553 inner: RawDrain<'a, (K, V), A>,
2554}
2555
2556impl<K, V, A: Allocator> Drain<'_, K, V, A> {
2557 /// Returns a iterator of references over the remaining items.
2558 #[cfg_attr(feature = "inline-more", inline)]
2559 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2560 Iter {
2561 inner: self.inner.iter(),
2562 marker: PhantomData,
2563 }
2564 }
2565}
2566
2567/// A draining iterator over entries of a `HashMap` which don't satisfy the predicate
2568/// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`.
2569///
2570/// This `struct` is created by the [`extract_if`] method on [`HashMap`]. See its
2571/// documentation for more.
2572///
2573/// [`extract_if`]: struct.HashMap.html#method.extract_if
2574/// [`HashMap`]: struct.HashMap.html
2575///
2576/// # Examples
2577///
2578/// ```
2579/// use hashbrown::HashMap;
2580///
2581/// let mut map: HashMap<i32, &str> = [(1, "a"), (2, "b"), (3, "c")].into();
2582///
2583/// let mut extract_if = map.extract_if(|k, _v| k % 2 != 0);
2584/// let mut vec = vec![extract_if.next(), extract_if.next()];
2585///
2586/// // The `ExtractIf` iterator produces items in arbitrary order, so the
2587/// // items must be sorted to test them against a sorted array.
2588/// vec.sort_unstable();
2589/// assert_eq!(vec, [Some((1, "a")),Some((3, "c"))]);
2590///
2591/// // It is fused iterator
2592/// assert_eq!(extract_if.next(), None);
2593/// assert_eq!(extract_if.next(), None);
2594/// drop(extract_if);
2595///
2596/// assert_eq!(map.len(), 1);
2597/// ```
2598#[must_use = "Iterators are lazy unless consumed"]
2599pub struct ExtractIf<'a, K, V, F, A: Allocator = Global>
2600where
2601 F: FnMut(&K, &mut V) -> bool,
2602{
2603 f: F,
2604 inner: RawExtractIf<'a, (K, V), A>,
2605}
2606
2607impl<K, V, F, A> Iterator for ExtractIf<'_, K, V, F, A>
2608where
2609 F: FnMut(&K, &mut V) -> bool,
2610 A: Allocator,
2611{
2612 type Item = (K, V);
2613
2614 #[cfg_attr(feature = "inline-more", inline)]
2615 fn next(&mut self) -> Option<Self::Item> {
2616 self.inner.next(|&mut (ref k, ref mut v)| (self.f)(k, v))
2617 }
2618
2619 #[inline]
2620 fn size_hint(&self) -> (usize, Option<usize>) {
2621 (0, self.inner.iter.size_hint().1)
2622 }
2623}
2624
2625impl<K, V, F> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2626
2627/// A mutable iterator over the values of a `HashMap` in arbitrary order.
2628/// The iterator element type is `&'a mut V`.
2629///
2630/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
2631/// documentation for more.
2632///
2633/// [`values_mut`]: struct.HashMap.html#method.values_mut
2634/// [`HashMap`]: struct.HashMap.html
2635///
2636/// # Examples
2637///
2638/// ```
2639/// use hashbrown::HashMap;
2640///
2641/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2642///
2643/// let mut values = map.values_mut();
2644/// values.next().map(|v| v.push_str(" Mississippi"));
2645/// values.next().map(|v| v.push_str(" Mississippi"));
2646///
2647/// // It is fused iterator
2648/// assert_eq!(values.next(), None);
2649/// assert_eq!(values.next(), None);
2650///
2651/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2652/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2653/// ```
2654pub struct ValuesMut<'a, K, V> {
2655 inner: IterMut<'a, K, V>,
2656}
2657
2658/// A view into a single entry in a map, which may either be vacant or occupied.
2659///
2660/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2661///
2662/// [`HashMap`]: struct.HashMap.html
2663/// [`entry`]: struct.HashMap.html#method.entry
2664///
2665/// # Examples
2666///
2667/// ```
2668/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2669///
2670/// let mut map = HashMap::new();
2671/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2672/// assert_eq!(map.len(), 3);
2673///
2674/// // Existing key (insert)
2675/// let entry: Entry<_, _, _> = map.entry("a");
2676/// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1);
2677/// assert_eq!(map.len(), 3);
2678/// // Nonexistent key (insert)
2679/// map.entry("d").insert(4);
2680///
2681/// // Existing key (or_insert)
2682/// let v = map.entry("b").or_insert(2);
2683/// assert_eq!(std::mem::replace(v, 2), 20);
2684/// // Nonexistent key (or_insert)
2685/// map.entry("e").or_insert(5);
2686///
2687/// // Existing key (or_insert_with)
2688/// let v = map.entry("c").or_insert_with(|| 3);
2689/// assert_eq!(std::mem::replace(v, 3), 30);
2690/// // Nonexistent key (or_insert_with)
2691/// map.entry("f").or_insert_with(|| 6);
2692///
2693/// println!("Our HashMap: {:?}", map);
2694///
2695/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
2696/// // The `Iter` iterator produces items in arbitrary order, so the
2697/// // items must be sorted to test them against a sorted array.
2698/// vec.sort_unstable();
2699/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]);
2700/// ```
2701pub enum Entry<'a, K, V, S, A = Global>
2702where
2703 A: Allocator,
2704{
2705 /// An occupied entry.
2706 ///
2707 /// # Examples
2708 ///
2709 /// ```
2710 /// use hashbrown::hash_map::{Entry, HashMap};
2711 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into();
2712 ///
2713 /// match map.entry("a") {
2714 /// Entry::Vacant(_) => unreachable!(),
2715 /// Entry::Occupied(_) => { }
2716 /// }
2717 /// ```
2718 Occupied(OccupiedEntry<'a, K, V, S, A>),
2719
2720 /// A vacant entry.
2721 ///
2722 /// # Examples
2723 ///
2724 /// ```
2725 /// use hashbrown::hash_map::{Entry, HashMap};
2726 /// let mut map: HashMap<&str, i32> = HashMap::new();
2727 ///
2728 /// match map.entry("a") {
2729 /// Entry::Occupied(_) => unreachable!(),
2730 /// Entry::Vacant(_) => { }
2731 /// }
2732 /// ```
2733 Vacant(VacantEntry<'a, K, V, S, A>),
2734}
2735
2736impl<K: Debug, V: Debug, S, A: Allocator> Debug for Entry<'_, K, V, S, A> {
2737 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2738 match *self {
2739 Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2740 Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2741 }
2742 }
2743}
2744
2745/// A view into an occupied entry in a [`HashMap`].
2746/// It is part of the [`Entry`] and [`EntryRef`] enums.
2747///
2748/// # Examples
2749///
2750/// ```
2751/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2752///
2753/// let mut map = HashMap::new();
2754/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2755///
2756/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").insert(100);
2757/// assert_eq!(map.len(), 3);
2758///
2759/// // Existing key (insert and update)
2760/// match map.entry("a") {
2761/// Entry::Vacant(_) => unreachable!(),
2762/// Entry::Occupied(mut view) => {
2763/// assert_eq!(view.get(), &100);
2764/// let v = view.get_mut();
2765/// *v *= 10;
2766/// assert_eq!(view.insert(1111), 1000);
2767/// }
2768/// }
2769///
2770/// assert_eq!(map[&"a"], 1111);
2771/// assert_eq!(map.len(), 3);
2772///
2773/// // Existing key (take)
2774/// match map.entry("c") {
2775/// Entry::Vacant(_) => unreachable!(),
2776/// Entry::Occupied(view) => {
2777/// assert_eq!(view.remove_entry(), ("c", 30));
2778/// }
2779/// }
2780/// assert_eq!(map.get(&"c"), None);
2781/// assert_eq!(map.len(), 2);
2782/// ```
2783pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2784 hash: u64,
2785 elem: Bucket<(K, V)>,
2786 table: &'a mut HashMap<K, V, S, A>,
2787}
2788
2789unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
2790where
2791 K: Send,
2792 V: Send,
2793 S: Send,
2794 A: Send + Allocator,
2795{
2796}
2797unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
2798where
2799 K: Sync,
2800 V: Sync,
2801 S: Sync,
2802 A: Sync + Allocator,
2803{
2804}
2805
2806impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedEntry<'_, K, V, S, A> {
2807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2808 f.debug_struct("OccupiedEntry")
2809 .field("key", self.key())
2810 .field("value", self.get())
2811 .finish()
2812 }
2813}
2814
2815/// A view into a vacant entry in a `HashMap`.
2816/// It is part of the [`Entry`] enum.
2817///
2818/// [`Entry`]: enum.Entry.html
2819///
2820/// # Examples
2821///
2822/// ```
2823/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry};
2824///
2825/// let mut map = HashMap::<&str, i32>::new();
2826///
2827/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
2828/// Entry::Vacant(view) => view,
2829/// Entry::Occupied(_) => unreachable!(),
2830/// };
2831/// entry_v.insert(10);
2832/// assert!(map[&"a"] == 10 && map.len() == 1);
2833///
2834/// // Nonexistent key (insert and update)
2835/// match map.entry("b") {
2836/// Entry::Occupied(_) => unreachable!(),
2837/// Entry::Vacant(view) => {
2838/// let value = view.insert(2);
2839/// assert_eq!(*value, 2);
2840/// *value = 20;
2841/// }
2842/// }
2843/// assert!(map[&"b"] == 20 && map.len() == 2);
2844/// ```
2845pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2846 hash: u64,
2847 key: K,
2848 table: &'a mut HashMap<K, V, S, A>,
2849}
2850
2851impl<K: Debug, V, S, A: Allocator> Debug for VacantEntry<'_, K, V, S, A> {
2852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2853 f.debug_tuple("VacantEntry").field(self.key()).finish()
2854 }
2855}
2856
2857/// A view into a single entry in a map, which may either be vacant or occupied,
2858/// with any borrowed form of the map's key type.
2859///
2860///
2861/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
2862///
2863/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
2864/// for the key type. It also require that key may be constructed from the borrowed
2865/// form through the [`From`] trait.
2866///
2867/// [`HashMap`]: struct.HashMap.html
2868/// [`entry_ref`]: struct.HashMap.html#method.entry_ref
2869/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
2870/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
2871/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
2872///
2873/// # Examples
2874///
2875/// ```
2876/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntry};
2877///
2878/// let mut map = HashMap::new();
2879/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
2880/// assert_eq!(map.len(), 3);
2881///
2882/// // Existing key (insert)
2883/// let key = String::from("a");
2884/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
2885/// let _raw_o: OccupiedEntry<_, _, _, _> = entry.insert(1);
2886/// assert_eq!(map.len(), 3);
2887/// // Nonexistent key (insert)
2888/// map.entry_ref("d").insert(4);
2889///
2890/// // Existing key (or_insert)
2891/// let v = map.entry_ref("b").or_insert(2);
2892/// assert_eq!(std::mem::replace(v, 2), 20);
2893/// // Nonexistent key (or_insert)
2894/// map.entry_ref("e").or_insert(5);
2895///
2896/// // Existing key (or_insert_with)
2897/// let v = map.entry_ref("c").or_insert_with(|| 3);
2898/// assert_eq!(std::mem::replace(v, 3), 30);
2899/// // Nonexistent key (or_insert_with)
2900/// map.entry_ref("f").or_insert_with(|| 6);
2901///
2902/// println!("Our HashMap: {:?}", map);
2903///
2904/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
2905/// assert_eq!(map[key], value)
2906/// }
2907/// assert_eq!(map.len(), 6);
2908/// ```
2909pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
2910where
2911 A: Allocator,
2912{
2913 /// An occupied entry.
2914 ///
2915 /// # Examples
2916 ///
2917 /// ```
2918 /// use hashbrown::hash_map::{EntryRef, HashMap};
2919 /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].into();
2920 ///
2921 /// match map.entry_ref("a") {
2922 /// EntryRef::Vacant(_) => unreachable!(),
2923 /// EntryRef::Occupied(_) => { }
2924 /// }
2925 /// ```
2926 Occupied(OccupiedEntry<'a, K, V, S, A>),
2927
2928 /// A vacant entry.
2929 ///
2930 /// # Examples
2931 ///
2932 /// ```
2933 /// use hashbrown::hash_map::{EntryRef, HashMap};
2934 /// let mut map: HashMap<String, i32> = HashMap::new();
2935 ///
2936 /// match map.entry_ref("a") {
2937 /// EntryRef::Occupied(_) => unreachable!(),
2938 /// EntryRef::Vacant(_) => { }
2939 /// }
2940 /// ```
2941 Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
2942}
2943
2944impl<K, Q, V, S, A> Debug for EntryRef<'_, '_, K, Q, V, S, A>
2945where
2946 K: Debug + Borrow<Q>,
2947 Q: Debug + ?Sized,
2948 V: Debug,
2949 A: Allocator,
2950{
2951 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2952 match *self {
2953 EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(),
2954 EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(),
2955 }
2956 }
2957}
2958
2959/// A view into a vacant entry in a `HashMap`.
2960/// It is part of the [`EntryRef`] enum.
2961///
2962/// [`EntryRef`]: enum.EntryRef.html
2963///
2964/// # Examples
2965///
2966/// ```
2967/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef};
2968///
2969/// let mut map = HashMap::<String, i32>::new();
2970///
2971/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
2972/// EntryRef::Vacant(view) => view,
2973/// EntryRef::Occupied(_) => unreachable!(),
2974/// };
2975/// entry_v.insert(10);
2976/// assert!(map["a"] == 10 && map.len() == 1);
2977///
2978/// // Nonexistent key (insert and update)
2979/// match map.entry_ref("b") {
2980/// EntryRef::Occupied(_) => unreachable!(),
2981/// EntryRef::Vacant(view) => {
2982/// let value = view.insert(2);
2983/// assert_eq!(*value, 2);
2984/// *value = 20;
2985/// }
2986/// }
2987/// assert!(map["b"] == 20 && map.len() == 2);
2988/// ```
2989pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> {
2990 hash: u64,
2991 key: &'b Q,
2992 table: &'a mut HashMap<K, V, S, A>,
2993}
2994
2995impl<K, Q, V, S, A> Debug for VacantEntryRef<'_, '_, K, Q, V, S, A>
2996where
2997 K: Borrow<Q>,
2998 Q: Debug + ?Sized,
2999 A: Allocator,
3000{
3001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3002 f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
3003 }
3004}
3005
3006/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
3007///
3008/// Contains the occupied entry, and the value that was not inserted.
3009///
3010/// # Examples
3011///
3012/// ```
3013/// use hashbrown::hash_map::{HashMap, OccupiedError};
3014///
3015/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into();
3016///
3017/// // try_insert method returns mutable reference to the value if keys are vacant,
3018/// // but if the map did have key present, nothing is updated, and the provided
3019/// // value is returned inside `Err(_)` variant
3020/// match map.try_insert("a", 100) {
3021/// Err(OccupiedError { mut entry, value }) => {
3022/// assert_eq!(entry.key(), &"a");
3023/// assert_eq!(value, 100);
3024/// assert_eq!(entry.insert(100), 10)
3025/// }
3026/// _ => unreachable!(),
3027/// }
3028/// assert_eq!(map[&"a"], 100);
3029/// ```
3030pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> {
3031 /// The entry in the map that was already occupied.
3032 pub entry: OccupiedEntry<'a, K, V, S, A>,
3033 /// The value which was not inserted, because the entry was already occupied.
3034 pub value: V,
3035}
3036
3037impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedError<'_, K, V, S, A> {
3038 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3039 f.debug_struct("OccupiedError")
3040 .field("key", self.entry.key())
3041 .field("old_value", self.entry.get())
3042 .field("new_value", &self.value)
3043 .finish()
3044 }
3045}
3046
3047impl<K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'_, K, V, S, A> {
3048 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3049 write!(
3050 f,
3051 "failed to insert {:?}, key {:?} already exists with value {:?}",
3052 self.value,
3053 self.entry.key(),
3054 self.entry.get(),
3055 )
3056 }
3057}
3058
3059impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
3060 type Item = (&'a K, &'a V);
3061 type IntoIter = Iter<'a, K, V>;
3062
3063 /// Creates an iterator over the entries of a `HashMap` in arbitrary order.
3064 /// The iterator element type is `(&'a K, &'a V)`.
3065 ///
3066 /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
3067 ///
3068 /// [`iter`]: struct.HashMap.html#method.iter
3069 /// [`HashMap`]: struct.HashMap.html
3070 ///
3071 /// # Examples
3072 ///
3073 /// ```
3074 /// use hashbrown::HashMap;
3075 /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
3076 /// let mut map_two = HashMap::new();
3077 ///
3078 /// for (key, value) in &map_one {
3079 /// println!("Key: {}, Value: {}", key, value);
3080 /// map_two.insert(*key, *value);
3081 /// }
3082 ///
3083 /// assert_eq!(map_one, map_two);
3084 /// ```
3085 #[cfg_attr(feature = "inline-more", inline)]
3086 fn into_iter(self) -> Iter<'a, K, V> {
3087 self.iter()
3088 }
3089}
3090
3091impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
3092 type Item = (&'a K, &'a mut V);
3093 type IntoIter = IterMut<'a, K, V>;
3094
3095 /// Creates an iterator over the entries of a `HashMap` in arbitrary order
3096 /// with mutable references to the values. The iterator element type is
3097 /// `(&'a K, &'a mut V)`.
3098 ///
3099 /// Return the same `IterMut` struct as by the [`iter_mut`] method on
3100 /// [`HashMap`].
3101 ///
3102 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
3103 /// [`HashMap`]: struct.HashMap.html
3104 ///
3105 /// # Examples
3106 ///
3107 /// ```
3108 /// use hashbrown::HashMap;
3109 /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3110 ///
3111 /// for (key, value) in &mut map {
3112 /// println!("Key: {}, Value: {}", key, value);
3113 /// *value *= 2;
3114 /// }
3115 ///
3116 /// let mut vec = map.iter().collect::<Vec<_>>();
3117 /// // The `Iter` iterator produces items in arbitrary order, so the
3118 /// // items must be sorted to test them against a sorted array.
3119 /// vec.sort_unstable();
3120 /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
3121 /// ```
3122 #[cfg_attr(feature = "inline-more", inline)]
3123 fn into_iter(self) -> IterMut<'a, K, V> {
3124 self.iter_mut()
3125 }
3126}
3127
3128impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
3129 type Item = (K, V);
3130 type IntoIter = IntoIter<K, V, A>;
3131
3132 /// Creates a consuming iterator, that is, one that moves each key-value
3133 /// pair out of the map in arbitrary order. The map cannot be used after
3134 /// calling this.
3135 ///
3136 /// # Examples
3137 ///
3138 /// ```
3139 /// use hashbrown::HashMap;
3140 ///
3141 /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3142 ///
3143 /// // Not possible with .iter()
3144 /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
3145 /// // The `IntoIter` iterator produces items in arbitrary order, so
3146 /// // the items must be sorted to test them against a sorted array.
3147 /// vec.sort_unstable();
3148 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
3149 /// ```
3150 #[cfg_attr(feature = "inline-more", inline)]
3151 fn into_iter(self) -> IntoIter<K, V, A> {
3152 IntoIter {
3153 inner: self.table.into_iter(),
3154 }
3155 }
3156}
3157
3158impl<K, V> Default for Iter<'_, K, V> {
3159 #[cfg_attr(feature = "inline-more", inline)]
3160 fn default() -> Self {
3161 Self {
3162 inner: Default::default(),
3163 marker: PhantomData,
3164 }
3165 }
3166}
3167impl<'a, K, V> Iterator for Iter<'a, K, V> {
3168 type Item = (&'a K, &'a V);
3169
3170 #[cfg_attr(feature = "inline-more", inline)]
3171 fn next(&mut self) -> Option<(&'a K, &'a V)> {
3172 // Avoid `Option::map` because it bloats LLVM IR.
3173 match self.inner.next() {
3174 Some(x) => unsafe {
3175 let r = x.as_ref();
3176 Some((&r.0, &r.1))
3177 },
3178 None => None,
3179 }
3180 }
3181 #[cfg_attr(feature = "inline-more", inline)]
3182 fn size_hint(&self) -> (usize, Option<usize>) {
3183 self.inner.size_hint()
3184 }
3185 #[cfg_attr(feature = "inline-more", inline)]
3186 fn fold<B, F>(self, init: B, mut f: F) -> B
3187 where
3188 Self: Sized,
3189 F: FnMut(B, Self::Item) -> B,
3190 {
3191 self.inner.fold(init, |acc, x| unsafe {
3192 let (k, v) = x.as_ref();
3193 f(acc, (k, v))
3194 })
3195 }
3196}
3197impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
3198 #[cfg_attr(feature = "inline-more", inline)]
3199 fn len(&self) -> usize {
3200 self.inner.len()
3201 }
3202}
3203
3204impl<K, V> FusedIterator for Iter<'_, K, V> {}
3205
3206impl<K, V> Default for IterMut<'_, K, V> {
3207 #[cfg_attr(feature = "inline-more", inline)]
3208 fn default() -> Self {
3209 Self {
3210 inner: Default::default(),
3211 marker: PhantomData,
3212 }
3213 }
3214}
3215impl<'a, K, V> Iterator for IterMut<'a, K, V> {
3216 type Item = (&'a K, &'a mut V);
3217
3218 #[cfg_attr(feature = "inline-more", inline)]
3219 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
3220 // Avoid `Option::map` because it bloats LLVM IR.
3221 match self.inner.next() {
3222 Some(x) => unsafe {
3223 let r = x.as_mut();
3224 Some((&r.0, &mut r.1))
3225 },
3226 None => None,
3227 }
3228 }
3229 #[cfg_attr(feature = "inline-more", inline)]
3230 fn size_hint(&self) -> (usize, Option<usize>) {
3231 self.inner.size_hint()
3232 }
3233 #[cfg_attr(feature = "inline-more", inline)]
3234 fn fold<B, F>(self, init: B, mut f: F) -> B
3235 where
3236 Self: Sized,
3237 F: FnMut(B, Self::Item) -> B,
3238 {
3239 self.inner.fold(init, |acc, x| unsafe {
3240 let (k, v) = x.as_mut();
3241 f(acc, (k, v))
3242 })
3243 }
3244}
3245impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
3246 #[cfg_attr(feature = "inline-more", inline)]
3247 fn len(&self) -> usize {
3248 self.inner.len()
3249 }
3250}
3251impl<K, V> FusedIterator for IterMut<'_, K, V> {}
3252
3253impl<K, V> fmt::Debug for IterMut<'_, K, V>
3254where
3255 K: fmt::Debug,
3256 V: fmt::Debug,
3257{
3258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3259 f.debug_list().entries(self.iter()).finish()
3260 }
3261}
3262
3263impl<K, V, A: Allocator> Default for IntoIter<K, V, A> {
3264 #[cfg_attr(feature = "inline-more", inline)]
3265 fn default() -> Self {
3266 Self {
3267 inner: Default::default(),
3268 }
3269 }
3270}
3271impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
3272 type Item = (K, V);
3273
3274 #[cfg_attr(feature = "inline-more", inline)]
3275 fn next(&mut self) -> Option<(K, V)> {
3276 self.inner.next()
3277 }
3278 #[cfg_attr(feature = "inline-more", inline)]
3279 fn size_hint(&self) -> (usize, Option<usize>) {
3280 self.inner.size_hint()
3281 }
3282 #[cfg_attr(feature = "inline-more", inline)]
3283 fn fold<B, F>(self, init: B, f: F) -> B
3284 where
3285 Self: Sized,
3286 F: FnMut(B, Self::Item) -> B,
3287 {
3288 self.inner.fold(init, f)
3289 }
3290}
3291impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
3292 #[cfg_attr(feature = "inline-more", inline)]
3293 fn len(&self) -> usize {
3294 self.inner.len()
3295 }
3296}
3297impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
3298
3299impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
3300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3301 f.debug_list().entries(self.iter()).finish()
3302 }
3303}
3304
3305impl<K, V> Default for Keys<'_, K, V> {
3306 #[cfg_attr(feature = "inline-more", inline)]
3307 fn default() -> Self {
3308 Self {
3309 inner: Default::default(),
3310 }
3311 }
3312}
3313impl<'a, K, V> Iterator for Keys<'a, K, V> {
3314 type Item = &'a K;
3315
3316 #[cfg_attr(feature = "inline-more", inline)]
3317 fn next(&mut self) -> Option<&'a K> {
3318 // Avoid `Option::map` because it bloats LLVM IR.
3319 match self.inner.next() {
3320 Some((k, _)) => Some(k),
3321 None => None,
3322 }
3323 }
3324 #[cfg_attr(feature = "inline-more", inline)]
3325 fn size_hint(&self) -> (usize, Option<usize>) {
3326 self.inner.size_hint()
3327 }
3328 #[cfg_attr(feature = "inline-more", inline)]
3329 fn fold<B, F>(self, init: B, mut f: F) -> B
3330 where
3331 Self: Sized,
3332 F: FnMut(B, Self::Item) -> B,
3333 {
3334 self.inner.fold(init, |acc, (k, _)| f(acc, k))
3335 }
3336}
3337impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
3338 #[cfg_attr(feature = "inline-more", inline)]
3339 fn len(&self) -> usize {
3340 self.inner.len()
3341 }
3342}
3343impl<K, V> FusedIterator for Keys<'_, K, V> {}
3344
3345impl<K, V> Default for Values<'_, K, V> {
3346 #[cfg_attr(feature = "inline-more", inline)]
3347 fn default() -> Self {
3348 Self {
3349 inner: Default::default(),
3350 }
3351 }
3352}
3353impl<'a, K, V> Iterator for Values<'a, K, V> {
3354 type Item = &'a V;
3355
3356 #[cfg_attr(feature = "inline-more", inline)]
3357 fn next(&mut self) -> Option<&'a V> {
3358 // Avoid `Option::map` because it bloats LLVM IR.
3359 match self.inner.next() {
3360 Some((_, v)) => Some(v),
3361 None => None,
3362 }
3363 }
3364 #[cfg_attr(feature = "inline-more", inline)]
3365 fn size_hint(&self) -> (usize, Option<usize>) {
3366 self.inner.size_hint()
3367 }
3368 #[cfg_attr(feature = "inline-more", inline)]
3369 fn fold<B, F>(self, init: B, mut f: F) -> B
3370 where
3371 Self: Sized,
3372 F: FnMut(B, Self::Item) -> B,
3373 {
3374 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3375 }
3376}
3377impl<K, V> ExactSizeIterator for Values<'_, K, V> {
3378 #[cfg_attr(feature = "inline-more", inline)]
3379 fn len(&self) -> usize {
3380 self.inner.len()
3381 }
3382}
3383impl<K, V> FusedIterator for Values<'_, K, V> {}
3384
3385impl<K, V> Default for ValuesMut<'_, K, V> {
3386 #[cfg_attr(feature = "inline-more", inline)]
3387 fn default() -> Self {
3388 Self {
3389 inner: Default::default(),
3390 }
3391 }
3392}
3393impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
3394 type Item = &'a mut V;
3395
3396 #[cfg_attr(feature = "inline-more", inline)]
3397 fn next(&mut self) -> Option<&'a mut V> {
3398 // Avoid `Option::map` because it bloats LLVM IR.
3399 match self.inner.next() {
3400 Some((_, v)) => Some(v),
3401 None => None,
3402 }
3403 }
3404 #[cfg_attr(feature = "inline-more", inline)]
3405 fn size_hint(&self) -> (usize, Option<usize>) {
3406 self.inner.size_hint()
3407 }
3408 #[cfg_attr(feature = "inline-more", inline)]
3409 fn fold<B, F>(self, init: B, mut f: F) -> B
3410 where
3411 Self: Sized,
3412 F: FnMut(B, Self::Item) -> B,
3413 {
3414 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3415 }
3416}
3417impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
3418 #[cfg_attr(feature = "inline-more", inline)]
3419 fn len(&self) -> usize {
3420 self.inner.len()
3421 }
3422}
3423impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
3424
3425impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
3426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3427 f.debug_list()
3428 .entries(self.inner.iter().map(|(_, val)| val))
3429 .finish()
3430 }
3431}
3432
3433impl<K, V, A: Allocator> Iterator for Drain<'_, K, V, A> {
3434 type Item = (K, V);
3435
3436 #[cfg_attr(feature = "inline-more", inline)]
3437 fn next(&mut self) -> Option<(K, V)> {
3438 self.inner.next()
3439 }
3440 #[cfg_attr(feature = "inline-more", inline)]
3441 fn size_hint(&self) -> (usize, Option<usize>) {
3442 self.inner.size_hint()
3443 }
3444 #[cfg_attr(feature = "inline-more", inline)]
3445 fn fold<B, F>(self, init: B, f: F) -> B
3446 where
3447 Self: Sized,
3448 F: FnMut(B, Self::Item) -> B,
3449 {
3450 self.inner.fold(init, f)
3451 }
3452}
3453impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
3454 #[cfg_attr(feature = "inline-more", inline)]
3455 fn len(&self) -> usize {
3456 self.inner.len()
3457 }
3458}
3459impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
3460
3461impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
3462where
3463 K: fmt::Debug,
3464 V: fmt::Debug,
3465 A: Allocator,
3466{
3467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3468 f.debug_list().entries(self.iter()).finish()
3469 }
3470}
3471
3472impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> {
3473 /// Sets the value of the entry, and returns an `OccupiedEntry`.
3474 ///
3475 /// # Examples
3476 ///
3477 /// ```
3478 /// use hashbrown::HashMap;
3479 ///
3480 /// let mut map: HashMap<&str, u32> = HashMap::new();
3481 /// let entry = map.entry("horseyland").insert(37);
3482 ///
3483 /// assert_eq!(entry.key(), &"horseyland");
3484 /// ```
3485 #[cfg_attr(feature = "inline-more", inline)]
3486 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
3487 where
3488 K: Hash,
3489 S: BuildHasher,
3490 {
3491 match self {
3492 Entry::Occupied(mut entry) => {
3493 entry.insert(value);
3494 entry
3495 }
3496 Entry::Vacant(entry) => entry.insert_entry(value),
3497 }
3498 }
3499
3500 /// Ensures a value is in the entry by inserting the default if empty, and returns
3501 /// a mutable reference to the value in the entry.
3502 ///
3503 /// # Examples
3504 ///
3505 /// ```
3506 /// use hashbrown::HashMap;
3507 ///
3508 /// let mut map: HashMap<&str, u32> = HashMap::new();
3509 ///
3510 /// // nonexistent key
3511 /// map.entry("poneyland").or_insert(3);
3512 /// assert_eq!(map["poneyland"], 3);
3513 ///
3514 /// // existing key
3515 /// *map.entry("poneyland").or_insert(10) *= 2;
3516 /// assert_eq!(map["poneyland"], 6);
3517 /// ```
3518 #[cfg_attr(feature = "inline-more", inline)]
3519 pub fn or_insert(self, default: V) -> &'a mut V
3520 where
3521 K: Hash,
3522 S: BuildHasher,
3523 {
3524 match self {
3525 Entry::Occupied(entry) => entry.into_mut(),
3526 Entry::Vacant(entry) => entry.insert(default),
3527 }
3528 }
3529
3530 /// Ensures a value is in the entry by inserting the result of the default function if empty,
3531 /// and returns a mutable reference to the value in the entry.
3532 ///
3533 /// # Examples
3534 ///
3535 /// ```
3536 /// use hashbrown::HashMap;
3537 ///
3538 /// let mut map: HashMap<&str, u32> = HashMap::new();
3539 ///
3540 /// // nonexistent key
3541 /// map.entry("poneyland").or_insert_with(|| 3);
3542 /// assert_eq!(map["poneyland"], 3);
3543 ///
3544 /// // existing key
3545 /// *map.entry("poneyland").or_insert_with(|| 10) *= 2;
3546 /// assert_eq!(map["poneyland"], 6);
3547 /// ```
3548 #[cfg_attr(feature = "inline-more", inline)]
3549 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
3550 where
3551 K: Hash,
3552 S: BuildHasher,
3553 {
3554 match self {
3555 Entry::Occupied(entry) => entry.into_mut(),
3556 Entry::Vacant(entry) => entry.insert(default()),
3557 }
3558 }
3559
3560 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
3561 /// This method allows for generating key-derived values for insertion by providing the default
3562 /// function a reference to the key that was moved during the `.entry(key)` method call.
3563 ///
3564 /// The reference to the moved key is provided so that cloning or copying the key is
3565 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
3566 ///
3567 /// # Examples
3568 ///
3569 /// ```
3570 /// use hashbrown::HashMap;
3571 ///
3572 /// let mut map: HashMap<&str, usize> = HashMap::new();
3573 ///
3574 /// // nonexistent key
3575 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
3576 /// assert_eq!(map["poneyland"], 9);
3577 ///
3578 /// // existing key
3579 /// *map.entry("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
3580 /// assert_eq!(map["poneyland"], 18);
3581 /// ```
3582 #[cfg_attr(feature = "inline-more", inline)]
3583 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
3584 where
3585 K: Hash,
3586 S: BuildHasher,
3587 {
3588 match self {
3589 Entry::Occupied(entry) => entry.into_mut(),
3590 Entry::Vacant(entry) => {
3591 let value = default(entry.key());
3592 entry.insert(value)
3593 }
3594 }
3595 }
3596
3597 /// Returns a reference to this entry's key.
3598 ///
3599 /// # Examples
3600 ///
3601 /// ```
3602 /// use hashbrown::HashMap;
3603 ///
3604 /// let mut map: HashMap<&str, u32> = HashMap::new();
3605 /// map.entry("poneyland").or_insert(3);
3606 /// // existing key
3607 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3608 /// // nonexistent key
3609 /// assert_eq!(map.entry("horseland").key(), &"horseland");
3610 /// ```
3611 #[cfg_attr(feature = "inline-more", inline)]
3612 pub fn key(&self) -> &K {
3613 match *self {
3614 Entry::Occupied(ref entry) => entry.key(),
3615 Entry::Vacant(ref entry) => entry.key(),
3616 }
3617 }
3618
3619 /// Provides in-place mutable access to an occupied entry before any
3620 /// potential inserts into the map.
3621 ///
3622 /// # Examples
3623 ///
3624 /// ```
3625 /// use hashbrown::HashMap;
3626 ///
3627 /// let mut map: HashMap<&str, u32> = HashMap::new();
3628 ///
3629 /// map.entry("poneyland")
3630 /// .and_modify(|e| { *e += 1 })
3631 /// .or_insert(42);
3632 /// assert_eq!(map["poneyland"], 42);
3633 ///
3634 /// map.entry("poneyland")
3635 /// .and_modify(|e| { *e += 1 })
3636 /// .or_insert(42);
3637 /// assert_eq!(map["poneyland"], 43);
3638 /// ```
3639 #[cfg_attr(feature = "inline-more", inline)]
3640 pub fn and_modify<F>(self, f: F) -> Self
3641 where
3642 F: FnOnce(&mut V),
3643 {
3644 match self {
3645 Entry::Occupied(mut entry) => {
3646 f(entry.get_mut());
3647 Entry::Occupied(entry)
3648 }
3649 Entry::Vacant(entry) => Entry::Vacant(entry),
3650 }
3651 }
3652
3653 /// Provides shared access to the key and owned access to the value of
3654 /// an occupied entry and allows to replace or remove it based on the
3655 /// value of the returned option.
3656 ///
3657 /// # Examples
3658 ///
3659 /// ```
3660 /// use hashbrown::HashMap;
3661 /// use hashbrown::hash_map::Entry;
3662 ///
3663 /// let mut map: HashMap<&str, u32> = HashMap::new();
3664 ///
3665 /// let entry = map
3666 /// .entry("poneyland")
3667 /// .and_replace_entry_with(|_k, _v| panic!());
3668 ///
3669 /// match entry {
3670 /// Entry::Vacant(e) => {
3671 /// assert_eq!(e.key(), &"poneyland");
3672 /// }
3673 /// Entry::Occupied(_) => panic!(),
3674 /// }
3675 ///
3676 /// map.insert("poneyland", 42);
3677 ///
3678 /// let entry = map
3679 /// .entry("poneyland")
3680 /// .and_replace_entry_with(|k, v| {
3681 /// assert_eq!(k, &"poneyland");
3682 /// assert_eq!(v, 42);
3683 /// Some(v + 1)
3684 /// });
3685 ///
3686 /// match entry {
3687 /// Entry::Occupied(e) => {
3688 /// assert_eq!(e.key(), &"poneyland");
3689 /// assert_eq!(e.get(), &43);
3690 /// }
3691 /// Entry::Vacant(_) => panic!(),
3692 /// }
3693 ///
3694 /// assert_eq!(map["poneyland"], 43);
3695 ///
3696 /// let entry = map
3697 /// .entry("poneyland")
3698 /// .and_replace_entry_with(|_k, _v| None);
3699 ///
3700 /// match entry {
3701 /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"),
3702 /// Entry::Occupied(_) => panic!(),
3703 /// }
3704 ///
3705 /// assert!(!map.contains_key("poneyland"));
3706 /// ```
3707 #[cfg_attr(feature = "inline-more", inline)]
3708 pub fn and_replace_entry_with<F>(self, f: F) -> Self
3709 where
3710 F: FnOnce(&K, V) -> Option<V>,
3711 {
3712 match self {
3713 Entry::Occupied(entry) => entry.replace_entry_with(f),
3714 Entry::Vacant(_) => self,
3715 }
3716 }
3717}
3718
3719impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> {
3720 /// Ensures a value is in the entry by inserting the default value if empty,
3721 /// and returns a mutable reference to the value in the entry.
3722 ///
3723 /// # Examples
3724 ///
3725 /// ```
3726 /// use hashbrown::HashMap;
3727 ///
3728 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
3729 ///
3730 /// // nonexistent key
3731 /// map.entry("poneyland").or_default();
3732 /// assert_eq!(map["poneyland"], None);
3733 ///
3734 /// map.insert("horseland", Some(3));
3735 ///
3736 /// // existing key
3737 /// assert_eq!(map.entry("horseland").or_default(), &mut Some(3));
3738 /// ```
3739 #[cfg_attr(feature = "inline-more", inline)]
3740 pub fn or_default(self) -> &'a mut V
3741 where
3742 K: Hash,
3743 S: BuildHasher,
3744 {
3745 match self {
3746 Entry::Occupied(entry) => entry.into_mut(),
3747 Entry::Vacant(entry) => entry.insert(Default::default()),
3748 }
3749 }
3750}
3751
3752impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> {
3753 /// Gets a reference to the key in the entry.
3754 ///
3755 /// # Examples
3756 ///
3757 /// ```
3758 /// use hashbrown::hash_map::{Entry, HashMap};
3759 ///
3760 /// let mut map: HashMap<&str, u32> = HashMap::new();
3761 /// map.entry("poneyland").or_insert(12);
3762 ///
3763 /// match map.entry("poneyland") {
3764 /// Entry::Vacant(_) => panic!(),
3765 /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"),
3766 /// }
3767 /// ```
3768 #[cfg_attr(feature = "inline-more", inline)]
3769 pub fn key(&self) -> &K {
3770 unsafe { &self.elem.as_ref().0 }
3771 }
3772
3773 /// Take the ownership of the key and value from the map.
3774 /// Keeps the allocated memory for reuse.
3775 ///
3776 /// # Examples
3777 ///
3778 /// ```
3779 /// use hashbrown::HashMap;
3780 /// use hashbrown::hash_map::Entry;
3781 ///
3782 /// let mut map: HashMap<&str, u32> = HashMap::new();
3783 /// // The map is empty
3784 /// assert!(map.is_empty() && map.capacity() == 0);
3785 ///
3786 /// map.entry("poneyland").or_insert(12);
3787 ///
3788 /// if let Entry::Occupied(o) = map.entry("poneyland") {
3789 /// // We delete the entry from the map.
3790 /// assert_eq!(o.remove_entry(), ("poneyland", 12));
3791 /// }
3792 ///
3793 /// assert_eq!(map.contains_key("poneyland"), false);
3794 /// // Now map hold none elements
3795 /// assert!(map.is_empty());
3796 /// ```
3797 #[cfg_attr(feature = "inline-more", inline)]
3798 pub fn remove_entry(self) -> (K, V) {
3799 unsafe { self.table.table.remove(self.elem).0 }
3800 }
3801
3802 /// Gets a reference to the value in the entry.
3803 ///
3804 /// # Examples
3805 ///
3806 /// ```
3807 /// use hashbrown::HashMap;
3808 /// use hashbrown::hash_map::Entry;
3809 ///
3810 /// let mut map: HashMap<&str, u32> = HashMap::new();
3811 /// map.entry("poneyland").or_insert(12);
3812 ///
3813 /// match map.entry("poneyland") {
3814 /// Entry::Vacant(_) => panic!(),
3815 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12),
3816 /// }
3817 /// ```
3818 #[cfg_attr(feature = "inline-more", inline)]
3819 pub fn get(&self) -> &V {
3820 unsafe { &self.elem.as_ref().1 }
3821 }
3822
3823 /// Gets a mutable reference to the value in the entry.
3824 ///
3825 /// If you need a reference to the `OccupiedEntry` which may outlive the
3826 /// destruction of the `Entry` value, see [`into_mut`].
3827 ///
3828 /// [`into_mut`]: #method.into_mut
3829 ///
3830 /// # Examples
3831 ///
3832 /// ```
3833 /// use hashbrown::HashMap;
3834 /// use hashbrown::hash_map::Entry;
3835 ///
3836 /// let mut map: HashMap<&str, u32> = HashMap::new();
3837 /// map.entry("poneyland").or_insert(12);
3838 ///
3839 /// assert_eq!(map["poneyland"], 12);
3840 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
3841 /// *o.get_mut() += 10;
3842 /// assert_eq!(*o.get(), 22);
3843 ///
3844 /// // We can use the same Entry multiple times.
3845 /// *o.get_mut() += 2;
3846 /// }
3847 ///
3848 /// assert_eq!(map["poneyland"], 24);
3849 /// ```
3850 #[cfg_attr(feature = "inline-more", inline)]
3851 pub fn get_mut(&mut self) -> &mut V {
3852 unsafe { &mut self.elem.as_mut().1 }
3853 }
3854
3855 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
3856 /// with a lifetime bound to the map itself.
3857 ///
3858 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
3859 ///
3860 /// [`get_mut`]: #method.get_mut
3861 ///
3862 /// # Examples
3863 ///
3864 /// ```
3865 /// use hashbrown::hash_map::{Entry, HashMap};
3866 ///
3867 /// let mut map: HashMap<&str, u32> = HashMap::new();
3868 /// map.entry("poneyland").or_insert(12);
3869 ///
3870 /// assert_eq!(map["poneyland"], 12);
3871 ///
3872 /// let value: &mut u32;
3873 /// match map.entry("poneyland") {
3874 /// Entry::Occupied(entry) => value = entry.into_mut(),
3875 /// Entry::Vacant(_) => panic!(),
3876 /// }
3877 /// *value += 10;
3878 ///
3879 /// assert_eq!(map["poneyland"], 22);
3880 /// ```
3881 #[cfg_attr(feature = "inline-more", inline)]
3882 pub fn into_mut(self) -> &'a mut V {
3883 unsafe { &mut self.elem.as_mut().1 }
3884 }
3885
3886 /// Sets the value of the entry, and returns the entry's old value.
3887 ///
3888 /// # Examples
3889 ///
3890 /// ```
3891 /// use hashbrown::HashMap;
3892 /// use hashbrown::hash_map::Entry;
3893 ///
3894 /// let mut map: HashMap<&str, u32> = HashMap::new();
3895 /// map.entry("poneyland").or_insert(12);
3896 ///
3897 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
3898 /// assert_eq!(o.insert(15), 12);
3899 /// }
3900 ///
3901 /// assert_eq!(map["poneyland"], 15);
3902 /// ```
3903 #[cfg_attr(feature = "inline-more", inline)]
3904 pub fn insert(&mut self, value: V) -> V {
3905 mem::replace(self.get_mut(), value)
3906 }
3907
3908 /// Takes the value out of the entry, and returns it.
3909 /// Keeps the allocated memory for reuse.
3910 ///
3911 /// # Examples
3912 ///
3913 /// ```
3914 /// use hashbrown::HashMap;
3915 /// use hashbrown::hash_map::Entry;
3916 ///
3917 /// let mut map: HashMap<&str, u32> = HashMap::new();
3918 /// // The map is empty
3919 /// assert!(map.is_empty() && map.capacity() == 0);
3920 ///
3921 /// map.entry("poneyland").or_insert(12);
3922 ///
3923 /// if let Entry::Occupied(o) = map.entry("poneyland") {
3924 /// assert_eq!(o.remove(), 12);
3925 /// }
3926 ///
3927 /// assert_eq!(map.contains_key("poneyland"), false);
3928 /// // Now map hold none elements
3929 /// assert!(map.is_empty());
3930 /// ```
3931 #[cfg_attr(feature = "inline-more", inline)]
3932 pub fn remove(self) -> V {
3933 self.remove_entry().1
3934 }
3935
3936 /// Provides shared access to the key and owned access to the value of
3937 /// the entry and allows to replace or remove it based on the
3938 /// value of the returned option.
3939 ///
3940 /// # Examples
3941 ///
3942 /// ```
3943 /// use hashbrown::HashMap;
3944 /// use hashbrown::hash_map::Entry;
3945 ///
3946 /// let mut map: HashMap<&str, u32> = HashMap::new();
3947 /// map.insert("poneyland", 42);
3948 ///
3949 /// let entry = match map.entry("poneyland") {
3950 /// Entry::Occupied(e) => {
3951 /// e.replace_entry_with(|k, v| {
3952 /// assert_eq!(k, &"poneyland");
3953 /// assert_eq!(v, 42);
3954 /// Some(v + 1)
3955 /// })
3956 /// }
3957 /// Entry::Vacant(_) => panic!(),
3958 /// };
3959 ///
3960 /// match entry {
3961 /// Entry::Occupied(e) => {
3962 /// assert_eq!(e.key(), &"poneyland");
3963 /// assert_eq!(e.get(), &43);
3964 /// }
3965 /// Entry::Vacant(_) => panic!(),
3966 /// }
3967 ///
3968 /// assert_eq!(map["poneyland"], 43);
3969 ///
3970 /// let entry = match map.entry("poneyland") {
3971 /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None),
3972 /// Entry::Vacant(_) => panic!(),
3973 /// };
3974 ///
3975 /// match entry {
3976 /// Entry::Vacant(e) => {
3977 /// assert_eq!(e.key(), &"poneyland");
3978 /// }
3979 /// Entry::Occupied(_) => panic!(),
3980 /// }
3981 ///
3982 /// assert!(!map.contains_key("poneyland"));
3983 /// ```
3984 #[cfg_attr(feature = "inline-more", inline)]
3985 pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
3986 where
3987 F: FnOnce(&K, V) -> Option<V>,
3988 {
3989 unsafe {
3990 let mut spare_key = None;
3991
3992 self.table
3993 .table
3994 .replace_bucket_with(self.elem.clone(), |(key, value)| {
3995 if let Some(new_value) = f(&key, value) {
3996 Some((key, new_value))
3997 } else {
3998 spare_key = Some(key);
3999 None
4000 }
4001 });
4002
4003 if let Some(key) = spare_key {
4004 Entry::Vacant(VacantEntry {
4005 hash: self.hash,
4006 key,
4007 table: self.table,
4008 })
4009 } else {
4010 Entry::Occupied(self)
4011 }
4012 }
4013 }
4014}
4015
4016impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> {
4017 /// Gets a reference to the key that would be used when inserting a value
4018 /// through the `VacantEntry`.
4019 ///
4020 /// # Examples
4021 ///
4022 /// ```
4023 /// use hashbrown::HashMap;
4024 ///
4025 /// let mut map: HashMap<&str, u32> = HashMap::new();
4026 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
4027 /// ```
4028 #[cfg_attr(feature = "inline-more", inline)]
4029 pub fn key(&self) -> &K {
4030 &self.key
4031 }
4032
4033 /// Take ownership of the key.
4034 ///
4035 /// # Examples
4036 ///
4037 /// ```
4038 /// use hashbrown::hash_map::{Entry, HashMap};
4039 ///
4040 /// let mut map: HashMap<&str, u32> = HashMap::new();
4041 ///
4042 /// match map.entry("poneyland") {
4043 /// Entry::Occupied(_) => panic!(),
4044 /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"),
4045 /// }
4046 /// ```
4047 #[cfg_attr(feature = "inline-more", inline)]
4048 pub fn into_key(self) -> K {
4049 self.key
4050 }
4051
4052 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4053 /// and returns a mutable reference to it.
4054 ///
4055 /// # Examples
4056 ///
4057 /// ```
4058 /// use hashbrown::HashMap;
4059 /// use hashbrown::hash_map::Entry;
4060 ///
4061 /// let mut map: HashMap<&str, u32> = HashMap::new();
4062 ///
4063 /// if let Entry::Vacant(o) = map.entry("poneyland") {
4064 /// o.insert(37);
4065 /// }
4066 /// assert_eq!(map["poneyland"], 37);
4067 /// ```
4068 #[cfg_attr(feature = "inline-more", inline)]
4069 pub fn insert(self, value: V) -> &'a mut V
4070 where
4071 K: Hash,
4072 S: BuildHasher,
4073 {
4074 let table = &mut self.table.table;
4075 let entry = table.insert_entry(
4076 self.hash,
4077 (self.key, value),
4078 make_hasher::<_, V, S>(&self.table.hash_builder),
4079 );
4080 &mut entry.1
4081 }
4082
4083 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4084 /// and returns an [`OccupiedEntry`].
4085 ///
4086 /// # Examples
4087 ///
4088 /// ```
4089 /// use hashbrown::HashMap;
4090 /// use hashbrown::hash_map::Entry;
4091 ///
4092 /// let mut map: HashMap<&str, u32> = HashMap::new();
4093 ///
4094 /// if let Entry::Vacant(v) = map.entry("poneyland") {
4095 /// let o = v.insert_entry(37);
4096 /// assert_eq!(o.get(), &37);
4097 /// }
4098 /// ```
4099 #[cfg_attr(feature = "inline-more", inline)]
4100 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4101 where
4102 K: Hash,
4103 S: BuildHasher,
4104 {
4105 let elem = self.table.table.insert(
4106 self.hash,
4107 (self.key, value),
4108 make_hasher::<_, V, S>(&self.table.hash_builder),
4109 );
4110 OccupiedEntry {
4111 hash: self.hash,
4112 elem,
4113 table: self.table,
4114 }
4115 }
4116}
4117
4118impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
4119 /// Sets the value of the entry, and returns an `OccupiedEntry`.
4120 ///
4121 /// # Examples
4122 ///
4123 /// ```
4124 /// use hashbrown::HashMap;
4125 ///
4126 /// let mut map: HashMap<String, u32> = HashMap::new();
4127 /// let entry = map.entry_ref("horseyland").insert(37);
4128 ///
4129 /// assert_eq!(entry.key(), "horseyland");
4130 /// ```
4131 #[cfg_attr(feature = "inline-more", inline)]
4132 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4133 where
4134 K: Hash + From<&'b Q>,
4135 S: BuildHasher,
4136 {
4137 match self {
4138 EntryRef::Occupied(mut entry) => {
4139 entry.insert(value);
4140 entry
4141 }
4142 EntryRef::Vacant(entry) => entry.insert_entry(value),
4143 }
4144 }
4145
4146 /// Ensures a value is in the entry by inserting the default if empty, and returns
4147 /// a mutable reference to the value in the entry.
4148 ///
4149 /// # Examples
4150 ///
4151 /// ```
4152 /// use hashbrown::HashMap;
4153 ///
4154 /// let mut map: HashMap<String, u32> = HashMap::new();
4155 ///
4156 /// // nonexistent key
4157 /// map.entry_ref("poneyland").or_insert(3);
4158 /// assert_eq!(map["poneyland"], 3);
4159 ///
4160 /// // existing key
4161 /// *map.entry_ref("poneyland").or_insert(10) *= 2;
4162 /// assert_eq!(map["poneyland"], 6);
4163 /// ```
4164 #[cfg_attr(feature = "inline-more", inline)]
4165 pub fn or_insert(self, default: V) -> &'a mut V
4166 where
4167 K: Hash + From<&'b Q>,
4168 S: BuildHasher,
4169 {
4170 match self {
4171 EntryRef::Occupied(entry) => entry.into_mut(),
4172 EntryRef::Vacant(entry) => entry.insert(default),
4173 }
4174 }
4175
4176 /// Ensures a value is in the entry by inserting the result of the default function if empty,
4177 /// and returns a mutable reference to the value in the entry.
4178 ///
4179 /// # Examples
4180 ///
4181 /// ```
4182 /// use hashbrown::HashMap;
4183 ///
4184 /// let mut map: HashMap<String, u32> = HashMap::new();
4185 ///
4186 /// // nonexistent key
4187 /// map.entry_ref("poneyland").or_insert_with(|| 3);
4188 /// assert_eq!(map["poneyland"], 3);
4189 ///
4190 /// // existing key
4191 /// *map.entry_ref("poneyland").or_insert_with(|| 10) *= 2;
4192 /// assert_eq!(map["poneyland"], 6);
4193 /// ```
4194 #[cfg_attr(feature = "inline-more", inline)]
4195 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
4196 where
4197 K: Hash + From<&'b Q>,
4198 S: BuildHasher,
4199 {
4200 match self {
4201 EntryRef::Occupied(entry) => entry.into_mut(),
4202 EntryRef::Vacant(entry) => entry.insert(default()),
4203 }
4204 }
4205
4206 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
4207 /// This method allows for generating key-derived values for insertion by providing the default
4208 /// function an access to the borrower form of the key.
4209 ///
4210 /// # Examples
4211 ///
4212 /// ```
4213 /// use hashbrown::HashMap;
4214 ///
4215 /// let mut map: HashMap<String, usize> = HashMap::new();
4216 ///
4217 /// // nonexistent key
4218 /// map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count());
4219 /// assert_eq!(map["poneyland"], 9);
4220 ///
4221 /// // existing key
4222 /// *map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
4223 /// assert_eq!(map["poneyland"], 18);
4224 /// ```
4225 #[cfg_attr(feature = "inline-more", inline)]
4226 pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V
4227 where
4228 K: Hash + Borrow<Q> + From<&'b Q>,
4229 S: BuildHasher,
4230 {
4231 match self {
4232 EntryRef::Occupied(entry) => entry.into_mut(),
4233 EntryRef::Vacant(entry) => {
4234 let value = default(entry.key);
4235 entry.insert(value)
4236 }
4237 }
4238 }
4239
4240 /// Returns a reference to this entry's key.
4241 ///
4242 /// # Examples
4243 ///
4244 /// ```
4245 /// use hashbrown::HashMap;
4246 ///
4247 /// let mut map: HashMap<String, u32> = HashMap::new();
4248 /// map.entry_ref("poneyland").or_insert(3);
4249 /// // existing key
4250 /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland");
4251 /// // nonexistent key
4252 /// assert_eq!(map.entry_ref("horseland").key(), "horseland");
4253 /// ```
4254 #[cfg_attr(feature = "inline-more", inline)]
4255 pub fn key(&self) -> &Q
4256 where
4257 K: Borrow<Q>,
4258 {
4259 match *self {
4260 EntryRef::Occupied(ref entry) => entry.key().borrow(),
4261 EntryRef::Vacant(ref entry) => entry.key(),
4262 }
4263 }
4264
4265 /// Provides in-place mutable access to an occupied entry before any
4266 /// potential inserts into the map.
4267 ///
4268 /// # Examples
4269 ///
4270 /// ```
4271 /// use hashbrown::HashMap;
4272 ///
4273 /// let mut map: HashMap<String, u32> = HashMap::new();
4274 ///
4275 /// map.entry_ref("poneyland")
4276 /// .and_modify(|e| { *e += 1 })
4277 /// .or_insert(42);
4278 /// assert_eq!(map["poneyland"], 42);
4279 ///
4280 /// map.entry_ref("poneyland")
4281 /// .and_modify(|e| { *e += 1 })
4282 /// .or_insert(42);
4283 /// assert_eq!(map["poneyland"], 43);
4284 /// ```
4285 #[cfg_attr(feature = "inline-more", inline)]
4286 pub fn and_modify<F>(self, f: F) -> Self
4287 where
4288 F: FnOnce(&mut V),
4289 {
4290 match self {
4291 EntryRef::Occupied(mut entry) => {
4292 f(entry.get_mut());
4293 EntryRef::Occupied(entry)
4294 }
4295 EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
4296 }
4297 }
4298}
4299
4300impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
4301 /// Ensures a value is in the entry by inserting the default value if empty,
4302 /// and returns a mutable reference to the value in the entry.
4303 ///
4304 /// # Examples
4305 ///
4306 /// ```
4307 /// use hashbrown::HashMap;
4308 ///
4309 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4310 ///
4311 /// // nonexistent key
4312 /// map.entry_ref("poneyland").or_default();
4313 /// assert_eq!(map["poneyland"], None);
4314 ///
4315 /// map.insert("horseland".to_string(), Some(3));
4316 ///
4317 /// // existing key
4318 /// assert_eq!(map.entry_ref("horseland").or_default(), &mut Some(3));
4319 /// ```
4320 #[cfg_attr(feature = "inline-more", inline)]
4321 pub fn or_default(self) -> &'a mut V
4322 where
4323 K: Hash + From<&'b Q>,
4324 S: BuildHasher,
4325 {
4326 match self {
4327 EntryRef::Occupied(entry) => entry.into_mut(),
4328 EntryRef::Vacant(entry) => entry.insert(Default::default()),
4329 }
4330 }
4331}
4332
4333impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S, A> {
4334 /// Gets a reference to the key that would be used when inserting a value
4335 /// through the `VacantEntryRef`.
4336 ///
4337 /// # Examples
4338 ///
4339 /// ```
4340 /// use hashbrown::HashMap;
4341 ///
4342 /// let mut map: HashMap<String, u32> = HashMap::new();
4343 /// let key: &str = "poneyland";
4344 /// assert_eq!(map.entry_ref(key).key(), "poneyland");
4345 /// ```
4346 #[cfg_attr(feature = "inline-more", inline)]
4347 pub fn key(&self) -> &'b Q {
4348 self.key
4349 }
4350
4351 /// Sets the value of the entry with the `VacantEntryRef`'s key,
4352 /// and returns a mutable reference to it.
4353 ///
4354 /// # Examples
4355 ///
4356 /// ```
4357 /// use hashbrown::HashMap;
4358 /// use hashbrown::hash_map::EntryRef;
4359 ///
4360 /// let mut map: HashMap<String, u32> = HashMap::new();
4361 /// let key: &str = "poneyland";
4362 ///
4363 /// if let EntryRef::Vacant(o) = map.entry_ref(key) {
4364 /// o.insert(37);
4365 /// }
4366 /// assert_eq!(map["poneyland"], 37);
4367 /// ```
4368 #[cfg_attr(feature = "inline-more", inline)]
4369 pub fn insert(self, value: V) -> &'a mut V
4370 where
4371 K: Hash + From<&'b Q>,
4372 S: BuildHasher,
4373 {
4374 let table = &mut self.table.table;
4375 let entry = table.insert_entry(
4376 self.hash,
4377 (self.key.into(), value),
4378 make_hasher::<_, V, S>(&self.table.hash_builder),
4379 );
4380 &mut entry.1
4381 }
4382
4383 /// Sets the value of the entry with the [`VacantEntryRef`]'s key,
4384 /// and returns an [`OccupiedEntry`].
4385 ///
4386 /// # Examples
4387 ///
4388 /// ```
4389 /// use hashbrown::HashMap;
4390 /// use hashbrown::hash_map::EntryRef;
4391 ///
4392 /// let mut map: HashMap<&str, u32> = HashMap::new();
4393 ///
4394 /// if let EntryRef::Vacant(v) = map.entry_ref("poneyland") {
4395 /// let o = v.insert_entry(37);
4396 /// assert_eq!(o.get(), &37);
4397 /// }
4398 /// ```
4399 #[cfg_attr(feature = "inline-more", inline)]
4400 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4401 where
4402 K: Hash + From<&'b Q>,
4403 S: BuildHasher,
4404 {
4405 let elem = self.table.table.insert(
4406 self.hash,
4407 (self.key.into(), value),
4408 make_hasher::<_, V, S>(&self.table.hash_builder),
4409 );
4410 OccupiedEntry {
4411 hash: self.hash,
4412 elem,
4413 table: self.table,
4414 }
4415 }
4416}
4417
4418impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A>
4419where
4420 K: Eq + Hash,
4421 S: BuildHasher + Default,
4422 A: Default + Allocator,
4423{
4424 #[cfg_attr(feature = "inline-more", inline)]
4425 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
4426 let iter = iter.into_iter();
4427 let mut map =
4428 Self::with_capacity_and_hasher_in(iter.size_hint().0, S::default(), A::default());
4429 iter.for_each(|(k, v)| {
4430 map.insert(k, v);
4431 });
4432 map
4433 }
4434}
4435
4436/// Inserts all new key-values from the iterator and replaces values with existing
4437/// keys with new values returned from the iterator.
4438impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
4439where
4440 K: Eq + Hash,
4441 S: BuildHasher,
4442 A: Allocator,
4443{
4444 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4445 /// Replace values with existing keys with new values returned from the iterator.
4446 ///
4447 /// # Examples
4448 ///
4449 /// ```
4450 /// use hashbrown::hash_map::HashMap;
4451 ///
4452 /// let mut map = HashMap::new();
4453 /// map.insert(1, 100);
4454 ///
4455 /// let some_iter = [(1, 1), (2, 2)].into_iter();
4456 /// map.extend(some_iter);
4457 /// // Replace values with existing keys with new values returned from the iterator.
4458 /// // So that the map.get(&1) doesn't return Some(&100).
4459 /// assert_eq!(map.get(&1), Some(&1));
4460 ///
4461 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4462 /// map.extend(some_vec);
4463 ///
4464 /// let some_arr = [(5, 5), (6, 6)];
4465 /// map.extend(some_arr);
4466 /// let old_map_len = map.len();
4467 ///
4468 /// // You can also extend from another HashMap
4469 /// let mut new_map = HashMap::new();
4470 /// new_map.extend(map);
4471 /// assert_eq!(new_map.len(), old_map_len);
4472 ///
4473 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4474 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4475 /// // items must be sorted to test them against a sorted array.
4476 /// vec.sort_unstable();
4477 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4478 /// ```
4479 #[cfg_attr(feature = "inline-more", inline)]
4480 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
4481 // Keys may be already present or show multiple times in the iterator.
4482 // Reserve the entire hint lower bound if the map is empty.
4483 // Otherwise reserve half the hint (rounded up), so the map
4484 // will only resize twice in the worst case.
4485 let iter = iter.into_iter();
4486 let reserve = if self.is_empty() {
4487 iter.size_hint().0
4488 } else {
4489 (iter.size_hint().0 + 1) / 2
4490 };
4491 self.reserve(reserve);
4492 iter.for_each(move |(k, v)| {
4493 self.insert(k, v);
4494 });
4495 }
4496
4497 #[inline]
4498 #[cfg(feature = "nightly")]
4499 fn extend_one(&mut self, (k, v): (K, V)) {
4500 self.insert(k, v);
4501 }
4502
4503 #[inline]
4504 #[cfg(feature = "nightly")]
4505 fn extend_reserve(&mut self, additional: usize) {
4506 // Keys may be already present or show multiple times in the iterator.
4507 // Reserve the entire hint lower bound if the map is empty.
4508 // Otherwise reserve half the hint (rounded up), so the map
4509 // will only resize twice in the worst case.
4510 let reserve = if self.is_empty() {
4511 additional
4512 } else {
4513 (additional + 1) / 2
4514 };
4515 self.reserve(reserve);
4516 }
4517}
4518
4519/// Inserts all new key-values from the iterator and replaces values with existing
4520/// keys with new values returned from the iterator.
4521impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
4522where
4523 K: Eq + Hash + Copy,
4524 V: Copy,
4525 S: BuildHasher,
4526 A: Allocator,
4527{
4528 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4529 /// Replace values with existing keys with new values returned from the iterator.
4530 /// The keys and values must implement [`Copy`] trait.
4531 ///
4532 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
4533 ///
4534 /// # Examples
4535 ///
4536 /// ```
4537 /// use hashbrown::hash_map::HashMap;
4538 ///
4539 /// let mut map = HashMap::new();
4540 /// map.insert(1, 100);
4541 ///
4542 /// let arr = [(1, 1), (2, 2)];
4543 /// let some_iter = arr.iter().map(|(k, v)| (k, v));
4544 /// map.extend(some_iter);
4545 /// // Replace values with existing keys with new values returned from the iterator.
4546 /// // So that the map.get(&1) doesn't return Some(&100).
4547 /// assert_eq!(map.get(&1), Some(&1));
4548 ///
4549 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4550 /// map.extend(some_vec.iter().map(|(k, v)| (k, v)));
4551 ///
4552 /// let some_arr = [(5, 5), (6, 6)];
4553 /// map.extend(some_arr.iter().map(|(k, v)| (k, v)));
4554 ///
4555 /// // You can also extend from another HashMap
4556 /// let mut new_map = HashMap::new();
4557 /// new_map.extend(&map);
4558 /// assert_eq!(new_map, map);
4559 ///
4560 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4561 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4562 /// // items must be sorted to test them against a sorted array.
4563 /// vec.sort_unstable();
4564 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4565 /// ```
4566 #[cfg_attr(feature = "inline-more", inline)]
4567 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
4568 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
4569 }
4570
4571 #[inline]
4572 #[cfg(feature = "nightly")]
4573 fn extend_one(&mut self, (k, v): (&'a K, &'a V)) {
4574 self.insert(*k, *v);
4575 }
4576
4577 #[inline]
4578 #[cfg(feature = "nightly")]
4579 fn extend_reserve(&mut self, additional: usize) {
4580 Extend::<(K, V)>::extend_reserve(self, additional);
4581 }
4582}
4583
4584/// Inserts all new key-values from the iterator and replaces values with existing
4585/// keys with new values returned from the iterator.
4586impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A>
4587where
4588 K: Eq + Hash + Copy,
4589 V: Copy,
4590 S: BuildHasher,
4591 A: Allocator,
4592{
4593 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4594 /// Replace values with existing keys with new values returned from the iterator.
4595 /// The keys and values must implement [`Copy`] trait.
4596 ///
4597 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
4598 ///
4599 /// # Examples
4600 ///
4601 /// ```
4602 /// use hashbrown::hash_map::HashMap;
4603 ///
4604 /// let mut map = HashMap::new();
4605 /// map.insert(1, 100);
4606 ///
4607 /// let arr = [(1, 1), (2, 2)];
4608 /// let some_iter = arr.iter();
4609 /// map.extend(some_iter);
4610 /// // Replace values with existing keys with new values returned from the iterator.
4611 /// // So that the map.get(&1) doesn't return Some(&100).
4612 /// assert_eq!(map.get(&1), Some(&1));
4613 ///
4614 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4615 /// map.extend(&some_vec);
4616 ///
4617 /// let some_arr = [(5, 5), (6, 6)];
4618 /// map.extend(&some_arr);
4619 ///
4620 /// let mut vec: Vec<_> = map.into_iter().collect();
4621 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4622 /// // items must be sorted to test them against a sorted array.
4623 /// vec.sort_unstable();
4624 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4625 /// ```
4626 #[cfg_attr(feature = "inline-more", inline)]
4627 fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
4628 self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
4629 }
4630
4631 #[inline]
4632 #[cfg(feature = "nightly")]
4633 fn extend_one(&mut self, &(k, v): &'a (K, V)) {
4634 self.insert(k, v);
4635 }
4636
4637 #[inline]
4638 #[cfg(feature = "nightly")]
4639 fn extend_reserve(&mut self, additional: usize) {
4640 Extend::<(K, V)>::extend_reserve(self, additional);
4641 }
4642}
4643
4644#[allow(dead_code)]
4645fn assert_covariance() {
4646 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
4647 v
4648 }
4649 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
4650 v
4651 }
4652 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
4653 v
4654 }
4655 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
4656 v
4657 }
4658 fn into_iter_key<'new, A: Allocator>(
4659 v: IntoIter<&'static str, u8, A>,
4660 ) -> IntoIter<&'new str, u8, A> {
4661 v
4662 }
4663 fn into_iter_val<'new, A: Allocator>(
4664 v: IntoIter<u8, &'static str, A>,
4665 ) -> IntoIter<u8, &'new str, A> {
4666 v
4667 }
4668 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
4669 v
4670 }
4671 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
4672 v
4673 }
4674 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
4675 v
4676 }
4677 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
4678 v
4679 }
4680 fn drain<'new>(
4681 d: Drain<'static, &'static str, &'static str>,
4682 ) -> Drain<'new, &'new str, &'new str> {
4683 d
4684 }
4685}
4686
4687#[cfg(test)]
4688mod test_map {
4689 use super::DefaultHashBuilder;
4690 use super::Entry::{Occupied, Vacant};
4691 use super::EntryRef;
4692 use super::HashMap;
4693 use alloc::string::{String, ToString};
4694 use alloc::sync::Arc;
4695 use allocator_api2::alloc::{AllocError, Allocator, Global};
4696 use core::alloc::Layout;
4697 use core::ptr::NonNull;
4698 use core::sync::atomic::{AtomicI8, Ordering};
4699 use rand::{rngs::SmallRng, Rng, SeedableRng};
4700 use std::borrow::ToOwned;
4701 use std::cell::RefCell;
4702 use std::vec::Vec;
4703
4704 #[test]
4705 fn test_zero_capacities() {
4706 type HM = HashMap<i32, i32>;
4707
4708 let m = HM::new();
4709 assert_eq!(m.capacity(), 0);
4710
4711 let m = HM::default();
4712 assert_eq!(m.capacity(), 0);
4713
4714 let m = HM::with_hasher(DefaultHashBuilder::default());
4715 assert_eq!(m.capacity(), 0);
4716
4717 let m = HM::with_capacity(0);
4718 assert_eq!(m.capacity(), 0);
4719
4720 let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
4721 assert_eq!(m.capacity(), 0);
4722
4723 let mut m = HM::new();
4724 m.insert(1, 1);
4725 m.insert(2, 2);
4726 m.remove(&1);
4727 m.remove(&2);
4728 m.shrink_to_fit();
4729 assert_eq!(m.capacity(), 0);
4730
4731 let mut m = HM::new();
4732 m.reserve(0);
4733 assert_eq!(m.capacity(), 0);
4734 }
4735
4736 #[test]
4737 fn test_create_capacity_zero() {
4738 let mut m = HashMap::with_capacity(0);
4739
4740 assert!(m.insert(1, 1).is_none());
4741
4742 assert!(m.contains_key(&1));
4743 assert!(!m.contains_key(&0));
4744 }
4745
4746 #[test]
4747 fn test_insert() {
4748 let mut m = HashMap::new();
4749 assert_eq!(m.len(), 0);
4750 assert!(m.insert(1, 2).is_none());
4751 assert_eq!(m.len(), 1);
4752 assert!(m.insert(2, 4).is_none());
4753 assert_eq!(m.len(), 2);
4754 assert_eq!(*m.get(&1).unwrap(), 2);
4755 assert_eq!(*m.get(&2).unwrap(), 4);
4756 }
4757
4758 #[test]
4759 fn test_clone() {
4760 let mut m = HashMap::new();
4761 assert_eq!(m.len(), 0);
4762 assert!(m.insert(1, 2).is_none());
4763 assert_eq!(m.len(), 1);
4764 assert!(m.insert(2, 4).is_none());
4765 assert_eq!(m.len(), 2);
4766 #[allow(clippy::redundant_clone)]
4767 let m2 = m.clone();
4768 assert_eq!(*m2.get(&1).unwrap(), 2);
4769 assert_eq!(*m2.get(&2).unwrap(), 4);
4770 assert_eq!(m2.len(), 2);
4771 }
4772
4773 #[test]
4774 fn test_clone_from() {
4775 let mut m = HashMap::new();
4776 let mut m2 = HashMap::new();
4777 assert_eq!(m.len(), 0);
4778 assert!(m.insert(1, 2).is_none());
4779 assert_eq!(m.len(), 1);
4780 assert!(m.insert(2, 4).is_none());
4781 assert_eq!(m.len(), 2);
4782 m2.clone_from(&m);
4783 assert_eq!(*m2.get(&1).unwrap(), 2);
4784 assert_eq!(*m2.get(&2).unwrap(), 4);
4785 assert_eq!(m2.len(), 2);
4786 }
4787
4788 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = const { RefCell::new(Vec::new()) } }
4789
4790 #[derive(Hash, PartialEq, Eq)]
4791 struct Droppable {
4792 k: usize,
4793 }
4794
4795 impl Droppable {
4796 fn new(k: usize) -> Droppable {
4797 DROP_VECTOR.with(|slot| {
4798 slot.borrow_mut()[k] += 1;
4799 });
4800
4801 Droppable { k }
4802 }
4803 }
4804
4805 impl Drop for Droppable {
4806 fn drop(&mut self) {
4807 DROP_VECTOR.with(|slot| {
4808 slot.borrow_mut()[self.k] -= 1;
4809 });
4810 }
4811 }
4812
4813 impl Clone for Droppable {
4814 fn clone(&self) -> Self {
4815 Droppable::new(self.k)
4816 }
4817 }
4818
4819 #[test]
4820 fn test_drops() {
4821 DROP_VECTOR.with(|slot| {
4822 *slot.borrow_mut() = vec![0; 200];
4823 });
4824
4825 {
4826 let mut m = HashMap::new();
4827
4828 DROP_VECTOR.with(|v| {
4829 for i in 0..200 {
4830 assert_eq!(v.borrow()[i], 0);
4831 }
4832 });
4833
4834 for i in 0..100 {
4835 let d1 = Droppable::new(i);
4836 let d2 = Droppable::new(i + 100);
4837 m.insert(d1, d2);
4838 }
4839
4840 DROP_VECTOR.with(|v| {
4841 for i in 0..200 {
4842 assert_eq!(v.borrow()[i], 1);
4843 }
4844 });
4845
4846 for i in 0..50 {
4847 let k = Droppable::new(i);
4848 let v = m.remove(&k);
4849
4850 assert!(v.is_some());
4851
4852 DROP_VECTOR.with(|v| {
4853 assert_eq!(v.borrow()[i], 1);
4854 assert_eq!(v.borrow()[i + 100], 1);
4855 });
4856 }
4857
4858 DROP_VECTOR.with(|v| {
4859 for i in 0..50 {
4860 assert_eq!(v.borrow()[i], 0);
4861 assert_eq!(v.borrow()[i + 100], 0);
4862 }
4863
4864 for i in 50..100 {
4865 assert_eq!(v.borrow()[i], 1);
4866 assert_eq!(v.borrow()[i + 100], 1);
4867 }
4868 });
4869 }
4870
4871 DROP_VECTOR.with(|v| {
4872 for i in 0..200 {
4873 assert_eq!(v.borrow()[i], 0);
4874 }
4875 });
4876 }
4877
4878 #[test]
4879 fn test_into_iter_drops() {
4880 DROP_VECTOR.with(|v| {
4881 *v.borrow_mut() = vec![0; 200];
4882 });
4883
4884 let hm = {
4885 let mut hm = HashMap::new();
4886
4887 DROP_VECTOR.with(|v| {
4888 for i in 0..200 {
4889 assert_eq!(v.borrow()[i], 0);
4890 }
4891 });
4892
4893 for i in 0..100 {
4894 let d1 = Droppable::new(i);
4895 let d2 = Droppable::new(i + 100);
4896 hm.insert(d1, d2);
4897 }
4898
4899 DROP_VECTOR.with(|v| {
4900 for i in 0..200 {
4901 assert_eq!(v.borrow()[i], 1);
4902 }
4903 });
4904
4905 hm
4906 };
4907
4908 // By the way, ensure that cloning doesn't screw up the dropping.
4909 drop(hm.clone());
4910
4911 {
4912 let mut half = hm.into_iter().take(50);
4913
4914 DROP_VECTOR.with(|v| {
4915 for i in 0..200 {
4916 assert_eq!(v.borrow()[i], 1);
4917 }
4918 });
4919
4920 for _ in half.by_ref() {}
4921
4922 DROP_VECTOR.with(|v| {
4923 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
4924
4925 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
4926
4927 assert_eq!(nk, 50);
4928 assert_eq!(nv, 50);
4929 });
4930 };
4931
4932 DROP_VECTOR.with(|v| {
4933 for i in 0..200 {
4934 assert_eq!(v.borrow()[i], 0);
4935 }
4936 });
4937 }
4938
4939 #[test]
4940 fn test_empty_remove() {
4941 let mut m: HashMap<i32, bool> = HashMap::new();
4942 assert_eq!(m.remove(&0), None);
4943 }
4944
4945 #[test]
4946 fn test_empty_entry() {
4947 let mut m: HashMap<i32, bool> = HashMap::new();
4948 match m.entry(0) {
4949 Occupied(_) => panic!(),
4950 Vacant(_) => {}
4951 }
4952 assert!(*m.entry(0).or_insert(true));
4953 assert_eq!(m.len(), 1);
4954 }
4955
4956 #[test]
4957 fn test_empty_entry_ref() {
4958 let mut m: HashMap<std::string::String, bool> = HashMap::new();
4959 match m.entry_ref("poneyland") {
4960 EntryRef::Occupied(_) => panic!(),
4961 EntryRef::Vacant(_) => {}
4962 }
4963 assert!(*m.entry_ref("poneyland").or_insert(true));
4964 assert_eq!(m.len(), 1);
4965 }
4966
4967 #[test]
4968 fn test_empty_iter() {
4969 let mut m: HashMap<i32, bool> = HashMap::new();
4970 assert_eq!(m.drain().next(), None);
4971 assert_eq!(m.keys().next(), None);
4972 assert_eq!(m.values().next(), None);
4973 assert_eq!(m.values_mut().next(), None);
4974 assert_eq!(m.iter().next(), None);
4975 assert_eq!(m.iter_mut().next(), None);
4976 assert_eq!(m.len(), 0);
4977 assert!(m.is_empty());
4978 assert_eq!(m.into_iter().next(), None);
4979 }
4980
4981 #[test]
4982 #[cfg_attr(miri, ignore)] // FIXME: takes too long
4983 fn test_lots_of_insertions() {
4984 let mut m = HashMap::new();
4985
4986 // Try this a few times to make sure we never screw up the hashmap's
4987 // internal state.
4988 for _ in 0..10 {
4989 assert!(m.is_empty());
4990
4991 for i in 1..1001 {
4992 assert!(m.insert(i, i).is_none());
4993
4994 for j in 1..=i {
4995 let r = m.get(&j);
4996 assert_eq!(r, Some(&j));
4997 }
4998
4999 for j in i + 1..1001 {
5000 let r = m.get(&j);
5001 assert_eq!(r, None);
5002 }
5003 }
5004
5005 for i in 1001..2001 {
5006 assert!(!m.contains_key(&i));
5007 }
5008
5009 // remove forwards
5010 for i in 1..1001 {
5011 assert!(m.remove(&i).is_some());
5012
5013 for j in 1..=i {
5014 assert!(!m.contains_key(&j));
5015 }
5016
5017 for j in i + 1..1001 {
5018 assert!(m.contains_key(&j));
5019 }
5020 }
5021
5022 for i in 1..1001 {
5023 assert!(!m.contains_key(&i));
5024 }
5025
5026 for i in 1..1001 {
5027 assert!(m.insert(i, i).is_none());
5028 }
5029
5030 // remove backwards
5031 for i in (1..1001).rev() {
5032 assert!(m.remove(&i).is_some());
5033
5034 for j in i..1001 {
5035 assert!(!m.contains_key(&j));
5036 }
5037
5038 for j in 1..i {
5039 assert!(m.contains_key(&j));
5040 }
5041 }
5042 }
5043 }
5044
5045 #[test]
5046 fn test_find_mut() {
5047 let mut m = HashMap::new();
5048 assert!(m.insert(1, 12).is_none());
5049 assert!(m.insert(2, 8).is_none());
5050 assert!(m.insert(5, 14).is_none());
5051 let new = 100;
5052 match m.get_mut(&5) {
5053 None => panic!(),
5054 Some(x) => *x = new,
5055 }
5056 assert_eq!(m.get(&5), Some(&new));
5057 }
5058
5059 #[test]
5060 fn test_insert_overwrite() {
5061 let mut m = HashMap::new();
5062 assert!(m.insert(1, 2).is_none());
5063 assert_eq!(*m.get(&1).unwrap(), 2);
5064 assert!(m.insert(1, 3).is_some());
5065 assert_eq!(*m.get(&1).unwrap(), 3);
5066 }
5067
5068 #[test]
5069 fn test_insert_conflicts() {
5070 let mut m = HashMap::with_capacity(4);
5071 assert!(m.insert(1, 2).is_none());
5072 assert!(m.insert(5, 3).is_none());
5073 assert!(m.insert(9, 4).is_none());
5074 assert_eq!(*m.get(&9).unwrap(), 4);
5075 assert_eq!(*m.get(&5).unwrap(), 3);
5076 assert_eq!(*m.get(&1).unwrap(), 2);
5077 }
5078
5079 #[test]
5080 fn test_conflict_remove() {
5081 let mut m = HashMap::with_capacity(4);
5082 assert!(m.insert(1, 2).is_none());
5083 assert_eq!(*m.get(&1).unwrap(), 2);
5084 assert!(m.insert(5, 3).is_none());
5085 assert_eq!(*m.get(&1).unwrap(), 2);
5086 assert_eq!(*m.get(&5).unwrap(), 3);
5087 assert!(m.insert(9, 4).is_none());
5088 assert_eq!(*m.get(&1).unwrap(), 2);
5089 assert_eq!(*m.get(&5).unwrap(), 3);
5090 assert_eq!(*m.get(&9).unwrap(), 4);
5091 assert!(m.remove(&1).is_some());
5092 assert_eq!(*m.get(&9).unwrap(), 4);
5093 assert_eq!(*m.get(&5).unwrap(), 3);
5094 }
5095
5096 #[test]
5097 fn test_insert_unique_unchecked() {
5098 let mut map = HashMap::new();
5099 let (k1, v1) = unsafe { map.insert_unique_unchecked(10, 11) };
5100 assert_eq!((&10, &mut 11), (k1, v1));
5101 let (k2, v2) = unsafe { map.insert_unique_unchecked(20, 21) };
5102 assert_eq!((&20, &mut 21), (k2, v2));
5103 assert_eq!(Some(&11), map.get(&10));
5104 assert_eq!(Some(&21), map.get(&20));
5105 assert_eq!(None, map.get(&30));
5106 }
5107
5108 #[test]
5109 fn test_is_empty() {
5110 let mut m = HashMap::with_capacity(4);
5111 assert!(m.insert(1, 2).is_none());
5112 assert!(!m.is_empty());
5113 assert!(m.remove(&1).is_some());
5114 assert!(m.is_empty());
5115 }
5116
5117 #[test]
5118 fn test_remove() {
5119 let mut m = HashMap::new();
5120 m.insert(1, 2);
5121 assert_eq!(m.remove(&1), Some(2));
5122 assert_eq!(m.remove(&1), None);
5123 }
5124
5125 #[test]
5126 fn test_remove_entry() {
5127 let mut m = HashMap::new();
5128 m.insert(1, 2);
5129 assert_eq!(m.remove_entry(&1), Some((1, 2)));
5130 assert_eq!(m.remove(&1), None);
5131 }
5132
5133 #[test]
5134 fn test_iterate() {
5135 let mut m = HashMap::with_capacity(4);
5136 for i in 0..32 {
5137 assert!(m.insert(i, i * 2).is_none());
5138 }
5139 assert_eq!(m.len(), 32);
5140
5141 let mut observed: u32 = 0;
5142
5143 for (k, v) in &m {
5144 assert_eq!(*v, *k * 2);
5145 observed |= 1 << *k;
5146 }
5147 assert_eq!(observed, 0xFFFF_FFFF);
5148 }
5149
5150 #[test]
5151 fn test_keys() {
5152 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5153 let map: HashMap<_, _> = vec.into_iter().collect();
5154 let keys: Vec<_> = map.keys().copied().collect();
5155 assert_eq!(keys.len(), 3);
5156 assert!(keys.contains(&1));
5157 assert!(keys.contains(&2));
5158 assert!(keys.contains(&3));
5159 }
5160
5161 #[test]
5162 fn test_values() {
5163 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5164 let map: HashMap<_, _> = vec.into_iter().collect();
5165 let values: Vec<_> = map.values().copied().collect();
5166 assert_eq!(values.len(), 3);
5167 assert!(values.contains(&'a'));
5168 assert!(values.contains(&'b'));
5169 assert!(values.contains(&'c'));
5170 }
5171
5172 #[test]
5173 fn test_values_mut() {
5174 let vec = vec![(1, 1), (2, 2), (3, 3)];
5175 let mut map: HashMap<_, _> = vec.into_iter().collect();
5176 for value in map.values_mut() {
5177 *value *= 2;
5178 }
5179 let values: Vec<_> = map.values().copied().collect();
5180 assert_eq!(values.len(), 3);
5181 assert!(values.contains(&2));
5182 assert!(values.contains(&4));
5183 assert!(values.contains(&6));
5184 }
5185
5186 #[test]
5187 fn test_into_keys() {
5188 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5189 let map: HashMap<_, _> = vec.into_iter().collect();
5190 let keys: Vec<_> = map.into_keys().collect();
5191
5192 assert_eq!(keys.len(), 3);
5193 assert!(keys.contains(&1));
5194 assert!(keys.contains(&2));
5195 assert!(keys.contains(&3));
5196 }
5197
5198 #[test]
5199 fn test_into_values() {
5200 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5201 let map: HashMap<_, _> = vec.into_iter().collect();
5202 let values: Vec<_> = map.into_values().collect();
5203
5204 assert_eq!(values.len(), 3);
5205 assert!(values.contains(&'a'));
5206 assert!(values.contains(&'b'));
5207 assert!(values.contains(&'c'));
5208 }
5209
5210 #[test]
5211 fn test_find() {
5212 let mut m = HashMap::new();
5213 assert!(m.get(&1).is_none());
5214 m.insert(1, 2);
5215 match m.get(&1) {
5216 None => panic!(),
5217 Some(v) => assert_eq!(*v, 2),
5218 }
5219 }
5220
5221 #[test]
5222 fn test_eq() {
5223 let mut m1 = HashMap::new();
5224 m1.insert(1, 2);
5225 m1.insert(2, 3);
5226 m1.insert(3, 4);
5227
5228 let mut m2 = HashMap::new();
5229 m2.insert(1, 2);
5230 m2.insert(2, 3);
5231
5232 assert!(m1 != m2);
5233
5234 m2.insert(3, 4);
5235
5236 assert_eq!(m1, m2);
5237 }
5238
5239 #[test]
5240 fn test_show() {
5241 let mut map = HashMap::new();
5242 let empty: HashMap<i32, i32> = HashMap::new();
5243
5244 map.insert(1, 2);
5245 map.insert(3, 4);
5246
5247 let map_str = format!("{map:?}");
5248
5249 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
5250 assert_eq!(format!("{empty:?}"), "{}");
5251 }
5252
5253 #[test]
5254 fn test_expand() {
5255 let mut m = HashMap::new();
5256
5257 assert_eq!(m.len(), 0);
5258 assert!(m.is_empty());
5259
5260 let mut i = 0;
5261 let old_raw_cap = m.raw_capacity();
5262 while old_raw_cap == m.raw_capacity() {
5263 m.insert(i, i);
5264 i += 1;
5265 }
5266
5267 assert_eq!(m.len(), i);
5268 assert!(!m.is_empty());
5269 }
5270
5271 #[test]
5272 fn test_behavior_resize_policy() {
5273 let mut m = HashMap::new();
5274
5275 assert_eq!(m.len(), 0);
5276 assert_eq!(m.raw_capacity(), 1);
5277 assert!(m.is_empty());
5278
5279 m.insert(0, 0);
5280 m.remove(&0);
5281 assert!(m.is_empty());
5282 let initial_raw_cap = m.raw_capacity();
5283 m.reserve(initial_raw_cap);
5284 let raw_cap = m.raw_capacity();
5285
5286 assert_eq!(raw_cap, initial_raw_cap * 2);
5287
5288 let mut i = 0;
5289 for _ in 0..raw_cap * 3 / 4 {
5290 m.insert(i, i);
5291 i += 1;
5292 }
5293 // three quarters full
5294
5295 assert_eq!(m.len(), i);
5296 assert_eq!(m.raw_capacity(), raw_cap);
5297
5298 for _ in 0..raw_cap / 4 {
5299 m.insert(i, i);
5300 i += 1;
5301 }
5302 // half full
5303
5304 let new_raw_cap = m.raw_capacity();
5305 assert_eq!(new_raw_cap, raw_cap * 2);
5306
5307 for _ in 0..raw_cap / 2 - 1 {
5308 i -= 1;
5309 m.remove(&i);
5310 assert_eq!(m.raw_capacity(), new_raw_cap);
5311 }
5312 // A little more than one quarter full.
5313 m.shrink_to_fit();
5314 assert_eq!(m.raw_capacity(), raw_cap);
5315 // again, a little more than half full
5316 for _ in 0..raw_cap / 2 {
5317 i -= 1;
5318 m.remove(&i);
5319 }
5320 m.shrink_to_fit();
5321
5322 assert_eq!(m.len(), i);
5323 assert!(!m.is_empty());
5324 assert_eq!(m.raw_capacity(), initial_raw_cap);
5325 }
5326
5327 #[test]
5328 fn test_reserve_shrink_to_fit() {
5329 let mut m = HashMap::new();
5330 m.insert(0, 0);
5331 m.remove(&0);
5332 assert!(m.capacity() >= m.len());
5333 for i in 0..128 {
5334 m.insert(i, i);
5335 }
5336 m.reserve(256);
5337
5338 let usable_cap = m.capacity();
5339 for i in 128..(128 + 256) {
5340 m.insert(i, i);
5341 assert_eq!(m.capacity(), usable_cap);
5342 }
5343
5344 for i in 100..(128 + 256) {
5345 assert_eq!(m.remove(&i), Some(i));
5346 }
5347 m.shrink_to_fit();
5348
5349 assert_eq!(m.len(), 100);
5350 assert!(!m.is_empty());
5351 assert!(m.capacity() >= m.len());
5352
5353 for i in 0..100 {
5354 assert_eq!(m.remove(&i), Some(i));
5355 }
5356 m.shrink_to_fit();
5357 m.insert(0, 0);
5358
5359 assert_eq!(m.len(), 1);
5360 assert!(m.capacity() >= m.len());
5361 assert_eq!(m.remove(&0), Some(0));
5362 }
5363
5364 #[test]
5365 fn test_from_iter() {
5366 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5367
5368 let map: HashMap<_, _> = xs.iter().copied().collect();
5369
5370 for &(k, v) in &xs {
5371 assert_eq!(map.get(&k), Some(&v));
5372 }
5373
5374 assert_eq!(map.iter().len(), xs.len() - 1);
5375 }
5376
5377 #[test]
5378 fn test_size_hint() {
5379 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5380
5381 let map: HashMap<_, _> = xs.iter().copied().collect();
5382
5383 let mut iter = map.iter();
5384
5385 for _ in iter.by_ref().take(3) {}
5386
5387 assert_eq!(iter.size_hint(), (3, Some(3)));
5388 }
5389
5390 #[test]
5391 fn test_iter_len() {
5392 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5393
5394 let map: HashMap<_, _> = xs.iter().copied().collect();
5395
5396 let mut iter = map.iter();
5397
5398 for _ in iter.by_ref().take(3) {}
5399
5400 assert_eq!(iter.len(), 3);
5401 }
5402
5403 #[test]
5404 fn test_mut_size_hint() {
5405 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5406
5407 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5408
5409 let mut iter = map.iter_mut();
5410
5411 for _ in iter.by_ref().take(3) {}
5412
5413 assert_eq!(iter.size_hint(), (3, Some(3)));
5414 }
5415
5416 #[test]
5417 fn test_iter_mut_len() {
5418 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5419
5420 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5421
5422 let mut iter = map.iter_mut();
5423
5424 for _ in iter.by_ref().take(3) {}
5425
5426 assert_eq!(iter.len(), 3);
5427 }
5428
5429 #[test]
5430 fn test_index() {
5431 let mut map = HashMap::new();
5432
5433 map.insert(1, 2);
5434 map.insert(2, 1);
5435 map.insert(3, 4);
5436
5437 assert_eq!(map[&2], 1);
5438 }
5439
5440 #[test]
5441 #[should_panic]
5442 fn test_index_nonexistent() {
5443 let mut map = HashMap::new();
5444
5445 map.insert(1, 2);
5446 map.insert(2, 1);
5447 map.insert(3, 4);
5448
5449 #[allow(clippy::no_effect)] // false positive lint
5450 map[&4];
5451 }
5452
5453 #[test]
5454 fn test_entry() {
5455 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
5456
5457 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5458
5459 // Existing key (insert)
5460 match map.entry(1) {
5461 Vacant(_) => unreachable!(),
5462 Occupied(mut view) => {
5463 assert_eq!(view.get(), &10);
5464 assert_eq!(view.insert(100), 10);
5465 }
5466 }
5467 assert_eq!(map.get(&1).unwrap(), &100);
5468 assert_eq!(map.len(), 6);
5469
5470 // Existing key (update)
5471 match map.entry(2) {
5472 Vacant(_) => unreachable!(),
5473 Occupied(mut view) => {
5474 let v = view.get_mut();
5475 let new_v = (*v) * 10;
5476 *v = new_v;
5477 }
5478 }
5479 assert_eq!(map.get(&2).unwrap(), &200);
5480 assert_eq!(map.len(), 6);
5481
5482 // Existing key (take)
5483 match map.entry(3) {
5484 Vacant(_) => unreachable!(),
5485 Occupied(view) => {
5486 assert_eq!(view.remove(), 30);
5487 }
5488 }
5489 assert_eq!(map.get(&3), None);
5490 assert_eq!(map.len(), 5);
5491
5492 // Inexistent key (insert)
5493 match map.entry(10) {
5494 Occupied(_) => unreachable!(),
5495 Vacant(view) => {
5496 assert_eq!(*view.insert(1000), 1000);
5497 }
5498 }
5499 assert_eq!(map.get(&10).unwrap(), &1000);
5500 assert_eq!(map.len(), 6);
5501 }
5502
5503 #[test]
5504 fn test_entry_ref() {
5505 let xs = [
5506 ("One".to_owned(), 10),
5507 ("Two".to_owned(), 20),
5508 ("Three".to_owned(), 30),
5509 ("Four".to_owned(), 40),
5510 ("Five".to_owned(), 50),
5511 ("Six".to_owned(), 60),
5512 ];
5513
5514 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
5515
5516 // Existing key (insert)
5517 match map.entry_ref("One") {
5518 EntryRef::Vacant(_) => unreachable!(),
5519 EntryRef::Occupied(mut view) => {
5520 assert_eq!(view.get(), &10);
5521 assert_eq!(view.insert(100), 10);
5522 }
5523 }
5524 assert_eq!(map.get("One").unwrap(), &100);
5525 assert_eq!(map.len(), 6);
5526
5527 // Existing key (update)
5528 match map.entry_ref("Two") {
5529 EntryRef::Vacant(_) => unreachable!(),
5530 EntryRef::Occupied(mut view) => {
5531 let v = view.get_mut();
5532 let new_v = (*v) * 10;
5533 *v = new_v;
5534 }
5535 }
5536 assert_eq!(map.get("Two").unwrap(), &200);
5537 assert_eq!(map.len(), 6);
5538
5539 // Existing key (take)
5540 match map.entry_ref("Three") {
5541 EntryRef::Vacant(_) => unreachable!(),
5542 EntryRef::Occupied(view) => {
5543 assert_eq!(view.remove(), 30);
5544 }
5545 }
5546 assert_eq!(map.get("Three"), None);
5547 assert_eq!(map.len(), 5);
5548
5549 // Inexistent key (insert)
5550 match map.entry_ref("Ten") {
5551 EntryRef::Occupied(_) => unreachable!(),
5552 EntryRef::Vacant(view) => {
5553 assert_eq!(*view.insert(1000), 1000);
5554 }
5555 }
5556 assert_eq!(map.get("Ten").unwrap(), &1000);
5557 assert_eq!(map.len(), 6);
5558 }
5559
5560 #[test]
5561 fn test_entry_take_doesnt_corrupt() {
5562 #![allow(deprecated)] //rand
5563 // Test for #19292
5564 fn check(m: &HashMap<i32, ()>) {
5565 for k in m.keys() {
5566 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5567 }
5568 }
5569
5570 let mut m = HashMap::new();
5571
5572 let mut rng = {
5573 let seed = u64::from_le_bytes(*b"testseed");
5574 SmallRng::seed_from_u64(seed)
5575 };
5576
5577 // Populate the map with some items.
5578 for _ in 0..50 {
5579 let x = rng.gen_range(-10..10);
5580 m.insert(x, ());
5581 }
5582
5583 for _ in 0..1000 {
5584 let x = rng.gen_range(-10..10);
5585 match m.entry(x) {
5586 Vacant(_) => {}
5587 Occupied(e) => {
5588 e.remove();
5589 }
5590 }
5591
5592 check(&m);
5593 }
5594 }
5595
5596 #[test]
5597 fn test_entry_ref_take_doesnt_corrupt() {
5598 #![allow(deprecated)] //rand
5599 // Test for #19292
5600 fn check(m: &HashMap<std::string::String, ()>) {
5601 for k in m.keys() {
5602 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5603 }
5604 }
5605
5606 let mut m = HashMap::new();
5607
5608 let mut rng = {
5609 let seed = u64::from_le_bytes(*b"testseed");
5610 SmallRng::seed_from_u64(seed)
5611 };
5612
5613 // Populate the map with some items.
5614 for _ in 0..50 {
5615 let mut x = std::string::String::with_capacity(1);
5616 x.push(rng.gen_range('a'..='z'));
5617 m.insert(x, ());
5618 }
5619
5620 for _ in 0..1000 {
5621 let mut x = std::string::String::with_capacity(1);
5622 x.push(rng.gen_range('a'..='z'));
5623 match m.entry_ref(x.as_str()) {
5624 EntryRef::Vacant(_) => {}
5625 EntryRef::Occupied(e) => {
5626 e.remove();
5627 }
5628 }
5629
5630 check(&m);
5631 }
5632 }
5633
5634 #[test]
5635 fn test_extend_ref_k_ref_v() {
5636 let mut a = HashMap::new();
5637 a.insert(1, "one");
5638 let mut b = HashMap::new();
5639 b.insert(2, "two");
5640 b.insert(3, "three");
5641
5642 a.extend(&b);
5643
5644 assert_eq!(a.len(), 3);
5645 assert_eq!(a[&1], "one");
5646 assert_eq!(a[&2], "two");
5647 assert_eq!(a[&3], "three");
5648 }
5649
5650 #[test]
5651 #[allow(clippy::needless_borrow)]
5652 fn test_extend_ref_kv_tuple() {
5653 use std::ops::AddAssign;
5654 let mut a = HashMap::new();
5655 a.insert(0, 0);
5656
5657 fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
5658 let mut outs: [(T, T); N] = [(start, start); N];
5659 let mut element = step;
5660 outs.iter_mut().skip(1).for_each(|(k, v)| {
5661 *k += element;
5662 *v += element;
5663 element += step;
5664 });
5665 outs
5666 }
5667
5668 let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
5669 let iter = for_iter.iter();
5670 let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
5671 a.extend(iter);
5672 a.extend(&vec);
5673 a.extend(create_arr::<i32, 100>(200, 1));
5674
5675 assert_eq!(a.len(), 300);
5676
5677 for item in 0..300 {
5678 assert_eq!(a[&item], item);
5679 }
5680 }
5681
5682 #[test]
5683 fn test_capacity_not_less_than_len() {
5684 let mut a = HashMap::new();
5685 let mut item = 0;
5686
5687 for _ in 0..116 {
5688 a.insert(item, 0);
5689 item += 1;
5690 }
5691
5692 assert!(a.capacity() > a.len());
5693
5694 let free = a.capacity() - a.len();
5695 for _ in 0..free {
5696 a.insert(item, 0);
5697 item += 1;
5698 }
5699
5700 assert_eq!(a.len(), a.capacity());
5701
5702 // Insert at capacity should cause allocation.
5703 a.insert(item, 0);
5704 assert!(a.capacity() > a.len());
5705 }
5706
5707 #[test]
5708 fn test_occupied_entry_key() {
5709 let mut a = HashMap::new();
5710 let key = "hello there";
5711 let value = "value goes here";
5712 assert!(a.is_empty());
5713 a.insert(key, value);
5714 assert_eq!(a.len(), 1);
5715 assert_eq!(a[key], value);
5716
5717 match a.entry(key) {
5718 Vacant(_) => panic!(),
5719 Occupied(e) => assert_eq!(key, *e.key()),
5720 }
5721 assert_eq!(a.len(), 1);
5722 assert_eq!(a[key], value);
5723 }
5724
5725 #[test]
5726 fn test_occupied_entry_ref_key() {
5727 let mut a = HashMap::new();
5728 let key = "hello there";
5729 let value = "value goes here";
5730 assert!(a.is_empty());
5731 a.insert(key.to_owned(), value);
5732 assert_eq!(a.len(), 1);
5733 assert_eq!(a[key], value);
5734
5735 match a.entry_ref(key) {
5736 EntryRef::Vacant(_) => panic!(),
5737 EntryRef::Occupied(e) => assert_eq!(key, e.key()),
5738 }
5739 assert_eq!(a.len(), 1);
5740 assert_eq!(a[key], value);
5741 }
5742
5743 #[test]
5744 fn test_vacant_entry_key() {
5745 let mut a = HashMap::new();
5746 let key = "hello there";
5747 let value = "value goes here";
5748
5749 assert!(a.is_empty());
5750 match a.entry(key) {
5751 Occupied(_) => panic!(),
5752 Vacant(e) => {
5753 assert_eq!(key, *e.key());
5754 e.insert(value);
5755 }
5756 }
5757 assert_eq!(a.len(), 1);
5758 assert_eq!(a[key], value);
5759 }
5760
5761 #[test]
5762 fn test_vacant_entry_ref_key() {
5763 let mut a: HashMap<std::string::String, &str> = HashMap::new();
5764 let key = "hello there";
5765 let value = "value goes here";
5766
5767 assert!(a.is_empty());
5768 match a.entry_ref(key) {
5769 EntryRef::Occupied(_) => panic!(),
5770 EntryRef::Vacant(e) => {
5771 assert_eq!(key, e.key());
5772 e.insert(value);
5773 }
5774 }
5775 assert_eq!(a.len(), 1);
5776 assert_eq!(a[key], value);
5777 }
5778
5779 #[test]
5780 fn test_occupied_entry_replace_entry_with() {
5781 let mut a = HashMap::new();
5782
5783 let key = "a key";
5784 let value = "an initial value";
5785 let new_value = "a new value";
5786
5787 let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
5788 assert_eq!(k, &key);
5789 assert_eq!(v, value);
5790 Some(new_value)
5791 });
5792
5793 match entry {
5794 Occupied(e) => {
5795 assert_eq!(e.key(), &key);
5796 assert_eq!(e.get(), &new_value);
5797 }
5798 Vacant(_) => panic!(),
5799 }
5800
5801 assert_eq!(a[key], new_value);
5802 assert_eq!(a.len(), 1);
5803
5804 let entry = match a.entry(key) {
5805 Occupied(e) => e.replace_entry_with(|k, v| {
5806 assert_eq!(k, &key);
5807 assert_eq!(v, new_value);
5808 None
5809 }),
5810 Vacant(_) => panic!(),
5811 };
5812
5813 match entry {
5814 Vacant(e) => assert_eq!(e.key(), &key),
5815 Occupied(_) => panic!(),
5816 }
5817
5818 assert!(!a.contains_key(key));
5819 assert_eq!(a.len(), 0);
5820 }
5821
5822 #[test]
5823 fn test_entry_and_replace_entry_with() {
5824 let mut a = HashMap::new();
5825
5826 let key = "a key";
5827 let value = "an initial value";
5828 let new_value = "a new value";
5829
5830 let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
5831
5832 match entry {
5833 Vacant(e) => assert_eq!(e.key(), &key),
5834 Occupied(_) => panic!(),
5835 }
5836
5837 a.insert(key, value);
5838
5839 let entry = a.entry(key).and_replace_entry_with(|k, v| {
5840 assert_eq!(k, &key);
5841 assert_eq!(v, value);
5842 Some(new_value)
5843 });
5844
5845 match entry {
5846 Occupied(e) => {
5847 assert_eq!(e.key(), &key);
5848 assert_eq!(e.get(), &new_value);
5849 }
5850 Vacant(_) => panic!(),
5851 }
5852
5853 assert_eq!(a[key], new_value);
5854 assert_eq!(a.len(), 1);
5855
5856 let entry = a.entry(key).and_replace_entry_with(|k, v| {
5857 assert_eq!(k, &key);
5858 assert_eq!(v, new_value);
5859 None
5860 });
5861
5862 match entry {
5863 Vacant(e) => assert_eq!(e.key(), &key),
5864 Occupied(_) => panic!(),
5865 }
5866
5867 assert!(!a.contains_key(key));
5868 assert_eq!(a.len(), 0);
5869 }
5870
5871 #[test]
5872 fn test_replace_entry_with_doesnt_corrupt() {
5873 #![allow(deprecated)] //rand
5874 // Test for #19292
5875 fn check(m: &HashMap<i32, ()>) {
5876 for k in m.keys() {
5877 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5878 }
5879 }
5880
5881 let mut m = HashMap::new();
5882
5883 let mut rng = {
5884 let seed = u64::from_le_bytes(*b"testseed");
5885 SmallRng::seed_from_u64(seed)
5886 };
5887
5888 // Populate the map with some items.
5889 for _ in 0..50 {
5890 let x = rng.gen_range(-10..10);
5891 m.insert(x, ());
5892 }
5893
5894 for _ in 0..1000 {
5895 let x = rng.gen_range(-10..10);
5896 m.entry(x).and_replace_entry_with(|_, _| None);
5897 check(&m);
5898 }
5899 }
5900
5901 #[test]
5902 fn test_retain() {
5903 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
5904
5905 map.retain(|&k, _| k % 2 == 0);
5906 assert_eq!(map.len(), 50);
5907 assert_eq!(map[&2], 20);
5908 assert_eq!(map[&4], 40);
5909 assert_eq!(map[&6], 60);
5910 }
5911
5912 #[test]
5913 fn test_extract_if() {
5914 {
5915 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
5916 let drained = map.extract_if(|&k, _| k % 2 == 0);
5917 let mut out = drained.collect::<Vec<_>>();
5918 out.sort_unstable();
5919 assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
5920 assert_eq!(map.len(), 4);
5921 }
5922 {
5923 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
5924 map.extract_if(|&k, _| k % 2 == 0).for_each(drop);
5925 assert_eq!(map.len(), 4);
5926 }
5927 }
5928
5929 #[test]
5930 #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613)
5931 fn test_try_reserve() {
5932 use crate::TryReserveError::{AllocError, CapacityOverflow};
5933
5934 const MAX_ISIZE: usize = isize::MAX as usize;
5935
5936 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
5937
5938 if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
5939 } else {
5940 panic!("usize::MAX should trigger an overflow!");
5941 }
5942
5943 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
5944 } else {
5945 panic!("isize::MAX should trigger an overflow!");
5946 }
5947
5948 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
5949 } else {
5950 // This may succeed if there is enough free memory. Attempt to
5951 // allocate a few more hashmaps to ensure the allocation will fail.
5952 let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
5953 let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
5954 let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
5955 let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
5956 let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
5957 if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
5958 } else {
5959 panic!("isize::MAX / 5 should trigger an OOM!");
5960 }
5961 }
5962 }
5963
5964 #[test]
5965 fn test_const_with_hasher() {
5966 use core::hash::BuildHasher;
5967 use std::collections::hash_map::DefaultHasher;
5968
5969 #[derive(Clone)]
5970 struct MyHasher;
5971 impl BuildHasher for MyHasher {
5972 type Hasher = DefaultHasher;
5973
5974 fn build_hasher(&self) -> DefaultHasher {
5975 DefaultHasher::new()
5976 }
5977 }
5978
5979 const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> =
5980 HashMap::with_hasher(MyHasher);
5981
5982 let mut map = EMPTY_MAP;
5983 map.insert(17, "seventeen".to_owned());
5984 assert_eq!("seventeen", map[&17]);
5985 }
5986
5987 #[test]
5988 fn test_get_many_mut() {
5989 let mut map = HashMap::new();
5990 map.insert("foo".to_owned(), 0);
5991 map.insert("bar".to_owned(), 10);
5992 map.insert("baz".to_owned(), 20);
5993 map.insert("qux".to_owned(), 30);
5994
5995 let xs = map.get_many_mut(["foo", "qux"]);
5996 assert_eq!(xs, [Some(&mut 0), Some(&mut 30)]);
5997
5998 let xs = map.get_many_mut(["foo", "dud"]);
5999 assert_eq!(xs, [Some(&mut 0), None]);
6000
6001 let ys = map.get_many_key_value_mut(["bar", "baz"]);
6002 assert_eq!(
6003 ys,
6004 [
6005 Some((&"bar".to_owned(), &mut 10)),
6006 Some((&"baz".to_owned(), &mut 20))
6007 ],
6008 );
6009
6010 let ys = map.get_many_key_value_mut(["bar", "dip"]);
6011 assert_eq!(ys, [Some((&"bar".to_string(), &mut 10)), None]);
6012 }
6013
6014 #[test]
6015 #[should_panic = "duplicate keys found"]
6016 fn test_get_many_mut_duplicate() {
6017 let mut map = HashMap::new();
6018 map.insert("foo".to_owned(), 0);
6019
6020 let _xs = map.get_many_mut(["foo", "foo"]);
6021 }
6022
6023 #[test]
6024 #[should_panic = "panic in drop"]
6025 fn test_clone_from_double_drop() {
6026 #[derive(Clone)]
6027 struct CheckedDrop {
6028 panic_in_drop: bool,
6029 dropped: bool,
6030 }
6031 impl Drop for CheckedDrop {
6032 fn drop(&mut self) {
6033 if self.panic_in_drop {
6034 self.dropped = true;
6035 panic!("panic in drop");
6036 }
6037 if self.dropped {
6038 panic!("double drop");
6039 }
6040 self.dropped = true;
6041 }
6042 }
6043 const DISARMED: CheckedDrop = CheckedDrop {
6044 panic_in_drop: false,
6045 dropped: false,
6046 };
6047 const ARMED: CheckedDrop = CheckedDrop {
6048 panic_in_drop: true,
6049 dropped: false,
6050 };
6051
6052 let mut map1 = HashMap::new();
6053 map1.insert(1, DISARMED);
6054 map1.insert(2, DISARMED);
6055 map1.insert(3, DISARMED);
6056 map1.insert(4, DISARMED);
6057
6058 let mut map2 = HashMap::new();
6059 map2.insert(1, DISARMED);
6060 map2.insert(2, ARMED);
6061 map2.insert(3, DISARMED);
6062 map2.insert(4, DISARMED);
6063
6064 map2.clone_from(&map1);
6065 }
6066
6067 #[test]
6068 #[should_panic = "panic in clone"]
6069 fn test_clone_from_memory_leaks() {
6070 use alloc::vec::Vec;
6071
6072 struct CheckedClone {
6073 panic_in_clone: bool,
6074 need_drop: Vec<i32>,
6075 }
6076 impl Clone for CheckedClone {
6077 fn clone(&self) -> Self {
6078 if self.panic_in_clone {
6079 panic!("panic in clone")
6080 }
6081 Self {
6082 panic_in_clone: self.panic_in_clone,
6083 need_drop: self.need_drop.clone(),
6084 }
6085 }
6086 }
6087 let mut map1 = HashMap::new();
6088 map1.insert(
6089 1,
6090 CheckedClone {
6091 panic_in_clone: false,
6092 need_drop: vec![0, 1, 2],
6093 },
6094 );
6095 map1.insert(
6096 2,
6097 CheckedClone {
6098 panic_in_clone: false,
6099 need_drop: vec![3, 4, 5],
6100 },
6101 );
6102 map1.insert(
6103 3,
6104 CheckedClone {
6105 panic_in_clone: true,
6106 need_drop: vec![6, 7, 8],
6107 },
6108 );
6109 let _map2 = map1.clone();
6110 }
6111
6112 struct MyAllocInner {
6113 drop_count: Arc<AtomicI8>,
6114 }
6115
6116 #[derive(Clone)]
6117 struct MyAlloc {
6118 _inner: Arc<MyAllocInner>,
6119 }
6120
6121 impl MyAlloc {
6122 fn new(drop_count: Arc<AtomicI8>) -> Self {
6123 MyAlloc {
6124 _inner: Arc::new(MyAllocInner { drop_count }),
6125 }
6126 }
6127 }
6128
6129 impl Drop for MyAllocInner {
6130 fn drop(&mut self) {
6131 println!("MyAlloc freed.");
6132 self.drop_count.fetch_sub(1, Ordering::SeqCst);
6133 }
6134 }
6135
6136 unsafe impl Allocator for MyAlloc {
6137 fn allocate(&self, layout: Layout) -> std::result::Result<NonNull<[u8]>, AllocError> {
6138 let g = Global;
6139 g.allocate(layout)
6140 }
6141
6142 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
6143 let g = Global;
6144 g.deallocate(ptr, layout)
6145 }
6146 }
6147
6148 #[test]
6149 fn test_hashmap_into_iter_bug() {
6150 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
6151
6152 {
6153 let mut map = HashMap::with_capacity_in(10, MyAlloc::new(dropped.clone()));
6154 for i in 0..10 {
6155 map.entry(i).or_insert_with(|| "i".to_string());
6156 }
6157
6158 for (k, v) in map {
6159 println!("{}, {}", k, v);
6160 }
6161 }
6162
6163 // All allocator clones should already be dropped.
6164 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6165 }
6166
6167 #[derive(Debug)]
6168 struct CheckedCloneDrop<T> {
6169 panic_in_clone: bool,
6170 panic_in_drop: bool,
6171 dropped: bool,
6172 data: T,
6173 }
6174
6175 impl<T> CheckedCloneDrop<T> {
6176 fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
6177 CheckedCloneDrop {
6178 panic_in_clone,
6179 panic_in_drop,
6180 dropped: false,
6181 data,
6182 }
6183 }
6184 }
6185
6186 impl<T: Clone> Clone for CheckedCloneDrop<T> {
6187 fn clone(&self) -> Self {
6188 if self.panic_in_clone {
6189 panic!("panic in clone")
6190 }
6191 Self {
6192 panic_in_clone: self.panic_in_clone,
6193 panic_in_drop: self.panic_in_drop,
6194 dropped: self.dropped,
6195 data: self.data.clone(),
6196 }
6197 }
6198 }
6199
6200 impl<T> Drop for CheckedCloneDrop<T> {
6201 fn drop(&mut self) {
6202 if self.panic_in_drop {
6203 self.dropped = true;
6204 panic!("panic in drop");
6205 }
6206 if self.dropped {
6207 panic!("double drop");
6208 }
6209 self.dropped = true;
6210 }
6211 }
6212
6213 /// Return hashmap with predefined distribution of elements.
6214 /// All elements will be located in the same order as elements
6215 /// returned by iterator.
6216 ///
6217 /// This function does not panic, but returns an error as a `String`
6218 /// to distinguish between a test panic and an error in the input data.
6219 fn get_test_map<I, T, A>(
6220 iter: I,
6221 mut fun: impl FnMut(u64) -> T,
6222 alloc: A,
6223 ) -> Result<HashMap<u64, CheckedCloneDrop<T>, DefaultHashBuilder, A>, String>
6224 where
6225 I: Iterator<Item = (bool, bool)> + Clone + ExactSizeIterator,
6226 A: Allocator,
6227 T: PartialEq + core::fmt::Debug,
6228 {
6229 use crate::scopeguard::guard;
6230
6231 let mut map: HashMap<u64, CheckedCloneDrop<T>, _, A> =
6232 HashMap::with_capacity_in(iter.size_hint().0, alloc);
6233 {
6234 let mut guard = guard(&mut map, |map| {
6235 for (_, value) in map.iter_mut() {
6236 value.panic_in_drop = false
6237 }
6238 });
6239
6240 let mut count = 0;
6241 // Hash and Key must be equal to each other for controlling the elements placement.
6242 for (panic_in_clone, panic_in_drop) in iter.clone() {
6243 if core::mem::needs_drop::<T>() && panic_in_drop {
6244 return Err(String::from(
6245 "panic_in_drop can be set with a type that doesn't need to be dropped",
6246 ));
6247 }
6248 guard.table.insert(
6249 count,
6250 (
6251 count,
6252 CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)),
6253 ),
6254 |(k, _)| *k,
6255 );
6256 count += 1;
6257 }
6258
6259 // Let's check that all elements are located as we wanted
6260 let mut check_count = 0;
6261 for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) {
6262 if *key != check_count {
6263 return Err(format!(
6264 "key != check_count,\nkey: `{}`,\ncheck_count: `{}`",
6265 key, check_count
6266 ));
6267 }
6268 if value.dropped
6269 || value.panic_in_clone != panic_in_clone
6270 || value.panic_in_drop != panic_in_drop
6271 || value.data != fun(check_count)
6272 {
6273 return Err(format!(
6274 "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \
6275 `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`",
6276 value, panic_in_clone, panic_in_drop, false, fun(check_count)
6277 ));
6278 }
6279 check_count += 1;
6280 }
6281
6282 if guard.len() != check_count as usize {
6283 return Err(format!(
6284 "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`",
6285 guard.len(),
6286 check_count
6287 ));
6288 }
6289
6290 if count != check_count {
6291 return Err(format!(
6292 "count != check_count,\ncount: `{}`,\ncheck_count: `{}`",
6293 count, check_count
6294 ));
6295 }
6296 core::mem::forget(guard);
6297 }
6298 Ok(map)
6299 }
6300
6301 const DISARMED: bool = false;
6302 const ARMED: bool = true;
6303
6304 const ARMED_FLAGS: [bool; 8] = [
6305 DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6306 ];
6307
6308 const DISARMED_FLAGS: [bool; 8] = [
6309 DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6310 ];
6311
6312 #[test]
6313 #[should_panic = "panic in clone"]
6314 fn test_clone_memory_leaks_and_double_drop_one() {
6315 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6316
6317 {
6318 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6319
6320 let map: HashMap<u64, CheckedCloneDrop<Vec<u64>>, DefaultHashBuilder, MyAlloc> =
6321 match get_test_map(
6322 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6323 |n| vec![n],
6324 MyAlloc::new(dropped.clone()),
6325 ) {
6326 Ok(map) => map,
6327 Err(msg) => panic!("{msg}"),
6328 };
6329
6330 // Clone should normally clone a few elements, and then (when the
6331 // clone function panics), deallocate both its own memory, memory
6332 // of `dropped: Arc<AtomicI8>` and the memory of already cloned
6333 // elements (Vec<i32> memory inside CheckedCloneDrop).
6334 let _map2 = map.clone();
6335 }
6336 }
6337
6338 #[test]
6339 #[should_panic = "panic in drop"]
6340 fn test_clone_memory_leaks_and_double_drop_two() {
6341 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6342
6343 {
6344 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6345
6346 let map: HashMap<u64, CheckedCloneDrop<u64>, DefaultHashBuilder, _> = match get_test_map(
6347 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6348 |n| n,
6349 MyAlloc::new(dropped.clone()),
6350 ) {
6351 Ok(map) => map,
6352 Err(msg) => panic!("{msg}"),
6353 };
6354
6355 let mut map2 = match get_test_map(
6356 DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS),
6357 |n| n,
6358 MyAlloc::new(dropped.clone()),
6359 ) {
6360 Ok(map) => map,
6361 Err(msg) => panic!("{msg}"),
6362 };
6363
6364 // The `clone_from` should try to drop the elements of `map2` without
6365 // double drop and leaking the allocator. Elements that have not been
6366 // dropped leak their memory.
6367 map2.clone_from(&map);
6368 }
6369 }
6370
6371 /// We check that we have a working table if the clone operation from another
6372 /// thread ended in a panic (when buckets of maps are equal to each other).
6373 #[test]
6374 fn test_catch_panic_clone_from_when_len_is_equal() {
6375 use std::thread;
6376
6377 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6378
6379 {
6380 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6381
6382 let mut map = match get_test_map(
6383 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6384 |n| vec![n],
6385 MyAlloc::new(dropped.clone()),
6386 ) {
6387 Ok(map) => map,
6388 Err(msg) => panic!("{msg}"),
6389 };
6390
6391 thread::scope(|s| {
6392 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6393 let scope_map =
6394 match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| vec![n * 2], MyAlloc::new(dropped.clone())) {
6395 Ok(map) => map,
6396 Err(msg) => return msg,
6397 };
6398 if map.table.buckets() != scope_map.table.buckets() {
6399 return format!(
6400 "map.table.buckets() != scope_map.table.buckets(),\nleft: `{}`,\nright: `{}`",
6401 map.table.buckets(), scope_map.table.buckets()
6402 );
6403 }
6404 map.clone_from(&scope_map);
6405 "We must fail the cloning!!!".to_owned()
6406 });
6407 if let Ok(msg) = result.join() {
6408 panic!("{msg}")
6409 }
6410 });
6411
6412 // Let's check that all iterators work fine and do not return elements
6413 // (especially `RawIterRange`, which does not depend on the number of
6414 // elements in the table, but looks directly at the control bytes)
6415 //
6416 // SAFETY: We know for sure that `RawTable` will outlive
6417 // the returned `RawIter / RawIterRange` iterator.
6418 assert_eq!(map.len(), 0);
6419 assert_eq!(map.iter().count(), 0);
6420 assert_eq!(unsafe { map.table.iter().count() }, 0);
6421 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6422
6423 for idx in 0..map.table.buckets() {
6424 let idx = idx as u64;
6425 assert!(
6426 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6427 "Index: {idx}"
6428 );
6429 }
6430 }
6431
6432 // All allocator clones should already be dropped.
6433 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6434 }
6435
6436 /// We check that we have a working table if the clone operation from another
6437 /// thread ended in a panic (when buckets of maps are not equal to each other).
6438 #[test]
6439 fn test_catch_panic_clone_from_when_len_is_not_equal() {
6440 use std::thread;
6441
6442 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6443
6444 {
6445 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6446
6447 let mut map = match get_test_map(
6448 [DISARMED].into_iter().zip([DISARMED]),
6449 |n| vec![n],
6450 MyAlloc::new(dropped.clone()),
6451 ) {
6452 Ok(map) => map,
6453 Err(msg) => panic!("{msg}"),
6454 };
6455
6456 thread::scope(|s| {
6457 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6458 let scope_map = match get_test_map(
6459 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6460 |n| vec![n * 2],
6461 MyAlloc::new(dropped.clone()),
6462 ) {
6463 Ok(map) => map,
6464 Err(msg) => return msg,
6465 };
6466 if map.table.buckets() == scope_map.table.buckets() {
6467 return format!(
6468 "map.table.buckets() == scope_map.table.buckets(): `{}`",
6469 map.table.buckets()
6470 );
6471 }
6472 map.clone_from(&scope_map);
6473 "We must fail the cloning!!!".to_owned()
6474 });
6475 if let Ok(msg) = result.join() {
6476 panic!("{msg}")
6477 }
6478 });
6479
6480 // Let's check that all iterators work fine and do not return elements
6481 // (especially `RawIterRange`, which does not depend on the number of
6482 // elements in the table, but looks directly at the control bytes)
6483 //
6484 // SAFETY: We know for sure that `RawTable` will outlive
6485 // the returned `RawIter / RawIterRange` iterator.
6486 assert_eq!(map.len(), 0);
6487 assert_eq!(map.iter().count(), 0);
6488 assert_eq!(unsafe { map.table.iter().count() }, 0);
6489 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6490
6491 for idx in 0..map.table.buckets() {
6492 let idx = idx as u64;
6493 assert!(
6494 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6495 "Index: {idx}"
6496 );
6497 }
6498 }
6499
6500 // All allocator clones should already be dropped.
6501 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6502 }
6503
6504 #[test]
6505 fn test_allocation_info() {
6506 assert_eq!(HashMap::<(), ()>::new().allocation_size(), 0);
6507 assert_eq!(HashMap::<u32, u32>::new().allocation_size(), 0);
6508 assert!(
6509 HashMap::<u32, u32>::with_capacity(1).allocation_size() > core::mem::size_of::<u32>()
6510 );
6511 }
6512}