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