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 if !self.table.is_empty() {
1310 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1311 match self.table.get(hash, equivalent_key(k)) {
1312 Some((_, v)) => Some(v),
1313 None => None,
1314 }
1315 } else {
1316 None
1317 }
1318 }
1319
1320 /// Returns the key-value pair corresponding to the supplied key.
1321 ///
1322 /// The supplied key may be any borrowed form of the map's key type, but
1323 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1324 /// the key type.
1325 ///
1326 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1327 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1328 ///
1329 /// # Examples
1330 ///
1331 /// ```
1332 /// use hashbrown::HashMap;
1333 ///
1334 /// let mut map = HashMap::new();
1335 /// map.insert(1, "a");
1336 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1337 /// assert_eq!(map.get_key_value(&2), None);
1338 /// ```
1339 #[inline]
1340 pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
1341 where
1342 Q: Hash + Equivalent<K> + ?Sized,
1343 {
1344 // Avoid `Option::map` because it bloats LLVM IR.
1345 if !self.table.is_empty() {
1346 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1347 match self.table.get(hash, equivalent_key(k)) {
1348 Some((key, value)) => Some((key, value)),
1349 None => None,
1350 }
1351 } else {
1352 None
1353 }
1354 }
1355
1356 /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
1357 ///
1358 /// The supplied key may be any borrowed form of the map's key type, but
1359 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1360 /// the key type.
1361 ///
1362 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1363 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1364 ///
1365 /// # Examples
1366 ///
1367 /// ```
1368 /// use hashbrown::HashMap;
1369 ///
1370 /// let mut map = HashMap::new();
1371 /// map.insert(1, "a");
1372 /// let (k, v) = map.get_key_value_mut(&1).unwrap();
1373 /// assert_eq!(k, &1);
1374 /// assert_eq!(v, &mut "a");
1375 /// *v = "b";
1376 /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
1377 /// assert_eq!(map.get_key_value_mut(&2), None);
1378 /// ```
1379 #[inline]
1380 pub fn get_key_value_mut<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
1381 where
1382 Q: Hash + Equivalent<K> + ?Sized,
1383 {
1384 // Avoid `Option::map` because it bloats LLVM IR.
1385 if !self.table.is_empty() {
1386 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1387 match self.table.get_mut(hash, equivalent_key(k)) {
1388 Some(&mut (ref key, ref mut value)) => Some((key, value)),
1389 None => None,
1390 }
1391 } else {
1392 None
1393 }
1394 }
1395
1396 /// Returns `true` if the map contains a value for the specified key.
1397 ///
1398 /// The key may be any borrowed form of the map's key type, but
1399 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1400 /// the key type.
1401 ///
1402 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1403 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1404 ///
1405 /// # Examples
1406 ///
1407 /// ```
1408 /// use hashbrown::HashMap;
1409 ///
1410 /// let mut map = HashMap::new();
1411 /// map.insert(1, "a");
1412 /// assert_eq!(map.contains_key(&1), true);
1413 /// assert_eq!(map.contains_key(&2), false);
1414 /// ```
1415 #[cfg_attr(feature = "inline-more", inline)]
1416 pub fn contains_key<Q>(&self, k: &Q) -> bool
1417 where
1418 Q: Hash + Equivalent<K> + ?Sized,
1419 {
1420 if !self.table.is_empty() {
1421 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1422 self.table.get(hash, equivalent_key(k)).is_some()
1423 } else {
1424 false
1425 }
1426 }
1427
1428 /// Returns a mutable reference to the value corresponding to the key.
1429 ///
1430 /// The key may be any borrowed form of the map's key type, but
1431 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1432 /// the key type.
1433 ///
1434 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1435 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1436 ///
1437 /// # Examples
1438 ///
1439 /// ```
1440 /// use hashbrown::HashMap;
1441 ///
1442 /// let mut map = HashMap::new();
1443 /// map.insert(1, "a");
1444 /// if let Some(x) = map.get_mut(&1) {
1445 /// *x = "b";
1446 /// }
1447 /// assert_eq!(map[&1], "b");
1448 ///
1449 /// assert_eq!(map.get_mut(&2), None);
1450 /// ```
1451 #[cfg_attr(feature = "inline-more", inline)]
1452 pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
1453 where
1454 Q: Hash + Equivalent<K> + ?Sized,
1455 {
1456 // Avoid `Option::map` because it bloats LLVM IR.
1457 if !self.table.is_empty() {
1458 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1459 match self.table.get_mut(hash, equivalent_key(k)) {
1460 Some(&mut (_, ref mut v)) => Some(v),
1461 None => None,
1462 }
1463 } else {
1464 None
1465 }
1466 }
1467
1468 /// Attempts to get mutable references to `N` values in the map at once.
1469 ///
1470 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1471 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1472 ///
1473 /// # Panics
1474 ///
1475 /// Panics if any keys are overlapping.
1476 ///
1477 /// # Examples
1478 ///
1479 /// ```
1480 /// use hashbrown::HashMap;
1481 ///
1482 /// let mut libraries = HashMap::new();
1483 /// libraries.insert("Bodleian Library".to_string(), 1602);
1484 /// libraries.insert("Athenæum".to_string(), 1807);
1485 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1486 /// libraries.insert("Library of Congress".to_string(), 1800);
1487 ///
1488 /// // Get Athenæum and Bodleian Library
1489 /// let [Some(a), Some(b)] = libraries.get_many_mut([
1490 /// "Athenæum",
1491 /// "Bodleian Library",
1492 /// ]) else { panic!() };
1493 ///
1494 /// // Assert values of Athenæum and Library of Congress
1495 /// let got = libraries.get_many_mut([
1496 /// "Athenæum",
1497 /// "Library of Congress",
1498 /// ]);
1499 /// assert_eq!(
1500 /// got,
1501 /// [
1502 /// Some(&mut 1807),
1503 /// Some(&mut 1800),
1504 /// ],
1505 /// );
1506 ///
1507 /// // Missing keys result in None
1508 /// let got = libraries.get_many_mut([
1509 /// "Athenæum",
1510 /// "New York Public Library",
1511 /// ]);
1512 /// assert_eq!(
1513 /// got,
1514 /// [
1515 /// Some(&mut 1807),
1516 /// None
1517 /// ]
1518 /// );
1519 /// ```
1520 ///
1521 /// ```should_panic
1522 /// use hashbrown::HashMap;
1523 ///
1524 /// let mut libraries = HashMap::new();
1525 /// libraries.insert("Athenæum".to_string(), 1807);
1526 ///
1527 /// // Duplicate keys panic!
1528 /// let got = libraries.get_many_mut([
1529 /// "Athenæum",
1530 /// "Athenæum",
1531 /// ]);
1532 /// ```
1533 pub fn get_many_mut<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut V>; N]
1534 where
1535 Q: Hash + Equivalent<K> + ?Sized,
1536 {
1537 self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v))
1538 }
1539
1540 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1541 /// the values are unique.
1542 ///
1543 /// Returns an array of length `N` with the results of each query. `None` will be used if
1544 /// the key is missing.
1545 ///
1546 /// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`).
1547 ///
1548 /// # Safety
1549 ///
1550 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1551 /// references are not used.
1552 ///
1553 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1554 ///
1555 /// # Examples
1556 ///
1557 /// ```
1558 /// use hashbrown::HashMap;
1559 ///
1560 /// let mut libraries = HashMap::new();
1561 /// libraries.insert("Bodleian Library".to_string(), 1602);
1562 /// libraries.insert("Athenæum".to_string(), 1807);
1563 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1564 /// libraries.insert("Library of Congress".to_string(), 1800);
1565 ///
1566 /// // SAFETY: The keys do not overlap.
1567 /// let [Some(a), Some(b)] = (unsafe { libraries.get_many_unchecked_mut([
1568 /// "Athenæum",
1569 /// "Bodleian Library",
1570 /// ]) }) else { panic!() };
1571 ///
1572 /// // SAFETY: The keys do not overlap.
1573 /// let got = unsafe { libraries.get_many_unchecked_mut([
1574 /// "Athenæum",
1575 /// "Library of Congress",
1576 /// ]) };
1577 /// assert_eq!(
1578 /// got,
1579 /// [
1580 /// Some(&mut 1807),
1581 /// Some(&mut 1800),
1582 /// ],
1583 /// );
1584 ///
1585 /// // SAFETY: The keys do not overlap.
1586 /// let got = unsafe { libraries.get_many_unchecked_mut([
1587 /// "Athenæum",
1588 /// "New York Public Library",
1589 /// ]) };
1590 /// // Missing keys result in None
1591 /// assert_eq!(got, [Some(&mut 1807), None]);
1592 /// ```
1593 pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
1594 &mut self,
1595 ks: [&Q; N],
1596 ) -> [Option<&'_ mut V>; N]
1597 where
1598 Q: Hash + Equivalent<K> + ?Sized,
1599 {
1600 self.get_many_unchecked_mut_inner(ks)
1601 .map(|res| res.map(|(_, v)| v))
1602 }
1603
1604 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1605 /// references to the corresponding keys.
1606 ///
1607 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1608 /// mutable reference will be returned to any value. `None` will be used if the key is missing.
1609 ///
1610 /// # Panics
1611 ///
1612 /// Panics if any keys are overlapping.
1613 ///
1614 /// # Examples
1615 ///
1616 /// ```
1617 /// use hashbrown::HashMap;
1618 ///
1619 /// let mut libraries = HashMap::new();
1620 /// libraries.insert("Bodleian Library".to_string(), 1602);
1621 /// libraries.insert("Athenæum".to_string(), 1807);
1622 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1623 /// libraries.insert("Library of Congress".to_string(), 1800);
1624 ///
1625 /// let got = libraries.get_many_key_value_mut([
1626 /// "Bodleian Library",
1627 /// "Herzogin-Anna-Amalia-Bibliothek",
1628 /// ]);
1629 /// assert_eq!(
1630 /// got,
1631 /// [
1632 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1633 /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
1634 /// ],
1635 /// );
1636 /// // Missing keys result in None
1637 /// let got = libraries.get_many_key_value_mut([
1638 /// "Bodleian Library",
1639 /// "Gewandhaus",
1640 /// ]);
1641 /// assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]);
1642 /// ```
1643 ///
1644 /// ```should_panic
1645 /// use hashbrown::HashMap;
1646 ///
1647 /// let mut libraries = HashMap::new();
1648 /// libraries.insert("Bodleian Library".to_string(), 1602);
1649 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1650 ///
1651 /// // Duplicate keys result in panic!
1652 /// let got = libraries.get_many_key_value_mut([
1653 /// "Bodleian Library",
1654 /// "Herzogin-Anna-Amalia-Bibliothek",
1655 /// "Herzogin-Anna-Amalia-Bibliothek",
1656 /// ]);
1657 /// ```
1658 pub fn get_many_key_value_mut<Q, const N: usize>(
1659 &mut self,
1660 ks: [&Q; N],
1661 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1662 where
1663 Q: Hash + Equivalent<K> + ?Sized,
1664 {
1665 self.get_many_mut_inner(ks)
1666 .map(|res| res.map(|(k, v)| (&*k, v)))
1667 }
1668
1669 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1670 /// references to the corresponding keys, without validating that the values are unique.
1671 ///
1672 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1673 /// any of the keys are missing.
1674 ///
1675 /// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`).
1676 ///
1677 /// # Safety
1678 ///
1679 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1680 /// references are not used.
1681 ///
1682 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1683 ///
1684 /// # Examples
1685 ///
1686 /// ```
1687 /// use hashbrown::HashMap;
1688 ///
1689 /// let mut libraries = HashMap::new();
1690 /// libraries.insert("Bodleian Library".to_string(), 1602);
1691 /// libraries.insert("Athenæum".to_string(), 1807);
1692 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1693 /// libraries.insert("Library of Congress".to_string(), 1800);
1694 ///
1695 /// let got = libraries.get_many_key_value_mut([
1696 /// "Bodleian Library",
1697 /// "Herzogin-Anna-Amalia-Bibliothek",
1698 /// ]);
1699 /// assert_eq!(
1700 /// got,
1701 /// [
1702 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1703 /// Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
1704 /// ],
1705 /// );
1706 /// // Missing keys result in None
1707 /// let got = libraries.get_many_key_value_mut([
1708 /// "Bodleian Library",
1709 /// "Gewandhaus",
1710 /// ]);
1711 /// assert_eq!(
1712 /// got,
1713 /// [
1714 /// Some((&"Bodleian Library".to_string(), &mut 1602)),
1715 /// None,
1716 /// ],
1717 /// );
1718 /// ```
1719 pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>(
1720 &mut self,
1721 ks: [&Q; N],
1722 ) -> [Option<(&'_ K, &'_ mut V)>; N]
1723 where
1724 Q: Hash + Equivalent<K> + ?Sized,
1725 {
1726 self.get_many_unchecked_mut_inner(ks)
1727 .map(|res| res.map(|(k, v)| (&*k, v)))
1728 }
1729
1730 fn get_many_mut_inner<Q, const N: usize>(&mut self, ks: [&Q; N]) -> [Option<&'_ mut (K, V)>; N]
1731 where
1732 Q: Hash + Equivalent<K> + ?Sized,
1733 {
1734 let hashes = self.build_hashes_inner(ks);
1735 self.table
1736 .get_many_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1737 }
1738
1739 unsafe fn get_many_unchecked_mut_inner<Q, const N: usize>(
1740 &mut self,
1741 ks: [&Q; N],
1742 ) -> [Option<&'_ mut (K, V)>; N]
1743 where
1744 Q: Hash + Equivalent<K> + ?Sized,
1745 {
1746 let hashes = self.build_hashes_inner(ks);
1747 self.table
1748 .get_many_unchecked_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1749 }
1750
1751 fn build_hashes_inner<Q, const N: usize>(&self, ks: [&Q; N]) -> [u64; N]
1752 where
1753 Q: Hash + Equivalent<K> + ?Sized,
1754 {
1755 let mut hashes = [0_u64; N];
1756 for i in 0..N {
1757 hashes[i] = make_hash::<Q, S>(&self.hash_builder, ks[i]);
1758 }
1759 hashes
1760 }
1761
1762 /// Inserts a key-value pair into the map.
1763 ///
1764 /// If the map did not have this key present, [`None`] is returned.
1765 ///
1766 /// If the map did have this key present, the value is updated, and the old
1767 /// value is returned. The key is not updated, though; this matters for
1768 /// types that can be `==` without being identical. See the [`std::collections`]
1769 /// [module-level documentation] for more.
1770 ///
1771 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
1772 /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html
1773 /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys
1774 ///
1775 /// # Examples
1776 ///
1777 /// ```
1778 /// use hashbrown::HashMap;
1779 ///
1780 /// let mut map = HashMap::new();
1781 /// assert_eq!(map.insert(37, "a"), None);
1782 /// assert_eq!(map.is_empty(), false);
1783 ///
1784 /// map.insert(37, "b");
1785 /// assert_eq!(map.insert(37, "c"), Some("b"));
1786 /// assert_eq!(map[&37], "c");
1787 /// ```
1788 #[cfg_attr(feature = "inline-more", inline)]
1789 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1790 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1791 match self.find_or_find_insert_slot(hash, &k) {
1792 Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
1793 Err(slot) => {
1794 unsafe {
1795 self.table.insert_in_slot(hash, slot, (k, v));
1796 }
1797 None
1798 }
1799 }
1800 }
1801
1802 #[cfg_attr(feature = "inline-more", inline)]
1803 pub(crate) fn find_or_find_insert_slot<Q>(
1804 &mut self,
1805 hash: u64,
1806 key: &Q,
1807 ) -> Result<Bucket<(K, V)>, crate::raw::InsertSlot>
1808 where
1809 Q: Equivalent<K> + ?Sized,
1810 {
1811 self.table.find_or_find_insert_slot(
1812 hash,
1813 equivalent_key(key),
1814 make_hasher(&self.hash_builder),
1815 )
1816 }
1817
1818 /// Insert a key-value pair into the map without checking
1819 /// if the key already exists in the map.
1820 ///
1821 /// This operation is faster than regular insert, because it does not perform
1822 /// lookup before insertion.
1823 ///
1824 /// This operation is useful during initial population of the map.
1825 /// For example, when constructing a map from another map, we know
1826 /// that keys are unique.
1827 ///
1828 /// Returns a reference to the key and value just inserted.
1829 ///
1830 /// # Safety
1831 ///
1832 /// This operation is safe if a key does not exist in the map.
1833 ///
1834 /// However, if a key exists in the map already, the behavior is unspecified:
1835 /// this operation may panic, loop forever, or any following operation with the map
1836 /// may panic, loop forever or return arbitrary result.
1837 ///
1838 /// That said, this operation (and following operations) are guaranteed to
1839 /// not violate memory safety.
1840 ///
1841 /// However this operation is still unsafe because the resulting `HashMap`
1842 /// may be passed to unsafe code which does expect the map to behave
1843 /// correctly, and would cause unsoundness as a result.
1844 ///
1845 /// # Examples
1846 ///
1847 /// ```
1848 /// use hashbrown::HashMap;
1849 ///
1850 /// let mut map1 = HashMap::new();
1851 /// assert_eq!(map1.insert(1, "a"), None);
1852 /// assert_eq!(map1.insert(2, "b"), None);
1853 /// assert_eq!(map1.insert(3, "c"), None);
1854 /// assert_eq!(map1.len(), 3);
1855 ///
1856 /// let mut map2 = HashMap::new();
1857 ///
1858 /// for (key, value) in map1.into_iter() {
1859 /// unsafe {
1860 /// map2.insert_unique_unchecked(key, value);
1861 /// }
1862 /// }
1863 ///
1864 /// let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") };
1865 /// assert_eq!(key, &4);
1866 /// assert_eq!(value, &mut "d");
1867 /// *value = "e";
1868 ///
1869 /// assert_eq!(map2[&1], "a");
1870 /// assert_eq!(map2[&2], "b");
1871 /// assert_eq!(map2[&3], "c");
1872 /// assert_eq!(map2[&4], "e");
1873 /// assert_eq!(map2.len(), 4);
1874 /// ```
1875 #[cfg_attr(feature = "inline-more", inline)]
1876 pub unsafe fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
1877 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1878 let bucket = self
1879 .table
1880 .insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder));
1881 let (k_ref, v_ref) = unsafe { bucket.as_mut() };
1882 (k_ref, v_ref)
1883 }
1884
1885 /// Tries to insert a key-value pair into the map, and returns
1886 /// a mutable reference to the value in the entry.
1887 ///
1888 /// # Errors
1889 ///
1890 /// If the map already had this key present, nothing is updated, and
1891 /// an error containing the occupied entry and the value is returned.
1892 ///
1893 /// # Examples
1894 ///
1895 /// Basic usage:
1896 ///
1897 /// ```
1898 /// use hashbrown::HashMap;
1899 /// use hashbrown::hash_map::OccupiedError;
1900 ///
1901 /// let mut map = HashMap::new();
1902 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1903 ///
1904 /// match map.try_insert(37, "b") {
1905 /// Err(OccupiedError { entry, value }) => {
1906 /// assert_eq!(entry.key(), &37);
1907 /// assert_eq!(entry.get(), &"a");
1908 /// assert_eq!(value, "b");
1909 /// }
1910 /// _ => panic!()
1911 /// }
1912 /// ```
1913 #[cfg_attr(feature = "inline-more", inline)]
1914 pub fn try_insert(
1915 &mut self,
1916 key: K,
1917 value: V,
1918 ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> {
1919 match self.entry(key) {
1920 Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
1921 Entry::Vacant(entry) => Ok(entry.insert(value)),
1922 }
1923 }
1924
1925 /// Removes a key from the map, returning the value at the key if the key
1926 /// was previously in the map. Keeps the allocated memory for reuse.
1927 ///
1928 /// The key may be any borrowed form of the map's key type, but
1929 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1930 /// the key type.
1931 ///
1932 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1933 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1934 ///
1935 /// # Examples
1936 ///
1937 /// ```
1938 /// use hashbrown::HashMap;
1939 ///
1940 /// let mut map = HashMap::new();
1941 /// // The map is empty
1942 /// assert!(map.is_empty() && map.capacity() == 0);
1943 ///
1944 /// map.insert(1, "a");
1945 ///
1946 /// assert_eq!(map.remove(&1), Some("a"));
1947 /// assert_eq!(map.remove(&1), None);
1948 ///
1949 /// // Now map holds none elements
1950 /// assert!(map.is_empty());
1951 /// ```
1952 #[cfg_attr(feature = "inline-more", inline)]
1953 pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
1954 where
1955 Q: Hash + Equivalent<K> + ?Sized,
1956 {
1957 // Avoid `Option::map` because it bloats LLVM IR.
1958 match self.remove_entry(k) {
1959 Some((_, v)) => Some(v),
1960 None => None,
1961 }
1962 }
1963
1964 /// Removes a key from the map, returning the stored key and value if the
1965 /// key was previously in the map. Keeps the allocated memory for reuse.
1966 ///
1967 /// The key may be any borrowed form of the map's key type, but
1968 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1969 /// the key type.
1970 ///
1971 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1972 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1973 ///
1974 /// # Examples
1975 ///
1976 /// ```
1977 /// use hashbrown::HashMap;
1978 ///
1979 /// let mut map = HashMap::new();
1980 /// // The map is empty
1981 /// assert!(map.is_empty() && map.capacity() == 0);
1982 ///
1983 /// map.insert(1, "a");
1984 ///
1985 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1986 /// assert_eq!(map.remove(&1), None);
1987 ///
1988 /// // Now map hold none elements
1989 /// assert!(map.is_empty());
1990 /// ```
1991 #[cfg_attr(feature = "inline-more", inline)]
1992 pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
1993 where
1994 Q: Hash + Equivalent<K> + ?Sized,
1995 {
1996 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1997 self.table.remove_entry(hash, equivalent_key(k))
1998 }
1999
2000 /// Returns the total amount of memory allocated internally by the hash
2001 /// set, in bytes.
2002 ///
2003 /// The returned number is informational only. It is intended to be
2004 /// primarily used for memory profiling.
2005 #[inline]
2006 pub fn allocation_size(&self) -> usize {
2007 self.table.allocation_size()
2008 }
2009}
2010
2011impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
2012where
2013 K: Eq + Hash,
2014 V: PartialEq,
2015 S: BuildHasher,
2016 A: Allocator,
2017{
2018 fn eq(&self, other: &Self) -> bool {
2019 if self.len() != other.len() {
2020 return false;
2021 }
2022
2023 self.iter()
2024 .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
2025 }
2026}
2027
2028impl<K, V, S, A> Eq for HashMap<K, V, S, A>
2029where
2030 K: Eq + Hash,
2031 V: Eq,
2032 S: BuildHasher,
2033 A: Allocator,
2034{
2035}
2036
2037impl<K, V, S, A> Debug for HashMap<K, V, S, A>
2038where
2039 K: Debug,
2040 V: Debug,
2041 A: Allocator,
2042{
2043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2044 f.debug_map().entries(self.iter()).finish()
2045 }
2046}
2047
2048impl<K, V, S, A> Default for HashMap<K, V, S, A>
2049where
2050 S: Default,
2051 A: Default + Allocator,
2052{
2053 /// Creates an empty `HashMap<K, V, S, A>`, with the `Default` value for the hasher and allocator.
2054 ///
2055 /// # Examples
2056 ///
2057 /// ```
2058 /// use hashbrown::HashMap;
2059 /// use std::collections::hash_map::RandomState;
2060 ///
2061 /// // You can specify all types of HashMap, including hasher and allocator.
2062 /// // Created map is empty and don't allocate memory
2063 /// let map: HashMap<u32, String> = Default::default();
2064 /// assert_eq!(map.capacity(), 0);
2065 /// let map: HashMap<u32, String, RandomState> = HashMap::default();
2066 /// assert_eq!(map.capacity(), 0);
2067 /// ```
2068 #[cfg_attr(feature = "inline-more", inline)]
2069 fn default() -> Self {
2070 Self::with_hasher_in(Default::default(), Default::default())
2071 }
2072}
2073
2074impl<K, Q, V, S, A> Index<&Q> for HashMap<K, V, S, A>
2075where
2076 K: Eq + Hash,
2077 Q: Hash + Equivalent<K> + ?Sized,
2078 S: BuildHasher,
2079 A: Allocator,
2080{
2081 type Output = V;
2082
2083 /// Returns a reference to the value corresponding to the supplied key.
2084 ///
2085 /// # Panics
2086 ///
2087 /// Panics if the key is not present in the `HashMap`.
2088 ///
2089 /// # Examples
2090 ///
2091 /// ```
2092 /// use hashbrown::HashMap;
2093 ///
2094 /// let map: HashMap<_, _> = [("a", "One"), ("b", "Two")].into();
2095 ///
2096 /// assert_eq!(map[&"a"], "One");
2097 /// assert_eq!(map[&"b"], "Two");
2098 /// ```
2099 #[cfg_attr(feature = "inline-more", inline)]
2100 fn index(&self, key: &Q) -> &V {
2101 self.get(key).expect("no entry found for key")
2102 }
2103}
2104
2105// The default hasher is used to match the std implementation signature
2106#[cfg(feature = "default-hasher")]
2107impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
2108where
2109 K: Eq + Hash,
2110 A: Default + Allocator,
2111{
2112 /// # Examples
2113 ///
2114 /// ```
2115 /// use hashbrown::HashMap;
2116 ///
2117 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
2118 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
2119 /// assert_eq!(map1, map2);
2120 /// ```
2121 fn from(arr: [(K, V); N]) -> Self {
2122 arr.into_iter().collect()
2123 }
2124}
2125
2126/// An iterator over the entries of a `HashMap` in arbitrary order.
2127/// The iterator element type is `(&'a K, &'a V)`.
2128///
2129/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
2130/// documentation for more.
2131///
2132/// [`iter`]: struct.HashMap.html#method.iter
2133/// [`HashMap`]: struct.HashMap.html
2134///
2135/// # Examples
2136///
2137/// ```
2138/// use hashbrown::HashMap;
2139///
2140/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2141///
2142/// let mut iter = map.iter();
2143/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2144///
2145/// // The `Iter` iterator produces items in arbitrary order, so the
2146/// // items must be sorted to test them against a sorted array.
2147/// vec.sort_unstable();
2148/// assert_eq!(vec, [Some((&1, &"a")), Some((&2, &"b")), Some((&3, &"c"))]);
2149///
2150/// // It is fused iterator
2151/// assert_eq!(iter.next(), None);
2152/// assert_eq!(iter.next(), None);
2153/// ```
2154pub struct Iter<'a, K, V> {
2155 inner: RawIter<(K, V)>,
2156 marker: PhantomData<(&'a K, &'a V)>,
2157}
2158
2159// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2160impl<K, V> Clone for Iter<'_, K, V> {
2161 #[cfg_attr(feature = "inline-more", inline)]
2162 fn clone(&self) -> Self {
2163 Iter {
2164 inner: self.inner.clone(),
2165 marker: PhantomData,
2166 }
2167 }
2168}
2169
2170impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
2171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2172 f.debug_list().entries(self.clone()).finish()
2173 }
2174}
2175
2176/// A mutable iterator over the entries of a `HashMap` in arbitrary order.
2177/// The iterator element type is `(&'a K, &'a mut V)`.
2178///
2179/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
2180/// documentation for more.
2181///
2182/// [`iter_mut`]: struct.HashMap.html#method.iter_mut
2183/// [`HashMap`]: struct.HashMap.html
2184///
2185/// # Examples
2186///
2187/// ```
2188/// use hashbrown::HashMap;
2189///
2190/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2191///
2192/// let mut iter = map.iter_mut();
2193/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2194/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2195///
2196/// // It is fused iterator
2197/// assert_eq!(iter.next(), None);
2198/// assert_eq!(iter.next(), None);
2199///
2200/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2201/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2202/// ```
2203pub struct IterMut<'a, K, V> {
2204 inner: RawIter<(K, V)>,
2205 // To ensure invariance with respect to V
2206 marker: PhantomData<(&'a K, &'a mut V)>,
2207}
2208
2209// We override the default Send impl which has K: Sync instead of K: Send. Both
2210// are correct, but this one is more general since it allows keys which
2211// implement Send but not Sync.
2212unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {}
2213
2214impl<K, V> IterMut<'_, K, V> {
2215 /// Returns a iterator of references over the remaining items.
2216 #[cfg_attr(feature = "inline-more", inline)]
2217 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2218 Iter {
2219 inner: self.inner.clone(),
2220 marker: PhantomData,
2221 }
2222 }
2223}
2224
2225/// An owning iterator over the entries of a `HashMap` in arbitrary order.
2226/// The iterator element type is `(K, V)`.
2227///
2228/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
2229/// (provided by the [`IntoIterator`] trait). See its documentation for more.
2230/// The map cannot be used after calling that method.
2231///
2232/// [`into_iter`]: struct.HashMap.html#method.into_iter
2233/// [`HashMap`]: struct.HashMap.html
2234/// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html
2235///
2236/// # Examples
2237///
2238/// ```
2239/// use hashbrown::HashMap;
2240///
2241/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2242///
2243/// let mut iter = map.into_iter();
2244/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2245///
2246/// // The `IntoIter` iterator produces items in arbitrary order, so the
2247/// // items must be sorted to test them against a sorted array.
2248/// vec.sort_unstable();
2249/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2250///
2251/// // It is fused iterator
2252/// assert_eq!(iter.next(), None);
2253/// assert_eq!(iter.next(), None);
2254/// ```
2255pub struct IntoIter<K, V, A: Allocator = Global> {
2256 inner: RawIntoIter<(K, V), A>,
2257}
2258
2259impl<K, V, A: Allocator> IntoIter<K, V, A> {
2260 /// Returns a iterator of references over the remaining items.
2261 #[cfg_attr(feature = "inline-more", inline)]
2262 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2263 Iter {
2264 inner: self.inner.iter(),
2265 marker: PhantomData,
2266 }
2267 }
2268}
2269
2270/// An owning iterator over the keys of a `HashMap` in arbitrary order.
2271/// The iterator element type is `K`.
2272///
2273/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
2274/// See its documentation for more.
2275/// The map cannot be used after calling that method.
2276///
2277/// [`into_keys`]: struct.HashMap.html#method.into_keys
2278/// [`HashMap`]: struct.HashMap.html
2279///
2280/// # Examples
2281///
2282/// ```
2283/// use hashbrown::HashMap;
2284///
2285/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2286///
2287/// let mut keys = map.into_keys();
2288/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2289///
2290/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
2291/// // keys must be sorted to test them against a sorted array.
2292/// vec.sort_unstable();
2293/// assert_eq!(vec, [Some(1), Some(2), Some(3)]);
2294///
2295/// // It is fused iterator
2296/// assert_eq!(keys.next(), None);
2297/// assert_eq!(keys.next(), None);
2298/// ```
2299pub struct IntoKeys<K, V, A: Allocator = Global> {
2300 inner: IntoIter<K, V, A>,
2301}
2302
2303impl<K, V, A: Allocator> Default for IntoKeys<K, V, A> {
2304 #[cfg_attr(feature = "inline-more", inline)]
2305 fn default() -> Self {
2306 Self {
2307 inner: Default::default(),
2308 }
2309 }
2310}
2311impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
2312 type Item = K;
2313
2314 #[inline]
2315 fn next(&mut self) -> Option<K> {
2316 self.inner.next().map(|(k, _)| k)
2317 }
2318 #[inline]
2319 fn size_hint(&self) -> (usize, Option<usize>) {
2320 self.inner.size_hint()
2321 }
2322 #[inline]
2323 fn fold<B, F>(self, init: B, mut f: F) -> B
2324 where
2325 Self: Sized,
2326 F: FnMut(B, Self::Item) -> B,
2327 {
2328 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2329 }
2330}
2331
2332impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
2333 #[inline]
2334 fn len(&self) -> usize {
2335 self.inner.len()
2336 }
2337}
2338
2339impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
2340
2341impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
2342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2343 f.debug_list()
2344 .entries(self.inner.iter().map(|(k, _)| k))
2345 .finish()
2346 }
2347}
2348
2349/// An owning iterator over the values of a `HashMap` in arbitrary order.
2350/// The iterator element type is `V`.
2351///
2352/// This `struct` is created by the [`into_values`] method on [`HashMap`].
2353/// See its documentation for more. The map cannot be used after calling that method.
2354///
2355/// [`into_values`]: struct.HashMap.html#method.into_values
2356/// [`HashMap`]: struct.HashMap.html
2357///
2358/// # Examples
2359///
2360/// ```
2361/// use hashbrown::HashMap;
2362///
2363/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2364///
2365/// let mut values = map.into_values();
2366/// let mut vec = vec![values.next(), values.next(), values.next()];
2367///
2368/// // The `IntoValues` iterator produces values in arbitrary order, so
2369/// // the values must be sorted to test them against a sorted array.
2370/// vec.sort_unstable();
2371/// assert_eq!(vec, [Some("a"), Some("b"), Some("c")]);
2372///
2373/// // It is fused iterator
2374/// assert_eq!(values.next(), None);
2375/// assert_eq!(values.next(), None);
2376/// ```
2377pub struct IntoValues<K, V, A: Allocator = Global> {
2378 inner: IntoIter<K, V, A>,
2379}
2380
2381impl<K, V, A: Allocator> Default for IntoValues<K, V, A> {
2382 #[cfg_attr(feature = "inline-more", inline)]
2383 fn default() -> Self {
2384 Self {
2385 inner: Default::default(),
2386 }
2387 }
2388}
2389impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
2390 type Item = V;
2391
2392 #[inline]
2393 fn next(&mut self) -> Option<V> {
2394 self.inner.next().map(|(_, v)| v)
2395 }
2396 #[inline]
2397 fn size_hint(&self) -> (usize, Option<usize>) {
2398 self.inner.size_hint()
2399 }
2400 #[inline]
2401 fn fold<B, F>(self, init: B, mut f: F) -> B
2402 where
2403 Self: Sized,
2404 F: FnMut(B, Self::Item) -> B,
2405 {
2406 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2407 }
2408}
2409
2410impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2411 #[inline]
2412 fn len(&self) -> usize {
2413 self.inner.len()
2414 }
2415}
2416
2417impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2418
2419impl<K, V: Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
2420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2421 f.debug_list()
2422 .entries(self.inner.iter().map(|(_, v)| v))
2423 .finish()
2424 }
2425}
2426
2427/// An iterator over the keys of a `HashMap` in arbitrary order.
2428/// The iterator element type is `&'a K`.
2429///
2430/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
2431/// documentation for more.
2432///
2433/// [`keys`]: struct.HashMap.html#method.keys
2434/// [`HashMap`]: struct.HashMap.html
2435///
2436/// # Examples
2437///
2438/// ```
2439/// use hashbrown::HashMap;
2440///
2441/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2442///
2443/// let mut keys = map.keys();
2444/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2445///
2446/// // The `Keys` iterator produces keys in arbitrary order, so the
2447/// // keys must be sorted to test them against a sorted array.
2448/// vec.sort_unstable();
2449/// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]);
2450///
2451/// // It is fused iterator
2452/// assert_eq!(keys.next(), None);
2453/// assert_eq!(keys.next(), None);
2454/// ```
2455pub struct Keys<'a, K, V> {
2456 inner: Iter<'a, K, V>,
2457}
2458
2459// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2460impl<K, V> Clone for Keys<'_, K, V> {
2461 #[cfg_attr(feature = "inline-more", inline)]
2462 fn clone(&self) -> Self {
2463 Keys {
2464 inner: self.inner.clone(),
2465 }
2466 }
2467}
2468
2469impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
2470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2471 f.debug_list().entries(self.clone()).finish()
2472 }
2473}
2474
2475/// An iterator over the values of a `HashMap` in arbitrary order.
2476/// The iterator element type is `&'a V`.
2477///
2478/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
2479/// documentation for more.
2480///
2481/// [`values`]: struct.HashMap.html#method.values
2482/// [`HashMap`]: struct.HashMap.html
2483///
2484/// # Examples
2485///
2486/// ```
2487/// use hashbrown::HashMap;
2488///
2489/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2490///
2491/// let mut values = map.values();
2492/// let mut vec = vec![values.next(), values.next(), values.next()];
2493///
2494/// // The `Values` iterator produces values in arbitrary order, so the
2495/// // values must be sorted to test them against a sorted array.
2496/// vec.sort_unstable();
2497/// assert_eq!(vec, [Some(&"a"), Some(&"b"), Some(&"c")]);
2498///
2499/// // It is fused iterator
2500/// assert_eq!(values.next(), None);
2501/// assert_eq!(values.next(), None);
2502/// ```
2503pub struct Values<'a, K, V> {
2504 inner: Iter<'a, K, V>,
2505}
2506
2507// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2508impl<K, V> Clone for Values<'_, K, V> {
2509 #[cfg_attr(feature = "inline-more", inline)]
2510 fn clone(&self) -> Self {
2511 Values {
2512 inner: self.inner.clone(),
2513 }
2514 }
2515}
2516
2517impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
2518 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2519 f.debug_list().entries(self.clone()).finish()
2520 }
2521}
2522
2523/// A draining iterator over the entries of a `HashMap` in arbitrary
2524/// order. The iterator element type is `(K, V)`.
2525///
2526/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
2527/// documentation for more.
2528///
2529/// [`drain`]: struct.HashMap.html#method.drain
2530/// [`HashMap`]: struct.HashMap.html
2531///
2532/// # Examples
2533///
2534/// ```
2535/// use hashbrown::HashMap;
2536///
2537/// let mut map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2538///
2539/// let mut drain_iter = map.drain();
2540/// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()];
2541///
2542/// // The `Drain` iterator produces items in arbitrary order, so the
2543/// // items must be sorted to test them against a sorted array.
2544/// vec.sort_unstable();
2545/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2546///
2547/// // It is fused iterator
2548/// assert_eq!(drain_iter.next(), None);
2549/// assert_eq!(drain_iter.next(), None);
2550/// ```
2551pub struct Drain<'a, K, V, A: Allocator = Global> {
2552 inner: RawDrain<'a, (K, V), A>,
2553}
2554
2555impl<K, V, A: Allocator> Drain<'_, K, V, A> {
2556 /// Returns a iterator of references over the remaining items.
2557 #[cfg_attr(feature = "inline-more", inline)]
2558 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2559 Iter {
2560 inner: self.inner.iter(),
2561 marker: PhantomData,
2562 }
2563 }
2564}
2565
2566/// A draining iterator over entries of a `HashMap` which don't satisfy the predicate
2567/// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`.
2568///
2569/// This `struct` is created by the [`extract_if`] method on [`HashMap`]. See its
2570/// documentation for more.
2571///
2572/// [`extract_if`]: struct.HashMap.html#method.extract_if
2573/// [`HashMap`]: struct.HashMap.html
2574///
2575/// # Examples
2576///
2577/// ```
2578/// use hashbrown::HashMap;
2579///
2580/// let mut map: HashMap<i32, &str> = [(1, "a"), (2, "b"), (3, "c")].into();
2581///
2582/// let mut extract_if = map.extract_if(|k, _v| k % 2 != 0);
2583/// let mut vec = vec![extract_if.next(), extract_if.next()];
2584///
2585/// // The `ExtractIf` iterator produces items in arbitrary order, so the
2586/// // items must be sorted to test them against a sorted array.
2587/// vec.sort_unstable();
2588/// assert_eq!(vec, [Some((1, "a")),Some((3, "c"))]);
2589///
2590/// // It is fused iterator
2591/// assert_eq!(extract_if.next(), None);
2592/// assert_eq!(extract_if.next(), None);
2593/// drop(extract_if);
2594///
2595/// assert_eq!(map.len(), 1);
2596/// ```
2597#[must_use = "Iterators are lazy unless consumed"]
2598pub struct ExtractIf<'a, K, V, F, A: Allocator = Global> {
2599 f: F,
2600 inner: RawExtractIf<'a, (K, V), A>,
2601}
2602
2603impl<K, V, F, A> Iterator for ExtractIf<'_, K, V, F, A>
2604where
2605 F: FnMut(&K, &mut V) -> bool,
2606 A: Allocator,
2607{
2608 type Item = (K, V);
2609
2610 #[cfg_attr(feature = "inline-more", inline)]
2611 fn next(&mut self) -> Option<Self::Item> {
2612 self.inner.next(|&mut (ref k, ref mut v)| (self.f)(k, v))
2613 }
2614
2615 #[inline]
2616 fn size_hint(&self) -> (usize, Option<usize>) {
2617 (0, self.inner.iter.size_hint().1)
2618 }
2619}
2620
2621impl<K, V, F> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2622
2623/// A mutable iterator over the values of a `HashMap` in arbitrary order.
2624/// The iterator element type is `&'a mut V`.
2625///
2626/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
2627/// documentation for more.
2628///
2629/// [`values_mut`]: struct.HashMap.html#method.values_mut
2630/// [`HashMap`]: struct.HashMap.html
2631///
2632/// # Examples
2633///
2634/// ```
2635/// use hashbrown::HashMap;
2636///
2637/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2638///
2639/// let mut values = map.values_mut();
2640/// values.next().map(|v| v.push_str(" Mississippi"));
2641/// values.next().map(|v| v.push_str(" Mississippi"));
2642///
2643/// // It is fused iterator
2644/// assert_eq!(values.next(), None);
2645/// assert_eq!(values.next(), None);
2646///
2647/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2648/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2649/// ```
2650pub struct ValuesMut<'a, K, V> {
2651 inner: IterMut<'a, K, V>,
2652}
2653
2654/// A view into a single entry in a map, which may either be vacant or occupied.
2655///
2656/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2657///
2658/// [`HashMap`]: struct.HashMap.html
2659/// [`entry`]: struct.HashMap.html#method.entry
2660///
2661/// # Examples
2662///
2663/// ```
2664/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2665///
2666/// let mut map = HashMap::new();
2667/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2668/// assert_eq!(map.len(), 3);
2669///
2670/// // Existing key (insert)
2671/// let entry: Entry<_, _, _> = map.entry("a");
2672/// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1);
2673/// assert_eq!(map.len(), 3);
2674/// // Nonexistent key (insert)
2675/// map.entry("d").insert(4);
2676///
2677/// // Existing key (or_insert)
2678/// let v = map.entry("b").or_insert(2);
2679/// assert_eq!(std::mem::replace(v, 2), 20);
2680/// // Nonexistent key (or_insert)
2681/// map.entry("e").or_insert(5);
2682///
2683/// // Existing key (or_insert_with)
2684/// let v = map.entry("c").or_insert_with(|| 3);
2685/// assert_eq!(std::mem::replace(v, 3), 30);
2686/// // Nonexistent key (or_insert_with)
2687/// map.entry("f").or_insert_with(|| 6);
2688///
2689/// println!("Our HashMap: {:?}", map);
2690///
2691/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
2692/// // The `Iter` iterator produces items in arbitrary order, so the
2693/// // items must be sorted to test them against a sorted array.
2694/// vec.sort_unstable();
2695/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]);
2696/// ```
2697pub enum Entry<'a, K, V, S, A = Global>
2698where
2699 A: Allocator,
2700{
2701 /// An occupied entry.
2702 ///
2703 /// # Examples
2704 ///
2705 /// ```
2706 /// use hashbrown::hash_map::{Entry, HashMap};
2707 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into();
2708 ///
2709 /// match map.entry("a") {
2710 /// Entry::Vacant(_) => unreachable!(),
2711 /// Entry::Occupied(_) => { }
2712 /// }
2713 /// ```
2714 Occupied(OccupiedEntry<'a, K, V, S, A>),
2715
2716 /// A vacant entry.
2717 ///
2718 /// # Examples
2719 ///
2720 /// ```
2721 /// use hashbrown::hash_map::{Entry, HashMap};
2722 /// let mut map: HashMap<&str, i32> = HashMap::new();
2723 ///
2724 /// match map.entry("a") {
2725 /// Entry::Occupied(_) => unreachable!(),
2726 /// Entry::Vacant(_) => { }
2727 /// }
2728 /// ```
2729 Vacant(VacantEntry<'a, K, V, S, A>),
2730}
2731
2732impl<K: Debug, V: Debug, S, A: Allocator> Debug for Entry<'_, K, V, S, A> {
2733 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2734 match *self {
2735 Entry::Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
2736 Entry::Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
2737 }
2738 }
2739}
2740
2741/// A view into an occupied entry in a [`HashMap`].
2742/// It is part of the [`Entry`] and [`EntryRef`] enums.
2743///
2744/// # Examples
2745///
2746/// ```
2747/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
2748///
2749/// let mut map = HashMap::new();
2750/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2751///
2752/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").insert(100);
2753/// assert_eq!(map.len(), 3);
2754///
2755/// // Existing key (insert and update)
2756/// match map.entry("a") {
2757/// Entry::Vacant(_) => unreachable!(),
2758/// Entry::Occupied(mut view) => {
2759/// assert_eq!(view.get(), &100);
2760/// let v = view.get_mut();
2761/// *v *= 10;
2762/// assert_eq!(view.insert(1111), 1000);
2763/// }
2764/// }
2765///
2766/// assert_eq!(map[&"a"], 1111);
2767/// assert_eq!(map.len(), 3);
2768///
2769/// // Existing key (take)
2770/// match map.entry("c") {
2771/// Entry::Vacant(_) => unreachable!(),
2772/// Entry::Occupied(view) => {
2773/// assert_eq!(view.remove_entry(), ("c", 30));
2774/// }
2775/// }
2776/// assert_eq!(map.get(&"c"), None);
2777/// assert_eq!(map.len(), 2);
2778/// ```
2779pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2780 hash: u64,
2781 elem: Bucket<(K, V)>,
2782 table: &'a mut HashMap<K, V, S, A>,
2783}
2784
2785unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
2786where
2787 K: Send,
2788 V: Send,
2789 S: Send,
2790 A: Send + Allocator,
2791{
2792}
2793unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
2794where
2795 K: Sync,
2796 V: Sync,
2797 S: Sync,
2798 A: Sync + Allocator,
2799{
2800}
2801
2802impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedEntry<'_, K, V, S, A> {
2803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2804 f.debug_struct("OccupiedEntry")
2805 .field("key", self.key())
2806 .field("value", self.get())
2807 .finish()
2808 }
2809}
2810
2811/// A view into a vacant entry in a `HashMap`.
2812/// It is part of the [`Entry`] enum.
2813///
2814/// [`Entry`]: enum.Entry.html
2815///
2816/// # Examples
2817///
2818/// ```
2819/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry};
2820///
2821/// let mut map = HashMap::<&str, i32>::new();
2822///
2823/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
2824/// Entry::Vacant(view) => view,
2825/// Entry::Occupied(_) => unreachable!(),
2826/// };
2827/// entry_v.insert(10);
2828/// assert!(map[&"a"] == 10 && map.len() == 1);
2829///
2830/// // Nonexistent key (insert and update)
2831/// match map.entry("b") {
2832/// Entry::Occupied(_) => unreachable!(),
2833/// Entry::Vacant(view) => {
2834/// let value = view.insert(2);
2835/// assert_eq!(*value, 2);
2836/// *value = 20;
2837/// }
2838/// }
2839/// assert!(map[&"b"] == 20 && map.len() == 2);
2840/// ```
2841pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
2842 hash: u64,
2843 key: K,
2844 table: &'a mut HashMap<K, V, S, A>,
2845}
2846
2847impl<K: Debug, V, S, A: Allocator> Debug for VacantEntry<'_, K, V, S, A> {
2848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2849 f.debug_tuple("VacantEntry").field(self.key()).finish()
2850 }
2851}
2852
2853/// A view into a single entry in a map, which may either be vacant or occupied,
2854/// with any borrowed form of the map's key type.
2855///
2856///
2857/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
2858///
2859/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
2860/// for the key type. It also require that key may be constructed from the borrowed
2861/// form through the [`From`] trait.
2862///
2863/// [`HashMap`]: struct.HashMap.html
2864/// [`entry_ref`]: struct.HashMap.html#method.entry_ref
2865/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
2866/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
2867/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
2868///
2869/// # Examples
2870///
2871/// ```
2872/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntry};
2873///
2874/// let mut map = HashMap::new();
2875/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
2876/// assert_eq!(map.len(), 3);
2877///
2878/// // Existing key (insert)
2879/// let key = String::from("a");
2880/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
2881/// let _raw_o: OccupiedEntry<_, _, _, _> = entry.insert(1);
2882/// assert_eq!(map.len(), 3);
2883/// // Nonexistent key (insert)
2884/// map.entry_ref("d").insert(4);
2885///
2886/// // Existing key (or_insert)
2887/// let v = map.entry_ref("b").or_insert(2);
2888/// assert_eq!(std::mem::replace(v, 2), 20);
2889/// // Nonexistent key (or_insert)
2890/// map.entry_ref("e").or_insert(5);
2891///
2892/// // Existing key (or_insert_with)
2893/// let v = map.entry_ref("c").or_insert_with(|| 3);
2894/// assert_eq!(std::mem::replace(v, 3), 30);
2895/// // Nonexistent key (or_insert_with)
2896/// map.entry_ref("f").or_insert_with(|| 6);
2897///
2898/// println!("Our HashMap: {:?}", map);
2899///
2900/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
2901/// assert_eq!(map[key], value)
2902/// }
2903/// assert_eq!(map.len(), 6);
2904/// ```
2905pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
2906where
2907 A: Allocator,
2908{
2909 /// An occupied entry.
2910 ///
2911 /// # Examples
2912 ///
2913 /// ```
2914 /// use hashbrown::hash_map::{EntryRef, HashMap};
2915 /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].into();
2916 ///
2917 /// match map.entry_ref("a") {
2918 /// EntryRef::Vacant(_) => unreachable!(),
2919 /// EntryRef::Occupied(_) => { }
2920 /// }
2921 /// ```
2922 Occupied(OccupiedEntry<'a, K, V, S, A>),
2923
2924 /// A vacant entry.
2925 ///
2926 /// # Examples
2927 ///
2928 /// ```
2929 /// use hashbrown::hash_map::{EntryRef, HashMap};
2930 /// let mut map: HashMap<String, i32> = HashMap::new();
2931 ///
2932 /// match map.entry_ref("a") {
2933 /// EntryRef::Occupied(_) => unreachable!(),
2934 /// EntryRef::Vacant(_) => { }
2935 /// }
2936 /// ```
2937 Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
2938}
2939
2940impl<K, Q, V, S, A> Debug for EntryRef<'_, '_, K, Q, V, S, A>
2941where
2942 K: Debug + Borrow<Q>,
2943 Q: Debug + ?Sized,
2944 V: Debug,
2945 A: Allocator,
2946{
2947 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2948 match *self {
2949 EntryRef::Vacant(ref v) => f.debug_tuple("EntryRef").field(v).finish(),
2950 EntryRef::Occupied(ref o) => f.debug_tuple("EntryRef").field(o).finish(),
2951 }
2952 }
2953}
2954
2955/// A view into a vacant entry in a `HashMap`.
2956/// It is part of the [`EntryRef`] enum.
2957///
2958/// [`EntryRef`]: enum.EntryRef.html
2959///
2960/// # Examples
2961///
2962/// ```
2963/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef};
2964///
2965/// let mut map = HashMap::<String, i32>::new();
2966///
2967/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
2968/// EntryRef::Vacant(view) => view,
2969/// EntryRef::Occupied(_) => unreachable!(),
2970/// };
2971/// entry_v.insert(10);
2972/// assert!(map["a"] == 10 && map.len() == 1);
2973///
2974/// // Nonexistent key (insert and update)
2975/// match map.entry_ref("b") {
2976/// EntryRef::Occupied(_) => unreachable!(),
2977/// EntryRef::Vacant(view) => {
2978/// let value = view.insert(2);
2979/// assert_eq!(*value, 2);
2980/// *value = 20;
2981/// }
2982/// }
2983/// assert!(map["b"] == 20 && map.len() == 2);
2984/// ```
2985pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> {
2986 hash: u64,
2987 key: &'b Q,
2988 table: &'a mut HashMap<K, V, S, A>,
2989}
2990
2991impl<K, Q, V, S, A> Debug for VacantEntryRef<'_, '_, K, Q, V, S, A>
2992where
2993 K: Borrow<Q>,
2994 Q: Debug + ?Sized,
2995 A: Allocator,
2996{
2997 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2998 f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
2999 }
3000}
3001
3002/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
3003///
3004/// Contains the occupied entry, and the value that was not inserted.
3005///
3006/// # Examples
3007///
3008/// ```
3009/// use hashbrown::hash_map::{HashMap, OccupiedError};
3010///
3011/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into();
3012///
3013/// // try_insert method returns mutable reference to the value if keys are vacant,
3014/// // but if the map did have key present, nothing is updated, and the provided
3015/// // value is returned inside `Err(_)` variant
3016/// match map.try_insert("a", 100) {
3017/// Err(OccupiedError { mut entry, value }) => {
3018/// assert_eq!(entry.key(), &"a");
3019/// assert_eq!(value, 100);
3020/// assert_eq!(entry.insert(100), 10)
3021/// }
3022/// _ => unreachable!(),
3023/// }
3024/// assert_eq!(map[&"a"], 100);
3025/// ```
3026pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> {
3027 /// The entry in the map that was already occupied.
3028 pub entry: OccupiedEntry<'a, K, V, S, A>,
3029 /// The value which was not inserted, because the entry was already occupied.
3030 pub value: V,
3031}
3032
3033impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedError<'_, K, V, S, A> {
3034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3035 f.debug_struct("OccupiedError")
3036 .field("key", self.entry.key())
3037 .field("old_value", self.entry.get())
3038 .field("new_value", &self.value)
3039 .finish()
3040 }
3041}
3042
3043impl<K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'_, K, V, S, A> {
3044 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3045 write!(
3046 f,
3047 "failed to insert {:?}, key {:?} already exists with value {:?}",
3048 self.value,
3049 self.entry.key(),
3050 self.entry.get(),
3051 )
3052 }
3053}
3054
3055impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
3056 type Item = (&'a K, &'a V);
3057 type IntoIter = Iter<'a, K, V>;
3058
3059 /// Creates an iterator over the entries of a `HashMap` in arbitrary order.
3060 /// The iterator element type is `(&'a K, &'a V)`.
3061 ///
3062 /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
3063 ///
3064 /// [`iter`]: struct.HashMap.html#method.iter
3065 /// [`HashMap`]: struct.HashMap.html
3066 ///
3067 /// # Examples
3068 ///
3069 /// ```
3070 /// use hashbrown::HashMap;
3071 /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
3072 /// let mut map_two = HashMap::new();
3073 ///
3074 /// for (key, value) in &map_one {
3075 /// println!("Key: {}, Value: {}", key, value);
3076 /// map_two.insert(*key, *value);
3077 /// }
3078 ///
3079 /// assert_eq!(map_one, map_two);
3080 /// ```
3081 #[cfg_attr(feature = "inline-more", inline)]
3082 fn into_iter(self) -> Iter<'a, K, V> {
3083 self.iter()
3084 }
3085}
3086
3087impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
3088 type Item = (&'a K, &'a mut V);
3089 type IntoIter = IterMut<'a, K, V>;
3090
3091 /// Creates an iterator over the entries of a `HashMap` in arbitrary order
3092 /// with mutable references to the values. The iterator element type is
3093 /// `(&'a K, &'a mut V)`.
3094 ///
3095 /// Return the same `IterMut` struct as by the [`iter_mut`] method on
3096 /// [`HashMap`].
3097 ///
3098 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
3099 /// [`HashMap`]: struct.HashMap.html
3100 ///
3101 /// # Examples
3102 ///
3103 /// ```
3104 /// use hashbrown::HashMap;
3105 /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3106 ///
3107 /// for (key, value) in &mut map {
3108 /// println!("Key: {}, Value: {}", key, value);
3109 /// *value *= 2;
3110 /// }
3111 ///
3112 /// let mut vec = map.iter().collect::<Vec<_>>();
3113 /// // The `Iter` iterator produces items in arbitrary order, so the
3114 /// // items must be sorted to test them against a sorted array.
3115 /// vec.sort_unstable();
3116 /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
3117 /// ```
3118 #[cfg_attr(feature = "inline-more", inline)]
3119 fn into_iter(self) -> IterMut<'a, K, V> {
3120 self.iter_mut()
3121 }
3122}
3123
3124impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
3125 type Item = (K, V);
3126 type IntoIter = IntoIter<K, V, A>;
3127
3128 /// Creates a consuming iterator, that is, one that moves each key-value
3129 /// pair out of the map in arbitrary order. The map cannot be used after
3130 /// calling this.
3131 ///
3132 /// # Examples
3133 ///
3134 /// ```
3135 /// use hashbrown::HashMap;
3136 ///
3137 /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
3138 ///
3139 /// // Not possible with .iter()
3140 /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
3141 /// // The `IntoIter` iterator produces items in arbitrary order, so
3142 /// // the items must be sorted to test them against a sorted array.
3143 /// vec.sort_unstable();
3144 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
3145 /// ```
3146 #[cfg_attr(feature = "inline-more", inline)]
3147 fn into_iter(self) -> IntoIter<K, V, A> {
3148 IntoIter {
3149 inner: self.table.into_iter(),
3150 }
3151 }
3152}
3153
3154impl<K, V> Default for Iter<'_, K, V> {
3155 #[cfg_attr(feature = "inline-more", inline)]
3156 fn default() -> Self {
3157 Self {
3158 inner: Default::default(),
3159 marker: PhantomData,
3160 }
3161 }
3162}
3163impl<'a, K, V> Iterator for Iter<'a, K, V> {
3164 type Item = (&'a K, &'a V);
3165
3166 #[cfg_attr(feature = "inline-more", inline)]
3167 fn next(&mut self) -> Option<(&'a K, &'a V)> {
3168 // Avoid `Option::map` because it bloats LLVM IR.
3169 match self.inner.next() {
3170 Some(x) => unsafe {
3171 let r = x.as_ref();
3172 Some((&r.0, &r.1))
3173 },
3174 None => None,
3175 }
3176 }
3177 #[cfg_attr(feature = "inline-more", inline)]
3178 fn size_hint(&self) -> (usize, Option<usize>) {
3179 self.inner.size_hint()
3180 }
3181 #[cfg_attr(feature = "inline-more", inline)]
3182 fn fold<B, F>(self, init: B, mut f: F) -> B
3183 where
3184 Self: Sized,
3185 F: FnMut(B, Self::Item) -> B,
3186 {
3187 self.inner.fold(init, |acc, x| unsafe {
3188 let (k, v) = x.as_ref();
3189 f(acc, (k, v))
3190 })
3191 }
3192}
3193impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
3194 #[cfg_attr(feature = "inline-more", inline)]
3195 fn len(&self) -> usize {
3196 self.inner.len()
3197 }
3198}
3199
3200impl<K, V> FusedIterator for Iter<'_, K, V> {}
3201
3202impl<K, V> Default for IterMut<'_, K, V> {
3203 #[cfg_attr(feature = "inline-more", inline)]
3204 fn default() -> Self {
3205 Self {
3206 inner: Default::default(),
3207 marker: PhantomData,
3208 }
3209 }
3210}
3211impl<'a, K, V> Iterator for IterMut<'a, K, V> {
3212 type Item = (&'a K, &'a mut V);
3213
3214 #[cfg_attr(feature = "inline-more", inline)]
3215 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
3216 // Avoid `Option::map` because it bloats LLVM IR.
3217 match self.inner.next() {
3218 Some(x) => unsafe {
3219 let r = x.as_mut();
3220 Some((&r.0, &mut r.1))
3221 },
3222 None => None,
3223 }
3224 }
3225 #[cfg_attr(feature = "inline-more", inline)]
3226 fn size_hint(&self) -> (usize, Option<usize>) {
3227 self.inner.size_hint()
3228 }
3229 #[cfg_attr(feature = "inline-more", inline)]
3230 fn fold<B, F>(self, init: B, mut f: F) -> B
3231 where
3232 Self: Sized,
3233 F: FnMut(B, Self::Item) -> B,
3234 {
3235 self.inner.fold(init, |acc, x| unsafe {
3236 let (k, v) = x.as_mut();
3237 f(acc, (k, v))
3238 })
3239 }
3240}
3241impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
3242 #[cfg_attr(feature = "inline-more", inline)]
3243 fn len(&self) -> usize {
3244 self.inner.len()
3245 }
3246}
3247impl<K, V> FusedIterator for IterMut<'_, K, V> {}
3248
3249impl<K, V> fmt::Debug for IterMut<'_, K, V>
3250where
3251 K: fmt::Debug,
3252 V: fmt::Debug,
3253{
3254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3255 f.debug_list().entries(self.iter()).finish()
3256 }
3257}
3258
3259impl<K, V, A: Allocator> Default for IntoIter<K, V, A> {
3260 #[cfg_attr(feature = "inline-more", inline)]
3261 fn default() -> Self {
3262 Self {
3263 inner: Default::default(),
3264 }
3265 }
3266}
3267impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
3268 type Item = (K, V);
3269
3270 #[cfg_attr(feature = "inline-more", inline)]
3271 fn next(&mut self) -> Option<(K, V)> {
3272 self.inner.next()
3273 }
3274 #[cfg_attr(feature = "inline-more", inline)]
3275 fn size_hint(&self) -> (usize, Option<usize>) {
3276 self.inner.size_hint()
3277 }
3278 #[cfg_attr(feature = "inline-more", inline)]
3279 fn fold<B, F>(self, init: B, f: F) -> B
3280 where
3281 Self: Sized,
3282 F: FnMut(B, Self::Item) -> B,
3283 {
3284 self.inner.fold(init, f)
3285 }
3286}
3287impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
3288 #[cfg_attr(feature = "inline-more", inline)]
3289 fn len(&self) -> usize {
3290 self.inner.len()
3291 }
3292}
3293impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
3294
3295impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
3296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3297 f.debug_list().entries(self.iter()).finish()
3298 }
3299}
3300
3301impl<K, V> Default for Keys<'_, K, V> {
3302 #[cfg_attr(feature = "inline-more", inline)]
3303 fn default() -> Self {
3304 Self {
3305 inner: Default::default(),
3306 }
3307 }
3308}
3309impl<'a, K, V> Iterator for Keys<'a, K, V> {
3310 type Item = &'a K;
3311
3312 #[cfg_attr(feature = "inline-more", inline)]
3313 fn next(&mut self) -> Option<&'a K> {
3314 // Avoid `Option::map` because it bloats LLVM IR.
3315 match self.inner.next() {
3316 Some((k, _)) => Some(k),
3317 None => None,
3318 }
3319 }
3320 #[cfg_attr(feature = "inline-more", inline)]
3321 fn size_hint(&self) -> (usize, Option<usize>) {
3322 self.inner.size_hint()
3323 }
3324 #[cfg_attr(feature = "inline-more", inline)]
3325 fn fold<B, F>(self, init: B, mut f: F) -> B
3326 where
3327 Self: Sized,
3328 F: FnMut(B, Self::Item) -> B,
3329 {
3330 self.inner.fold(init, |acc, (k, _)| f(acc, k))
3331 }
3332}
3333impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
3334 #[cfg_attr(feature = "inline-more", inline)]
3335 fn len(&self) -> usize {
3336 self.inner.len()
3337 }
3338}
3339impl<K, V> FusedIterator for Keys<'_, K, V> {}
3340
3341impl<K, V> Default for Values<'_, K, V> {
3342 #[cfg_attr(feature = "inline-more", inline)]
3343 fn default() -> Self {
3344 Self {
3345 inner: Default::default(),
3346 }
3347 }
3348}
3349impl<'a, K, V> Iterator for Values<'a, K, V> {
3350 type Item = &'a V;
3351
3352 #[cfg_attr(feature = "inline-more", inline)]
3353 fn next(&mut self) -> Option<&'a V> {
3354 // Avoid `Option::map` because it bloats LLVM IR.
3355 match self.inner.next() {
3356 Some((_, v)) => Some(v),
3357 None => None,
3358 }
3359 }
3360 #[cfg_attr(feature = "inline-more", inline)]
3361 fn size_hint(&self) -> (usize, Option<usize>) {
3362 self.inner.size_hint()
3363 }
3364 #[cfg_attr(feature = "inline-more", inline)]
3365 fn fold<B, F>(self, init: B, mut f: F) -> B
3366 where
3367 Self: Sized,
3368 F: FnMut(B, Self::Item) -> B,
3369 {
3370 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3371 }
3372}
3373impl<K, V> ExactSizeIterator for Values<'_, K, V> {
3374 #[cfg_attr(feature = "inline-more", inline)]
3375 fn len(&self) -> usize {
3376 self.inner.len()
3377 }
3378}
3379impl<K, V> FusedIterator for Values<'_, K, V> {}
3380
3381impl<K, V> Default for ValuesMut<'_, K, V> {
3382 #[cfg_attr(feature = "inline-more", inline)]
3383 fn default() -> Self {
3384 Self {
3385 inner: Default::default(),
3386 }
3387 }
3388}
3389impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
3390 type Item = &'a mut V;
3391
3392 #[cfg_attr(feature = "inline-more", inline)]
3393 fn next(&mut self) -> Option<&'a mut V> {
3394 // Avoid `Option::map` because it bloats LLVM IR.
3395 match self.inner.next() {
3396 Some((_, v)) => Some(v),
3397 None => None,
3398 }
3399 }
3400 #[cfg_attr(feature = "inline-more", inline)]
3401 fn size_hint(&self) -> (usize, Option<usize>) {
3402 self.inner.size_hint()
3403 }
3404 #[cfg_attr(feature = "inline-more", inline)]
3405 fn fold<B, F>(self, init: B, mut f: F) -> B
3406 where
3407 Self: Sized,
3408 F: FnMut(B, Self::Item) -> B,
3409 {
3410 self.inner.fold(init, |acc, (_, v)| f(acc, v))
3411 }
3412}
3413impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
3414 #[cfg_attr(feature = "inline-more", inline)]
3415 fn len(&self) -> usize {
3416 self.inner.len()
3417 }
3418}
3419impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
3420
3421impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
3422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3423 f.debug_list()
3424 .entries(self.inner.iter().map(|(_, val)| val))
3425 .finish()
3426 }
3427}
3428
3429impl<K, V, A: Allocator> Iterator for Drain<'_, K, V, A> {
3430 type Item = (K, V);
3431
3432 #[cfg_attr(feature = "inline-more", inline)]
3433 fn next(&mut self) -> Option<(K, V)> {
3434 self.inner.next()
3435 }
3436 #[cfg_attr(feature = "inline-more", inline)]
3437 fn size_hint(&self) -> (usize, Option<usize>) {
3438 self.inner.size_hint()
3439 }
3440 #[cfg_attr(feature = "inline-more", inline)]
3441 fn fold<B, F>(self, init: B, f: F) -> B
3442 where
3443 Self: Sized,
3444 F: FnMut(B, Self::Item) -> B,
3445 {
3446 self.inner.fold(init, f)
3447 }
3448}
3449impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
3450 #[cfg_attr(feature = "inline-more", inline)]
3451 fn len(&self) -> usize {
3452 self.inner.len()
3453 }
3454}
3455impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
3456
3457impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
3458where
3459 K: fmt::Debug,
3460 V: fmt::Debug,
3461 A: Allocator,
3462{
3463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3464 f.debug_list().entries(self.iter()).finish()
3465 }
3466}
3467
3468impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> {
3469 /// Sets the value of the entry, and returns an `OccupiedEntry`.
3470 ///
3471 /// # Examples
3472 ///
3473 /// ```
3474 /// use hashbrown::HashMap;
3475 ///
3476 /// let mut map: HashMap<&str, u32> = HashMap::new();
3477 /// let entry = map.entry("horseyland").insert(37);
3478 ///
3479 /// assert_eq!(entry.key(), &"horseyland");
3480 /// ```
3481 #[cfg_attr(feature = "inline-more", inline)]
3482 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
3483 where
3484 K: Hash,
3485 S: BuildHasher,
3486 {
3487 match self {
3488 Entry::Occupied(mut entry) => {
3489 entry.insert(value);
3490 entry
3491 }
3492 Entry::Vacant(entry) => entry.insert_entry(value),
3493 }
3494 }
3495
3496 /// Ensures a value is in the entry by inserting the default if empty, and returns
3497 /// a mutable reference to the value in the entry.
3498 ///
3499 /// # Examples
3500 ///
3501 /// ```
3502 /// use hashbrown::HashMap;
3503 ///
3504 /// let mut map: HashMap<&str, u32> = HashMap::new();
3505 ///
3506 /// // nonexistent key
3507 /// map.entry("poneyland").or_insert(3);
3508 /// assert_eq!(map["poneyland"], 3);
3509 ///
3510 /// // existing key
3511 /// *map.entry("poneyland").or_insert(10) *= 2;
3512 /// assert_eq!(map["poneyland"], 6);
3513 /// ```
3514 #[cfg_attr(feature = "inline-more", inline)]
3515 pub fn or_insert(self, default: V) -> &'a mut V
3516 where
3517 K: Hash,
3518 S: BuildHasher,
3519 {
3520 match self {
3521 Entry::Occupied(entry) => entry.into_mut(),
3522 Entry::Vacant(entry) => entry.insert(default),
3523 }
3524 }
3525
3526 /// Ensures a value is in the entry by inserting the default if empty,
3527 /// and returns an [`OccupiedEntry`].
3528 ///
3529 /// # Examples
3530 ///
3531 /// ```
3532 /// use hashbrown::HashMap;
3533 ///
3534 /// let mut map: HashMap<&str, u32> = HashMap::new();
3535 ///
3536 /// // nonexistent key
3537 /// let entry = map.entry("poneyland").or_insert_entry(3);
3538 /// assert_eq!(entry.key(), &"poneyland");
3539 /// assert_eq!(entry.get(), &3);
3540 ///
3541 /// // existing key
3542 /// let mut entry = map.entry("poneyland").or_insert_entry(10);
3543 /// assert_eq!(entry.key(), &"poneyland");
3544 /// assert_eq!(entry.get(), &3);
3545 /// ```
3546 #[cfg_attr(feature = "inline-more", inline)]
3547 pub fn or_insert_entry(self, default: V) -> OccupiedEntry<'a, K, V, S, A>
3548 where
3549 K: Hash,
3550 S: BuildHasher,
3551 {
3552 match self {
3553 Entry::Occupied(entry) => entry,
3554 Entry::Vacant(entry) => entry.insert_entry(default),
3555 }
3556 }
3557
3558 /// Ensures a value is in the entry by inserting the result of the default function if empty,
3559 /// and returns a mutable reference to the value in the entry.
3560 ///
3561 /// # Examples
3562 ///
3563 /// ```
3564 /// use hashbrown::HashMap;
3565 ///
3566 /// let mut map: HashMap<&str, u32> = HashMap::new();
3567 ///
3568 /// // nonexistent key
3569 /// map.entry("poneyland").or_insert_with(|| 3);
3570 /// assert_eq!(map["poneyland"], 3);
3571 ///
3572 /// // existing key
3573 /// *map.entry("poneyland").or_insert_with(|| 10) *= 2;
3574 /// assert_eq!(map["poneyland"], 6);
3575 /// ```
3576 #[cfg_attr(feature = "inline-more", inline)]
3577 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
3578 where
3579 K: Hash,
3580 S: BuildHasher,
3581 {
3582 match self {
3583 Entry::Occupied(entry) => entry.into_mut(),
3584 Entry::Vacant(entry) => entry.insert(default()),
3585 }
3586 }
3587
3588 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
3589 /// This method allows for generating key-derived values for insertion by providing the default
3590 /// function a reference to the key that was moved during the `.entry(key)` method call.
3591 ///
3592 /// The reference to the moved key is provided so that cloning or copying the key is
3593 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
3594 ///
3595 /// # Examples
3596 ///
3597 /// ```
3598 /// use hashbrown::HashMap;
3599 ///
3600 /// let mut map: HashMap<&str, usize> = HashMap::new();
3601 ///
3602 /// // nonexistent key
3603 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
3604 /// assert_eq!(map["poneyland"], 9);
3605 ///
3606 /// // existing key
3607 /// *map.entry("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
3608 /// assert_eq!(map["poneyland"], 18);
3609 /// ```
3610 #[cfg_attr(feature = "inline-more", inline)]
3611 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
3612 where
3613 K: Hash,
3614 S: BuildHasher,
3615 {
3616 match self {
3617 Entry::Occupied(entry) => entry.into_mut(),
3618 Entry::Vacant(entry) => {
3619 let value = default(entry.key());
3620 entry.insert(value)
3621 }
3622 }
3623 }
3624
3625 /// Returns a reference to this entry's key.
3626 ///
3627 /// # Examples
3628 ///
3629 /// ```
3630 /// use hashbrown::HashMap;
3631 ///
3632 /// let mut map: HashMap<&str, u32> = HashMap::new();
3633 /// map.entry("poneyland").or_insert(3);
3634 /// // existing key
3635 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3636 /// // nonexistent key
3637 /// assert_eq!(map.entry("horseland").key(), &"horseland");
3638 /// ```
3639 #[cfg_attr(feature = "inline-more", inline)]
3640 pub fn key(&self) -> &K {
3641 match *self {
3642 Entry::Occupied(ref entry) => entry.key(),
3643 Entry::Vacant(ref entry) => entry.key(),
3644 }
3645 }
3646
3647 /// Provides in-place mutable access to an occupied entry before any
3648 /// potential inserts into the map.
3649 ///
3650 /// # Examples
3651 ///
3652 /// ```
3653 /// use hashbrown::HashMap;
3654 ///
3655 /// let mut map: HashMap<&str, u32> = HashMap::new();
3656 ///
3657 /// map.entry("poneyland")
3658 /// .and_modify(|e| { *e += 1 })
3659 /// .or_insert(42);
3660 /// assert_eq!(map["poneyland"], 42);
3661 ///
3662 /// map.entry("poneyland")
3663 /// .and_modify(|e| { *e += 1 })
3664 /// .or_insert(42);
3665 /// assert_eq!(map["poneyland"], 43);
3666 /// ```
3667 #[cfg_attr(feature = "inline-more", inline)]
3668 pub fn and_modify<F>(self, f: F) -> Self
3669 where
3670 F: FnOnce(&mut V),
3671 {
3672 match self {
3673 Entry::Occupied(mut entry) => {
3674 f(entry.get_mut());
3675 Entry::Occupied(entry)
3676 }
3677 Entry::Vacant(entry) => Entry::Vacant(entry),
3678 }
3679 }
3680
3681 /// Provides shared access to the key and owned access to the value of
3682 /// an occupied entry and allows to replace or remove it based on the
3683 /// value of the returned option.
3684 ///
3685 /// # Examples
3686 ///
3687 /// ```
3688 /// use hashbrown::HashMap;
3689 /// use hashbrown::hash_map::Entry;
3690 ///
3691 /// let mut map: HashMap<&str, u32> = HashMap::new();
3692 ///
3693 /// let entry = map
3694 /// .entry("poneyland")
3695 /// .and_replace_entry_with(|_k, _v| panic!());
3696 ///
3697 /// match entry {
3698 /// Entry::Vacant(e) => {
3699 /// assert_eq!(e.key(), &"poneyland");
3700 /// }
3701 /// Entry::Occupied(_) => panic!(),
3702 /// }
3703 ///
3704 /// map.insert("poneyland", 42);
3705 ///
3706 /// let entry = map
3707 /// .entry("poneyland")
3708 /// .and_replace_entry_with(|k, v| {
3709 /// assert_eq!(k, &"poneyland");
3710 /// assert_eq!(v, 42);
3711 /// Some(v + 1)
3712 /// });
3713 ///
3714 /// match entry {
3715 /// Entry::Occupied(e) => {
3716 /// assert_eq!(e.key(), &"poneyland");
3717 /// assert_eq!(e.get(), &43);
3718 /// }
3719 /// Entry::Vacant(_) => panic!(),
3720 /// }
3721 ///
3722 /// assert_eq!(map["poneyland"], 43);
3723 ///
3724 /// let entry = map
3725 /// .entry("poneyland")
3726 /// .and_replace_entry_with(|_k, _v| None);
3727 ///
3728 /// match entry {
3729 /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"),
3730 /// Entry::Occupied(_) => panic!(),
3731 /// }
3732 ///
3733 /// assert!(!map.contains_key("poneyland"));
3734 /// ```
3735 #[cfg_attr(feature = "inline-more", inline)]
3736 pub fn and_replace_entry_with<F>(self, f: F) -> Self
3737 where
3738 F: FnOnce(&K, V) -> Option<V>,
3739 {
3740 match self {
3741 Entry::Occupied(entry) => entry.replace_entry_with(f),
3742 Entry::Vacant(_) => self,
3743 }
3744 }
3745}
3746
3747impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> {
3748 /// Ensures a value is in the entry by inserting the default value if empty,
3749 /// and returns a mutable reference to the value in the entry.
3750 ///
3751 /// # Examples
3752 ///
3753 /// ```
3754 /// use hashbrown::HashMap;
3755 ///
3756 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
3757 ///
3758 /// // nonexistent key
3759 /// map.entry("poneyland").or_default();
3760 /// assert_eq!(map["poneyland"], None);
3761 ///
3762 /// map.insert("horseland", Some(3));
3763 ///
3764 /// // existing key
3765 /// assert_eq!(map.entry("horseland").or_default(), &mut Some(3));
3766 /// ```
3767 #[cfg_attr(feature = "inline-more", inline)]
3768 pub fn or_default(self) -> &'a mut V
3769 where
3770 K: Hash,
3771 S: BuildHasher,
3772 {
3773 match self {
3774 Entry::Occupied(entry) => entry.into_mut(),
3775 Entry::Vacant(entry) => entry.insert(Default::default()),
3776 }
3777 }
3778}
3779
3780impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> {
3781 /// Gets a reference to the key in the entry.
3782 ///
3783 /// # Examples
3784 ///
3785 /// ```
3786 /// use hashbrown::hash_map::{Entry, HashMap};
3787 ///
3788 /// let mut map: HashMap<&str, u32> = HashMap::new();
3789 /// map.entry("poneyland").or_insert(12);
3790 ///
3791 /// match map.entry("poneyland") {
3792 /// Entry::Vacant(_) => panic!(),
3793 /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"),
3794 /// }
3795 /// ```
3796 #[cfg_attr(feature = "inline-more", inline)]
3797 pub fn key(&self) -> &K {
3798 unsafe { &self.elem.as_ref().0 }
3799 }
3800
3801 /// Take the ownership of the key and value from the map.
3802 /// Keeps the allocated memory for reuse.
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 /// // The map is empty
3812 /// assert!(map.is_empty() && map.capacity() == 0);
3813 ///
3814 /// map.entry("poneyland").or_insert(12);
3815 ///
3816 /// if let Entry::Occupied(o) = map.entry("poneyland") {
3817 /// // We delete the entry from the map.
3818 /// assert_eq!(o.remove_entry(), ("poneyland", 12));
3819 /// }
3820 ///
3821 /// assert_eq!(map.contains_key("poneyland"), false);
3822 /// // Now map hold none elements
3823 /// assert!(map.is_empty());
3824 /// ```
3825 #[cfg_attr(feature = "inline-more", inline)]
3826 pub fn remove_entry(self) -> (K, V) {
3827 unsafe { self.table.table.remove(self.elem).0 }
3828 }
3829
3830 /// Gets a reference to the value in the entry.
3831 ///
3832 /// # Examples
3833 ///
3834 /// ```
3835 /// use hashbrown::HashMap;
3836 /// use hashbrown::hash_map::Entry;
3837 ///
3838 /// let mut map: HashMap<&str, u32> = HashMap::new();
3839 /// map.entry("poneyland").or_insert(12);
3840 ///
3841 /// match map.entry("poneyland") {
3842 /// Entry::Vacant(_) => panic!(),
3843 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12),
3844 /// }
3845 /// ```
3846 #[cfg_attr(feature = "inline-more", inline)]
3847 pub fn get(&self) -> &V {
3848 unsafe { &self.elem.as_ref().1 }
3849 }
3850
3851 /// Gets a mutable reference to the value in the entry.
3852 ///
3853 /// If you need a reference to the `OccupiedEntry` which may outlive the
3854 /// destruction of the `Entry` value, see [`into_mut`].
3855 ///
3856 /// [`into_mut`]: #method.into_mut
3857 ///
3858 /// # Examples
3859 ///
3860 /// ```
3861 /// use hashbrown::HashMap;
3862 /// use hashbrown::hash_map::Entry;
3863 ///
3864 /// let mut map: HashMap<&str, u32> = HashMap::new();
3865 /// map.entry("poneyland").or_insert(12);
3866 ///
3867 /// assert_eq!(map["poneyland"], 12);
3868 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
3869 /// *o.get_mut() += 10;
3870 /// assert_eq!(*o.get(), 22);
3871 ///
3872 /// // We can use the same Entry multiple times.
3873 /// *o.get_mut() += 2;
3874 /// }
3875 ///
3876 /// assert_eq!(map["poneyland"], 24);
3877 /// ```
3878 #[cfg_attr(feature = "inline-more", inline)]
3879 pub fn get_mut(&mut self) -> &mut V {
3880 unsafe { &mut self.elem.as_mut().1 }
3881 }
3882
3883 /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
3884 /// with a lifetime bound to the map itself.
3885 ///
3886 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
3887 ///
3888 /// [`get_mut`]: #method.get_mut
3889 ///
3890 /// # Examples
3891 ///
3892 /// ```
3893 /// use hashbrown::hash_map::{Entry, HashMap};
3894 ///
3895 /// let mut map: HashMap<&str, u32> = HashMap::new();
3896 /// map.entry("poneyland").or_insert(12);
3897 ///
3898 /// assert_eq!(map["poneyland"], 12);
3899 ///
3900 /// let value: &mut u32;
3901 /// match map.entry("poneyland") {
3902 /// Entry::Occupied(entry) => value = entry.into_mut(),
3903 /// Entry::Vacant(_) => panic!(),
3904 /// }
3905 /// *value += 10;
3906 ///
3907 /// assert_eq!(map["poneyland"], 22);
3908 /// ```
3909 #[cfg_attr(feature = "inline-more", inline)]
3910 pub fn into_mut(self) -> &'a mut V {
3911 unsafe { &mut self.elem.as_mut().1 }
3912 }
3913
3914 /// Sets the value of the entry, and returns the entry's old value.
3915 ///
3916 /// # Examples
3917 ///
3918 /// ```
3919 /// use hashbrown::HashMap;
3920 /// use hashbrown::hash_map::Entry;
3921 ///
3922 /// let mut map: HashMap<&str, u32> = HashMap::new();
3923 /// map.entry("poneyland").or_insert(12);
3924 ///
3925 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
3926 /// assert_eq!(o.insert(15), 12);
3927 /// }
3928 ///
3929 /// assert_eq!(map["poneyland"], 15);
3930 /// ```
3931 #[cfg_attr(feature = "inline-more", inline)]
3932 pub fn insert(&mut self, value: V) -> V {
3933 mem::replace(self.get_mut(), value)
3934 }
3935
3936 /// Takes the value out of the entry, and returns it.
3937 /// Keeps the allocated memory for reuse.
3938 ///
3939 /// # Examples
3940 ///
3941 /// ```
3942 /// use hashbrown::HashMap;
3943 /// use hashbrown::hash_map::Entry;
3944 ///
3945 /// let mut map: HashMap<&str, u32> = HashMap::new();
3946 /// // The map is empty
3947 /// assert!(map.is_empty() && map.capacity() == 0);
3948 ///
3949 /// map.entry("poneyland").or_insert(12);
3950 ///
3951 /// if let Entry::Occupied(o) = map.entry("poneyland") {
3952 /// assert_eq!(o.remove(), 12);
3953 /// }
3954 ///
3955 /// assert_eq!(map.contains_key("poneyland"), false);
3956 /// // Now map hold none elements
3957 /// assert!(map.is_empty());
3958 /// ```
3959 #[cfg_attr(feature = "inline-more", inline)]
3960 pub fn remove(self) -> V {
3961 self.remove_entry().1
3962 }
3963
3964 /// Provides shared access to the key and owned access to the value of
3965 /// the entry and allows to replace or remove it based on the
3966 /// value of the returned option.
3967 ///
3968 /// # Examples
3969 ///
3970 /// ```
3971 /// use hashbrown::HashMap;
3972 /// use hashbrown::hash_map::Entry;
3973 ///
3974 /// let mut map: HashMap<&str, u32> = HashMap::new();
3975 /// map.insert("poneyland", 42);
3976 ///
3977 /// let entry = match map.entry("poneyland") {
3978 /// Entry::Occupied(e) => {
3979 /// e.replace_entry_with(|k, v| {
3980 /// assert_eq!(k, &"poneyland");
3981 /// assert_eq!(v, 42);
3982 /// Some(v + 1)
3983 /// })
3984 /// }
3985 /// Entry::Vacant(_) => panic!(),
3986 /// };
3987 ///
3988 /// match entry {
3989 /// Entry::Occupied(e) => {
3990 /// assert_eq!(e.key(), &"poneyland");
3991 /// assert_eq!(e.get(), &43);
3992 /// }
3993 /// Entry::Vacant(_) => panic!(),
3994 /// }
3995 ///
3996 /// assert_eq!(map["poneyland"], 43);
3997 ///
3998 /// let entry = match map.entry("poneyland") {
3999 /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None),
4000 /// Entry::Vacant(_) => panic!(),
4001 /// };
4002 ///
4003 /// match entry {
4004 /// Entry::Vacant(e) => {
4005 /// assert_eq!(e.key(), &"poneyland");
4006 /// }
4007 /// Entry::Occupied(_) => panic!(),
4008 /// }
4009 ///
4010 /// assert!(!map.contains_key("poneyland"));
4011 /// ```
4012 #[cfg_attr(feature = "inline-more", inline)]
4013 pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
4014 where
4015 F: FnOnce(&K, V) -> Option<V>,
4016 {
4017 unsafe {
4018 let mut spare_key = None;
4019
4020 self.table
4021 .table
4022 .replace_bucket_with(self.elem.clone(), |(key, value)| {
4023 if let Some(new_value) = f(&key, value) {
4024 Some((key, new_value))
4025 } else {
4026 spare_key = Some(key);
4027 None
4028 }
4029 });
4030
4031 if let Some(key) = spare_key {
4032 Entry::Vacant(VacantEntry {
4033 hash: self.hash,
4034 key,
4035 table: self.table,
4036 })
4037 } else {
4038 Entry::Occupied(self)
4039 }
4040 }
4041 }
4042}
4043
4044impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> {
4045 /// Gets a reference to the key that would be used when inserting a value
4046 /// through the `VacantEntry`.
4047 ///
4048 /// # Examples
4049 ///
4050 /// ```
4051 /// use hashbrown::HashMap;
4052 ///
4053 /// let mut map: HashMap<&str, u32> = HashMap::new();
4054 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
4055 /// ```
4056 #[cfg_attr(feature = "inline-more", inline)]
4057 pub fn key(&self) -> &K {
4058 &self.key
4059 }
4060
4061 /// Take ownership of the key.
4062 ///
4063 /// # Examples
4064 ///
4065 /// ```
4066 /// use hashbrown::hash_map::{Entry, HashMap};
4067 ///
4068 /// let mut map: HashMap<&str, u32> = HashMap::new();
4069 ///
4070 /// match map.entry("poneyland") {
4071 /// Entry::Occupied(_) => panic!(),
4072 /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"),
4073 /// }
4074 /// ```
4075 #[cfg_attr(feature = "inline-more", inline)]
4076 pub fn into_key(self) -> K {
4077 self.key
4078 }
4079
4080 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4081 /// and returns a mutable reference to it.
4082 ///
4083 /// # Examples
4084 ///
4085 /// ```
4086 /// use hashbrown::HashMap;
4087 /// use hashbrown::hash_map::Entry;
4088 ///
4089 /// let mut map: HashMap<&str, u32> = HashMap::new();
4090 ///
4091 /// if let Entry::Vacant(o) = map.entry("poneyland") {
4092 /// o.insert(37);
4093 /// }
4094 /// assert_eq!(map["poneyland"], 37);
4095 /// ```
4096 #[cfg_attr(feature = "inline-more", inline)]
4097 pub fn insert(self, value: V) -> &'a mut V
4098 where
4099 K: Hash,
4100 S: BuildHasher,
4101 {
4102 let table = &mut self.table.table;
4103 let entry = table.insert_entry(
4104 self.hash,
4105 (self.key, value),
4106 make_hasher::<_, V, S>(&self.table.hash_builder),
4107 );
4108 &mut entry.1
4109 }
4110
4111 /// Sets the value of the entry with the [`VacantEntry`]'s key,
4112 /// and returns an [`OccupiedEntry`].
4113 ///
4114 /// # Examples
4115 ///
4116 /// ```
4117 /// use hashbrown::HashMap;
4118 /// use hashbrown::hash_map::Entry;
4119 ///
4120 /// let mut map: HashMap<&str, u32> = HashMap::new();
4121 ///
4122 /// if let Entry::Vacant(v) = map.entry("poneyland") {
4123 /// let o = v.insert_entry(37);
4124 /// assert_eq!(o.get(), &37);
4125 /// }
4126 /// ```
4127 #[cfg_attr(feature = "inline-more", inline)]
4128 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4129 where
4130 K: Hash,
4131 S: BuildHasher,
4132 {
4133 let elem = self.table.table.insert(
4134 self.hash,
4135 (self.key, value),
4136 make_hasher::<_, V, S>(&self.table.hash_builder),
4137 );
4138 OccupiedEntry {
4139 hash: self.hash,
4140 elem,
4141 table: self.table,
4142 }
4143 }
4144}
4145
4146impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
4147 /// Sets the value of the entry, and returns an `OccupiedEntry`.
4148 ///
4149 /// # Examples
4150 ///
4151 /// ```
4152 /// use hashbrown::HashMap;
4153 ///
4154 /// let mut map: HashMap<String, u32> = HashMap::new();
4155 /// let entry = map.entry_ref("horseyland").insert(37);
4156 ///
4157 /// assert_eq!(entry.key(), "horseyland");
4158 /// ```
4159 #[cfg_attr(feature = "inline-more", inline)]
4160 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4161 where
4162 K: Hash,
4163 &'b Q: Into<K>,
4164 S: BuildHasher,
4165 {
4166 match self {
4167 EntryRef::Occupied(mut entry) => {
4168 entry.insert(value);
4169 entry
4170 }
4171 EntryRef::Vacant(entry) => entry.insert_entry(value),
4172 }
4173 }
4174
4175 /// Ensures a value is in the entry by inserting the default if empty, and returns
4176 /// a mutable reference to the value in the entry.
4177 ///
4178 /// # Examples
4179 ///
4180 /// ```
4181 /// use hashbrown::HashMap;
4182 ///
4183 /// let mut map: HashMap<String, u32> = HashMap::new();
4184 ///
4185 /// // nonexistent key
4186 /// map.entry_ref("poneyland").or_insert(3);
4187 /// assert_eq!(map["poneyland"], 3);
4188 ///
4189 /// // existing key
4190 /// *map.entry_ref("poneyland").or_insert(10) *= 2;
4191 /// assert_eq!(map["poneyland"], 6);
4192 /// ```
4193 #[cfg_attr(feature = "inline-more", inline)]
4194 pub fn or_insert(self, default: V) -> &'a mut V
4195 where
4196 K: Hash,
4197 &'b Q: Into<K>,
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 the result of the default function if empty,
4207 /// and returns a mutable reference to the value in the entry.
4208 ///
4209 /// # Examples
4210 ///
4211 /// ```
4212 /// use hashbrown::HashMap;
4213 ///
4214 /// let mut map: HashMap<String, u32> = HashMap::new();
4215 ///
4216 /// // nonexistent key
4217 /// map.entry_ref("poneyland").or_insert_with(|| 3);
4218 /// assert_eq!(map["poneyland"], 3);
4219 ///
4220 /// // existing key
4221 /// *map.entry_ref("poneyland").or_insert_with(|| 10) *= 2;
4222 /// assert_eq!(map["poneyland"], 6);
4223 /// ```
4224 #[cfg_attr(feature = "inline-more", inline)]
4225 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
4226 where
4227 K: Hash,
4228 &'b Q: Into<K>,
4229 S: BuildHasher,
4230 {
4231 match self {
4232 EntryRef::Occupied(entry) => entry.into_mut(),
4233 EntryRef::Vacant(entry) => entry.insert(default()),
4234 }
4235 }
4236
4237 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
4238 /// This method allows for generating key-derived values for insertion by providing the default
4239 /// function an access to the borrower form of the key.
4240 ///
4241 /// # Examples
4242 ///
4243 /// ```
4244 /// use hashbrown::HashMap;
4245 ///
4246 /// let mut map: HashMap<String, usize> = HashMap::new();
4247 ///
4248 /// // nonexistent key
4249 /// map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count());
4250 /// assert_eq!(map["poneyland"], 9);
4251 ///
4252 /// // existing key
4253 /// *map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
4254 /// assert_eq!(map["poneyland"], 18);
4255 /// ```
4256 #[cfg_attr(feature = "inline-more", inline)]
4257 pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V
4258 where
4259 K: Hash + Borrow<Q>,
4260 &'b Q: Into<K>,
4261 S: BuildHasher,
4262 {
4263 match self {
4264 EntryRef::Occupied(entry) => entry.into_mut(),
4265 EntryRef::Vacant(entry) => {
4266 let value = default(entry.key);
4267 entry.insert(value)
4268 }
4269 }
4270 }
4271
4272 /// Returns a reference to this entry's key.
4273 ///
4274 /// # Examples
4275 ///
4276 /// ```
4277 /// use hashbrown::HashMap;
4278 ///
4279 /// let mut map: HashMap<String, u32> = HashMap::new();
4280 /// map.entry_ref("poneyland").or_insert(3);
4281 /// // existing key
4282 /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland");
4283 /// // nonexistent key
4284 /// assert_eq!(map.entry_ref("horseland").key(), "horseland");
4285 /// ```
4286 #[cfg_attr(feature = "inline-more", inline)]
4287 pub fn key(&self) -> &Q
4288 where
4289 K: Borrow<Q>,
4290 {
4291 match *self {
4292 EntryRef::Occupied(ref entry) => entry.key().borrow(),
4293 EntryRef::Vacant(ref entry) => entry.key(),
4294 }
4295 }
4296
4297 /// Provides in-place mutable access to an occupied entry before any
4298 /// potential inserts into the map.
4299 ///
4300 /// # Examples
4301 ///
4302 /// ```
4303 /// use hashbrown::HashMap;
4304 ///
4305 /// let mut map: HashMap<String, u32> = HashMap::new();
4306 ///
4307 /// map.entry_ref("poneyland")
4308 /// .and_modify(|e| { *e += 1 })
4309 /// .or_insert(42);
4310 /// assert_eq!(map["poneyland"], 42);
4311 ///
4312 /// map.entry_ref("poneyland")
4313 /// .and_modify(|e| { *e += 1 })
4314 /// .or_insert(42);
4315 /// assert_eq!(map["poneyland"], 43);
4316 /// ```
4317 #[cfg_attr(feature = "inline-more", inline)]
4318 pub fn and_modify<F>(self, f: F) -> Self
4319 where
4320 F: FnOnce(&mut V),
4321 {
4322 match self {
4323 EntryRef::Occupied(mut entry) => {
4324 f(entry.get_mut());
4325 EntryRef::Occupied(entry)
4326 }
4327 EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
4328 }
4329 }
4330}
4331
4332impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
4333 /// Ensures a value is in the entry by inserting the default value if empty,
4334 /// and returns a mutable reference to the value in the entry.
4335 ///
4336 /// # Examples
4337 ///
4338 /// ```
4339 /// use hashbrown::HashMap;
4340 ///
4341 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4342 ///
4343 /// // nonexistent key
4344 /// map.entry_ref("poneyland").or_default();
4345 /// assert_eq!(map["poneyland"], None);
4346 ///
4347 /// map.insert("horseland".to_string(), Some(3));
4348 ///
4349 /// // existing key
4350 /// assert_eq!(map.entry_ref("horseland").or_default(), &mut Some(3));
4351 /// ```
4352 #[cfg_attr(feature = "inline-more", inline)]
4353 pub fn or_default(self) -> &'a mut V
4354 where
4355 K: Hash,
4356 &'b Q: Into<K>,
4357 S: BuildHasher,
4358 {
4359 match self {
4360 EntryRef::Occupied(entry) => entry.into_mut(),
4361 EntryRef::Vacant(entry) => entry.insert(Default::default()),
4362 }
4363 }
4364
4365 /// Ensures a value is in the entry by inserting the default value if empty,
4366 /// and returns an [`OccupiedEntry`].
4367 ///
4368 /// # Examples
4369 ///
4370 /// ```
4371 /// use hashbrown::HashMap;
4372 ///
4373 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
4374 ///
4375 /// // nonexistent key
4376 /// let entry = map.entry_ref("poneyland").or_default_entry();
4377 /// assert_eq!(entry.key(), &"poneyland");
4378 /// assert_eq!(entry.get(), &None);
4379 ///
4380 /// // existing key
4381 /// map.insert("horseland".to_string(), Some(3));
4382 /// let entry = map.entry_ref("horseland").or_default_entry();
4383 /// assert_eq!(entry.key(), &"horseland");
4384 /// assert_eq!(entry.get(), &Some(3));
4385 /// ```
4386 #[cfg_attr(feature = "inline-more", inline)]
4387 pub fn or_default_entry(self) -> OccupiedEntry<'a, K, V, S, A>
4388 where
4389 K: Hash + From<&'b Q>,
4390 S: BuildHasher,
4391 {
4392 match self {
4393 EntryRef::Occupied(entry) => entry,
4394 EntryRef::Vacant(entry) => entry.insert_entry(Default::default()),
4395 }
4396 }
4397}
4398
4399impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S, A> {
4400 /// Gets a reference to the key that would be used when inserting a value
4401 /// through the `VacantEntryRef`.
4402 ///
4403 /// # Examples
4404 ///
4405 /// ```
4406 /// use hashbrown::HashMap;
4407 ///
4408 /// let mut map: HashMap<String, u32> = HashMap::new();
4409 /// let key: &str = "poneyland";
4410 /// assert_eq!(map.entry_ref(key).key(), "poneyland");
4411 /// ```
4412 #[cfg_attr(feature = "inline-more", inline)]
4413 pub fn key(&self) -> &'b Q {
4414 self.key
4415 }
4416
4417 /// Sets the value of the entry with the `VacantEntryRef`'s key,
4418 /// and returns a mutable reference to it.
4419 ///
4420 /// # Examples
4421 ///
4422 /// ```
4423 /// use hashbrown::HashMap;
4424 /// use hashbrown::hash_map::EntryRef;
4425 ///
4426 /// let mut map: HashMap<String, u32> = HashMap::new();
4427 /// let key: &str = "poneyland";
4428 ///
4429 /// if let EntryRef::Vacant(o) = map.entry_ref(key) {
4430 /// o.insert(37);
4431 /// }
4432 /// assert_eq!(map["poneyland"], 37);
4433 /// ```
4434 #[cfg_attr(feature = "inline-more", inline)]
4435 pub fn insert(self, value: V) -> &'a mut V
4436 where
4437 K: Hash,
4438 &'b Q: Into<K>,
4439 S: BuildHasher,
4440 {
4441 let table = &mut self.table.table;
4442 let entry = table.insert_entry(
4443 self.hash,
4444 (self.key.into(), value),
4445 make_hasher::<_, V, S>(&self.table.hash_builder),
4446 );
4447 &mut entry.1
4448 }
4449
4450 /// Sets the value of the entry with the [`VacantEntryRef`]'s key,
4451 /// and returns an [`OccupiedEntry`].
4452 ///
4453 /// # Examples
4454 ///
4455 /// ```
4456 /// use hashbrown::HashMap;
4457 /// use hashbrown::hash_map::EntryRef;
4458 ///
4459 /// let mut map: HashMap<&str, u32> = HashMap::new();
4460 ///
4461 /// if let EntryRef::Vacant(v) = map.entry_ref("poneyland") {
4462 /// let o = v.insert_entry(37);
4463 /// assert_eq!(o.get(), &37);
4464 /// }
4465 /// ```
4466 #[cfg_attr(feature = "inline-more", inline)]
4467 pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
4468 where
4469 K: Hash,
4470 &'b Q: Into<K>,
4471 S: BuildHasher,
4472 {
4473 let elem = self.table.table.insert(
4474 self.hash,
4475 (self.key.into(), value),
4476 make_hasher::<_, V, S>(&self.table.hash_builder),
4477 );
4478 OccupiedEntry {
4479 hash: self.hash,
4480 elem,
4481 table: self.table,
4482 }
4483 }
4484}
4485
4486impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A>
4487where
4488 K: Eq + Hash,
4489 S: BuildHasher + Default,
4490 A: Default + Allocator,
4491{
4492 #[cfg_attr(feature = "inline-more", inline)]
4493 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
4494 let iter = iter.into_iter();
4495 let mut map =
4496 Self::with_capacity_and_hasher_in(iter.size_hint().0, S::default(), A::default());
4497 iter.for_each(|(k, v)| {
4498 map.insert(k, v);
4499 });
4500 map
4501 }
4502}
4503
4504/// Inserts all new key-values from the iterator and replaces values with existing
4505/// keys with new values returned from the iterator.
4506impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
4507where
4508 K: Eq + Hash,
4509 S: BuildHasher,
4510 A: Allocator,
4511{
4512 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4513 /// Replace values with existing keys with new values returned from the iterator.
4514 ///
4515 /// # Examples
4516 ///
4517 /// ```
4518 /// use hashbrown::hash_map::HashMap;
4519 ///
4520 /// let mut map = HashMap::new();
4521 /// map.insert(1, 100);
4522 ///
4523 /// let some_iter = [(1, 1), (2, 2)].into_iter();
4524 /// map.extend(some_iter);
4525 /// // Replace values with existing keys with new values returned from the iterator.
4526 /// // So that the map.get(&1) doesn't return Some(&100).
4527 /// assert_eq!(map.get(&1), Some(&1));
4528 ///
4529 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4530 /// map.extend(some_vec);
4531 ///
4532 /// let some_arr = [(5, 5), (6, 6)];
4533 /// map.extend(some_arr);
4534 /// let old_map_len = map.len();
4535 ///
4536 /// // You can also extend from another HashMap
4537 /// let mut new_map = HashMap::new();
4538 /// new_map.extend(map);
4539 /// assert_eq!(new_map.len(), old_map_len);
4540 ///
4541 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4542 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4543 /// // items must be sorted to test them against a sorted array.
4544 /// vec.sort_unstable();
4545 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4546 /// ```
4547 #[cfg_attr(feature = "inline-more", inline)]
4548 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
4549 // Keys may be already present or show multiple times in the iterator.
4550 // Reserve the entire hint lower bound if the map is empty.
4551 // Otherwise reserve half the hint (rounded up), so the map
4552 // will only resize twice in the worst case.
4553 let iter = iter.into_iter();
4554 let reserve = if self.is_empty() {
4555 iter.size_hint().0
4556 } else {
4557 (iter.size_hint().0 + 1) / 2
4558 };
4559 self.reserve(reserve);
4560 iter.for_each(move |(k, v)| {
4561 self.insert(k, v);
4562 });
4563 }
4564
4565 #[inline]
4566 #[cfg(feature = "nightly")]
4567 fn extend_one(&mut self, (k, v): (K, V)) {
4568 self.insert(k, v);
4569 }
4570
4571 #[inline]
4572 #[cfg(feature = "nightly")]
4573 fn extend_reserve(&mut self, additional: usize) {
4574 // Keys may be already present or show multiple times in the iterator.
4575 // Reserve the entire hint lower bound if the map is empty.
4576 // Otherwise reserve half the hint (rounded up), so the map
4577 // will only resize twice in the worst case.
4578 let reserve = if self.is_empty() {
4579 additional
4580 } else {
4581 (additional + 1) / 2
4582 };
4583 self.reserve(reserve);
4584 }
4585}
4586
4587/// Inserts all new key-values from the iterator and replaces values with existing
4588/// keys with new values returned from the iterator.
4589impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
4590where
4591 K: Eq + Hash + Copy,
4592 V: Copy,
4593 S: BuildHasher,
4594 A: Allocator,
4595{
4596 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4597 /// Replace values with existing keys with new values returned from the iterator.
4598 /// The keys and values must implement [`Copy`] trait.
4599 ///
4600 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
4601 ///
4602 /// # Examples
4603 ///
4604 /// ```
4605 /// use hashbrown::hash_map::HashMap;
4606 ///
4607 /// let mut map = HashMap::new();
4608 /// map.insert(1, 100);
4609 ///
4610 /// let arr = [(1, 1), (2, 2)];
4611 /// let some_iter = arr.iter().map(|(k, v)| (k, v));
4612 /// map.extend(some_iter);
4613 /// // Replace values with existing keys with new values returned from the iterator.
4614 /// // So that the map.get(&1) doesn't return Some(&100).
4615 /// assert_eq!(map.get(&1), Some(&1));
4616 ///
4617 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4618 /// map.extend(some_vec.iter().map(|(k, v)| (k, v)));
4619 ///
4620 /// let some_arr = [(5, 5), (6, 6)];
4621 /// map.extend(some_arr.iter().map(|(k, v)| (k, v)));
4622 ///
4623 /// // You can also extend from another HashMap
4624 /// let mut new_map = HashMap::new();
4625 /// new_map.extend(&map);
4626 /// assert_eq!(new_map, map);
4627 ///
4628 /// let mut vec: Vec<_> = new_map.into_iter().collect();
4629 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4630 /// // items must be sorted to test them against a sorted array.
4631 /// vec.sort_unstable();
4632 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4633 /// ```
4634 #[cfg_attr(feature = "inline-more", inline)]
4635 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
4636 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
4637 }
4638
4639 #[inline]
4640 #[cfg(feature = "nightly")]
4641 fn extend_one(&mut self, (k, v): (&'a K, &'a V)) {
4642 self.insert(*k, *v);
4643 }
4644
4645 #[inline]
4646 #[cfg(feature = "nightly")]
4647 fn extend_reserve(&mut self, additional: usize) {
4648 Extend::<(K, V)>::extend_reserve(self, additional);
4649 }
4650}
4651
4652/// Inserts all new key-values from the iterator and replaces values with existing
4653/// keys with new values returned from the iterator.
4654impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A>
4655where
4656 K: Eq + Hash + Copy,
4657 V: Copy,
4658 S: BuildHasher,
4659 A: Allocator,
4660{
4661 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
4662 /// Replace values with existing keys with new values returned from the iterator.
4663 /// The keys and values must implement [`Copy`] trait.
4664 ///
4665 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
4666 ///
4667 /// # Examples
4668 ///
4669 /// ```
4670 /// use hashbrown::hash_map::HashMap;
4671 ///
4672 /// let mut map = HashMap::new();
4673 /// map.insert(1, 100);
4674 ///
4675 /// let arr = [(1, 1), (2, 2)];
4676 /// let some_iter = arr.iter();
4677 /// map.extend(some_iter);
4678 /// // Replace values with existing keys with new values returned from the iterator.
4679 /// // So that the map.get(&1) doesn't return Some(&100).
4680 /// assert_eq!(map.get(&1), Some(&1));
4681 ///
4682 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
4683 /// map.extend(&some_vec);
4684 ///
4685 /// let some_arr = [(5, 5), (6, 6)];
4686 /// map.extend(&some_arr);
4687 ///
4688 /// let mut vec: Vec<_> = map.into_iter().collect();
4689 /// // The `IntoIter` iterator produces items in arbitrary order, so the
4690 /// // items must be sorted to test them against a sorted array.
4691 /// vec.sort_unstable();
4692 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
4693 /// ```
4694 #[cfg_attr(feature = "inline-more", inline)]
4695 fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
4696 self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
4697 }
4698
4699 #[inline]
4700 #[cfg(feature = "nightly")]
4701 fn extend_one(&mut self, &(k, v): &'a (K, V)) {
4702 self.insert(k, v);
4703 }
4704
4705 #[inline]
4706 #[cfg(feature = "nightly")]
4707 fn extend_reserve(&mut self, additional: usize) {
4708 Extend::<(K, V)>::extend_reserve(self, additional);
4709 }
4710}
4711
4712#[allow(dead_code)]
4713fn assert_covariance() {
4714 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
4715 v
4716 }
4717 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
4718 v
4719 }
4720 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
4721 v
4722 }
4723 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
4724 v
4725 }
4726 fn into_iter_key<'new, A: Allocator>(
4727 v: IntoIter<&'static str, u8, A>,
4728 ) -> IntoIter<&'new str, u8, A> {
4729 v
4730 }
4731 fn into_iter_val<'new, A: Allocator>(
4732 v: IntoIter<u8, &'static str, A>,
4733 ) -> IntoIter<u8, &'new str, A> {
4734 v
4735 }
4736 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
4737 v
4738 }
4739 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
4740 v
4741 }
4742 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
4743 v
4744 }
4745 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
4746 v
4747 }
4748 fn drain<'new>(
4749 d: Drain<'static, &'static str, &'static str>,
4750 ) -> Drain<'new, &'new str, &'new str> {
4751 d
4752 }
4753}
4754
4755#[cfg(test)]
4756mod test_map {
4757 use super::DefaultHashBuilder;
4758 use super::Entry::{Occupied, Vacant};
4759 use super::EntryRef;
4760 use super::HashMap;
4761 use crate::raw::{AllocError, Allocator, Global};
4762 use alloc::string::{String, ToString};
4763 use alloc::sync::Arc;
4764 use core::alloc::Layout;
4765 use core::ptr::NonNull;
4766 use core::sync::atomic::{AtomicI8, Ordering};
4767 use rand::{rngs::SmallRng, Rng, SeedableRng};
4768 use std::borrow::ToOwned;
4769 use std::cell::RefCell;
4770 use std::vec::Vec;
4771
4772 #[test]
4773 fn test_zero_capacities() {
4774 type HM = HashMap<i32, i32>;
4775
4776 let m = HM::new();
4777 assert_eq!(m.capacity(), 0);
4778
4779 let m = HM::default();
4780 assert_eq!(m.capacity(), 0);
4781
4782 let m = HM::with_hasher(DefaultHashBuilder::default());
4783 assert_eq!(m.capacity(), 0);
4784
4785 let m = HM::with_capacity(0);
4786 assert_eq!(m.capacity(), 0);
4787
4788 let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
4789 assert_eq!(m.capacity(), 0);
4790
4791 let mut m = HM::new();
4792 m.insert(1, 1);
4793 m.insert(2, 2);
4794 m.remove(&1);
4795 m.remove(&2);
4796 m.shrink_to_fit();
4797 assert_eq!(m.capacity(), 0);
4798
4799 let mut m = HM::new();
4800 m.reserve(0);
4801 assert_eq!(m.capacity(), 0);
4802 }
4803
4804 #[test]
4805 fn test_create_capacity_zero() {
4806 let mut m = HashMap::with_capacity(0);
4807
4808 assert!(m.insert(1, 1).is_none());
4809
4810 assert!(m.contains_key(&1));
4811 assert!(!m.contains_key(&0));
4812 }
4813
4814 #[test]
4815 fn test_insert() {
4816 let mut m = HashMap::new();
4817 assert_eq!(m.len(), 0);
4818 assert!(m.insert(1, 2).is_none());
4819 assert_eq!(m.len(), 1);
4820 assert!(m.insert(2, 4).is_none());
4821 assert_eq!(m.len(), 2);
4822 assert_eq!(*m.get(&1).unwrap(), 2);
4823 assert_eq!(*m.get(&2).unwrap(), 4);
4824 }
4825
4826 #[test]
4827 fn test_clone() {
4828 let mut m = HashMap::new();
4829 assert_eq!(m.len(), 0);
4830 assert!(m.insert(1, 2).is_none());
4831 assert_eq!(m.len(), 1);
4832 assert!(m.insert(2, 4).is_none());
4833 assert_eq!(m.len(), 2);
4834 #[allow(clippy::redundant_clone)]
4835 let m2 = m.clone();
4836 assert_eq!(*m2.get(&1).unwrap(), 2);
4837 assert_eq!(*m2.get(&2).unwrap(), 4);
4838 assert_eq!(m2.len(), 2);
4839 }
4840
4841 #[test]
4842 fn test_clone_from() {
4843 let mut m = HashMap::new();
4844 let mut m2 = HashMap::new();
4845 assert_eq!(m.len(), 0);
4846 assert!(m.insert(1, 2).is_none());
4847 assert_eq!(m.len(), 1);
4848 assert!(m.insert(2, 4).is_none());
4849 assert_eq!(m.len(), 2);
4850 m2.clone_from(&m);
4851 assert_eq!(*m2.get(&1).unwrap(), 2);
4852 assert_eq!(*m2.get(&2).unwrap(), 4);
4853 assert_eq!(m2.len(), 2);
4854 }
4855
4856 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = const { RefCell::new(Vec::new()) } }
4857
4858 #[derive(Hash, PartialEq, Eq)]
4859 struct Droppable {
4860 k: usize,
4861 }
4862
4863 impl Droppable {
4864 fn new(k: usize) -> Droppable {
4865 DROP_VECTOR.with(|slot| {
4866 slot.borrow_mut()[k] += 1;
4867 });
4868
4869 Droppable { k }
4870 }
4871 }
4872
4873 impl Drop for Droppable {
4874 fn drop(&mut self) {
4875 DROP_VECTOR.with(|slot| {
4876 slot.borrow_mut()[self.k] -= 1;
4877 });
4878 }
4879 }
4880
4881 impl Clone for Droppable {
4882 fn clone(&self) -> Self {
4883 Droppable::new(self.k)
4884 }
4885 }
4886
4887 #[test]
4888 fn test_drops() {
4889 DROP_VECTOR.with(|slot| {
4890 *slot.borrow_mut() = vec![0; 200];
4891 });
4892
4893 {
4894 let mut m = HashMap::new();
4895
4896 DROP_VECTOR.with(|v| {
4897 for i in 0..200 {
4898 assert_eq!(v.borrow()[i], 0);
4899 }
4900 });
4901
4902 for i in 0..100 {
4903 let d1 = Droppable::new(i);
4904 let d2 = Droppable::new(i + 100);
4905 m.insert(d1, d2);
4906 }
4907
4908 DROP_VECTOR.with(|v| {
4909 for i in 0..200 {
4910 assert_eq!(v.borrow()[i], 1);
4911 }
4912 });
4913
4914 for i in 0..50 {
4915 let k = Droppable::new(i);
4916 let v = m.remove(&k);
4917
4918 assert!(v.is_some());
4919
4920 DROP_VECTOR.with(|v| {
4921 assert_eq!(v.borrow()[i], 1);
4922 assert_eq!(v.borrow()[i + 100], 1);
4923 });
4924 }
4925
4926 DROP_VECTOR.with(|v| {
4927 for i in 0..50 {
4928 assert_eq!(v.borrow()[i], 0);
4929 assert_eq!(v.borrow()[i + 100], 0);
4930 }
4931
4932 for i in 50..100 {
4933 assert_eq!(v.borrow()[i], 1);
4934 assert_eq!(v.borrow()[i + 100], 1);
4935 }
4936 });
4937 }
4938
4939 DROP_VECTOR.with(|v| {
4940 for i in 0..200 {
4941 assert_eq!(v.borrow()[i], 0);
4942 }
4943 });
4944 }
4945
4946 #[test]
4947 fn test_into_iter_drops() {
4948 DROP_VECTOR.with(|v| {
4949 *v.borrow_mut() = vec![0; 200];
4950 });
4951
4952 let hm = {
4953 let mut hm = HashMap::new();
4954
4955 DROP_VECTOR.with(|v| {
4956 for i in 0..200 {
4957 assert_eq!(v.borrow()[i], 0);
4958 }
4959 });
4960
4961 for i in 0..100 {
4962 let d1 = Droppable::new(i);
4963 let d2 = Droppable::new(i + 100);
4964 hm.insert(d1, d2);
4965 }
4966
4967 DROP_VECTOR.with(|v| {
4968 for i in 0..200 {
4969 assert_eq!(v.borrow()[i], 1);
4970 }
4971 });
4972
4973 hm
4974 };
4975
4976 // By the way, ensure that cloning doesn't screw up the dropping.
4977 drop(hm.clone());
4978
4979 {
4980 let mut half = hm.into_iter().take(50);
4981
4982 DROP_VECTOR.with(|v| {
4983 for i in 0..200 {
4984 assert_eq!(v.borrow()[i], 1);
4985 }
4986 });
4987
4988 for _ in half.by_ref() {}
4989
4990 DROP_VECTOR.with(|v| {
4991 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
4992
4993 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
4994
4995 assert_eq!(nk, 50);
4996 assert_eq!(nv, 50);
4997 });
4998 };
4999
5000 DROP_VECTOR.with(|v| {
5001 for i in 0..200 {
5002 assert_eq!(v.borrow()[i], 0);
5003 }
5004 });
5005 }
5006
5007 #[test]
5008 fn test_empty_remove() {
5009 let mut m: HashMap<i32, bool> = HashMap::new();
5010 assert_eq!(m.remove(&0), None);
5011 }
5012
5013 #[test]
5014 fn test_empty_entry() {
5015 let mut m: HashMap<i32, bool> = HashMap::new();
5016 match m.entry(0) {
5017 Occupied(_) => panic!(),
5018 Vacant(_) => {}
5019 }
5020 assert!(*m.entry(0).or_insert(true));
5021 assert_eq!(m.len(), 1);
5022 }
5023
5024 #[test]
5025 fn test_empty_entry_ref() {
5026 let mut m: HashMap<std::string::String, bool> = HashMap::new();
5027 match m.entry_ref("poneyland") {
5028 EntryRef::Occupied(_) => panic!(),
5029 EntryRef::Vacant(_) => {}
5030 }
5031 assert!(*m.entry_ref("poneyland").or_insert(true));
5032 assert_eq!(m.len(), 1);
5033 }
5034
5035 #[test]
5036 fn test_empty_iter() {
5037 let mut m: HashMap<i32, bool> = HashMap::new();
5038 assert_eq!(m.drain().next(), None);
5039 assert_eq!(m.keys().next(), None);
5040 assert_eq!(m.values().next(), None);
5041 assert_eq!(m.values_mut().next(), None);
5042 assert_eq!(m.iter().next(), None);
5043 assert_eq!(m.iter_mut().next(), None);
5044 assert_eq!(m.len(), 0);
5045 assert!(m.is_empty());
5046 assert_eq!(m.into_iter().next(), None);
5047 }
5048
5049 #[test]
5050 #[cfg_attr(miri, ignore)] // FIXME: takes too long
5051 fn test_lots_of_insertions() {
5052 let mut m = HashMap::new();
5053
5054 // Try this a few times to make sure we never screw up the hashmap's
5055 // internal state.
5056 for _ in 0..10 {
5057 assert!(m.is_empty());
5058
5059 for i in 1..1001 {
5060 assert!(m.insert(i, i).is_none());
5061
5062 for j in 1..=i {
5063 let r = m.get(&j);
5064 assert_eq!(r, Some(&j));
5065 }
5066
5067 for j in i + 1..1001 {
5068 let r = m.get(&j);
5069 assert_eq!(r, None);
5070 }
5071 }
5072
5073 for i in 1001..2001 {
5074 assert!(!m.contains_key(&i));
5075 }
5076
5077 // remove forwards
5078 for i in 1..1001 {
5079 assert!(m.remove(&i).is_some());
5080
5081 for j in 1..=i {
5082 assert!(!m.contains_key(&j));
5083 }
5084
5085 for j in i + 1..1001 {
5086 assert!(m.contains_key(&j));
5087 }
5088 }
5089
5090 for i in 1..1001 {
5091 assert!(!m.contains_key(&i));
5092 }
5093
5094 for i in 1..1001 {
5095 assert!(m.insert(i, i).is_none());
5096 }
5097
5098 // remove backwards
5099 for i in (1..1001).rev() {
5100 assert!(m.remove(&i).is_some());
5101
5102 for j in i..1001 {
5103 assert!(!m.contains_key(&j));
5104 }
5105
5106 for j in 1..i {
5107 assert!(m.contains_key(&j));
5108 }
5109 }
5110 }
5111 }
5112
5113 #[test]
5114 fn test_find_mut() {
5115 let mut m = HashMap::new();
5116 assert!(m.insert(1, 12).is_none());
5117 assert!(m.insert(2, 8).is_none());
5118 assert!(m.insert(5, 14).is_none());
5119 let new = 100;
5120 match m.get_mut(&5) {
5121 None => panic!(),
5122 Some(x) => *x = new,
5123 }
5124 assert_eq!(m.get(&5), Some(&new));
5125 let mut hashmap: HashMap<i32, String> = HashMap::default();
5126 let key = &1;
5127 let result = hashmap.get_mut(key);
5128 assert!(result.is_none());
5129 }
5130
5131 #[test]
5132 fn test_insert_overwrite() {
5133 let mut m = HashMap::new();
5134 assert!(m.insert(1, 2).is_none());
5135 assert_eq!(*m.get(&1).unwrap(), 2);
5136 assert!(m.insert(1, 3).is_some());
5137 assert_eq!(*m.get(&1).unwrap(), 3);
5138 }
5139
5140 #[test]
5141 fn test_insert_conflicts() {
5142 let mut m = HashMap::with_capacity(4);
5143 assert!(m.insert(1, 2).is_none());
5144 assert!(m.insert(5, 3).is_none());
5145 assert!(m.insert(9, 4).is_none());
5146 assert_eq!(*m.get(&9).unwrap(), 4);
5147 assert_eq!(*m.get(&5).unwrap(), 3);
5148 assert_eq!(*m.get(&1).unwrap(), 2);
5149 }
5150
5151 #[test]
5152 fn test_conflict_remove() {
5153 let mut m = HashMap::with_capacity(4);
5154 assert!(m.insert(1, 2).is_none());
5155 assert_eq!(*m.get(&1).unwrap(), 2);
5156 assert!(m.insert(5, 3).is_none());
5157 assert_eq!(*m.get(&1).unwrap(), 2);
5158 assert_eq!(*m.get(&5).unwrap(), 3);
5159 assert!(m.insert(9, 4).is_none());
5160 assert_eq!(*m.get(&1).unwrap(), 2);
5161 assert_eq!(*m.get(&5).unwrap(), 3);
5162 assert_eq!(*m.get(&9).unwrap(), 4);
5163 assert!(m.remove(&1).is_some());
5164 assert_eq!(*m.get(&9).unwrap(), 4);
5165 assert_eq!(*m.get(&5).unwrap(), 3);
5166 }
5167
5168 #[test]
5169 fn test_insert_unique_unchecked() {
5170 let mut map = HashMap::new();
5171 let (k1, v1) = unsafe { map.insert_unique_unchecked(10, 11) };
5172 assert_eq!((&10, &mut 11), (k1, v1));
5173 let (k2, v2) = unsafe { map.insert_unique_unchecked(20, 21) };
5174 assert_eq!((&20, &mut 21), (k2, v2));
5175 assert_eq!(Some(&11), map.get(&10));
5176 assert_eq!(Some(&21), map.get(&20));
5177 assert_eq!(None, map.get(&30));
5178 }
5179
5180 #[test]
5181 fn test_is_empty() {
5182 let mut m = HashMap::with_capacity(4);
5183 assert!(m.insert(1, 2).is_none());
5184 assert!(!m.is_empty());
5185 assert!(m.remove(&1).is_some());
5186 assert!(m.is_empty());
5187 }
5188
5189 #[test]
5190 fn test_remove() {
5191 let mut m = HashMap::new();
5192 m.insert(1, 2);
5193 assert_eq!(m.remove(&1), Some(2));
5194 assert_eq!(m.remove(&1), None);
5195 }
5196
5197 #[test]
5198 fn test_remove_entry() {
5199 let mut m = HashMap::new();
5200 m.insert(1, 2);
5201 assert_eq!(m.remove_entry(&1), Some((1, 2)));
5202 assert_eq!(m.remove(&1), None);
5203 }
5204
5205 #[test]
5206 fn test_iterate() {
5207 let mut m = HashMap::with_capacity(4);
5208 for i in 0..32 {
5209 assert!(m.insert(i, i * 2).is_none());
5210 }
5211 assert_eq!(m.len(), 32);
5212
5213 let mut observed: u32 = 0;
5214
5215 for (k, v) in &m {
5216 assert_eq!(*v, *k * 2);
5217 observed |= 1 << *k;
5218 }
5219 assert_eq!(observed, 0xFFFF_FFFF);
5220 }
5221
5222 #[test]
5223 fn test_keys() {
5224 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5225 let map: HashMap<_, _> = vec.into_iter().collect();
5226 let keys: Vec<_> = map.keys().copied().collect();
5227 assert_eq!(keys.len(), 3);
5228 assert!(keys.contains(&1));
5229 assert!(keys.contains(&2));
5230 assert!(keys.contains(&3));
5231 }
5232
5233 #[test]
5234 fn test_values() {
5235 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5236 let map: HashMap<_, _> = vec.into_iter().collect();
5237 let values: Vec<_> = map.values().copied().collect();
5238 assert_eq!(values.len(), 3);
5239 assert!(values.contains(&'a'));
5240 assert!(values.contains(&'b'));
5241 assert!(values.contains(&'c'));
5242 }
5243
5244 #[test]
5245 fn test_values_mut() {
5246 let vec = vec![(1, 1), (2, 2), (3, 3)];
5247 let mut map: HashMap<_, _> = vec.into_iter().collect();
5248 for value in map.values_mut() {
5249 *value *= 2;
5250 }
5251 let values: Vec<_> = map.values().copied().collect();
5252 assert_eq!(values.len(), 3);
5253 assert!(values.contains(&2));
5254 assert!(values.contains(&4));
5255 assert!(values.contains(&6));
5256 }
5257
5258 #[test]
5259 fn test_into_keys() {
5260 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5261 let map: HashMap<_, _> = vec.into_iter().collect();
5262 let keys: Vec<_> = map.into_keys().collect();
5263
5264 assert_eq!(keys.len(), 3);
5265 assert!(keys.contains(&1));
5266 assert!(keys.contains(&2));
5267 assert!(keys.contains(&3));
5268 }
5269
5270 #[test]
5271 fn test_into_values() {
5272 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
5273 let map: HashMap<_, _> = vec.into_iter().collect();
5274 let values: Vec<_> = map.into_values().collect();
5275
5276 assert_eq!(values.len(), 3);
5277 assert!(values.contains(&'a'));
5278 assert!(values.contains(&'b'));
5279 assert!(values.contains(&'c'));
5280 }
5281
5282 #[test]
5283 fn test_find() {
5284 let mut m = HashMap::new();
5285 assert!(m.get(&1).is_none());
5286 m.insert(1, 2);
5287 match m.get(&1) {
5288 None => panic!(),
5289 Some(v) => assert_eq!(*v, 2),
5290 }
5291 }
5292
5293 #[test]
5294 fn test_eq() {
5295 let mut m1 = HashMap::new();
5296 m1.insert(1, 2);
5297 m1.insert(2, 3);
5298 m1.insert(3, 4);
5299
5300 let mut m2 = HashMap::new();
5301 m2.insert(1, 2);
5302 m2.insert(2, 3);
5303
5304 assert!(m1 != m2);
5305
5306 m2.insert(3, 4);
5307
5308 assert_eq!(m1, m2);
5309 }
5310
5311 #[test]
5312 fn test_show() {
5313 let mut map = HashMap::new();
5314 let empty: HashMap<i32, i32> = HashMap::new();
5315
5316 map.insert(1, 2);
5317 map.insert(3, 4);
5318
5319 let map_str = format!("{map:?}");
5320
5321 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
5322 assert_eq!(format!("{empty:?}"), "{}");
5323 }
5324
5325 #[test]
5326 fn test_expand() {
5327 let mut m = HashMap::new();
5328
5329 assert_eq!(m.len(), 0);
5330 assert!(m.is_empty());
5331
5332 let mut i = 0;
5333 let old_raw_cap = m.raw_capacity();
5334 while old_raw_cap == m.raw_capacity() {
5335 m.insert(i, i);
5336 i += 1;
5337 }
5338
5339 assert_eq!(m.len(), i);
5340 assert!(!m.is_empty());
5341 }
5342
5343 #[test]
5344 fn test_behavior_resize_policy() {
5345 let mut m = HashMap::new();
5346
5347 assert_eq!(m.len(), 0);
5348 assert_eq!(m.raw_capacity(), 1);
5349 assert!(m.is_empty());
5350
5351 m.insert(0, 0);
5352 m.remove(&0);
5353 assert!(m.is_empty());
5354 let initial_raw_cap = m.raw_capacity();
5355 m.reserve(initial_raw_cap);
5356 let raw_cap = m.raw_capacity();
5357
5358 assert_eq!(raw_cap, initial_raw_cap * 2);
5359
5360 let mut i = 0;
5361 for _ in 0..raw_cap * 3 / 4 {
5362 m.insert(i, i);
5363 i += 1;
5364 }
5365 // three quarters full
5366
5367 assert_eq!(m.len(), i);
5368 assert_eq!(m.raw_capacity(), raw_cap);
5369
5370 for _ in 0..raw_cap / 4 {
5371 m.insert(i, i);
5372 i += 1;
5373 }
5374 // half full
5375
5376 let new_raw_cap = m.raw_capacity();
5377 assert_eq!(new_raw_cap, raw_cap * 2);
5378
5379 for _ in 0..raw_cap / 2 - 1 {
5380 i -= 1;
5381 m.remove(&i);
5382 assert_eq!(m.raw_capacity(), new_raw_cap);
5383 }
5384 // A little more than one quarter full.
5385 m.shrink_to_fit();
5386 assert_eq!(m.raw_capacity(), raw_cap);
5387 // again, a little more than half full
5388 for _ in 0..raw_cap / 2 {
5389 i -= 1;
5390 m.remove(&i);
5391 }
5392 m.shrink_to_fit();
5393
5394 assert_eq!(m.len(), i);
5395 assert!(!m.is_empty());
5396 assert_eq!(m.raw_capacity(), initial_raw_cap);
5397 }
5398
5399 #[test]
5400 fn test_reserve_shrink_to_fit() {
5401 let mut m = HashMap::new();
5402 m.insert(0, 0);
5403 m.remove(&0);
5404 assert!(m.capacity() >= m.len());
5405 for i in 0..128 {
5406 m.insert(i, i);
5407 }
5408 m.reserve(256);
5409
5410 let usable_cap = m.capacity();
5411 for i in 128..(128 + 256) {
5412 m.insert(i, i);
5413 assert_eq!(m.capacity(), usable_cap);
5414 }
5415
5416 for i in 100..(128 + 256) {
5417 assert_eq!(m.remove(&i), Some(i));
5418 }
5419 m.shrink_to_fit();
5420
5421 assert_eq!(m.len(), 100);
5422 assert!(!m.is_empty());
5423 assert!(m.capacity() >= m.len());
5424
5425 for i in 0..100 {
5426 assert_eq!(m.remove(&i), Some(i));
5427 }
5428 m.shrink_to_fit();
5429 m.insert(0, 0);
5430
5431 assert_eq!(m.len(), 1);
5432 assert!(m.capacity() >= m.len());
5433 assert_eq!(m.remove(&0), Some(0));
5434 }
5435
5436 #[test]
5437 fn test_from_iter() {
5438 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5439
5440 let map: HashMap<_, _> = xs.iter().copied().collect();
5441
5442 for &(k, v) in &xs {
5443 assert_eq!(map.get(&k), Some(&v));
5444 }
5445
5446 assert_eq!(map.iter().len(), xs.len() - 1);
5447 }
5448
5449 #[test]
5450 fn test_size_hint() {
5451 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5452
5453 let map: HashMap<_, _> = xs.iter().copied().collect();
5454
5455 let mut iter = map.iter();
5456
5457 for _ in iter.by_ref().take(3) {}
5458
5459 assert_eq!(iter.size_hint(), (3, Some(3)));
5460 }
5461
5462 #[test]
5463 fn test_iter_len() {
5464 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5465
5466 let map: HashMap<_, _> = xs.iter().copied().collect();
5467
5468 let mut iter = map.iter();
5469
5470 for _ in iter.by_ref().take(3) {}
5471
5472 assert_eq!(iter.len(), 3);
5473 }
5474
5475 #[test]
5476 fn test_mut_size_hint() {
5477 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5478
5479 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5480
5481 let mut iter = map.iter_mut();
5482
5483 for _ in iter.by_ref().take(3) {}
5484
5485 assert_eq!(iter.size_hint(), (3, Some(3)));
5486 }
5487
5488 #[test]
5489 fn test_iter_mut_len() {
5490 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
5491
5492 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5493
5494 let mut iter = map.iter_mut();
5495
5496 for _ in iter.by_ref().take(3) {}
5497
5498 assert_eq!(iter.len(), 3);
5499 }
5500
5501 #[test]
5502 fn test_index() {
5503 let mut map = HashMap::new();
5504
5505 map.insert(1, 2);
5506 map.insert(2, 1);
5507 map.insert(3, 4);
5508
5509 assert_eq!(map[&2], 1);
5510 }
5511
5512 #[test]
5513 #[should_panic]
5514 fn test_index_nonexistent() {
5515 let mut map = HashMap::new();
5516
5517 map.insert(1, 2);
5518 map.insert(2, 1);
5519 map.insert(3, 4);
5520
5521 _ = map[&4];
5522 }
5523
5524 #[test]
5525 fn test_entry() {
5526 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
5527
5528 let mut map: HashMap<_, _> = xs.iter().copied().collect();
5529
5530 // Existing key (insert)
5531 match map.entry(1) {
5532 Vacant(_) => unreachable!(),
5533 Occupied(mut view) => {
5534 assert_eq!(view.get(), &10);
5535 assert_eq!(view.insert(100), 10);
5536 }
5537 }
5538 assert_eq!(map.get(&1).unwrap(), &100);
5539 assert_eq!(map.len(), 6);
5540
5541 // Existing key (update)
5542 match map.entry(2) {
5543 Vacant(_) => unreachable!(),
5544 Occupied(mut view) => {
5545 let v = view.get_mut();
5546 let new_v = (*v) * 10;
5547 *v = new_v;
5548 }
5549 }
5550 assert_eq!(map.get(&2).unwrap(), &200);
5551 assert_eq!(map.len(), 6);
5552
5553 // Existing key (take)
5554 match map.entry(3) {
5555 Vacant(_) => unreachable!(),
5556 Occupied(view) => {
5557 assert_eq!(view.remove(), 30);
5558 }
5559 }
5560 assert_eq!(map.get(&3), None);
5561 assert_eq!(map.len(), 5);
5562
5563 // Inexistent key (insert)
5564 match map.entry(10) {
5565 Occupied(_) => unreachable!(),
5566 Vacant(view) => {
5567 assert_eq!(*view.insert(1000), 1000);
5568 }
5569 }
5570 assert_eq!(map.get(&10).unwrap(), &1000);
5571 assert_eq!(map.len(), 6);
5572 }
5573
5574 #[test]
5575 fn test_entry_ref() {
5576 let xs = [
5577 ("One".to_owned(), 10),
5578 ("Two".to_owned(), 20),
5579 ("Three".to_owned(), 30),
5580 ("Four".to_owned(), 40),
5581 ("Five".to_owned(), 50),
5582 ("Six".to_owned(), 60),
5583 ];
5584
5585 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
5586
5587 // Existing key (insert)
5588 match map.entry_ref("One") {
5589 EntryRef::Vacant(_) => unreachable!(),
5590 EntryRef::Occupied(mut view) => {
5591 assert_eq!(view.get(), &10);
5592 assert_eq!(view.insert(100), 10);
5593 }
5594 }
5595 assert_eq!(map.get("One").unwrap(), &100);
5596 assert_eq!(map.len(), 6);
5597
5598 // Existing key (update)
5599 match map.entry_ref("Two") {
5600 EntryRef::Vacant(_) => unreachable!(),
5601 EntryRef::Occupied(mut view) => {
5602 let v = view.get_mut();
5603 let new_v = (*v) * 10;
5604 *v = new_v;
5605 }
5606 }
5607 assert_eq!(map.get("Two").unwrap(), &200);
5608 assert_eq!(map.len(), 6);
5609
5610 // Existing key (take)
5611 match map.entry_ref("Three") {
5612 EntryRef::Vacant(_) => unreachable!(),
5613 EntryRef::Occupied(view) => {
5614 assert_eq!(view.remove(), 30);
5615 }
5616 }
5617 assert_eq!(map.get("Three"), None);
5618 assert_eq!(map.len(), 5);
5619
5620 // Inexistent key (insert)
5621 match map.entry_ref("Ten") {
5622 EntryRef::Occupied(_) => unreachable!(),
5623 EntryRef::Vacant(view) => {
5624 assert_eq!(*view.insert(1000), 1000);
5625 }
5626 }
5627 assert_eq!(map.get("Ten").unwrap(), &1000);
5628 assert_eq!(map.len(), 6);
5629 }
5630
5631 #[test]
5632 fn test_entry_take_doesnt_corrupt() {
5633 #![allow(deprecated)] //rand
5634 // Test for #19292
5635 fn check(m: &HashMap<i32, ()>) {
5636 for k in m.keys() {
5637 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5638 }
5639 }
5640
5641 let mut m = HashMap::new();
5642
5643 let mut rng = {
5644 let seed = u64::from_le_bytes(*b"testseed");
5645 SmallRng::seed_from_u64(seed)
5646 };
5647
5648 // Populate the map with some items.
5649 for _ in 0..50 {
5650 let x = rng.gen_range(-10..10);
5651 m.insert(x, ());
5652 }
5653
5654 for _ in 0..1000 {
5655 let x = rng.gen_range(-10..10);
5656 match m.entry(x) {
5657 Vacant(_) => {}
5658 Occupied(e) => {
5659 e.remove();
5660 }
5661 }
5662
5663 check(&m);
5664 }
5665 }
5666
5667 #[test]
5668 fn test_entry_ref_take_doesnt_corrupt() {
5669 #![allow(deprecated)] //rand
5670 // Test for #19292
5671 fn check(m: &HashMap<std::string::String, ()>) {
5672 for k in m.keys() {
5673 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5674 }
5675 }
5676
5677 let mut m = HashMap::new();
5678
5679 let mut rng = {
5680 let seed = u64::from_le_bytes(*b"testseed");
5681 SmallRng::seed_from_u64(seed)
5682 };
5683
5684 // Populate the map with some items.
5685 for _ in 0..50 {
5686 let mut x = std::string::String::with_capacity(1);
5687 x.push(rng.gen_range('a'..='z'));
5688 m.insert(x, ());
5689 }
5690
5691 for _ in 0..1000 {
5692 let mut x = std::string::String::with_capacity(1);
5693 x.push(rng.gen_range('a'..='z'));
5694 match m.entry_ref(x.as_str()) {
5695 EntryRef::Vacant(_) => {}
5696 EntryRef::Occupied(e) => {
5697 e.remove();
5698 }
5699 }
5700
5701 check(&m);
5702 }
5703 }
5704
5705 #[test]
5706 fn test_extend_ref_k_ref_v() {
5707 let mut a = HashMap::new();
5708 a.insert(1, "one");
5709 let mut b = HashMap::new();
5710 b.insert(2, "two");
5711 b.insert(3, "three");
5712
5713 a.extend(&b);
5714
5715 assert_eq!(a.len(), 3);
5716 assert_eq!(a[&1], "one");
5717 assert_eq!(a[&2], "two");
5718 assert_eq!(a[&3], "three");
5719 }
5720
5721 #[test]
5722 #[allow(clippy::needless_borrow)]
5723 fn test_extend_ref_kv_tuple() {
5724 use std::ops::AddAssign;
5725 let mut a = HashMap::new();
5726 a.insert(0, 0);
5727
5728 fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
5729 let mut outs: [(T, T); N] = [(start, start); N];
5730 let mut element = step;
5731 outs.iter_mut().skip(1).for_each(|(k, v)| {
5732 *k += element;
5733 *v += element;
5734 element += step;
5735 });
5736 outs
5737 }
5738
5739 let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
5740 let iter = for_iter.iter();
5741 let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
5742 a.extend(iter);
5743 a.extend(&vec);
5744 a.extend(create_arr::<i32, 100>(200, 1));
5745
5746 assert_eq!(a.len(), 300);
5747
5748 for item in 0..300 {
5749 assert_eq!(a[&item], item);
5750 }
5751 }
5752
5753 #[test]
5754 fn test_capacity_not_less_than_len() {
5755 let mut a = HashMap::new();
5756 let mut item = 0;
5757
5758 for _ in 0..116 {
5759 a.insert(item, 0);
5760 item += 1;
5761 }
5762
5763 assert!(a.capacity() > a.len());
5764
5765 let free = a.capacity() - a.len();
5766 for _ in 0..free {
5767 a.insert(item, 0);
5768 item += 1;
5769 }
5770
5771 assert_eq!(a.len(), a.capacity());
5772
5773 // Insert at capacity should cause allocation.
5774 a.insert(item, 0);
5775 assert!(a.capacity() > a.len());
5776 }
5777
5778 #[test]
5779 fn test_occupied_entry_key() {
5780 let mut a = HashMap::new();
5781 let key = "hello there";
5782 let value = "value goes here";
5783 assert!(a.is_empty());
5784 a.insert(key, value);
5785 assert_eq!(a.len(), 1);
5786 assert_eq!(a[key], value);
5787
5788 match a.entry(key) {
5789 Vacant(_) => panic!(),
5790 Occupied(e) => assert_eq!(key, *e.key()),
5791 }
5792 assert_eq!(a.len(), 1);
5793 assert_eq!(a[key], value);
5794 }
5795
5796 #[test]
5797 fn test_occupied_entry_ref_key() {
5798 let mut a = HashMap::new();
5799 let key = "hello there";
5800 let value = "value goes here";
5801 assert!(a.is_empty());
5802 a.insert(key.to_owned(), value);
5803 assert_eq!(a.len(), 1);
5804 assert_eq!(a[key], value);
5805
5806 match a.entry_ref(key) {
5807 EntryRef::Vacant(_) => panic!(),
5808 EntryRef::Occupied(e) => assert_eq!(key, e.key()),
5809 }
5810 assert_eq!(a.len(), 1);
5811 assert_eq!(a[key], value);
5812 }
5813
5814 #[test]
5815 fn test_vacant_entry_key() {
5816 let mut a = HashMap::new();
5817 let key = "hello there";
5818 let value = "value goes here";
5819
5820 assert!(a.is_empty());
5821 match a.entry(key) {
5822 Occupied(_) => panic!(),
5823 Vacant(e) => {
5824 assert_eq!(key, *e.key());
5825 e.insert(value);
5826 }
5827 }
5828 assert_eq!(a.len(), 1);
5829 assert_eq!(a[key], value);
5830 }
5831
5832 #[test]
5833 fn test_vacant_entry_ref_key() {
5834 let mut a: HashMap<std::string::String, &str> = HashMap::new();
5835 let key = "hello there";
5836 let value = "value goes here";
5837
5838 assert!(a.is_empty());
5839 match a.entry_ref(key) {
5840 EntryRef::Occupied(_) => panic!(),
5841 EntryRef::Vacant(e) => {
5842 assert_eq!(key, e.key());
5843 e.insert(value);
5844 }
5845 }
5846 assert_eq!(a.len(), 1);
5847 assert_eq!(a[key], value);
5848 }
5849
5850 #[test]
5851 fn test_occupied_entry_replace_entry_with() {
5852 let mut a = HashMap::new();
5853
5854 let key = "a key";
5855 let value = "an initial value";
5856 let new_value = "a new value";
5857
5858 let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
5859 assert_eq!(k, &key);
5860 assert_eq!(v, value);
5861 Some(new_value)
5862 });
5863
5864 match entry {
5865 Occupied(e) => {
5866 assert_eq!(e.key(), &key);
5867 assert_eq!(e.get(), &new_value);
5868 }
5869 Vacant(_) => panic!(),
5870 }
5871
5872 assert_eq!(a[key], new_value);
5873 assert_eq!(a.len(), 1);
5874
5875 let entry = match a.entry(key) {
5876 Occupied(e) => e.replace_entry_with(|k, v| {
5877 assert_eq!(k, &key);
5878 assert_eq!(v, new_value);
5879 None
5880 }),
5881 Vacant(_) => panic!(),
5882 };
5883
5884 match entry {
5885 Vacant(e) => assert_eq!(e.key(), &key),
5886 Occupied(_) => panic!(),
5887 }
5888
5889 assert!(!a.contains_key(key));
5890 assert_eq!(a.len(), 0);
5891 }
5892
5893 #[test]
5894 fn test_entry_and_replace_entry_with() {
5895 let mut a = HashMap::new();
5896
5897 let key = "a key";
5898 let value = "an initial value";
5899 let new_value = "a new value";
5900
5901 let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
5902
5903 match entry {
5904 Vacant(e) => assert_eq!(e.key(), &key),
5905 Occupied(_) => panic!(),
5906 }
5907
5908 a.insert(key, value);
5909
5910 let entry = a.entry(key).and_replace_entry_with(|k, v| {
5911 assert_eq!(k, &key);
5912 assert_eq!(v, value);
5913 Some(new_value)
5914 });
5915
5916 match entry {
5917 Occupied(e) => {
5918 assert_eq!(e.key(), &key);
5919 assert_eq!(e.get(), &new_value);
5920 }
5921 Vacant(_) => panic!(),
5922 }
5923
5924 assert_eq!(a[key], new_value);
5925 assert_eq!(a.len(), 1);
5926
5927 let entry = a.entry(key).and_replace_entry_with(|k, v| {
5928 assert_eq!(k, &key);
5929 assert_eq!(v, new_value);
5930 None
5931 });
5932
5933 match entry {
5934 Vacant(e) => assert_eq!(e.key(), &key),
5935 Occupied(_) => panic!(),
5936 }
5937
5938 assert!(!a.contains_key(key));
5939 assert_eq!(a.len(), 0);
5940 }
5941
5942 #[test]
5943 fn test_replace_entry_with_doesnt_corrupt() {
5944 #![allow(deprecated)] //rand
5945 // Test for #19292
5946 fn check(m: &HashMap<i32, ()>) {
5947 for k in m.keys() {
5948 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
5949 }
5950 }
5951
5952 let mut m = HashMap::new();
5953
5954 let mut rng = {
5955 let seed = u64::from_le_bytes(*b"testseed");
5956 SmallRng::seed_from_u64(seed)
5957 };
5958
5959 // Populate the map with some items.
5960 for _ in 0..50 {
5961 let x = rng.gen_range(-10..10);
5962 m.insert(x, ());
5963 }
5964
5965 for _ in 0..1000 {
5966 let x = rng.gen_range(-10..10);
5967 m.entry(x).and_replace_entry_with(|_, _| None);
5968 check(&m);
5969 }
5970 }
5971
5972 #[test]
5973 fn test_retain() {
5974 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
5975
5976 map.retain(|&k, _| k % 2 == 0);
5977 assert_eq!(map.len(), 50);
5978 assert_eq!(map[&2], 20);
5979 assert_eq!(map[&4], 40);
5980 assert_eq!(map[&6], 60);
5981 }
5982
5983 #[test]
5984 fn test_extract_if() {
5985 {
5986 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
5987 let drained = map.extract_if(|&k, _| k % 2 == 0);
5988 let mut out = drained.collect::<Vec<_>>();
5989 out.sort_unstable();
5990 assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
5991 assert_eq!(map.len(), 4);
5992 }
5993 {
5994 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
5995 map.extract_if(|&k, _| k % 2 == 0).for_each(drop);
5996 assert_eq!(map.len(), 4);
5997 }
5998 }
5999
6000 #[test]
6001 #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613)
6002 fn test_try_reserve() {
6003 use crate::TryReserveError::{AllocError, CapacityOverflow};
6004
6005 const MAX_ISIZE: usize = isize::MAX as usize;
6006
6007 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
6008
6009 if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
6010 } else {
6011 panic!("usize::MAX should trigger an overflow!");
6012 }
6013
6014 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
6015 } else {
6016 panic!("isize::MAX should trigger an overflow!");
6017 }
6018
6019 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
6020 } else {
6021 // This may succeed if there is enough free memory. Attempt to
6022 // allocate a few more hashmaps to ensure the allocation will fail.
6023 let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
6024 let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
6025 let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
6026 let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
6027 let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
6028 if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
6029 } else {
6030 panic!("isize::MAX / 5 should trigger an OOM!");
6031 }
6032 }
6033 }
6034
6035 #[test]
6036 fn test_const_with_hasher() {
6037 use core::hash::BuildHasher;
6038 use std::collections::hash_map::DefaultHasher;
6039
6040 #[derive(Clone)]
6041 struct MyHasher;
6042 impl BuildHasher for MyHasher {
6043 type Hasher = DefaultHasher;
6044
6045 fn build_hasher(&self) -> DefaultHasher {
6046 DefaultHasher::new()
6047 }
6048 }
6049
6050 const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> =
6051 HashMap::with_hasher(MyHasher);
6052
6053 let mut map = EMPTY_MAP;
6054 map.insert(17, "seventeen".to_owned());
6055 assert_eq!("seventeen", map[&17]);
6056 }
6057
6058 #[test]
6059 fn test_get_many_mut() {
6060 let mut map = HashMap::new();
6061 map.insert("foo".to_owned(), 0);
6062 map.insert("bar".to_owned(), 10);
6063 map.insert("baz".to_owned(), 20);
6064 map.insert("qux".to_owned(), 30);
6065
6066 let xs = map.get_many_mut(["foo", "qux"]);
6067 assert_eq!(xs, [Some(&mut 0), Some(&mut 30)]);
6068
6069 let xs = map.get_many_mut(["foo", "dud"]);
6070 assert_eq!(xs, [Some(&mut 0), None]);
6071
6072 let ys = map.get_many_key_value_mut(["bar", "baz"]);
6073 assert_eq!(
6074 ys,
6075 [
6076 Some((&"bar".to_owned(), &mut 10)),
6077 Some((&"baz".to_owned(), &mut 20))
6078 ],
6079 );
6080
6081 let ys = map.get_many_key_value_mut(["bar", "dip"]);
6082 assert_eq!(ys, [Some((&"bar".to_string(), &mut 10)), None]);
6083 }
6084
6085 #[test]
6086 #[should_panic = "duplicate keys found"]
6087 fn test_get_many_mut_duplicate() {
6088 let mut map = HashMap::new();
6089 map.insert("foo".to_owned(), 0);
6090
6091 let _xs = map.get_many_mut(["foo", "foo"]);
6092 }
6093
6094 #[test]
6095 #[should_panic = "panic in drop"]
6096 fn test_clone_from_double_drop() {
6097 #[derive(Clone)]
6098 struct CheckedDrop {
6099 panic_in_drop: bool,
6100 dropped: bool,
6101 }
6102 impl Drop for CheckedDrop {
6103 fn drop(&mut self) {
6104 if self.panic_in_drop {
6105 self.dropped = true;
6106 panic!("panic in drop");
6107 }
6108 if self.dropped {
6109 panic!("double drop");
6110 }
6111 self.dropped = true;
6112 }
6113 }
6114 const DISARMED: CheckedDrop = CheckedDrop {
6115 panic_in_drop: false,
6116 dropped: false,
6117 };
6118 const ARMED: CheckedDrop = CheckedDrop {
6119 panic_in_drop: true,
6120 dropped: false,
6121 };
6122
6123 let mut map1 = HashMap::new();
6124 map1.insert(1, DISARMED);
6125 map1.insert(2, DISARMED);
6126 map1.insert(3, DISARMED);
6127 map1.insert(4, DISARMED);
6128
6129 let mut map2 = HashMap::new();
6130 map2.insert(1, DISARMED);
6131 map2.insert(2, ARMED);
6132 map2.insert(3, DISARMED);
6133 map2.insert(4, DISARMED);
6134
6135 map2.clone_from(&map1);
6136 }
6137
6138 #[test]
6139 #[should_panic = "panic in clone"]
6140 fn test_clone_from_memory_leaks() {
6141 use alloc::vec::Vec;
6142
6143 struct CheckedClone {
6144 panic_in_clone: bool,
6145 need_drop: Vec<i32>,
6146 }
6147 impl Clone for CheckedClone {
6148 fn clone(&self) -> Self {
6149 if self.panic_in_clone {
6150 panic!("panic in clone")
6151 }
6152 Self {
6153 panic_in_clone: self.panic_in_clone,
6154 need_drop: self.need_drop.clone(),
6155 }
6156 }
6157 }
6158 let mut map1 = HashMap::new();
6159 map1.insert(
6160 1,
6161 CheckedClone {
6162 panic_in_clone: false,
6163 need_drop: vec![0, 1, 2],
6164 },
6165 );
6166 map1.insert(
6167 2,
6168 CheckedClone {
6169 panic_in_clone: false,
6170 need_drop: vec![3, 4, 5],
6171 },
6172 );
6173 map1.insert(
6174 3,
6175 CheckedClone {
6176 panic_in_clone: true,
6177 need_drop: vec![6, 7, 8],
6178 },
6179 );
6180 let _map2 = map1.clone();
6181 }
6182
6183 struct MyAllocInner {
6184 drop_count: Arc<AtomicI8>,
6185 }
6186
6187 #[derive(Clone)]
6188 struct MyAlloc {
6189 _inner: Arc<MyAllocInner>,
6190 }
6191
6192 impl MyAlloc {
6193 fn new(drop_count: Arc<AtomicI8>) -> Self {
6194 MyAlloc {
6195 _inner: Arc::new(MyAllocInner { drop_count }),
6196 }
6197 }
6198 }
6199
6200 impl Drop for MyAllocInner {
6201 fn drop(&mut self) {
6202 println!("MyAlloc freed.");
6203 self.drop_count.fetch_sub(1, Ordering::SeqCst);
6204 }
6205 }
6206
6207 unsafe impl Allocator for MyAlloc {
6208 fn allocate(&self, layout: Layout) -> std::result::Result<NonNull<[u8]>, AllocError> {
6209 let g = Global;
6210 g.allocate(layout)
6211 }
6212
6213 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
6214 let g = Global;
6215 g.deallocate(ptr, layout)
6216 }
6217 }
6218
6219 #[test]
6220 fn test_hashmap_into_iter_bug() {
6221 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
6222
6223 {
6224 let mut map = HashMap::with_capacity_in(10, MyAlloc::new(dropped.clone()));
6225 for i in 0..10 {
6226 map.entry(i).or_insert_with(|| "i".to_string());
6227 }
6228
6229 for (k, v) in map {
6230 println!("{k}, {v}");
6231 }
6232 }
6233
6234 // All allocator clones should already be dropped.
6235 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6236 }
6237
6238 #[derive(Debug)]
6239 struct CheckedCloneDrop<T> {
6240 panic_in_clone: bool,
6241 panic_in_drop: bool,
6242 dropped: bool,
6243 data: T,
6244 }
6245
6246 impl<T> CheckedCloneDrop<T> {
6247 fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
6248 CheckedCloneDrop {
6249 panic_in_clone,
6250 panic_in_drop,
6251 dropped: false,
6252 data,
6253 }
6254 }
6255 }
6256
6257 impl<T: Clone> Clone for CheckedCloneDrop<T> {
6258 fn clone(&self) -> Self {
6259 if self.panic_in_clone {
6260 panic!("panic in clone")
6261 }
6262 Self {
6263 panic_in_clone: self.panic_in_clone,
6264 panic_in_drop: self.panic_in_drop,
6265 dropped: self.dropped,
6266 data: self.data.clone(),
6267 }
6268 }
6269 }
6270
6271 impl<T> Drop for CheckedCloneDrop<T> {
6272 fn drop(&mut self) {
6273 if self.panic_in_drop {
6274 self.dropped = true;
6275 panic!("panic in drop");
6276 }
6277 if self.dropped {
6278 panic!("double drop");
6279 }
6280 self.dropped = true;
6281 }
6282 }
6283
6284 /// Return hashmap with predefined distribution of elements.
6285 /// All elements will be located in the same order as elements
6286 /// returned by iterator.
6287 ///
6288 /// This function does not panic, but returns an error as a `String`
6289 /// to distinguish between a test panic and an error in the input data.
6290 fn get_test_map<I, T, A>(
6291 iter: I,
6292 mut fun: impl FnMut(u64) -> T,
6293 alloc: A,
6294 ) -> Result<HashMap<u64, CheckedCloneDrop<T>, DefaultHashBuilder, A>, String>
6295 where
6296 I: Iterator<Item = (bool, bool)> + Clone + ExactSizeIterator,
6297 A: Allocator,
6298 T: PartialEq + core::fmt::Debug,
6299 {
6300 use crate::scopeguard::guard;
6301
6302 let mut map: HashMap<u64, CheckedCloneDrop<T>, _, A> =
6303 HashMap::with_capacity_in(iter.size_hint().0, alloc);
6304 {
6305 let mut guard = guard(&mut map, |map| {
6306 for (_, value) in map.iter_mut() {
6307 value.panic_in_drop = false
6308 }
6309 });
6310
6311 let mut count = 0;
6312 // Hash and Key must be equal to each other for controlling the elements placement.
6313 for (panic_in_clone, panic_in_drop) in iter.clone() {
6314 if core::mem::needs_drop::<T>() && panic_in_drop {
6315 return Err(String::from(
6316 "panic_in_drop can be set with a type that doesn't need to be dropped",
6317 ));
6318 }
6319 guard.table.insert(
6320 count,
6321 (
6322 count,
6323 CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)),
6324 ),
6325 |(k, _)| *k,
6326 );
6327 count += 1;
6328 }
6329
6330 // Let's check that all elements are located as we wanted
6331 let mut check_count = 0;
6332 for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) {
6333 if *key != check_count {
6334 return Err(format!(
6335 "key != check_count,\nkey: `{key}`,\ncheck_count: `{check_count}`"
6336 ));
6337 }
6338 if value.dropped
6339 || value.panic_in_clone != panic_in_clone
6340 || value.panic_in_drop != panic_in_drop
6341 || value.data != fun(check_count)
6342 {
6343 return Err(format!(
6344 "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \
6345 `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`",
6346 value, panic_in_clone, panic_in_drop, false, fun(check_count)
6347 ));
6348 }
6349 check_count += 1;
6350 }
6351
6352 if guard.len() != check_count as usize {
6353 return Err(format!(
6354 "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`",
6355 guard.len(),
6356 check_count
6357 ));
6358 }
6359
6360 if count != check_count {
6361 return Err(format!(
6362 "count != check_count,\ncount: `{count}`,\ncheck_count: `{check_count}`"
6363 ));
6364 }
6365 core::mem::forget(guard);
6366 }
6367 Ok(map)
6368 }
6369
6370 const DISARMED: bool = false;
6371 const ARMED: bool = true;
6372
6373 const ARMED_FLAGS: [bool; 8] = [
6374 DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6375 ];
6376
6377 const DISARMED_FLAGS: [bool; 8] = [
6378 DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED,
6379 ];
6380
6381 #[test]
6382 #[should_panic = "panic in clone"]
6383 fn test_clone_memory_leaks_and_double_drop_one() {
6384 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6385
6386 {
6387 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6388
6389 let map: HashMap<u64, CheckedCloneDrop<Vec<u64>>, DefaultHashBuilder, MyAlloc> =
6390 match get_test_map(
6391 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6392 |n| vec![n],
6393 MyAlloc::new(dropped.clone()),
6394 ) {
6395 Ok(map) => map,
6396 Err(msg) => panic!("{msg}"),
6397 };
6398
6399 // Clone should normally clone a few elements, and then (when the
6400 // clone function panics), deallocate both its own memory, memory
6401 // of `dropped: Arc<AtomicI8>` and the memory of already cloned
6402 // elements (Vec<i32> memory inside CheckedCloneDrop).
6403 let _map2 = map.clone();
6404 }
6405 }
6406
6407 #[test]
6408 #[should_panic = "panic in drop"]
6409 fn test_clone_memory_leaks_and_double_drop_two() {
6410 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6411
6412 {
6413 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6414
6415 let map: HashMap<u64, CheckedCloneDrop<u64>, DefaultHashBuilder, _> = match get_test_map(
6416 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6417 |n| n,
6418 MyAlloc::new(dropped.clone()),
6419 ) {
6420 Ok(map) => map,
6421 Err(msg) => panic!("{msg}"),
6422 };
6423
6424 let mut map2 = match get_test_map(
6425 DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS),
6426 |n| n,
6427 MyAlloc::new(dropped.clone()),
6428 ) {
6429 Ok(map) => map,
6430 Err(msg) => panic!("{msg}"),
6431 };
6432
6433 // The `clone_from` should try to drop the elements of `map2` without
6434 // double drop and leaking the allocator. Elements that have not been
6435 // dropped leak their memory.
6436 map2.clone_from(&map);
6437 }
6438 }
6439
6440 /// We check that we have a working table if the clone operation from another
6441 /// thread ended in a panic (when buckets of maps are equal to each other).
6442 #[test]
6443 fn test_catch_panic_clone_from_when_len_is_equal() {
6444 use std::thread;
6445
6446 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6447
6448 {
6449 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6450
6451 let mut map = match get_test_map(
6452 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6453 |n| vec![n],
6454 MyAlloc::new(dropped.clone()),
6455 ) {
6456 Ok(map) => map,
6457 Err(msg) => panic!("{msg}"),
6458 };
6459
6460 thread::scope(|s| {
6461 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6462 let scope_map =
6463 match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| vec![n * 2], MyAlloc::new(dropped.clone())) {
6464 Ok(map) => map,
6465 Err(msg) => return msg,
6466 };
6467 if map.table.buckets() != scope_map.table.buckets() {
6468 return format!(
6469 "map.table.buckets() != scope_map.table.buckets(),\nleft: `{}`,\nright: `{}`",
6470 map.table.buckets(), scope_map.table.buckets()
6471 );
6472 }
6473 map.clone_from(&scope_map);
6474 "We must fail the cloning!!!".to_owned()
6475 });
6476 if let Ok(msg) = result.join() {
6477 panic!("{msg}")
6478 }
6479 });
6480
6481 // Let's check that all iterators work fine and do not return elements
6482 // (especially `RawIterRange`, which does not depend on the number of
6483 // elements in the table, but looks directly at the control bytes)
6484 //
6485 // SAFETY: We know for sure that `RawTable` will outlive
6486 // the returned `RawIter / RawIterRange` iterator.
6487 assert_eq!(map.len(), 0);
6488 assert_eq!(map.iter().count(), 0);
6489 assert_eq!(unsafe { map.table.iter().count() }, 0);
6490 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6491
6492 for idx in 0..map.table.buckets() {
6493 let idx = idx as u64;
6494 assert!(
6495 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6496 "Index: {idx}"
6497 );
6498 }
6499 }
6500
6501 // All allocator clones should already be dropped.
6502 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6503 }
6504
6505 /// We check that we have a working table if the clone operation from another
6506 /// thread ended in a panic (when buckets of maps are not equal to each other).
6507 #[test]
6508 fn test_catch_panic_clone_from_when_len_is_not_equal() {
6509 use std::thread;
6510
6511 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
6512
6513 {
6514 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
6515
6516 let mut map = match get_test_map(
6517 [DISARMED].into_iter().zip([DISARMED]),
6518 |n| vec![n],
6519 MyAlloc::new(dropped.clone()),
6520 ) {
6521 Ok(map) => map,
6522 Err(msg) => panic!("{msg}"),
6523 };
6524
6525 thread::scope(|s| {
6526 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
6527 let scope_map = match get_test_map(
6528 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
6529 |n| vec![n * 2],
6530 MyAlloc::new(dropped.clone()),
6531 ) {
6532 Ok(map) => map,
6533 Err(msg) => return msg,
6534 };
6535 if map.table.buckets() == scope_map.table.buckets() {
6536 return format!(
6537 "map.table.buckets() == scope_map.table.buckets(): `{}`",
6538 map.table.buckets()
6539 );
6540 }
6541 map.clone_from(&scope_map);
6542 "We must fail the cloning!!!".to_owned()
6543 });
6544 if let Ok(msg) = result.join() {
6545 panic!("{msg}")
6546 }
6547 });
6548
6549 // Let's check that all iterators work fine and do not return elements
6550 // (especially `RawIterRange`, which does not depend on the number of
6551 // elements in the table, but looks directly at the control bytes)
6552 //
6553 // SAFETY: We know for sure that `RawTable` will outlive
6554 // the returned `RawIter / RawIterRange` iterator.
6555 assert_eq!(map.len(), 0);
6556 assert_eq!(map.iter().count(), 0);
6557 assert_eq!(unsafe { map.table.iter().count() }, 0);
6558 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
6559
6560 for idx in 0..map.table.buckets() {
6561 let idx = idx as u64;
6562 assert!(
6563 map.table.find(idx, |(k, _)| *k == idx).is_none(),
6564 "Index: {idx}"
6565 );
6566 }
6567 }
6568
6569 // All allocator clones should already be dropped.
6570 assert_eq!(dropped.load(Ordering::SeqCst), 0);
6571 }
6572
6573 #[test]
6574 fn test_allocation_info() {
6575 assert_eq!(HashMap::<(), ()>::new().allocation_size(), 0);
6576 assert_eq!(HashMap::<u32, u32>::new().allocation_size(), 0);
6577 assert!(
6578 HashMap::<u32, u32>::with_capacity(1).allocation_size() > core::mem::size_of::<u32>()
6579 );
6580 }
6581}