1use crate::raw::{
2 Allocator, Bucket, Global, RawDrain, RawExtractIf, RawIntoIter, RawIter, RawTable,
3};
4use crate::{Equivalent, TryReserveError};
5use core::borrow::Borrow;
6use core::fmt::{self, Debug};
7use core::hash::{BuildHasher, Hash};
8use core::iter::{FromIterator, FusedIterator};
9use core::marker::PhantomData;
10use core::mem;
11use core::ops::Index;
12
13/// Default hasher for `HashMap`.
14#[cfg(feature = "ahash")]
15pub type DefaultHashBuilder = core::hash::BuildHasherDefault<ahash::AHasher>;
16
17/// Dummy default hasher for `HashMap`.
18#[cfg(not(feature = "ahash"))]
19pub enum DefaultHashBuilder {}
20
21/// A hash map implemented with quadratic probing and SIMD lookup.
22///
23/// The default hashing algorithm is currently [`AHash`], though this is
24/// subject to change at any point in the future. This hash function is very
25/// fast for all types of keys, but this algorithm will typically *not* protect
26/// against attacks such as HashDoS.
27///
28/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
29/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
30/// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
31///
32/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
33/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
34/// If you implement these yourself, it is important that the following
35/// property holds:
36///
37/// ```text
38/// k1 == k2 -> hash(k1) == hash(k2)
39/// ```
40///
41/// In other words, if two keys are equal, their hashes must be equal.
42///
43/// It is a logic error for a key to be modified in such a way that the key's
44/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
45/// the [`Eq`] trait, changes while it is in the map. This is normally only
46/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
47///
48/// It is also a logic error for the [`Hash`] implementation of a key to panic.
49/// This is generally only possible if the trait is implemented manually. If a
50/// panic does occur then the contents of the `HashMap` may become corrupted and
51/// some items may be dropped from the table.
52///
53/// # Examples
54///
55/// ```
56/// use hashbrown::HashMap;
57///
58/// // Type inference lets us omit an explicit type signature (which
59/// // would be `HashMap<String, String>` in this example).
60/// let mut book_reviews = HashMap::new();
61///
62/// // Review some books.
63/// book_reviews.insert(
64/// "Adventures of Huckleberry Finn".to_string(),
65/// "My favorite book.".to_string(),
66/// );
67/// book_reviews.insert(
68/// "Grimms' Fairy Tales".to_string(),
69/// "Masterpiece.".to_string(),
70/// );
71/// book_reviews.insert(
72/// "Pride and Prejudice".to_string(),
73/// "Very enjoyable.".to_string(),
74/// );
75/// book_reviews.insert(
76/// "The Adventures of Sherlock Holmes".to_string(),
77/// "Eye lyked it alot.".to_string(),
78/// );
79///
80/// // Check for a specific one.
81/// // When collections store owned values (String), they can still be
82/// // queried using references (&str).
83/// if !book_reviews.contains_key("Les Misérables") {
84/// println!("We've got {} reviews, but Les Misérables ain't one.",
85/// book_reviews.len());
86/// }
87///
88/// // oops, this review has a lot of spelling mistakes, let's delete it.
89/// book_reviews.remove("The Adventures of Sherlock Holmes");
90///
91/// // Look up the values associated with some keys.
92/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
93/// for &book in &to_find {
94/// match book_reviews.get(book) {
95/// Some(review) => println!("{}: {}", book, review),
96/// None => println!("{} is unreviewed.", book)
97/// }
98/// }
99///
100/// // Look up the value for a key (will panic if the key is not found).
101/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
102///
103/// // Iterate over everything.
104/// for (book, review) in &book_reviews {
105/// println!("{}: \"{}\"", book, review);
106/// }
107/// ```
108///
109/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
110/// for more complex methods of getting, setting, updating and removing keys and
111/// their values:
112///
113/// ```
114/// use hashbrown::HashMap;
115///
116/// // type inference lets us omit an explicit type signature (which
117/// // would be `HashMap<&str, u8>` in this example).
118/// let mut player_stats = HashMap::new();
119///
120/// fn random_stat_buff() -> u8 {
121/// // could actually return some random value here - let's just return
122/// // some fixed value for now
123/// 42
124/// }
125///
126/// // insert a key only if it doesn't already exist
127/// player_stats.entry("health").or_insert(100);
128///
129/// // insert a key using a function that provides a new value only if it
130/// // doesn't already exist
131/// player_stats.entry("defence").or_insert_with(random_stat_buff);
132///
133/// // update a key, guarding against the key possibly not being set
134/// let stat = player_stats.entry("attack").or_insert(100);
135/// *stat += random_stat_buff();
136/// ```
137///
138/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
139/// We must also derive [`PartialEq`].
140///
141/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
142/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
143/// [`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
144/// [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html
145/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
146/// [`default`]: #method.default
147/// [`with_hasher`]: #method.with_hasher
148/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
149/// [`fnv`]: https://crates.io/crates/fnv
150/// [`AHash`]: https://crates.io/crates/ahash
151///
152/// ```
153/// use hashbrown::HashMap;
154///
155/// #[derive(Hash, Eq, PartialEq, Debug)]
156/// struct Viking {
157/// name: String,
158/// country: String,
159/// }
160///
161/// impl Viking {
162/// /// Creates a new Viking.
163/// fn new(name: &str, country: &str) -> Viking {
164/// Viking { name: name.to_string(), country: country.to_string() }
165/// }
166/// }
167///
168/// // Use a HashMap to store the vikings' health points.
169/// let mut vikings = HashMap::new();
170///
171/// vikings.insert(Viking::new("Einar", "Norway"), 25);
172/// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
173/// vikings.insert(Viking::new("Harald", "Iceland"), 12);
174///
175/// // Use derived implementation to print the status of the vikings.
176/// for (viking, health) in &vikings {
177/// println!("{:?} has {} hp", viking, health);
178/// }
179/// ```
180///
181/// A `HashMap` with fixed list of elements can be initialized from an array:
182///
183/// ```
184/// use hashbrown::HashMap;
185///
186/// let timber_resources: HashMap<&str, i32> = [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
187/// .iter().cloned().collect();
188/// // use the values stored in map
189/// ```
190pub struct HashMap<K, V, S = DefaultHashBuilder, A: Allocator = Global> {
191 pub(crate) hash_builder: S,
192 pub(crate) table: RawTable<(K, V), A>,
193}
194
195impl<K: Clone, V: Clone, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A> {
196 fn clone(&self) -> Self {
197 HashMap {
198 hash_builder: self.hash_builder.clone(),
199 table: self.table.clone(),
200 }
201 }
202
203 fn clone_from(&mut self, source: &Self) {
204 self.table.clone_from(&source.table);
205
206 // Update hash_builder only if we successfully cloned all elements.
207 self.hash_builder.clone_from(&source.hash_builder);
208 }
209}
210
211/// Ensures that a single closure type across uses of this which, in turn prevents multiple
212/// instances of any functions like RawTable::reserve from being generated
213#[cfg_attr(feature = "inline-more", inline)]
214pub(crate) fn make_hasher<Q, V, S>(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_
215where
216 Q: Hash,
217 S: BuildHasher,
218{
219 move |val| make_hash::<Q, S>(hash_builder, &val.0)
220}
221
222/// Ensures that a single closure type across uses of this which, in turn prevents multiple
223/// instances of any functions like RawTable::reserve from being generated
224#[cfg_attr(feature = "inline-more", inline)]
225fn equivalent_key<Q, K, V>(k: &Q) -> impl Fn(&(K, V)) -> bool + '_
226where
227 Q: ?Sized + Equivalent<K>,
228{
229 move |x| k.equivalent(&x.0)
230}
231
232/// Ensures that a single closure type across uses of this which, in turn prevents multiple
233/// instances of any functions like RawTable::reserve from being generated
234#[cfg_attr(feature = "inline-more", inline)]
235fn equivalent<Q, K>(k: &Q) -> impl Fn(&K) -> bool + '_
236where
237 Q: ?Sized + Equivalent<K>,
238{
239 move |x: &{unknown}| k.equivalent(key:x)
240}
241
242#[cfg(not(feature = "nightly"))]
243#[cfg_attr(feature = "inline-more", inline)]
244pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
245where
246 Q: Hash + ?Sized,
247 S: BuildHasher,
248{
249 use core::hash::Hasher;
250 let mut state = hash_builder.build_hasher();
251 val.hash(&mut state);
252 state.finish()
253}
254
255#[cfg(feature = "nightly")]
256#[cfg_attr(feature = "inline-more", inline)]
257pub(crate) fn make_hash<Q, S>(hash_builder: &S, val: &Q) -> u64
258where
259 Q: Hash + ?Sized,
260 S: BuildHasher,
261{
262 hash_builder.hash_one(val)
263}
264
265#[cfg(feature = "ahash")]
266impl<K, V> HashMap<K, V, DefaultHashBuilder> {
267 /// Creates an empty `HashMap`.
268 ///
269 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
270 /// is first inserted into.
271 ///
272 /// # HashDoS resistance
273 ///
274 /// The `hash_builder` normally use a fixed key by default and that does
275 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
276 /// Users who require HashDoS resistance should explicitly use
277 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
278 /// as the hasher when creating a [`HashMap`], for example with
279 /// [`with_hasher`](HashMap::with_hasher) method.
280 ///
281 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
282 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// use hashbrown::HashMap;
288 /// let mut map: HashMap<&str, i32> = HashMap::new();
289 /// assert_eq!(map.len(), 0);
290 /// assert_eq!(map.capacity(), 0);
291 /// ```
292 #[cfg_attr(feature = "inline-more", inline)]
293 pub fn new() -> Self {
294 Self::default()
295 }
296
297 /// Creates an empty `HashMap` with the specified capacity.
298 ///
299 /// The hash map will be able to hold at least `capacity` elements without
300 /// reallocating. If `capacity` is 0, the hash map will not allocate.
301 ///
302 /// # HashDoS resistance
303 ///
304 /// The `hash_builder` normally use a fixed key by default and that does
305 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
306 /// Users who require HashDoS resistance should explicitly use
307 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
308 /// as the hasher when creating a [`HashMap`], for example with
309 /// [`with_capacity_and_hasher`](HashMap::with_capacity_and_hasher) method.
310 ///
311 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
312 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// use hashbrown::HashMap;
318 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
319 /// assert_eq!(map.len(), 0);
320 /// assert!(map.capacity() >= 10);
321 /// ```
322 #[cfg_attr(feature = "inline-more", inline)]
323 pub fn with_capacity(capacity: usize) -> Self {
324 Self::with_capacity_and_hasher(capacity, DefaultHashBuilder::default())
325 }
326}
327
328#[cfg(feature = "ahash")]
329impl<K, V, A: Allocator> HashMap<K, V, DefaultHashBuilder, A> {
330 /// Creates an empty `HashMap` using the given allocator.
331 ///
332 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
333 /// is first inserted into.
334 ///
335 /// # HashDoS resistance
336 ///
337 /// The `hash_builder` normally use a fixed key by default and that does
338 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
339 /// Users who require HashDoS resistance should explicitly use
340 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
341 /// as the hasher when creating a [`HashMap`], for example with
342 /// [`with_hasher_in`](HashMap::with_hasher_in) method.
343 ///
344 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
345 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// use hashbrown::HashMap;
351 /// use bumpalo::Bump;
352 ///
353 /// let bump = Bump::new();
354 /// let mut map = HashMap::new_in(&bump);
355 ///
356 /// // The created HashMap holds none elements
357 /// assert_eq!(map.len(), 0);
358 ///
359 /// // The created HashMap also doesn't allocate memory
360 /// assert_eq!(map.capacity(), 0);
361 ///
362 /// // Now we insert element inside created HashMap
363 /// map.insert("One", 1);
364 /// // We can see that the HashMap holds 1 element
365 /// assert_eq!(map.len(), 1);
366 /// // And it also allocates some capacity
367 /// assert!(map.capacity() > 1);
368 /// ```
369 #[cfg_attr(feature = "inline-more", inline)]
370 pub fn new_in(alloc: A) -> Self {
371 Self::with_hasher_in(DefaultHashBuilder::default(), alloc)
372 }
373
374 /// Creates an empty `HashMap` with the specified capacity using the given allocator.
375 ///
376 /// The hash map will be able to hold at least `capacity` elements without
377 /// reallocating. If `capacity` is 0, the hash map will not allocate.
378 ///
379 /// # HashDoS resistance
380 ///
381 /// The `hash_builder` normally use a fixed key by default and that does
382 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
383 /// Users who require HashDoS resistance should explicitly use
384 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
385 /// as the hasher when creating a [`HashMap`], for example with
386 /// [`with_capacity_and_hasher_in`](HashMap::with_capacity_and_hasher_in) method.
387 ///
388 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
389 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
390 ///
391 /// # Examples
392 ///
393 /// ```
394 /// use hashbrown::HashMap;
395 /// use bumpalo::Bump;
396 ///
397 /// let bump = Bump::new();
398 /// let mut map = HashMap::with_capacity_in(5, &bump);
399 ///
400 /// // The created HashMap holds none elements
401 /// assert_eq!(map.len(), 0);
402 /// // But it can hold at least 5 elements without reallocating
403 /// let empty_map_capacity = map.capacity();
404 /// assert!(empty_map_capacity >= 5);
405 ///
406 /// // Now we insert some 5 elements inside created HashMap
407 /// map.insert("One", 1);
408 /// map.insert("Two", 2);
409 /// map.insert("Three", 3);
410 /// map.insert("Four", 4);
411 /// map.insert("Five", 5);
412 ///
413 /// // We can see that the HashMap holds 5 elements
414 /// assert_eq!(map.len(), 5);
415 /// // But its capacity isn't changed
416 /// assert_eq!(map.capacity(), empty_map_capacity)
417 /// ```
418 #[cfg_attr(feature = "inline-more", inline)]
419 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
420 Self::with_capacity_and_hasher_in(capacity, DefaultHashBuilder::default(), alloc)
421 }
422}
423
424impl<K, V, S> HashMap<K, V, S> {
425 /// Creates an empty `HashMap` which will use the given hash builder to hash
426 /// keys.
427 ///
428 /// The hash map is initially created with a capacity of 0, so it will not
429 /// allocate until it is first inserted into.
430 ///
431 /// # HashDoS resistance
432 ///
433 /// The `hash_builder` normally use a fixed key by default and that does
434 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
435 /// Users who require HashDoS resistance should explicitly use
436 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
437 /// as the hasher when creating a [`HashMap`].
438 ///
439 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
440 /// the HashMap to be useful, see its documentation for details.
441 ///
442 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
443 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
444 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
445 ///
446 /// # Examples
447 ///
448 /// ```
449 /// use hashbrown::HashMap;
450 /// use hashbrown::hash_map::DefaultHashBuilder;
451 ///
452 /// let s = DefaultHashBuilder::default();
453 /// let mut map = HashMap::with_hasher(s);
454 /// assert_eq!(map.len(), 0);
455 /// assert_eq!(map.capacity(), 0);
456 ///
457 /// map.insert(1, 2);
458 /// ```
459 #[cfg_attr(feature = "inline-more", inline)]
460 pub const fn with_hasher(hash_builder: S) -> Self {
461 Self {
462 hash_builder,
463 table: RawTable::new(),
464 }
465 }
466
467 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
468 /// to hash the keys.
469 ///
470 /// The hash map will be able to hold at least `capacity` elements without
471 /// reallocating. If `capacity` is 0, the hash map will not allocate.
472 ///
473 /// # HashDoS resistance
474 ///
475 /// The `hash_builder` normally use a fixed key by default and that does
476 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
477 /// Users who require HashDoS resistance should explicitly use
478 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
479 /// as the hasher when creating a [`HashMap`].
480 ///
481 /// The `hash_builder` passed should implement the [`BuildHasher`] trait for
482 /// the HashMap to be useful, see its documentation for details.
483 ///
484 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
485 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
486 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
487 ///
488 /// # Examples
489 ///
490 /// ```
491 /// use hashbrown::HashMap;
492 /// use hashbrown::hash_map::DefaultHashBuilder;
493 ///
494 /// let s = DefaultHashBuilder::default();
495 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
496 /// assert_eq!(map.len(), 0);
497 /// assert!(map.capacity() >= 10);
498 ///
499 /// map.insert(1, 2);
500 /// ```
501 #[cfg_attr(feature = "inline-more", inline)]
502 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
503 Self {
504 hash_builder,
505 table: RawTable::with_capacity(capacity),
506 }
507 }
508}
509
510impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
511 /// Returns a reference to the underlying allocator.
512 #[inline]
513 pub fn allocator(&self) -> &A {
514 self.table.allocator()
515 }
516
517 /// Creates an empty `HashMap` which will use the given hash builder to hash
518 /// keys. It will be allocated with the given allocator.
519 ///
520 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
521 /// is first inserted into.
522 ///
523 /// # HashDoS resistance
524 ///
525 /// The `hash_builder` normally use a fixed key by default and that does
526 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
527 /// Users who require HashDoS resistance should explicitly use
528 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
529 /// as the hasher when creating a [`HashMap`].
530 ///
531 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
532 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// use hashbrown::HashMap;
538 /// use hashbrown::hash_map::DefaultHashBuilder;
539 ///
540 /// let s = DefaultHashBuilder::default();
541 /// let mut map = HashMap::with_hasher(s);
542 /// map.insert(1, 2);
543 /// ```
544 #[cfg_attr(feature = "inline-more", inline)]
545 pub const fn with_hasher_in(hash_builder: S, alloc: A) -> Self {
546 Self {
547 hash_builder,
548 table: RawTable::new_in(alloc),
549 }
550 }
551
552 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
553 /// to hash the keys. It will be allocated with the given allocator.
554 ///
555 /// The hash map will be able to hold at least `capacity` elements without
556 /// reallocating. If `capacity` is 0, the hash map will not allocate.
557 ///
558 /// # HashDoS resistance
559 ///
560 /// The `hash_builder` normally use a fixed key by default and that does
561 /// not allow the `HashMap` to be protected against attacks such as [`HashDoS`].
562 /// Users who require HashDoS resistance should explicitly use
563 /// [`ahash::RandomState`] or [`std::collections::hash_map::RandomState`]
564 /// as the hasher when creating a [`HashMap`].
565 ///
566 /// [`HashDoS`]: https://en.wikipedia.org/wiki/Collision_attack
567 /// [`std::collections::hash_map::RandomState`]: https://doc.rust-lang.org/std/collections/hash_map/struct.RandomState.html
568 ///
569 /// # Examples
570 ///
571 /// ```
572 /// use hashbrown::HashMap;
573 /// use hashbrown::hash_map::DefaultHashBuilder;
574 ///
575 /// let s = DefaultHashBuilder::default();
576 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
577 /// map.insert(1, 2);
578 /// ```
579 #[cfg_attr(feature = "inline-more", inline)]
580 pub fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> Self {
581 Self {
582 hash_builder,
583 table: RawTable::with_capacity_in(capacity, alloc),
584 }
585 }
586
587 /// Returns a reference to the map's [`BuildHasher`].
588 ///
589 /// [`BuildHasher`]: https://doc.rust-lang.org/std/hash/trait.BuildHasher.html
590 ///
591 /// # Examples
592 ///
593 /// ```
594 /// use hashbrown::HashMap;
595 /// use hashbrown::hash_map::DefaultHashBuilder;
596 ///
597 /// let hasher = DefaultHashBuilder::default();
598 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
599 /// let hasher: &DefaultHashBuilder = map.hasher();
600 /// ```
601 #[cfg_attr(feature = "inline-more", inline)]
602 pub fn hasher(&self) -> &S {
603 &self.hash_builder
604 }
605
606 /// Returns the number of elements the map can hold without reallocating.
607 ///
608 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
609 /// more, but is guaranteed to be able to hold at least this many.
610 ///
611 /// # Examples
612 ///
613 /// ```
614 /// use hashbrown::HashMap;
615 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
616 /// assert_eq!(map.len(), 0);
617 /// assert!(map.capacity() >= 100);
618 /// ```
619 #[cfg_attr(feature = "inline-more", inline)]
620 pub fn capacity(&self) -> usize {
621 self.table.capacity()
622 }
623
624 /// An iterator visiting all keys in arbitrary order.
625 /// The iterator element type is `&'a K`.
626 ///
627 /// # Examples
628 ///
629 /// ```
630 /// use hashbrown::HashMap;
631 ///
632 /// let mut map = HashMap::new();
633 /// map.insert("a", 1);
634 /// map.insert("b", 2);
635 /// map.insert("c", 3);
636 /// assert_eq!(map.len(), 3);
637 /// let mut vec: Vec<&str> = Vec::new();
638 ///
639 /// for key in map.keys() {
640 /// println!("{}", key);
641 /// vec.push(*key);
642 /// }
643 ///
644 /// // The `Keys` iterator produces keys in arbitrary order, so the
645 /// // keys must be sorted to test them against a sorted array.
646 /// vec.sort_unstable();
647 /// assert_eq!(vec, ["a", "b", "c"]);
648 ///
649 /// assert_eq!(map.len(), 3);
650 /// ```
651 #[cfg_attr(feature = "inline-more", inline)]
652 pub fn keys(&self) -> Keys<'_, K, V> {
653 Keys { inner: self.iter() }
654 }
655
656 /// An iterator visiting all values in arbitrary order.
657 /// The iterator element type is `&'a V`.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// use hashbrown::HashMap;
663 ///
664 /// let mut map = HashMap::new();
665 /// map.insert("a", 1);
666 /// map.insert("b", 2);
667 /// map.insert("c", 3);
668 /// assert_eq!(map.len(), 3);
669 /// let mut vec: Vec<i32> = Vec::new();
670 ///
671 /// for val in map.values() {
672 /// println!("{}", val);
673 /// vec.push(*val);
674 /// }
675 ///
676 /// // The `Values` iterator produces values in arbitrary order, so the
677 /// // values must be sorted to test them against a sorted array.
678 /// vec.sort_unstable();
679 /// assert_eq!(vec, [1, 2, 3]);
680 ///
681 /// assert_eq!(map.len(), 3);
682 /// ```
683 #[cfg_attr(feature = "inline-more", inline)]
684 pub fn values(&self) -> Values<'_, K, V> {
685 Values { inner: self.iter() }
686 }
687
688 /// An iterator visiting all values mutably in arbitrary order.
689 /// The iterator element type is `&'a mut V`.
690 ///
691 /// # Examples
692 ///
693 /// ```
694 /// use hashbrown::HashMap;
695 ///
696 /// let mut map = HashMap::new();
697 ///
698 /// map.insert("a", 1);
699 /// map.insert("b", 2);
700 /// map.insert("c", 3);
701 ///
702 /// for val in map.values_mut() {
703 /// *val = *val + 10;
704 /// }
705 ///
706 /// assert_eq!(map.len(), 3);
707 /// let mut vec: Vec<i32> = Vec::new();
708 ///
709 /// for val in map.values() {
710 /// println!("{}", val);
711 /// vec.push(*val);
712 /// }
713 ///
714 /// // The `Values` iterator produces values in arbitrary order, so the
715 /// // values must be sorted to test them against a sorted array.
716 /// vec.sort_unstable();
717 /// assert_eq!(vec, [11, 12, 13]);
718 ///
719 /// assert_eq!(map.len(), 3);
720 /// ```
721 #[cfg_attr(feature = "inline-more", inline)]
722 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
723 ValuesMut {
724 inner: self.iter_mut(),
725 }
726 }
727
728 /// An iterator visiting all key-value pairs in arbitrary order.
729 /// The iterator element type is `(&'a K, &'a V)`.
730 ///
731 /// # Examples
732 ///
733 /// ```
734 /// use hashbrown::HashMap;
735 ///
736 /// let mut map = HashMap::new();
737 /// map.insert("a", 1);
738 /// map.insert("b", 2);
739 /// map.insert("c", 3);
740 /// assert_eq!(map.len(), 3);
741 /// let mut vec: Vec<(&str, i32)> = Vec::new();
742 ///
743 /// for (key, val) in map.iter() {
744 /// println!("key: {} val: {}", key, val);
745 /// vec.push((*key, *val));
746 /// }
747 ///
748 /// // The `Iter` iterator produces items in arbitrary order, so the
749 /// // items must be sorted to test them against a sorted array.
750 /// vec.sort_unstable();
751 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
752 ///
753 /// assert_eq!(map.len(), 3);
754 /// ```
755 #[cfg_attr(feature = "inline-more", inline)]
756 pub fn iter(&self) -> Iter<'_, K, V> {
757 // Here we tie the lifetime of self to the iter.
758 unsafe {
759 Iter {
760 inner: self.table.iter(),
761 marker: PhantomData,
762 }
763 }
764 }
765
766 /// An iterator visiting all key-value pairs in arbitrary order,
767 /// with mutable references to the values.
768 /// The iterator element type is `(&'a K, &'a mut V)`.
769 ///
770 /// # Examples
771 ///
772 /// ```
773 /// use hashbrown::HashMap;
774 ///
775 /// let mut map = HashMap::new();
776 /// map.insert("a", 1);
777 /// map.insert("b", 2);
778 /// map.insert("c", 3);
779 ///
780 /// // Update all values
781 /// for (_, val) in map.iter_mut() {
782 /// *val *= 2;
783 /// }
784 ///
785 /// assert_eq!(map.len(), 3);
786 /// let mut vec: Vec<(&str, i32)> = Vec::new();
787 ///
788 /// for (key, val) in &map {
789 /// println!("key: {} val: {}", key, val);
790 /// vec.push((*key, *val));
791 /// }
792 ///
793 /// // The `Iter` iterator produces items in arbitrary order, so the
794 /// // items must be sorted to test them against a sorted array.
795 /// vec.sort_unstable();
796 /// assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
797 ///
798 /// assert_eq!(map.len(), 3);
799 /// ```
800 #[cfg_attr(feature = "inline-more", inline)]
801 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
802 // Here we tie the lifetime of self to the iter.
803 unsafe {
804 IterMut {
805 inner: self.table.iter(),
806 marker: PhantomData,
807 }
808 }
809 }
810
811 #[cfg(test)]
812 #[cfg_attr(feature = "inline-more", inline)]
813 fn raw_capacity(&self) -> usize {
814 self.table.buckets()
815 }
816
817 /// Returns the number of elements in the map.
818 ///
819 /// # Examples
820 ///
821 /// ```
822 /// use hashbrown::HashMap;
823 ///
824 /// let mut a = HashMap::new();
825 /// assert_eq!(a.len(), 0);
826 /// a.insert(1, "a");
827 /// assert_eq!(a.len(), 1);
828 /// ```
829 #[cfg_attr(feature = "inline-more", inline)]
830 pub fn len(&self) -> usize {
831 self.table.len()
832 }
833
834 /// Returns `true` if the map contains no elements.
835 ///
836 /// # Examples
837 ///
838 /// ```
839 /// use hashbrown::HashMap;
840 ///
841 /// let mut a = HashMap::new();
842 /// assert!(a.is_empty());
843 /// a.insert(1, "a");
844 /// assert!(!a.is_empty());
845 /// ```
846 #[cfg_attr(feature = "inline-more", inline)]
847 pub fn is_empty(&self) -> bool {
848 self.len() == 0
849 }
850
851 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
852 /// allocated memory for reuse.
853 ///
854 /// If the returned iterator is dropped before being fully consumed, it
855 /// drops the remaining key-value pairs. The returned iterator keeps a
856 /// mutable borrow on the vector to optimize its implementation.
857 ///
858 /// # Examples
859 ///
860 /// ```
861 /// use hashbrown::HashMap;
862 ///
863 /// let mut a = HashMap::new();
864 /// a.insert(1, "a");
865 /// a.insert(2, "b");
866 /// let capacity_before_drain = a.capacity();
867 ///
868 /// for (k, v) in a.drain().take(1) {
869 /// assert!(k == 1 || k == 2);
870 /// assert!(v == "a" || v == "b");
871 /// }
872 ///
873 /// // As we can see, the map is empty and contains no element.
874 /// assert!(a.is_empty() && a.len() == 0);
875 /// // But map capacity is equal to old one.
876 /// assert_eq!(a.capacity(), capacity_before_drain);
877 ///
878 /// let mut a = HashMap::new();
879 /// a.insert(1, "a");
880 /// a.insert(2, "b");
881 ///
882 /// { // Iterator is dropped without being consumed.
883 /// let d = a.drain();
884 /// }
885 ///
886 /// // But the map is empty even if we do not use Drain iterator.
887 /// assert!(a.is_empty());
888 /// ```
889 #[cfg_attr(feature = "inline-more", inline)]
890 pub fn drain(&mut self) -> Drain<'_, K, V, A> {
891 Drain {
892 inner: self.table.drain(),
893 }
894 }
895
896 /// Retains only the elements specified by the predicate. Keeps the
897 /// allocated memory for reuse.
898 ///
899 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
900 /// The elements are visited in unsorted (and unspecified) order.
901 ///
902 /// # Examples
903 ///
904 /// ```
905 /// use hashbrown::HashMap;
906 ///
907 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
908 /// assert_eq!(map.len(), 8);
909 ///
910 /// map.retain(|&k, _| k % 2 == 0);
911 ///
912 /// // We can see, that the number of elements inside map is changed.
913 /// assert_eq!(map.len(), 4);
914 ///
915 /// let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
916 /// vec.sort_unstable();
917 /// assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
918 /// ```
919 pub fn retain<F>(&mut self, mut f: F)
920 where
921 F: FnMut(&K, &mut V) -> bool,
922 {
923 // Here we only use `iter` as a temporary, preventing use-after-free
924 unsafe {
925 for item in self.table.iter() {
926 let &mut (ref key, ref mut value) = item.as_mut();
927 if !f(key, value) {
928 self.table.erase(item);
929 }
930 }
931 }
932 }
933
934 /// Drains elements which are true under the given predicate,
935 /// and returns an iterator over the removed items.
936 ///
937 /// In other words, move all pairs `(k, v)` such that `f(&k, &mut v)` returns `true` out
938 /// into another iterator.
939 ///
940 /// Note that `extract_if` lets you mutate every value in the filter closure, regardless of
941 /// whether you choose to keep or remove it.
942 ///
943 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
944 /// or the iteration short-circuits, then the remaining elements will be retained.
945 /// Use [`retain()`] with a negated predicate if you do not need the returned iterator.
946 ///
947 /// Keeps the allocated memory for reuse.
948 ///
949 /// [`retain()`]: HashMap::retain
950 ///
951 /// # Examples
952 ///
953 /// ```
954 /// use hashbrown::HashMap;
955 ///
956 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
957 ///
958 /// let drained: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
959 ///
960 /// let mut evens = drained.keys().cloned().collect::<Vec<_>>();
961 /// let mut odds = map.keys().cloned().collect::<Vec<_>>();
962 /// evens.sort();
963 /// odds.sort();
964 ///
965 /// assert_eq!(evens, vec![0, 2, 4, 6]);
966 /// assert_eq!(odds, vec![1, 3, 5, 7]);
967 ///
968 /// let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
969 ///
970 /// { // Iterator is dropped without being consumed.
971 /// let d = map.extract_if(|k, _v| k % 2 != 0);
972 /// }
973 ///
974 /// // ExtractIf was not exhausted, therefore no elements were drained.
975 /// assert_eq!(map.len(), 8);
976 /// ```
977 #[cfg_attr(feature = "inline-more", inline)]
978 pub fn extract_if<F>(&mut self, f: F) -> ExtractIf<'_, K, V, F, A>
979 where
980 F: FnMut(&K, &mut V) -> bool,
981 {
982 ExtractIf {
983 f,
984 inner: RawExtractIf {
985 iter: unsafe { self.table.iter() },
986 table: &mut self.table,
987 },
988 }
989 }
990
991 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
992 /// for reuse.
993 ///
994 /// # Examples
995 ///
996 /// ```
997 /// use hashbrown::HashMap;
998 ///
999 /// let mut a = HashMap::new();
1000 /// a.insert(1, "a");
1001 /// let capacity_before_clear = a.capacity();
1002 ///
1003 /// a.clear();
1004 ///
1005 /// // Map is empty.
1006 /// assert!(a.is_empty());
1007 /// // But map capacity is equal to old one.
1008 /// assert_eq!(a.capacity(), capacity_before_clear);
1009 /// ```
1010 #[cfg_attr(feature = "inline-more", inline)]
1011 pub fn clear(&mut self) {
1012 self.table.clear();
1013 }
1014
1015 /// Creates a consuming iterator visiting all the keys in arbitrary order.
1016 /// The map cannot be used after calling this.
1017 /// The iterator element type is `K`.
1018 ///
1019 /// # Examples
1020 ///
1021 /// ```
1022 /// use hashbrown::HashMap;
1023 ///
1024 /// let mut map = HashMap::new();
1025 /// map.insert("a", 1);
1026 /// map.insert("b", 2);
1027 /// map.insert("c", 3);
1028 ///
1029 /// let mut vec: Vec<&str> = map.into_keys().collect();
1030 ///
1031 /// // The `IntoKeys` iterator produces keys in arbitrary order, so the
1032 /// // keys must be sorted to test them against a sorted array.
1033 /// vec.sort_unstable();
1034 /// assert_eq!(vec, ["a", "b", "c"]);
1035 /// ```
1036 #[inline]
1037 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1038 IntoKeys {
1039 inner: self.into_iter(),
1040 }
1041 }
1042
1043 /// Creates a consuming iterator visiting all the values in arbitrary order.
1044 /// The map cannot be used after calling this.
1045 /// The iterator element type is `V`.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// use hashbrown::HashMap;
1051 ///
1052 /// let mut map = HashMap::new();
1053 /// map.insert("a", 1);
1054 /// map.insert("b", 2);
1055 /// map.insert("c", 3);
1056 ///
1057 /// let mut vec: Vec<i32> = map.into_values().collect();
1058 ///
1059 /// // The `IntoValues` iterator produces values in arbitrary order, so
1060 /// // the values must be sorted to test them against a sorted array.
1061 /// vec.sort_unstable();
1062 /// assert_eq!(vec, [1, 2, 3]);
1063 /// ```
1064 #[inline]
1065 pub fn into_values(self) -> IntoValues<K, V, A> {
1066 IntoValues {
1067 inner: self.into_iter(),
1068 }
1069 }
1070}
1071
1072impl<K, V, S, A> HashMap<K, V, S, A>
1073where
1074 K: Eq + Hash,
1075 S: BuildHasher,
1076 A: Allocator,
1077{
1078 /// Reserves capacity for at least `additional` more elements to be inserted
1079 /// in the `HashMap`. The collection may reserve more space to avoid
1080 /// frequent reallocations.
1081 ///
1082 /// # Panics
1083 ///
1084 /// Panics if the new capacity exceeds [`isize::MAX`] bytes and [`abort`] the program
1085 /// in case of allocation error. Use [`try_reserve`](HashMap::try_reserve) instead
1086 /// if you want to handle memory allocation failure.
1087 ///
1088 /// [`isize::MAX`]: https://doc.rust-lang.org/std/primitive.isize.html
1089 /// [`abort`]: https://doc.rust-lang.org/alloc/alloc/fn.handle_alloc_error.html
1090 ///
1091 /// # Examples
1092 ///
1093 /// ```
1094 /// use hashbrown::HashMap;
1095 /// let mut map: HashMap<&str, i32> = HashMap::new();
1096 /// // Map is empty and doesn't allocate memory
1097 /// assert_eq!(map.capacity(), 0);
1098 ///
1099 /// map.reserve(10);
1100 ///
1101 /// // And now map can hold at least 10 elements
1102 /// assert!(map.capacity() >= 10);
1103 /// ```
1104 #[cfg_attr(feature = "inline-more", inline)]
1105 pub fn reserve(&mut self, additional: usize) {
1106 self.table
1107 .reserve(additional, make_hasher::<_, V, S>(&self.hash_builder));
1108 }
1109
1110 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1111 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
1112 /// frequent reallocations.
1113 ///
1114 /// # Errors
1115 ///
1116 /// If the capacity overflows, or the allocator reports a failure, then an error
1117 /// is returned.
1118 ///
1119 /// # Examples
1120 ///
1121 /// ```
1122 /// use hashbrown::HashMap;
1123 ///
1124 /// let mut map: HashMap<&str, isize> = HashMap::new();
1125 /// // Map is empty and doesn't allocate memory
1126 /// assert_eq!(map.capacity(), 0);
1127 ///
1128 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
1129 ///
1130 /// // And now map can hold at least 10 elements
1131 /// assert!(map.capacity() >= 10);
1132 /// ```
1133 /// If the capacity overflows, or the allocator reports a failure, then an error
1134 /// is returned:
1135 /// ```
1136 /// # fn test() {
1137 /// use hashbrown::HashMap;
1138 /// use hashbrown::TryReserveError;
1139 /// let mut map: HashMap<i32, i32> = HashMap::new();
1140 ///
1141 /// match map.try_reserve(usize::MAX) {
1142 /// Err(error) => match error {
1143 /// TryReserveError::CapacityOverflow => {}
1144 /// _ => panic!("TryReserveError::AllocError ?"),
1145 /// },
1146 /// _ => panic!(),
1147 /// }
1148 /// # }
1149 /// # fn main() {
1150 /// # #[cfg(not(miri))]
1151 /// # test()
1152 /// # }
1153 /// ```
1154 #[cfg_attr(feature = "inline-more", inline)]
1155 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1156 self.table
1157 .try_reserve(additional, make_hasher::<_, V, S>(&self.hash_builder))
1158 }
1159
1160 /// Shrinks the capacity of the map as much as possible. It will drop
1161 /// down as much as possible while maintaining the internal rules
1162 /// and possibly leaving some space in accordance with the resize policy.
1163 ///
1164 /// # Examples
1165 ///
1166 /// ```
1167 /// use hashbrown::HashMap;
1168 ///
1169 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1170 /// map.insert(1, 2);
1171 /// map.insert(3, 4);
1172 /// assert!(map.capacity() >= 100);
1173 /// map.shrink_to_fit();
1174 /// assert!(map.capacity() >= 2);
1175 /// ```
1176 #[cfg_attr(feature = "inline-more", inline)]
1177 pub fn shrink_to_fit(&mut self) {
1178 self.table
1179 .shrink_to(0, make_hasher::<_, V, S>(&self.hash_builder));
1180 }
1181
1182 /// Shrinks the capacity of the map with a lower limit. It will drop
1183 /// down no lower than the supplied limit while maintaining the internal rules
1184 /// and possibly leaving some space in accordance with the resize policy.
1185 ///
1186 /// This function does nothing if the current capacity is smaller than the
1187 /// supplied minimum capacity.
1188 ///
1189 /// # Examples
1190 ///
1191 /// ```
1192 /// use hashbrown::HashMap;
1193 ///
1194 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1195 /// map.insert(1, 2);
1196 /// map.insert(3, 4);
1197 /// assert!(map.capacity() >= 100);
1198 /// map.shrink_to(10);
1199 /// assert!(map.capacity() >= 10);
1200 /// map.shrink_to(0);
1201 /// assert!(map.capacity() >= 2);
1202 /// map.shrink_to(10);
1203 /// assert!(map.capacity() >= 2);
1204 /// ```
1205 #[cfg_attr(feature = "inline-more", inline)]
1206 pub fn shrink_to(&mut self, min_capacity: usize) {
1207 self.table
1208 .shrink_to(min_capacity, make_hasher::<_, V, S>(&self.hash_builder));
1209 }
1210
1211 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```
1216 /// use hashbrown::HashMap;
1217 ///
1218 /// let mut letters = HashMap::new();
1219 ///
1220 /// for ch in "a short treatise on fungi".chars() {
1221 /// let counter = letters.entry(ch).or_insert(0);
1222 /// *counter += 1;
1223 /// }
1224 ///
1225 /// assert_eq!(letters[&'s'], 2);
1226 /// assert_eq!(letters[&'t'], 3);
1227 /// assert_eq!(letters[&'u'], 1);
1228 /// assert_eq!(letters.get(&'y'), None);
1229 /// ```
1230 #[cfg_attr(feature = "inline-more", inline)]
1231 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> {
1232 let hash = make_hash::<K, S>(&self.hash_builder, &key);
1233 if let Some(elem) = self.table.find(hash, equivalent_key(&key)) {
1234 Entry::Occupied(OccupiedEntry {
1235 hash,
1236 key: Some(key),
1237 elem,
1238 table: self,
1239 })
1240 } else {
1241 Entry::Vacant(VacantEntry {
1242 hash,
1243 key,
1244 table: self,
1245 })
1246 }
1247 }
1248
1249 /// Gets the given key's corresponding entry by reference in the map for in-place manipulation.
1250 ///
1251 /// # Examples
1252 ///
1253 /// ```
1254 /// use hashbrown::HashMap;
1255 ///
1256 /// let mut words: HashMap<String, usize> = HashMap::new();
1257 /// let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
1258 /// for (i, &s) in source.iter().enumerate() {
1259 /// let counter = words.entry_ref(s).or_insert(0);
1260 /// *counter += 1;
1261 /// }
1262 ///
1263 /// assert_eq!(words["poneyland"], 3);
1264 /// assert_eq!(words["horseyland"], 1);
1265 /// ```
1266 #[cfg_attr(feature = "inline-more", inline)]
1267 pub fn entry_ref<'a, 'b, Q: ?Sized>(&'a mut self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A>
1268 where
1269 Q: Hash + Equivalent<K>,
1270 {
1271 let hash = make_hash::<Q, S>(&self.hash_builder, key);
1272 if let Some(elem) = self.table.find(hash, equivalent_key(key)) {
1273 EntryRef::Occupied(OccupiedEntryRef {
1274 hash,
1275 key: Some(KeyOrRef::Borrowed(key)),
1276 elem,
1277 table: self,
1278 })
1279 } else {
1280 EntryRef::Vacant(VacantEntryRef {
1281 hash,
1282 key: KeyOrRef::Borrowed(key),
1283 table: self,
1284 })
1285 }
1286 }
1287
1288 /// Returns a reference to the value corresponding to the key.
1289 ///
1290 /// The key may be any borrowed form of the map's key type, but
1291 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1292 /// the key type.
1293 ///
1294 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1295 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1296 ///
1297 /// # Examples
1298 ///
1299 /// ```
1300 /// use hashbrown::HashMap;
1301 ///
1302 /// let mut map = HashMap::new();
1303 /// map.insert(1, "a");
1304 /// assert_eq!(map.get(&1), Some(&"a"));
1305 /// assert_eq!(map.get(&2), None);
1306 /// ```
1307 #[inline]
1308 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1309 where
1310 Q: Hash + Equivalent<K>,
1311 {
1312 // Avoid `Option::map` because it bloats LLVM IR.
1313 match self.get_inner(k) {
1314 Some((_, v)) => Some(v),
1315 None => None,
1316 }
1317 }
1318
1319 /// Returns the key-value pair corresponding to the supplied key.
1320 ///
1321 /// The supplied key may be any borrowed form of the map's key type, but
1322 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1323 /// the key type.
1324 ///
1325 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1326 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1327 ///
1328 /// # Examples
1329 ///
1330 /// ```
1331 /// use hashbrown::HashMap;
1332 ///
1333 /// let mut map = HashMap::new();
1334 /// map.insert(1, "a");
1335 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1336 /// assert_eq!(map.get_key_value(&2), None);
1337 /// ```
1338 #[inline]
1339 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1340 where
1341 Q: Hash + Equivalent<K>,
1342 {
1343 // Avoid `Option::map` because it bloats LLVM IR.
1344 match self.get_inner(k) {
1345 Some((key, value)) => Some((key, value)),
1346 None => None,
1347 }
1348 }
1349
1350 #[inline]
1351 fn get_inner<Q: ?Sized>(&self, k: &Q) -> Option<&(K, V)>
1352 where
1353 Q: Hash + Equivalent<K>,
1354 {
1355 if self.table.is_empty() {
1356 None
1357 } else {
1358 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1359 self.table.get(hash, equivalent_key(k))
1360 }
1361 }
1362
1363 /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value.
1364 ///
1365 /// The supplied key may be any borrowed form of the map's key type, but
1366 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1367 /// the key type.
1368 ///
1369 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1370 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1371 ///
1372 /// # Examples
1373 ///
1374 /// ```
1375 /// use hashbrown::HashMap;
1376 ///
1377 /// let mut map = HashMap::new();
1378 /// map.insert(1, "a");
1379 /// let (k, v) = map.get_key_value_mut(&1).unwrap();
1380 /// assert_eq!(k, &1);
1381 /// assert_eq!(v, &mut "a");
1382 /// *v = "b";
1383 /// assert_eq!(map.get_key_value_mut(&1), Some((&1, &mut "b")));
1384 /// assert_eq!(map.get_key_value_mut(&2), None);
1385 /// ```
1386 #[inline]
1387 pub fn get_key_value_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<(&K, &mut V)>
1388 where
1389 Q: Hash + Equivalent<K>,
1390 {
1391 // Avoid `Option::map` because it bloats LLVM IR.
1392 match self.get_inner_mut(k) {
1393 Some(&mut (ref key, ref mut value)) => Some((key, value)),
1394 None => None,
1395 }
1396 }
1397
1398 /// Returns `true` if the map contains a value for the specified key.
1399 ///
1400 /// The key may be any borrowed form of the map's key type, but
1401 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1402 /// the key type.
1403 ///
1404 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1405 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1406 ///
1407 /// # Examples
1408 ///
1409 /// ```
1410 /// use hashbrown::HashMap;
1411 ///
1412 /// let mut map = HashMap::new();
1413 /// map.insert(1, "a");
1414 /// assert_eq!(map.contains_key(&1), true);
1415 /// assert_eq!(map.contains_key(&2), false);
1416 /// ```
1417 #[cfg_attr(feature = "inline-more", inline)]
1418 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1419 where
1420 Q: Hash + Equivalent<K>,
1421 {
1422 self.get_inner(k).is_some()
1423 }
1424
1425 /// Returns a mutable reference to the value corresponding to the key.
1426 ///
1427 /// The key may be any borrowed form of the map's key type, but
1428 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1429 /// the key type.
1430 ///
1431 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1432 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1433 ///
1434 /// # Examples
1435 ///
1436 /// ```
1437 /// use hashbrown::HashMap;
1438 ///
1439 /// let mut map = HashMap::new();
1440 /// map.insert(1, "a");
1441 /// if let Some(x) = map.get_mut(&1) {
1442 /// *x = "b";
1443 /// }
1444 /// assert_eq!(map[&1], "b");
1445 ///
1446 /// assert_eq!(map.get_mut(&2), None);
1447 /// ```
1448 #[cfg_attr(feature = "inline-more", inline)]
1449 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1450 where
1451 Q: Hash + Equivalent<K>,
1452 {
1453 // Avoid `Option::map` because it bloats LLVM IR.
1454 match self.get_inner_mut(k) {
1455 Some(&mut (_, ref mut v)) => Some(v),
1456 None => None,
1457 }
1458 }
1459
1460 #[inline]
1461 fn get_inner_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut (K, V)>
1462 where
1463 Q: Hash + Equivalent<K>,
1464 {
1465 if self.table.is_empty() {
1466 None
1467 } else {
1468 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1469 self.table.get_mut(hash, equivalent_key(k))
1470 }
1471 }
1472
1473 /// Attempts to get mutable references to `N` values in the map at once.
1474 ///
1475 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1476 /// mutable reference will be returned to any value. `None` will be returned if any of the
1477 /// keys are duplicates or missing.
1478 ///
1479 /// # Examples
1480 ///
1481 /// ```
1482 /// use hashbrown::HashMap;
1483 ///
1484 /// let mut libraries = HashMap::new();
1485 /// libraries.insert("Bodleian Library".to_string(), 1602);
1486 /// libraries.insert("Athenæum".to_string(), 1807);
1487 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1488 /// libraries.insert("Library of Congress".to_string(), 1800);
1489 ///
1490 /// let got = libraries.get_many_mut([
1491 /// "Athenæum",
1492 /// "Library of Congress",
1493 /// ]);
1494 /// assert_eq!(
1495 /// got,
1496 /// Some([
1497 /// &mut 1807,
1498 /// &mut 1800,
1499 /// ]),
1500 /// );
1501 ///
1502 /// // Missing keys result in None
1503 /// let got = libraries.get_many_mut([
1504 /// "Athenæum",
1505 /// "New York Public Library",
1506 /// ]);
1507 /// assert_eq!(got, None);
1508 ///
1509 /// // Duplicate keys result in None
1510 /// let got = libraries.get_many_mut([
1511 /// "Athenæum",
1512 /// "Athenæum",
1513 /// ]);
1514 /// assert_eq!(got, None);
1515 /// ```
1516 pub fn get_many_mut<Q: ?Sized, const N: usize>(&mut self, ks: [&Q; N]) -> Option<[&'_ mut V; N]>
1517 where
1518 Q: Hash + Equivalent<K>,
1519 {
1520 self.get_many_mut_inner(ks).map(|res| res.map(|(_, v)| v))
1521 }
1522
1523 /// Attempts to get mutable references to `N` values in the map at once, without validating that
1524 /// the values are unique.
1525 ///
1526 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1527 /// any of the keys are missing.
1528 ///
1529 /// For a safe alternative see [`get_many_mut`](`HashMap::get_many_mut`).
1530 ///
1531 /// # Safety
1532 ///
1533 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1534 /// references are not used.
1535 ///
1536 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1537 ///
1538 /// # Examples
1539 ///
1540 /// ```
1541 /// use hashbrown::HashMap;
1542 ///
1543 /// let mut libraries = HashMap::new();
1544 /// libraries.insert("Bodleian Library".to_string(), 1602);
1545 /// libraries.insert("Athenæum".to_string(), 1807);
1546 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1547 /// libraries.insert("Library of Congress".to_string(), 1800);
1548 ///
1549 /// let got = libraries.get_many_mut([
1550 /// "Athenæum",
1551 /// "Library of Congress",
1552 /// ]);
1553 /// assert_eq!(
1554 /// got,
1555 /// Some([
1556 /// &mut 1807,
1557 /// &mut 1800,
1558 /// ]),
1559 /// );
1560 ///
1561 /// // Missing keys result in None
1562 /// let got = libraries.get_many_mut([
1563 /// "Athenæum",
1564 /// "New York Public Library",
1565 /// ]);
1566 /// assert_eq!(got, None);
1567 /// ```
1568 pub unsafe fn get_many_unchecked_mut<Q: ?Sized, const N: usize>(
1569 &mut self,
1570 ks: [&Q; N],
1571 ) -> Option<[&'_ mut V; N]>
1572 where
1573 Q: Hash + Equivalent<K>,
1574 {
1575 self.get_many_unchecked_mut_inner(ks)
1576 .map(|res| res.map(|(_, v)| v))
1577 }
1578
1579 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1580 /// references to the corresponding keys.
1581 ///
1582 /// Returns an array of length `N` with the results of each query. For soundness, at most one
1583 /// mutable reference will be returned to any value. `None` will be returned if any of the keys
1584 /// are duplicates or missing.
1585 ///
1586 /// # Examples
1587 ///
1588 /// ```
1589 /// use hashbrown::HashMap;
1590 ///
1591 /// let mut libraries = HashMap::new();
1592 /// libraries.insert("Bodleian Library".to_string(), 1602);
1593 /// libraries.insert("Athenæum".to_string(), 1807);
1594 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1595 /// libraries.insert("Library of Congress".to_string(), 1800);
1596 ///
1597 /// let got = libraries.get_many_key_value_mut([
1598 /// "Bodleian Library",
1599 /// "Herzogin-Anna-Amalia-Bibliothek",
1600 /// ]);
1601 /// assert_eq!(
1602 /// got,
1603 /// Some([
1604 /// (&"Bodleian Library".to_string(), &mut 1602),
1605 /// (&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691),
1606 /// ]),
1607 /// );
1608 /// // Missing keys result in None
1609 /// let got = libraries.get_many_key_value_mut([
1610 /// "Bodleian Library",
1611 /// "Gewandhaus",
1612 /// ]);
1613 /// assert_eq!(got, None);
1614 ///
1615 /// // Duplicate keys result in None
1616 /// let got = libraries.get_many_key_value_mut([
1617 /// "Bodleian Library",
1618 /// "Herzogin-Anna-Amalia-Bibliothek",
1619 /// "Herzogin-Anna-Amalia-Bibliothek",
1620 /// ]);
1621 /// assert_eq!(got, None);
1622 /// ```
1623 pub fn get_many_key_value_mut<Q: ?Sized, const N: usize>(
1624 &mut self,
1625 ks: [&Q; N],
1626 ) -> Option<[(&'_ K, &'_ mut V); N]>
1627 where
1628 Q: Hash + Equivalent<K>,
1629 {
1630 self.get_many_mut_inner(ks)
1631 .map(|res| res.map(|(k, v)| (&*k, v)))
1632 }
1633
1634 /// Attempts to get mutable references to `N` values in the map at once, with immutable
1635 /// references to the corresponding keys, without validating that the values are unique.
1636 ///
1637 /// Returns an array of length `N` with the results of each query. `None` will be returned if
1638 /// any of the keys are missing.
1639 ///
1640 /// For a safe alternative see [`get_many_key_value_mut`](`HashMap::get_many_key_value_mut`).
1641 ///
1642 /// # Safety
1643 ///
1644 /// Calling this method with overlapping keys is *[undefined behavior]* even if the resulting
1645 /// references are not used.
1646 ///
1647 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1648 ///
1649 /// # Examples
1650 ///
1651 /// ```
1652 /// use hashbrown::HashMap;
1653 ///
1654 /// let mut libraries = HashMap::new();
1655 /// libraries.insert("Bodleian Library".to_string(), 1602);
1656 /// libraries.insert("Athenæum".to_string(), 1807);
1657 /// libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
1658 /// libraries.insert("Library of Congress".to_string(), 1800);
1659 ///
1660 /// let got = libraries.get_many_key_value_mut([
1661 /// "Bodleian Library",
1662 /// "Herzogin-Anna-Amalia-Bibliothek",
1663 /// ]);
1664 /// assert_eq!(
1665 /// got,
1666 /// Some([
1667 /// (&"Bodleian Library".to_string(), &mut 1602),
1668 /// (&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691),
1669 /// ]),
1670 /// );
1671 /// // Missing keys result in None
1672 /// let got = libraries.get_many_key_value_mut([
1673 /// "Bodleian Library",
1674 /// "Gewandhaus",
1675 /// ]);
1676 /// assert_eq!(got, None);
1677 /// ```
1678 pub unsafe fn get_many_key_value_unchecked_mut<Q: ?Sized, const N: usize>(
1679 &mut self,
1680 ks: [&Q; N],
1681 ) -> Option<[(&'_ K, &'_ mut V); N]>
1682 where
1683 Q: Hash + Equivalent<K>,
1684 {
1685 self.get_many_unchecked_mut_inner(ks)
1686 .map(|res| res.map(|(k, v)| (&*k, v)))
1687 }
1688
1689 fn get_many_mut_inner<Q: ?Sized, const N: usize>(
1690 &mut self,
1691 ks: [&Q; N],
1692 ) -> Option<[&'_ mut (K, V); N]>
1693 where
1694 Q: Hash + Equivalent<K>,
1695 {
1696 let hashes = self.build_hashes_inner(ks);
1697 self.table
1698 .get_many_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1699 }
1700
1701 unsafe fn get_many_unchecked_mut_inner<Q: ?Sized, const N: usize>(
1702 &mut self,
1703 ks: [&Q; N],
1704 ) -> Option<[&'_ mut (K, V); N]>
1705 where
1706 Q: Hash + Equivalent<K>,
1707 {
1708 let hashes = self.build_hashes_inner(ks);
1709 self.table
1710 .get_many_unchecked_mut(hashes, |i, (k, _)| ks[i].equivalent(k))
1711 }
1712
1713 fn build_hashes_inner<Q: ?Sized, const N: usize>(&self, ks: [&Q; N]) -> [u64; N]
1714 where
1715 Q: Hash + Equivalent<K>,
1716 {
1717 let mut hashes = [0_u64; N];
1718 for i in 0..N {
1719 hashes[i] = make_hash::<Q, S>(&self.hash_builder, ks[i]);
1720 }
1721 hashes
1722 }
1723
1724 /// Inserts a key-value pair into the map.
1725 ///
1726 /// If the map did not have this key present, [`None`] is returned.
1727 ///
1728 /// If the map did have this key present, the value is updated, and the old
1729 /// value is returned. The key is not updated, though; this matters for
1730 /// types that can be `==` without being identical. See the [`std::collections`]
1731 /// [module-level documentation] for more.
1732 ///
1733 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
1734 /// [`std::collections`]: https://doc.rust-lang.org/std/collections/index.html
1735 /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys
1736 ///
1737 /// # Examples
1738 ///
1739 /// ```
1740 /// use hashbrown::HashMap;
1741 ///
1742 /// let mut map = HashMap::new();
1743 /// assert_eq!(map.insert(37, "a"), None);
1744 /// assert_eq!(map.is_empty(), false);
1745 ///
1746 /// map.insert(37, "b");
1747 /// assert_eq!(map.insert(37, "c"), Some("b"));
1748 /// assert_eq!(map[&37], "c");
1749 /// ```
1750 #[cfg_attr(feature = "inline-more", inline)]
1751 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1752 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1753 let hasher = make_hasher::<_, V, S>(&self.hash_builder);
1754 match self
1755 .table
1756 .find_or_find_insert_slot(hash, equivalent_key(&k), hasher)
1757 {
1758 Ok(bucket) => Some(mem::replace(unsafe { &mut bucket.as_mut().1 }, v)),
1759 Err(slot) => {
1760 unsafe {
1761 self.table.insert_in_slot(hash, slot, (k, v));
1762 }
1763 None
1764 }
1765 }
1766 }
1767
1768 /// Insert a key-value pair into the map without checking
1769 /// if the key already exists in the map.
1770 ///
1771 /// Returns a reference to the key and value just inserted.
1772 ///
1773 /// This operation is safe if a key does not exist in the map.
1774 ///
1775 /// However, if a key exists in the map already, the behavior is unspecified:
1776 /// this operation may panic, loop forever, or any following operation with the map
1777 /// may panic, loop forever or return arbitrary result.
1778 ///
1779 /// That said, this operation (and following operations) are guaranteed to
1780 /// not violate memory safety.
1781 ///
1782 /// This operation is faster than regular insert, because it does not perform
1783 /// lookup before insertion.
1784 ///
1785 /// This operation is useful during initial population of the map.
1786 /// For example, when constructing a map from another map, we know
1787 /// that keys are unique.
1788 ///
1789 /// # Examples
1790 ///
1791 /// ```
1792 /// use hashbrown::HashMap;
1793 ///
1794 /// let mut map1 = HashMap::new();
1795 /// assert_eq!(map1.insert(1, "a"), None);
1796 /// assert_eq!(map1.insert(2, "b"), None);
1797 /// assert_eq!(map1.insert(3, "c"), None);
1798 /// assert_eq!(map1.len(), 3);
1799 ///
1800 /// let mut map2 = HashMap::new();
1801 ///
1802 /// for (key, value) in map1.into_iter() {
1803 /// map2.insert_unique_unchecked(key, value);
1804 /// }
1805 ///
1806 /// let (key, value) = map2.insert_unique_unchecked(4, "d");
1807 /// assert_eq!(key, &4);
1808 /// assert_eq!(value, &mut "d");
1809 /// *value = "e";
1810 ///
1811 /// assert_eq!(map2[&1], "a");
1812 /// assert_eq!(map2[&2], "b");
1813 /// assert_eq!(map2[&3], "c");
1814 /// assert_eq!(map2[&4], "e");
1815 /// assert_eq!(map2.len(), 4);
1816 /// ```
1817 #[cfg_attr(feature = "inline-more", inline)]
1818 pub fn insert_unique_unchecked(&mut self, k: K, v: V) -> (&K, &mut V) {
1819 let hash = make_hash::<K, S>(&self.hash_builder, &k);
1820 let bucket = self
1821 .table
1822 .insert(hash, (k, v), make_hasher::<_, V, S>(&self.hash_builder));
1823 let (k_ref, v_ref) = unsafe { bucket.as_mut() };
1824 (k_ref, v_ref)
1825 }
1826
1827 /// Tries to insert a key-value pair into the map, and returns
1828 /// a mutable reference to the value in the entry.
1829 ///
1830 /// # Errors
1831 ///
1832 /// If the map already had this key present, nothing is updated, and
1833 /// an error containing the occupied entry and the value is returned.
1834 ///
1835 /// # Examples
1836 ///
1837 /// Basic usage:
1838 ///
1839 /// ```
1840 /// use hashbrown::HashMap;
1841 /// use hashbrown::hash_map::OccupiedError;
1842 ///
1843 /// let mut map = HashMap::new();
1844 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1845 ///
1846 /// match map.try_insert(37, "b") {
1847 /// Err(OccupiedError { entry, value }) => {
1848 /// assert_eq!(entry.key(), &37);
1849 /// assert_eq!(entry.get(), &"a");
1850 /// assert_eq!(value, "b");
1851 /// }
1852 /// _ => panic!()
1853 /// }
1854 /// ```
1855 #[cfg_attr(feature = "inline-more", inline)]
1856 pub fn try_insert(
1857 &mut self,
1858 key: K,
1859 value: V,
1860 ) -> Result<&mut V, OccupiedError<'_, K, V, S, A>> {
1861 match self.entry(key) {
1862 Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
1863 Entry::Vacant(entry) => Ok(entry.insert(value)),
1864 }
1865 }
1866
1867 /// Removes a key from the map, returning the value at the key if the key
1868 /// was previously in the map. Keeps the allocated memory for reuse.
1869 ///
1870 /// The key may be any borrowed form of the map's key type, but
1871 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1872 /// the key type.
1873 ///
1874 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1875 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1876 ///
1877 /// # Examples
1878 ///
1879 /// ```
1880 /// use hashbrown::HashMap;
1881 ///
1882 /// let mut map = HashMap::new();
1883 /// // The map is empty
1884 /// assert!(map.is_empty() && map.capacity() == 0);
1885 ///
1886 /// map.insert(1, "a");
1887 ///
1888 /// assert_eq!(map.remove(&1), Some("a"));
1889 /// assert_eq!(map.remove(&1), None);
1890 ///
1891 /// // Now map holds none elements
1892 /// assert!(map.is_empty());
1893 /// ```
1894 #[cfg_attr(feature = "inline-more", inline)]
1895 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1896 where
1897 Q: Hash + Equivalent<K>,
1898 {
1899 // Avoid `Option::map` because it bloats LLVM IR.
1900 match self.remove_entry(k) {
1901 Some((_, v)) => Some(v),
1902 None => None,
1903 }
1904 }
1905
1906 /// Removes a key from the map, returning the stored key and value if the
1907 /// key was previously in the map. Keeps the allocated memory for reuse.
1908 ///
1909 /// The key may be any borrowed form of the map's key type, but
1910 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1911 /// the key type.
1912 ///
1913 /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
1914 /// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
1915 ///
1916 /// # Examples
1917 ///
1918 /// ```
1919 /// use hashbrown::HashMap;
1920 ///
1921 /// let mut map = HashMap::new();
1922 /// // The map is empty
1923 /// assert!(map.is_empty() && map.capacity() == 0);
1924 ///
1925 /// map.insert(1, "a");
1926 ///
1927 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1928 /// assert_eq!(map.remove(&1), None);
1929 ///
1930 /// // Now map hold none elements
1931 /// assert!(map.is_empty());
1932 /// ```
1933 #[cfg_attr(feature = "inline-more", inline)]
1934 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1935 where
1936 Q: Hash + Equivalent<K>,
1937 {
1938 let hash = make_hash::<Q, S>(&self.hash_builder, k);
1939 self.table.remove_entry(hash, equivalent_key(k))
1940 }
1941}
1942
1943impl<K, V, S, A: Allocator> HashMap<K, V, S, A> {
1944 /// Creates a raw entry builder for the HashMap.
1945 ///
1946 /// Raw entries provide the lowest level of control for searching and
1947 /// manipulating a map. They must be manually initialized with a hash and
1948 /// then manually searched. After this, insertions into a vacant entry
1949 /// still require an owned key to be provided.
1950 ///
1951 /// Raw entries are useful for such exotic situations as:
1952 ///
1953 /// * Hash memoization
1954 /// * Deferring the creation of an owned key until it is known to be required
1955 /// * Using a search key that doesn't work with the Borrow trait
1956 /// * Using custom comparison logic without newtype wrappers
1957 ///
1958 /// Because raw entries provide much more low-level control, it's much easier
1959 /// to put the HashMap into an inconsistent state which, while memory-safe,
1960 /// will cause the map to produce seemingly random results. Higher-level and
1961 /// more foolproof APIs like `entry` should be preferred when possible.
1962 ///
1963 /// In particular, the hash used to initialized the raw entry must still be
1964 /// consistent with the hash of the key that is ultimately stored in the entry.
1965 /// This is because implementations of HashMap may need to recompute hashes
1966 /// when resizing, at which point only the keys are available.
1967 ///
1968 /// Raw entries give mutable access to the keys. This must not be used
1969 /// to modify how the key would compare or hash, as the map will not re-evaluate
1970 /// where the key should go, meaning the keys may become "lost" if their
1971 /// location does not reflect their state. For instance, if you change a key
1972 /// so that the map now contains keys which compare equal, search may start
1973 /// acting erratically, with two keys randomly masking each other. Implementations
1974 /// are free to assume this doesn't happen (within the limits of memory-safety).
1975 ///
1976 /// # Examples
1977 ///
1978 /// ```
1979 /// use core::hash::{BuildHasher, Hash};
1980 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
1981 ///
1982 /// let mut map = HashMap::new();
1983 /// map.extend([("a", 100), ("b", 200), ("c", 300)]);
1984 ///
1985 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
1986 /// use core::hash::Hasher;
1987 /// let mut state = hash_builder.build_hasher();
1988 /// key.hash(&mut state);
1989 /// state.finish()
1990 /// }
1991 ///
1992 /// // Existing key (insert and update)
1993 /// match map.raw_entry_mut().from_key(&"a") {
1994 /// RawEntryMut::Vacant(_) => unreachable!(),
1995 /// RawEntryMut::Occupied(mut view) => {
1996 /// assert_eq!(view.get(), &100);
1997 /// let v = view.get_mut();
1998 /// let new_v = (*v) * 10;
1999 /// *v = new_v;
2000 /// assert_eq!(view.insert(1111), 1000);
2001 /// }
2002 /// }
2003 ///
2004 /// assert_eq!(map[&"a"], 1111);
2005 /// assert_eq!(map.len(), 3);
2006 ///
2007 /// // Existing key (take)
2008 /// let hash = compute_hash(map.hasher(), &"c");
2009 /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") {
2010 /// RawEntryMut::Vacant(_) => unreachable!(),
2011 /// RawEntryMut::Occupied(view) => {
2012 /// assert_eq!(view.remove_entry(), ("c", 300));
2013 /// }
2014 /// }
2015 /// assert_eq!(map.raw_entry().from_key(&"c"), None);
2016 /// assert_eq!(map.len(), 2);
2017 ///
2018 /// // Nonexistent key (insert and update)
2019 /// let key = "d";
2020 /// let hash = compute_hash(map.hasher(), &key);
2021 /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
2022 /// RawEntryMut::Occupied(_) => unreachable!(),
2023 /// RawEntryMut::Vacant(view) => {
2024 /// let (k, value) = view.insert("d", 4000);
2025 /// assert_eq!((*k, *value), ("d", 4000));
2026 /// *value = 40000;
2027 /// }
2028 /// }
2029 /// assert_eq!(map[&"d"], 40000);
2030 /// assert_eq!(map.len(), 3);
2031 ///
2032 /// match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
2033 /// RawEntryMut::Vacant(_) => unreachable!(),
2034 /// RawEntryMut::Occupied(view) => {
2035 /// assert_eq!(view.remove_entry(), ("d", 40000));
2036 /// }
2037 /// }
2038 /// assert_eq!(map.get(&"d"), None);
2039 /// assert_eq!(map.len(), 2);
2040 /// ```
2041 #[cfg_attr(feature = "inline-more", inline)]
2042 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S, A> {
2043 RawEntryBuilderMut { map: self }
2044 }
2045
2046 /// Creates a raw immutable entry builder for the HashMap.
2047 ///
2048 /// Raw entries provide the lowest level of control for searching and
2049 /// manipulating a map. They must be manually initialized with a hash and
2050 /// then manually searched.
2051 ///
2052 /// This is useful for
2053 /// * Hash memoization
2054 /// * Using a search key that doesn't work with the Borrow trait
2055 /// * Using custom comparison logic without newtype wrappers
2056 ///
2057 /// Unless you are in such a situation, higher-level and more foolproof APIs like
2058 /// `get` should be preferred.
2059 ///
2060 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
2061 ///
2062 /// # Examples
2063 ///
2064 /// ```
2065 /// use core::hash::{BuildHasher, Hash};
2066 /// use hashbrown::HashMap;
2067 ///
2068 /// let mut map = HashMap::new();
2069 /// map.extend([("a", 100), ("b", 200), ("c", 300)]);
2070 ///
2071 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2072 /// use core::hash::Hasher;
2073 /// let mut state = hash_builder.build_hasher();
2074 /// key.hash(&mut state);
2075 /// state.finish()
2076 /// }
2077 ///
2078 /// for k in ["a", "b", "c", "d", "e", "f"] {
2079 /// let hash = compute_hash(map.hasher(), k);
2080 /// let v = map.get(&k).cloned();
2081 /// let kv = v.as_ref().map(|v| (&k, v));
2082 ///
2083 /// println!("Key: {} and value: {:?}", k, v);
2084 ///
2085 /// assert_eq!(map.raw_entry().from_key(&k), kv);
2086 /// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
2087 /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
2088 /// }
2089 /// ```
2090 #[cfg_attr(feature = "inline-more", inline)]
2091 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S, A> {
2092 RawEntryBuilder { map: self }
2093 }
2094
2095 /// Returns a reference to the [`RawTable`] used underneath [`HashMap`].
2096 /// This function is only available if the `raw` feature of the crate is enabled.
2097 ///
2098 /// See [`raw_table_mut`] for more.
2099 ///
2100 /// [`raw_table_mut`]: Self::raw_table_mut
2101 #[cfg(feature = "raw")]
2102 #[cfg_attr(feature = "inline-more", inline)]
2103 pub fn raw_table(&self) -> &RawTable<(K, V), A> {
2104 &self.table
2105 }
2106
2107 /// Returns a mutable reference to the [`RawTable`] used underneath [`HashMap`].
2108 /// This function is only available if the `raw` feature of the crate is enabled.
2109 ///
2110 /// # Note
2111 ///
2112 /// Calling this function is safe, but using the raw hash table API may require
2113 /// unsafe functions or blocks.
2114 ///
2115 /// `RawTable` API gives the lowest level of control under the map that can be useful
2116 /// for extending the HashMap's API, but may lead to *[undefined behavior]*.
2117 ///
2118 /// [`HashMap`]: struct.HashMap.html
2119 /// [`RawTable`]: crate::raw::RawTable
2120 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2121 ///
2122 /// # Examples
2123 ///
2124 /// ```
2125 /// use core::hash::{BuildHasher, Hash};
2126 /// use hashbrown::HashMap;
2127 ///
2128 /// let mut map = HashMap::new();
2129 /// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2130 /// assert_eq!(map.len(), 3);
2131 ///
2132 /// // Let's imagine that we have a value and a hash of the key, but not the key itself.
2133 /// // However, if you want to remove the value from the map by hash and value, and you
2134 /// // know exactly that the value is unique, then you can create a function like this:
2135 /// fn remove_by_hash<K, V, S, F>(
2136 /// map: &mut HashMap<K, V, S>,
2137 /// hash: u64,
2138 /// is_match: F,
2139 /// ) -> Option<(K, V)>
2140 /// where
2141 /// F: Fn(&(K, V)) -> bool,
2142 /// {
2143 /// let raw_table = map.raw_table_mut();
2144 /// match raw_table.find(hash, is_match) {
2145 /// Some(bucket) => Some(unsafe { raw_table.remove(bucket).0 }),
2146 /// None => None,
2147 /// }
2148 /// }
2149 ///
2150 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2151 /// use core::hash::Hasher;
2152 /// let mut state = hash_builder.build_hasher();
2153 /// key.hash(&mut state);
2154 /// state.finish()
2155 /// }
2156 ///
2157 /// let hash = compute_hash(map.hasher(), "a");
2158 /// assert_eq!(remove_by_hash(&mut map, hash, |(_, v)| *v == 10), Some(("a", 10)));
2159 /// assert_eq!(map.get(&"a"), None);
2160 /// assert_eq!(map.len(), 2);
2161 /// ```
2162 #[cfg(feature = "raw")]
2163 #[cfg_attr(feature = "inline-more", inline)]
2164 pub fn raw_table_mut(&mut self) -> &mut RawTable<(K, V), A> {
2165 &mut self.table
2166 }
2167}
2168
2169impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
2170where
2171 K: Eq + Hash,
2172 V: PartialEq,
2173 S: BuildHasher,
2174 A: Allocator,
2175{
2176 fn eq(&self, other: &Self) -> bool {
2177 if self.len() != other.len() {
2178 return false;
2179 }
2180
2181 self.iter()
2182 .all(|(key: &{unknown}, value)| other.get(key).map_or(false, |v| *value == *v))
2183 }
2184}
2185
2186impl<K, V, S, A> Eq for HashMap<K, V, S, A>
2187where
2188 K: Eq + Hash,
2189 V: Eq,
2190 S: BuildHasher,
2191 A: Allocator,
2192{
2193}
2194
2195impl<K, V, S, A> Debug for HashMap<K, V, S, A>
2196where
2197 K: Debug,
2198 V: Debug,
2199 A: Allocator,
2200{
2201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2202 f.debug_map().entries(self.iter()).finish()
2203 }
2204}
2205
2206impl<K, V, S, A> Default for HashMap<K, V, S, A>
2207where
2208 S: Default,
2209 A: Default + Allocator,
2210{
2211 /// Creates an empty `HashMap<K, V, S, A>`, with the `Default` value for the hasher and allocator.
2212 ///
2213 /// # Examples
2214 ///
2215 /// ```
2216 /// use hashbrown::HashMap;
2217 /// use std::collections::hash_map::RandomState;
2218 ///
2219 /// // You can specify all types of HashMap, including hasher and allocator.
2220 /// // Created map is empty and don't allocate memory
2221 /// let map: HashMap<u32, String> = Default::default();
2222 /// assert_eq!(map.capacity(), 0);
2223 /// let map: HashMap<u32, String, RandomState> = HashMap::default();
2224 /// assert_eq!(map.capacity(), 0);
2225 /// ```
2226 #[cfg_attr(feature = "inline-more", inline)]
2227 fn default() -> Self {
2228 Self::with_hasher_in(hash_builder:Default::default(), alloc:Default::default())
2229 }
2230}
2231
2232impl<K, Q: ?Sized, V, S, A> Index<&Q> for HashMap<K, V, S, A>
2233where
2234 K: Eq + Hash,
2235 Q: Hash + Equivalent<K>,
2236 S: BuildHasher,
2237 A: Allocator,
2238{
2239 type Output = V;
2240
2241 /// Returns a reference to the value corresponding to the supplied key.
2242 ///
2243 /// # Panics
2244 ///
2245 /// Panics if the key is not present in the `HashMap`.
2246 ///
2247 /// # Examples
2248 ///
2249 /// ```
2250 /// use hashbrown::HashMap;
2251 ///
2252 /// let map: HashMap<_, _> = [("a", "One"), ("b", "Two")].into();
2253 ///
2254 /// assert_eq!(map[&"a"], "One");
2255 /// assert_eq!(map[&"b"], "Two");
2256 /// ```
2257 #[cfg_attr(feature = "inline-more", inline)]
2258 fn index(&self, key: &Q) -> &V {
2259 self.get(key).expect("no entry found for key")
2260 }
2261}
2262
2263// The default hasher is used to match the std implementation signature
2264#[cfg(feature = "ahash")]
2265impl<K, V, A, const N: usize> From<[(K, V); N]> for HashMap<K, V, DefaultHashBuilder, A>
2266where
2267 K: Eq + Hash,
2268 A: Default + Allocator,
2269{
2270 /// # Examples
2271 ///
2272 /// ```
2273 /// use hashbrown::HashMap;
2274 ///
2275 /// let map1 = HashMap::from([(1, 2), (3, 4)]);
2276 /// let map2: HashMap<_, _> = [(1, 2), (3, 4)].into();
2277 /// assert_eq!(map1, map2);
2278 /// ```
2279 fn from(arr: [(K, V); N]) -> Self {
2280 arr.into_iter().collect()
2281 }
2282}
2283
2284/// An iterator over the entries of a `HashMap` in arbitrary order.
2285/// The iterator element type is `(&'a K, &'a V)`.
2286///
2287/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
2288/// documentation for more.
2289///
2290/// [`iter`]: struct.HashMap.html#method.iter
2291/// [`HashMap`]: struct.HashMap.html
2292///
2293/// # Examples
2294///
2295/// ```
2296/// use hashbrown::HashMap;
2297///
2298/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2299///
2300/// let mut iter = map.iter();
2301/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2302///
2303/// // The `Iter` iterator produces items in arbitrary order, so the
2304/// // items must be sorted to test them against a sorted array.
2305/// vec.sort_unstable();
2306/// assert_eq!(vec, [Some((&1, &"a")), Some((&2, &"b")), Some((&3, &"c"))]);
2307///
2308/// // It is fused iterator
2309/// assert_eq!(iter.next(), None);
2310/// assert_eq!(iter.next(), None);
2311/// ```
2312pub struct Iter<'a, K, V> {
2313 inner: RawIter<(K, V)>,
2314 marker: PhantomData<(&'a K, &'a V)>,
2315}
2316
2317// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2318impl<K, V> Clone for Iter<'_, K, V> {
2319 #[cfg_attr(feature = "inline-more", inline)]
2320 fn clone(&self) -> Self {
2321 Iter {
2322 inner: self.inner.clone(),
2323 marker: PhantomData,
2324 }
2325 }
2326}
2327
2328impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
2329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2330 f.debug_list().entries(self.clone()).finish()
2331 }
2332}
2333
2334/// A mutable iterator over the entries of a `HashMap` in arbitrary order.
2335/// The iterator element type is `(&'a K, &'a mut V)`.
2336///
2337/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
2338/// documentation for more.
2339///
2340/// [`iter_mut`]: struct.HashMap.html#method.iter_mut
2341/// [`HashMap`]: struct.HashMap.html
2342///
2343/// # Examples
2344///
2345/// ```
2346/// use hashbrown::HashMap;
2347///
2348/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2349///
2350/// let mut iter = map.iter_mut();
2351/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2352/// iter.next().map(|(_, v)| v.push_str(" Mississippi"));
2353///
2354/// // It is fused iterator
2355/// assert_eq!(iter.next(), None);
2356/// assert_eq!(iter.next(), None);
2357///
2358/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2359/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2360/// ```
2361pub struct IterMut<'a, K, V> {
2362 inner: RawIter<(K, V)>,
2363 // To ensure invariance with respect to V
2364 marker: PhantomData<(&'a K, &'a mut V)>,
2365}
2366
2367// We override the default Send impl which has K: Sync instead of K: Send. Both
2368// are correct, but this one is more general since it allows keys which
2369// implement Send but not Sync.
2370unsafe impl<K: Send, V: Send> Send for IterMut<'_, K, V> {}
2371
2372impl<K, V> IterMut<'_, K, V> {
2373 /// Returns a iterator of references over the remaining items.
2374 #[cfg_attr(feature = "inline-more", inline)]
2375 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2376 Iter {
2377 inner: self.inner.clone(),
2378 marker: PhantomData,
2379 }
2380 }
2381}
2382
2383/// An owning iterator over the entries of a `HashMap` in arbitrary order.
2384/// The iterator element type is `(K, V)`.
2385///
2386/// This `struct` is created by the [`into_iter`] method on [`HashMap`]
2387/// (provided by the [`IntoIterator`] trait). See its documentation for more.
2388/// The map cannot be used after calling that method.
2389///
2390/// [`into_iter`]: struct.HashMap.html#method.into_iter
2391/// [`HashMap`]: struct.HashMap.html
2392/// [`IntoIterator`]: https://doc.rust-lang.org/core/iter/trait.IntoIterator.html
2393///
2394/// # Examples
2395///
2396/// ```
2397/// use hashbrown::HashMap;
2398///
2399/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2400///
2401/// let mut iter = map.into_iter();
2402/// let mut vec = vec![iter.next(), iter.next(), iter.next()];
2403///
2404/// // The `IntoIter` iterator produces items in arbitrary order, so the
2405/// // items must be sorted to test them against a sorted array.
2406/// vec.sort_unstable();
2407/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2408///
2409/// // It is fused iterator
2410/// assert_eq!(iter.next(), None);
2411/// assert_eq!(iter.next(), None);
2412/// ```
2413pub struct IntoIter<K, V, A: Allocator = Global> {
2414 inner: RawIntoIter<(K, V), A>,
2415}
2416
2417impl<K, V, A: Allocator> IntoIter<K, V, A> {
2418 /// Returns a iterator of references over the remaining items.
2419 #[cfg_attr(feature = "inline-more", inline)]
2420 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2421 Iter {
2422 inner: self.inner.iter(),
2423 marker: PhantomData,
2424 }
2425 }
2426}
2427
2428/// An owning iterator over the keys of a `HashMap` in arbitrary order.
2429/// The iterator element type is `K`.
2430///
2431/// This `struct` is created by the [`into_keys`] method on [`HashMap`].
2432/// See its documentation for more.
2433/// The map cannot be used after calling that method.
2434///
2435/// [`into_keys`]: struct.HashMap.html#method.into_keys
2436/// [`HashMap`]: struct.HashMap.html
2437///
2438/// # Examples
2439///
2440/// ```
2441/// use hashbrown::HashMap;
2442///
2443/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2444///
2445/// let mut keys = map.into_keys();
2446/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2447///
2448/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
2449/// // keys must be sorted to test them against a sorted array.
2450/// vec.sort_unstable();
2451/// assert_eq!(vec, [Some(1), Some(2), Some(3)]);
2452///
2453/// // It is fused iterator
2454/// assert_eq!(keys.next(), None);
2455/// assert_eq!(keys.next(), None);
2456/// ```
2457pub struct IntoKeys<K, V, A: Allocator = Global> {
2458 inner: IntoIter<K, V, A>,
2459}
2460
2461impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
2462 type Item = K;
2463
2464 #[inline]
2465 fn next(&mut self) -> Option<K> {
2466 self.inner.next().map(|(k, _)| k)
2467 }
2468 #[inline]
2469 fn size_hint(&self) -> (usize, Option<usize>) {
2470 self.inner.size_hint()
2471 }
2472 #[inline]
2473 fn fold<B, F>(self, init: B, mut f: F) -> B
2474 where
2475 Self: Sized,
2476 F: FnMut(B, Self::Item) -> B,
2477 {
2478 self.inner.fold(init, |acc, (k, _)| f(acc, k))
2479 }
2480}
2481
2482impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
2483 #[inline]
2484 fn len(&self) -> usize {
2485 self.inner.len()
2486 }
2487}
2488
2489impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
2490
2491impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
2492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2493 f.debug_list()
2494 .entries(self.inner.iter().map(|(k, _)| k))
2495 .finish()
2496 }
2497}
2498
2499/// An owning iterator over the values of a `HashMap` in arbitrary order.
2500/// The iterator element type is `V`.
2501///
2502/// This `struct` is created by the [`into_values`] method on [`HashMap`].
2503/// See its documentation for more. The map cannot be used after calling that method.
2504///
2505/// [`into_values`]: struct.HashMap.html#method.into_values
2506/// [`HashMap`]: struct.HashMap.html
2507///
2508/// # Examples
2509///
2510/// ```
2511/// use hashbrown::HashMap;
2512///
2513/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2514///
2515/// let mut values = map.into_values();
2516/// let mut vec = vec![values.next(), values.next(), values.next()];
2517///
2518/// // The `IntoValues` iterator produces values in arbitrary order, so
2519/// // the values must be sorted to test them against a sorted array.
2520/// vec.sort_unstable();
2521/// assert_eq!(vec, [Some("a"), Some("b"), Some("c")]);
2522///
2523/// // It is fused iterator
2524/// assert_eq!(values.next(), None);
2525/// assert_eq!(values.next(), None);
2526/// ```
2527pub struct IntoValues<K, V, A: Allocator = Global> {
2528 inner: IntoIter<K, V, A>,
2529}
2530
2531impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
2532 type Item = V;
2533
2534 #[inline]
2535 fn next(&mut self) -> Option<V> {
2536 self.inner.next().map(|(_, v)| v)
2537 }
2538 #[inline]
2539 fn size_hint(&self) -> (usize, Option<usize>) {
2540 self.inner.size_hint()
2541 }
2542 #[inline]
2543 fn fold<B, F>(self, init: B, mut f: F) -> B
2544 where
2545 Self: Sized,
2546 F: FnMut(B, Self::Item) -> B,
2547 {
2548 self.inner.fold(init, |acc, (_, v)| f(acc, v))
2549 }
2550}
2551
2552impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2553 #[inline]
2554 fn len(&self) -> usize {
2555 self.inner.len()
2556 }
2557}
2558
2559impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2560
2561impl<K, V: Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
2562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2563 f.debug_list()
2564 .entries(self.inner.iter().map(|(_, v)| v))
2565 .finish()
2566 }
2567}
2568
2569/// An iterator over the keys of a `HashMap` in arbitrary order.
2570/// The iterator element type is `&'a K`.
2571///
2572/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
2573/// documentation for more.
2574///
2575/// [`keys`]: struct.HashMap.html#method.keys
2576/// [`HashMap`]: struct.HashMap.html
2577///
2578/// # Examples
2579///
2580/// ```
2581/// use hashbrown::HashMap;
2582///
2583/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2584///
2585/// let mut keys = map.keys();
2586/// let mut vec = vec![keys.next(), keys.next(), keys.next()];
2587///
2588/// // The `Keys` iterator produces keys in arbitrary order, so the
2589/// // keys must be sorted to test them against a sorted array.
2590/// vec.sort_unstable();
2591/// assert_eq!(vec, [Some(&1), Some(&2), Some(&3)]);
2592///
2593/// // It is fused iterator
2594/// assert_eq!(keys.next(), None);
2595/// assert_eq!(keys.next(), None);
2596/// ```
2597pub struct Keys<'a, K, V> {
2598 inner: Iter<'a, K, V>,
2599}
2600
2601// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2602impl<K, V> Clone for Keys<'_, K, V> {
2603 #[cfg_attr(feature = "inline-more", inline)]
2604 fn clone(&self) -> Self {
2605 Keys {
2606 inner: self.inner.clone(),
2607 }
2608 }
2609}
2610
2611impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
2612 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2613 f.debug_list().entries(self.clone()).finish()
2614 }
2615}
2616
2617/// An iterator over the values of a `HashMap` in arbitrary order.
2618/// The iterator element type is `&'a V`.
2619///
2620/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
2621/// documentation for more.
2622///
2623/// [`values`]: struct.HashMap.html#method.values
2624/// [`HashMap`]: struct.HashMap.html
2625///
2626/// # Examples
2627///
2628/// ```
2629/// use hashbrown::HashMap;
2630///
2631/// let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2632///
2633/// let mut values = map.values();
2634/// let mut vec = vec![values.next(), values.next(), values.next()];
2635///
2636/// // The `Values` iterator produces values in arbitrary order, so the
2637/// // values must be sorted to test them against a sorted array.
2638/// vec.sort_unstable();
2639/// assert_eq!(vec, [Some(&"a"), Some(&"b"), Some(&"c")]);
2640///
2641/// // It is fused iterator
2642/// assert_eq!(values.next(), None);
2643/// assert_eq!(values.next(), None);
2644/// ```
2645pub struct Values<'a, K, V> {
2646 inner: Iter<'a, K, V>,
2647}
2648
2649// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2650impl<K, V> Clone for Values<'_, K, V> {
2651 #[cfg_attr(feature = "inline-more", inline)]
2652 fn clone(&self) -> Self {
2653 Values {
2654 inner: self.inner.clone(),
2655 }
2656 }
2657}
2658
2659impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
2660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2661 f.debug_list().entries(self.clone()).finish()
2662 }
2663}
2664
2665/// A draining iterator over the entries of a `HashMap` in arbitrary
2666/// order. The iterator element type is `(K, V)`.
2667///
2668/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
2669/// documentation for more.
2670///
2671/// [`drain`]: struct.HashMap.html#method.drain
2672/// [`HashMap`]: struct.HashMap.html
2673///
2674/// # Examples
2675///
2676/// ```
2677/// use hashbrown::HashMap;
2678///
2679/// let mut map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
2680///
2681/// let mut drain_iter = map.drain();
2682/// let mut vec = vec![drain_iter.next(), drain_iter.next(), drain_iter.next()];
2683///
2684/// // The `Drain` iterator produces items in arbitrary order, so the
2685/// // items must be sorted to test them against a sorted array.
2686/// vec.sort_unstable();
2687/// assert_eq!(vec, [Some((1, "a")), Some((2, "b")), Some((3, "c"))]);
2688///
2689/// // It is fused iterator
2690/// assert_eq!(drain_iter.next(), None);
2691/// assert_eq!(drain_iter.next(), None);
2692/// ```
2693pub struct Drain<'a, K, V, A: Allocator = Global> {
2694 inner: RawDrain<'a, (K, V), A>,
2695}
2696
2697impl<K, V, A: Allocator> Drain<'_, K, V, A> {
2698 /// Returns a iterator of references over the remaining items.
2699 #[cfg_attr(feature = "inline-more", inline)]
2700 pub(super) fn iter(&self) -> Iter<'_, K, V> {
2701 Iter {
2702 inner: self.inner.iter(),
2703 marker: PhantomData,
2704 }
2705 }
2706}
2707
2708/// A draining iterator over entries of a `HashMap` which don't satisfy the predicate
2709/// `f(&k, &mut v)` in arbitrary order. The iterator element type is `(K, V)`.
2710///
2711/// This `struct` is created by the [`extract_if`] method on [`HashMap`]. See its
2712/// documentation for more.
2713///
2714/// [`extract_if`]: struct.HashMap.html#method.extract_if
2715/// [`HashMap`]: struct.HashMap.html
2716///
2717/// # Examples
2718///
2719/// ```
2720/// use hashbrown::HashMap;
2721///
2722/// let mut map: HashMap<i32, &str> = [(1, "a"), (2, "b"), (3, "c")].into();
2723///
2724/// let mut extract_if = map.extract_if(|k, _v| k % 2 != 0);
2725/// let mut vec = vec![extract_if.next(), extract_if.next()];
2726///
2727/// // The `ExtractIf` iterator produces items in arbitrary order, so the
2728/// // items must be sorted to test them against a sorted array.
2729/// vec.sort_unstable();
2730/// assert_eq!(vec, [Some((1, "a")),Some((3, "c"))]);
2731///
2732/// // It is fused iterator
2733/// assert_eq!(extract_if.next(), None);
2734/// assert_eq!(extract_if.next(), None);
2735/// drop(extract_if);
2736///
2737/// assert_eq!(map.len(), 1);
2738/// ```
2739#[must_use = "Iterators are lazy unless consumed"]
2740pub struct ExtractIf<'a, K, V, F, A: Allocator = Global>
2741where
2742 F: FnMut(&K, &mut V) -> bool,
2743{
2744 f: F,
2745 inner: RawExtractIf<'a, (K, V), A>,
2746}
2747
2748impl<K, V, F, A> Iterator for ExtractIf<'_, K, V, F, A>
2749where
2750 F: FnMut(&K, &mut V) -> bool,
2751 A: Allocator,
2752{
2753 type Item = (K, V);
2754
2755 #[cfg_attr(feature = "inline-more", inline)]
2756 fn next(&mut self) -> Option<Self::Item> {
2757 self.inner.next(|&mut (ref k: &{unknown}, ref mut v: &mut {unknown})| (self.f)(k, v))
2758 }
2759
2760 #[inline]
2761 fn size_hint(&self) -> (usize, Option<usize>) {
2762 (0, self.inner.iter.size_hint().1)
2763 }
2764}
2765
2766impl<K, V, F> FusedIterator for ExtractIf<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
2767
2768/// A mutable iterator over the values of a `HashMap` in arbitrary order.
2769/// The iterator element type is `&'a mut V`.
2770///
2771/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
2772/// documentation for more.
2773///
2774/// [`values_mut`]: struct.HashMap.html#method.values_mut
2775/// [`HashMap`]: struct.HashMap.html
2776///
2777/// # Examples
2778///
2779/// ```
2780/// use hashbrown::HashMap;
2781///
2782/// let mut map: HashMap<_, _> = [(1, "One".to_owned()), (2, "Two".into())].into();
2783///
2784/// let mut values = map.values_mut();
2785/// values.next().map(|v| v.push_str(" Mississippi"));
2786/// values.next().map(|v| v.push_str(" Mississippi"));
2787///
2788/// // It is fused iterator
2789/// assert_eq!(values.next(), None);
2790/// assert_eq!(values.next(), None);
2791///
2792/// assert_eq!(map.get(&1).unwrap(), &"One Mississippi".to_owned());
2793/// assert_eq!(map.get(&2).unwrap(), &"Two Mississippi".to_owned());
2794/// ```
2795pub struct ValuesMut<'a, K, V> {
2796 inner: IterMut<'a, K, V>,
2797}
2798
2799/// A builder for computing where in a [`HashMap`] a key-value pair would be stored.
2800///
2801/// See the [`HashMap::raw_entry_mut`] docs for usage examples.
2802///
2803/// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
2804///
2805/// # Examples
2806///
2807/// ```
2808/// use hashbrown::hash_map::{RawEntryBuilderMut, RawEntryMut::Vacant, RawEntryMut::Occupied};
2809/// use hashbrown::HashMap;
2810/// use core::hash::{BuildHasher, Hash};
2811///
2812/// let mut map = HashMap::new();
2813/// map.extend([(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16)]);
2814/// assert_eq!(map.len(), 6);
2815///
2816/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2817/// use core::hash::Hasher;
2818/// let mut state = hash_builder.build_hasher();
2819/// key.hash(&mut state);
2820/// state.finish()
2821/// }
2822///
2823/// let builder: RawEntryBuilderMut<_, _, _> = map.raw_entry_mut();
2824///
2825/// // Existing key
2826/// match builder.from_key(&6) {
2827/// Vacant(_) => unreachable!(),
2828/// Occupied(view) => assert_eq!(view.get(), &16),
2829/// }
2830///
2831/// for key in 0..12 {
2832/// let hash = compute_hash(map.hasher(), &key);
2833/// let value = map.get(&key).cloned();
2834/// let key_value = value.as_ref().map(|v| (&key, v));
2835///
2836/// println!("Key: {} and value: {:?}", key, value);
2837///
2838/// match map.raw_entry_mut().from_key(&key) {
2839/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value),
2840/// Vacant(_) => assert_eq!(value, None),
2841/// }
2842/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) {
2843/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value),
2844/// Vacant(_) => assert_eq!(value, None),
2845/// }
2846/// match map.raw_entry_mut().from_hash(hash, |q| *q == key) {
2847/// Occupied(mut o) => assert_eq!(Some(o.get_key_value()), key_value),
2848/// Vacant(_) => assert_eq!(value, None),
2849/// }
2850/// }
2851///
2852/// assert_eq!(map.len(), 6);
2853/// ```
2854pub struct RawEntryBuilderMut<'a, K, V, S, A: Allocator = Global> {
2855 map: &'a mut HashMap<K, V, S, A>,
2856}
2857
2858/// A view into a single entry in a map, which may either be vacant or occupied.
2859///
2860/// This is a lower-level version of [`Entry`].
2861///
2862/// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`],
2863/// then calling one of the methods of that [`RawEntryBuilderMut`].
2864///
2865/// [`HashMap`]: struct.HashMap.html
2866/// [`Entry`]: enum.Entry.html
2867/// [`raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
2868/// [`RawEntryBuilderMut`]: struct.RawEntryBuilderMut.html
2869///
2870/// # Examples
2871///
2872/// ```
2873/// use core::hash::{BuildHasher, Hash};
2874/// use hashbrown::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut};
2875///
2876/// let mut map = HashMap::new();
2877/// map.extend([('a', 1), ('b', 2), ('c', 3)]);
2878/// assert_eq!(map.len(), 3);
2879///
2880/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2881/// use core::hash::Hasher;
2882/// let mut state = hash_builder.build_hasher();
2883/// key.hash(&mut state);
2884/// state.finish()
2885/// }
2886///
2887/// // Existing key (insert)
2888/// let raw: RawEntryMut<_, _, _> = map.raw_entry_mut().from_key(&'a');
2889/// let _raw_o: RawOccupiedEntryMut<_, _, _> = raw.insert('a', 10);
2890/// assert_eq!(map.len(), 3);
2891///
2892/// // Nonexistent key (insert)
2893/// map.raw_entry_mut().from_key(&'d').insert('d', 40);
2894/// assert_eq!(map.len(), 4);
2895///
2896/// // Existing key (or_insert)
2897/// let hash = compute_hash(map.hasher(), &'b');
2898/// let kv = map
2899/// .raw_entry_mut()
2900/// .from_key_hashed_nocheck(hash, &'b')
2901/// .or_insert('b', 20);
2902/// assert_eq!(kv, (&mut 'b', &mut 2));
2903/// *kv.1 = 20;
2904/// assert_eq!(map.len(), 4);
2905///
2906/// // Nonexistent key (or_insert)
2907/// let hash = compute_hash(map.hasher(), &'e');
2908/// let kv = map
2909/// .raw_entry_mut()
2910/// .from_key_hashed_nocheck(hash, &'e')
2911/// .or_insert('e', 50);
2912/// assert_eq!(kv, (&mut 'e', &mut 50));
2913/// assert_eq!(map.len(), 5);
2914///
2915/// // Existing key (or_insert_with)
2916/// let hash = compute_hash(map.hasher(), &'c');
2917/// let kv = map
2918/// .raw_entry_mut()
2919/// .from_hash(hash, |q| q == &'c')
2920/// .or_insert_with(|| ('c', 30));
2921/// assert_eq!(kv, (&mut 'c', &mut 3));
2922/// *kv.1 = 30;
2923/// assert_eq!(map.len(), 5);
2924///
2925/// // Nonexistent key (or_insert_with)
2926/// let hash = compute_hash(map.hasher(), &'f');
2927/// let kv = map
2928/// .raw_entry_mut()
2929/// .from_hash(hash, |q| q == &'f')
2930/// .or_insert_with(|| ('f', 60));
2931/// assert_eq!(kv, (&mut 'f', &mut 60));
2932/// assert_eq!(map.len(), 6);
2933///
2934/// println!("Our HashMap: {:?}", map);
2935///
2936/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
2937/// // The `Iter` iterator produces items in arbitrary order, so the
2938/// // items must be sorted to test them against a sorted array.
2939/// vec.sort_unstable();
2940/// assert_eq!(vec, [('a', 10), ('b', 20), ('c', 30), ('d', 40), ('e', 50), ('f', 60)]);
2941/// ```
2942pub enum RawEntryMut<'a, K, V, S, A: Allocator = Global> {
2943 /// An occupied entry.
2944 ///
2945 /// # Examples
2946 ///
2947 /// ```
2948 /// use hashbrown::{hash_map::RawEntryMut, HashMap};
2949 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into();
2950 ///
2951 /// match map.raw_entry_mut().from_key(&"a") {
2952 /// RawEntryMut::Vacant(_) => unreachable!(),
2953 /// RawEntryMut::Occupied(_) => { }
2954 /// }
2955 /// ```
2956 Occupied(RawOccupiedEntryMut<'a, K, V, S, A>),
2957 /// A vacant entry.
2958 ///
2959 /// # Examples
2960 ///
2961 /// ```
2962 /// use hashbrown::{hash_map::RawEntryMut, HashMap};
2963 /// let mut map: HashMap<&str, i32> = HashMap::new();
2964 ///
2965 /// match map.raw_entry_mut().from_key("a") {
2966 /// RawEntryMut::Occupied(_) => unreachable!(),
2967 /// RawEntryMut::Vacant(_) => { }
2968 /// }
2969 /// ```
2970 Vacant(RawVacantEntryMut<'a, K, V, S, A>),
2971}
2972
2973/// A view into an occupied entry in a `HashMap`.
2974/// It is part of the [`RawEntryMut`] enum.
2975///
2976/// [`RawEntryMut`]: enum.RawEntryMut.html
2977///
2978/// # Examples
2979///
2980/// ```
2981/// use core::hash::{BuildHasher, Hash};
2982/// use hashbrown::hash_map::{HashMap, RawEntryMut, RawOccupiedEntryMut};
2983///
2984/// let mut map = HashMap::new();
2985/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
2986///
2987/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
2988/// use core::hash::Hasher;
2989/// let mut state = hash_builder.build_hasher();
2990/// key.hash(&mut state);
2991/// state.finish()
2992/// }
2993///
2994/// let _raw_o: RawOccupiedEntryMut<_, _, _> = map.raw_entry_mut().from_key(&"a").insert("a", 100);
2995/// assert_eq!(map.len(), 3);
2996///
2997/// // Existing key (insert and update)
2998/// match map.raw_entry_mut().from_key(&"a") {
2999/// RawEntryMut::Vacant(_) => unreachable!(),
3000/// RawEntryMut::Occupied(mut view) => {
3001/// assert_eq!(view.get(), &100);
3002/// let v = view.get_mut();
3003/// let new_v = (*v) * 10;
3004/// *v = new_v;
3005/// assert_eq!(view.insert(1111), 1000);
3006/// }
3007/// }
3008///
3009/// assert_eq!(map[&"a"], 1111);
3010/// assert_eq!(map.len(), 3);
3011///
3012/// // Existing key (take)
3013/// let hash = compute_hash(map.hasher(), &"c");
3014/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"c") {
3015/// RawEntryMut::Vacant(_) => unreachable!(),
3016/// RawEntryMut::Occupied(view) => {
3017/// assert_eq!(view.remove_entry(), ("c", 30));
3018/// }
3019/// }
3020/// assert_eq!(map.raw_entry().from_key(&"c"), None);
3021/// assert_eq!(map.len(), 2);
3022///
3023/// let hash = compute_hash(map.hasher(), &"b");
3024/// match map.raw_entry_mut().from_hash(hash, |q| *q == "b") {
3025/// RawEntryMut::Vacant(_) => unreachable!(),
3026/// RawEntryMut::Occupied(view) => {
3027/// assert_eq!(view.remove_entry(), ("b", 20));
3028/// }
3029/// }
3030/// assert_eq!(map.get(&"b"), None);
3031/// assert_eq!(map.len(), 1);
3032/// ```
3033pub struct RawOccupiedEntryMut<'a, K, V, S, A: Allocator = Global> {
3034 elem: Bucket<(K, V)>,
3035 table: &'a mut RawTable<(K, V), A>,
3036 hash_builder: &'a S,
3037}
3038
3039unsafe impl<K, V, S, A> Send for RawOccupiedEntryMut<'_, K, V, S, A>
3040where
3041 K: Send,
3042 V: Send,
3043 S: Send,
3044 A: Send + Allocator,
3045{
3046}
3047unsafe impl<K, V, S, A> Sync for RawOccupiedEntryMut<'_, K, V, S, A>
3048where
3049 K: Sync,
3050 V: Sync,
3051 S: Sync,
3052 A: Sync + Allocator,
3053{
3054}
3055
3056/// A view into a vacant entry in a `HashMap`.
3057/// It is part of the [`RawEntryMut`] enum.
3058///
3059/// [`RawEntryMut`]: enum.RawEntryMut.html
3060///
3061/// # Examples
3062///
3063/// ```
3064/// use core::hash::{BuildHasher, Hash};
3065/// use hashbrown::hash_map::{HashMap, RawEntryMut, RawVacantEntryMut};
3066///
3067/// let mut map = HashMap::<&str, i32>::new();
3068///
3069/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3070/// use core::hash::Hasher;
3071/// let mut state = hash_builder.build_hasher();
3072/// key.hash(&mut state);
3073/// state.finish()
3074/// }
3075///
3076/// let raw_v: RawVacantEntryMut<_, _, _> = match map.raw_entry_mut().from_key(&"a") {
3077/// RawEntryMut::Vacant(view) => view,
3078/// RawEntryMut::Occupied(_) => unreachable!(),
3079/// };
3080/// raw_v.insert("a", 10);
3081/// assert!(map[&"a"] == 10 && map.len() == 1);
3082///
3083/// // Nonexistent key (insert and update)
3084/// let hash = compute_hash(map.hasher(), &"b");
3085/// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &"b") {
3086/// RawEntryMut::Occupied(_) => unreachable!(),
3087/// RawEntryMut::Vacant(view) => {
3088/// let (k, value) = view.insert("b", 2);
3089/// assert_eq!((*k, *value), ("b", 2));
3090/// *value = 20;
3091/// }
3092/// }
3093/// assert!(map[&"b"] == 20 && map.len() == 2);
3094///
3095/// let hash = compute_hash(map.hasher(), &"c");
3096/// match map.raw_entry_mut().from_hash(hash, |q| *q == "c") {
3097/// RawEntryMut::Occupied(_) => unreachable!(),
3098/// RawEntryMut::Vacant(view) => {
3099/// assert_eq!(view.insert("c", 30), (&mut "c", &mut 30));
3100/// }
3101/// }
3102/// assert!(map[&"c"] == 30 && map.len() == 3);
3103/// ```
3104pub struct RawVacantEntryMut<'a, K, V, S, A: Allocator = Global> {
3105 table: &'a mut RawTable<(K, V), A>,
3106 hash_builder: &'a S,
3107}
3108
3109/// A builder for computing where in a [`HashMap`] a key-value pair would be stored.
3110///
3111/// See the [`HashMap::raw_entry`] docs for usage examples.
3112///
3113/// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
3114///
3115/// # Examples
3116///
3117/// ```
3118/// use hashbrown::hash_map::{HashMap, RawEntryBuilder};
3119/// use core::hash::{BuildHasher, Hash};
3120///
3121/// let mut map = HashMap::new();
3122/// map.extend([(1, 10), (2, 20), (3, 30)]);
3123///
3124/// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3125/// use core::hash::Hasher;
3126/// let mut state = hash_builder.build_hasher();
3127/// key.hash(&mut state);
3128/// state.finish()
3129/// }
3130///
3131/// for k in 0..6 {
3132/// let hash = compute_hash(map.hasher(), &k);
3133/// let v = map.get(&k).cloned();
3134/// let kv = v.as_ref().map(|v| (&k, v));
3135///
3136/// println!("Key: {} and value: {:?}", k, v);
3137/// let builder: RawEntryBuilder<_, _, _> = map.raw_entry();
3138/// assert_eq!(builder.from_key(&k), kv);
3139/// assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
3140/// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
3141/// }
3142/// ```
3143pub struct RawEntryBuilder<'a, K, V, S, A: Allocator = Global> {
3144 map: &'a HashMap<K, V, S, A>,
3145}
3146
3147impl<'a, K, V, S, A: Allocator> RawEntryBuilderMut<'a, K, V, S, A> {
3148 /// Creates a `RawEntryMut` from the given key.
3149 ///
3150 /// # Examples
3151 ///
3152 /// ```
3153 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3154 ///
3155 /// let mut map: HashMap<&str, u32> = HashMap::new();
3156 /// let key = "a";
3157 /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key(&key);
3158 /// entry.insert(key, 100);
3159 /// assert_eq!(map[&"a"], 100);
3160 /// ```
3161 #[cfg_attr(feature = "inline-more", inline)]
3162 #[allow(clippy::wrong_self_convention)]
3163 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S, A>
3164 where
3165 S: BuildHasher,
3166 Q: Hash + Equivalent<K>,
3167 {
3168 let hash = make_hash::<Q, S>(&self.map.hash_builder, k);
3169 self.from_key_hashed_nocheck(hash, k)
3170 }
3171
3172 /// Creates a `RawEntryMut` from the given key and its hash.
3173 ///
3174 /// # Examples
3175 ///
3176 /// ```
3177 /// use core::hash::{BuildHasher, Hash};
3178 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3179 ///
3180 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3181 /// use core::hash::Hasher;
3182 /// let mut state = hash_builder.build_hasher();
3183 /// key.hash(&mut state);
3184 /// state.finish()
3185 /// }
3186 ///
3187 /// let mut map: HashMap<&str, u32> = HashMap::new();
3188 /// let key = "a";
3189 /// let hash = compute_hash(map.hasher(), &key);
3190 /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_key_hashed_nocheck(hash, &key);
3191 /// entry.insert(key, 100);
3192 /// assert_eq!(map[&"a"], 100);
3193 /// ```
3194 #[inline]
3195 #[allow(clippy::wrong_self_convention)]
3196 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A>
3197 where
3198 Q: Equivalent<K>,
3199 {
3200 self.from_hash(hash, equivalent(k))
3201 }
3202}
3203
3204impl<'a, K, V, S, A: Allocator> RawEntryBuilderMut<'a, K, V, S, A> {
3205 /// Creates a `RawEntryMut` from the given hash and matching function.
3206 ///
3207 /// # Examples
3208 ///
3209 /// ```
3210 /// use core::hash::{BuildHasher, Hash};
3211 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3212 ///
3213 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3214 /// use core::hash::Hasher;
3215 /// let mut state = hash_builder.build_hasher();
3216 /// key.hash(&mut state);
3217 /// state.finish()
3218 /// }
3219 ///
3220 /// let mut map: HashMap<&str, u32> = HashMap::new();
3221 /// let key = "a";
3222 /// let hash = compute_hash(map.hasher(), &key);
3223 /// let entry: RawEntryMut<&str, u32, _> = map.raw_entry_mut().from_hash(hash, |k| k == &key);
3224 /// entry.insert(key, 100);
3225 /// assert_eq!(map[&"a"], 100);
3226 /// ```
3227 #[cfg_attr(feature = "inline-more", inline)]
3228 #[allow(clippy::wrong_self_convention)]
3229 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A>
3230 where
3231 for<'b> F: FnMut(&'b K) -> bool,
3232 {
3233 self.search(hash, is_match)
3234 }
3235
3236 #[cfg_attr(feature = "inline-more", inline)]
3237 fn search<F>(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A>
3238 where
3239 for<'b> F: FnMut(&'b K) -> bool,
3240 {
3241 match self.map.table.find(hash, |(k, _)| is_match(k)) {
3242 Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut {
3243 elem,
3244 table: &mut self.map.table,
3245 hash_builder: &self.map.hash_builder,
3246 }),
3247 None => RawEntryMut::Vacant(RawVacantEntryMut {
3248 table: &mut self.map.table,
3249 hash_builder: &self.map.hash_builder,
3250 }),
3251 }
3252 }
3253}
3254
3255impl<'a, K, V, S, A: Allocator> RawEntryBuilder<'a, K, V, S, A> {
3256 /// Access an immutable entry by key.
3257 ///
3258 /// # Examples
3259 ///
3260 /// ```
3261 /// use hashbrown::HashMap;
3262 ///
3263 /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3264 /// let key = "a";
3265 /// assert_eq!(map.raw_entry().from_key(&key), Some((&"a", &100)));
3266 /// ```
3267 #[cfg_attr(feature = "inline-more", inline)]
3268 #[allow(clippy::wrong_self_convention)]
3269 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
3270 where
3271 S: BuildHasher,
3272 Q: Hash + Equivalent<K>,
3273 {
3274 let hash = make_hash::<Q, S>(&self.map.hash_builder, k);
3275 self.from_key_hashed_nocheck(hash, k)
3276 }
3277
3278 /// Access an immutable entry by a key and its hash.
3279 ///
3280 /// # Examples
3281 ///
3282 /// ```
3283 /// use core::hash::{BuildHasher, Hash};
3284 /// use hashbrown::HashMap;
3285 ///
3286 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3287 /// use core::hash::Hasher;
3288 /// let mut state = hash_builder.build_hasher();
3289 /// key.hash(&mut state);
3290 /// state.finish()
3291 /// }
3292 ///
3293 /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3294 /// let key = "a";
3295 /// let hash = compute_hash(map.hasher(), &key);
3296 /// assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &key), Some((&"a", &100)));
3297 /// ```
3298 #[cfg_attr(feature = "inline-more", inline)]
3299 #[allow(clippy::wrong_self_convention)]
3300 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
3301 where
3302 Q: Equivalent<K>,
3303 {
3304 self.from_hash(hash, equivalent(k))
3305 }
3306
3307 #[cfg_attr(feature = "inline-more", inline)]
3308 fn search<F>(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)>
3309 where
3310 F: FnMut(&K) -> bool,
3311 {
3312 match self.map.table.get(hash, |(k, _)| is_match(k)) {
3313 Some((key, value)) => Some((key, value)),
3314 None => None,
3315 }
3316 }
3317
3318 /// Access an immutable entry by hash and matching function.
3319 ///
3320 /// # Examples
3321 ///
3322 /// ```
3323 /// use core::hash::{BuildHasher, Hash};
3324 /// use hashbrown::HashMap;
3325 ///
3326 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3327 /// use core::hash::Hasher;
3328 /// let mut state = hash_builder.build_hasher();
3329 /// key.hash(&mut state);
3330 /// state.finish()
3331 /// }
3332 ///
3333 /// let map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3334 /// let key = "a";
3335 /// let hash = compute_hash(map.hasher(), &key);
3336 /// assert_eq!(map.raw_entry().from_hash(hash, |k| k == &key), Some((&"a", &100)));
3337 /// ```
3338 #[cfg_attr(feature = "inline-more", inline)]
3339 #[allow(clippy::wrong_self_convention)]
3340 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
3341 where
3342 F: FnMut(&K) -> bool,
3343 {
3344 self.search(hash, is_match)
3345 }
3346}
3347
3348impl<'a, K, V, S, A: Allocator> RawEntryMut<'a, K, V, S, A> {
3349 /// Sets the value of the entry, and returns a RawOccupiedEntryMut.
3350 ///
3351 /// # Examples
3352 ///
3353 /// ```
3354 /// use hashbrown::HashMap;
3355 ///
3356 /// let mut map: HashMap<&str, u32> = HashMap::new();
3357 /// let entry = map.raw_entry_mut().from_key("horseyland").insert("horseyland", 37);
3358 ///
3359 /// assert_eq!(entry.remove_entry(), ("horseyland", 37));
3360 /// ```
3361 #[cfg_attr(feature = "inline-more", inline)]
3362 pub fn insert(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A>
3363 where
3364 K: Hash,
3365 S: BuildHasher,
3366 {
3367 match self {
3368 RawEntryMut::Occupied(mut entry) => {
3369 entry.insert(value);
3370 entry
3371 }
3372 RawEntryMut::Vacant(entry) => entry.insert_entry(key, value),
3373 }
3374 }
3375
3376 /// Ensures a value is in the entry by inserting the default if empty, and returns
3377 /// mutable references to the key and value in the entry.
3378 ///
3379 /// # Examples
3380 ///
3381 /// ```
3382 /// use hashbrown::HashMap;
3383 ///
3384 /// let mut map: HashMap<&str, u32> = HashMap::new();
3385 ///
3386 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
3387 /// assert_eq!(map["poneyland"], 3);
3388 ///
3389 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
3390 /// assert_eq!(map["poneyland"], 6);
3391 /// ```
3392 #[cfg_attr(feature = "inline-more", inline)]
3393 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
3394 where
3395 K: Hash,
3396 S: BuildHasher,
3397 {
3398 match self {
3399 RawEntryMut::Occupied(entry) => entry.into_key_value(),
3400 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
3401 }
3402 }
3403
3404 /// Ensures a value is in the entry by inserting the result of the default function if empty,
3405 /// and returns mutable references to the key and value in the entry.
3406 ///
3407 /// # Examples
3408 ///
3409 /// ```
3410 /// use hashbrown::HashMap;
3411 ///
3412 /// let mut map: HashMap<&str, String> = HashMap::new();
3413 ///
3414 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
3415 /// ("poneyland", "hoho".to_string())
3416 /// });
3417 ///
3418 /// assert_eq!(map["poneyland"], "hoho".to_string());
3419 /// ```
3420 #[cfg_attr(feature = "inline-more", inline)]
3421 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
3422 where
3423 F: FnOnce() -> (K, V),
3424 K: Hash,
3425 S: BuildHasher,
3426 {
3427 match self {
3428 RawEntryMut::Occupied(entry) => entry.into_key_value(),
3429 RawEntryMut::Vacant(entry) => {
3430 let (k, v) = default();
3431 entry.insert(k, v)
3432 }
3433 }
3434 }
3435
3436 /// Provides in-place mutable access to an occupied entry before any
3437 /// potential inserts into the map.
3438 ///
3439 /// # Examples
3440 ///
3441 /// ```
3442 /// use hashbrown::HashMap;
3443 ///
3444 /// let mut map: HashMap<&str, u32> = HashMap::new();
3445 ///
3446 /// map.raw_entry_mut()
3447 /// .from_key("poneyland")
3448 /// .and_modify(|_k, v| { *v += 1 })
3449 /// .or_insert("poneyland", 42);
3450 /// assert_eq!(map["poneyland"], 42);
3451 ///
3452 /// map.raw_entry_mut()
3453 /// .from_key("poneyland")
3454 /// .and_modify(|_k, v| { *v += 1 })
3455 /// .or_insert("poneyland", 0);
3456 /// assert_eq!(map["poneyland"], 43);
3457 /// ```
3458 #[cfg_attr(feature = "inline-more", inline)]
3459 pub fn and_modify<F>(self, f: F) -> Self
3460 where
3461 F: FnOnce(&mut K, &mut V),
3462 {
3463 match self {
3464 RawEntryMut::Occupied(mut entry) => {
3465 {
3466 let (k, v) = entry.get_key_value_mut();
3467 f(k, v);
3468 }
3469 RawEntryMut::Occupied(entry)
3470 }
3471 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
3472 }
3473 }
3474
3475 /// Provides shared access to the key and owned access to the value of
3476 /// an occupied entry and allows to replace or remove it based on the
3477 /// value of the returned option.
3478 ///
3479 /// # Examples
3480 ///
3481 /// ```
3482 /// use hashbrown::HashMap;
3483 /// use hashbrown::hash_map::RawEntryMut;
3484 ///
3485 /// let mut map: HashMap<&str, u32> = HashMap::new();
3486 ///
3487 /// let entry = map
3488 /// .raw_entry_mut()
3489 /// .from_key("poneyland")
3490 /// .and_replace_entry_with(|_k, _v| panic!());
3491 ///
3492 /// match entry {
3493 /// RawEntryMut::Vacant(_) => {},
3494 /// RawEntryMut::Occupied(_) => panic!(),
3495 /// }
3496 ///
3497 /// map.insert("poneyland", 42);
3498 ///
3499 /// let entry = map
3500 /// .raw_entry_mut()
3501 /// .from_key("poneyland")
3502 /// .and_replace_entry_with(|k, v| {
3503 /// assert_eq!(k, &"poneyland");
3504 /// assert_eq!(v, 42);
3505 /// Some(v + 1)
3506 /// });
3507 ///
3508 /// match entry {
3509 /// RawEntryMut::Occupied(e) => {
3510 /// assert_eq!(e.key(), &"poneyland");
3511 /// assert_eq!(e.get(), &43);
3512 /// },
3513 /// RawEntryMut::Vacant(_) => panic!(),
3514 /// }
3515 ///
3516 /// assert_eq!(map["poneyland"], 43);
3517 ///
3518 /// let entry = map
3519 /// .raw_entry_mut()
3520 /// .from_key("poneyland")
3521 /// .and_replace_entry_with(|_k, _v| None);
3522 ///
3523 /// match entry {
3524 /// RawEntryMut::Vacant(_) => {},
3525 /// RawEntryMut::Occupied(_) => panic!(),
3526 /// }
3527 ///
3528 /// assert!(!map.contains_key("poneyland"));
3529 /// ```
3530 #[cfg_attr(feature = "inline-more", inline)]
3531 pub fn and_replace_entry_with<F>(self, f: F) -> Self
3532 where
3533 F: FnOnce(&K, V) -> Option<V>,
3534 {
3535 match self {
3536 RawEntryMut::Occupied(entry) => entry.replace_entry_with(f),
3537 RawEntryMut::Vacant(_) => self,
3538 }
3539 }
3540}
3541
3542impl<'a, K, V, S, A: Allocator> RawOccupiedEntryMut<'a, K, V, S, A> {
3543 /// Gets a reference to the key in the entry.
3544 ///
3545 /// # Examples
3546 ///
3547 /// ```
3548 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3549 ///
3550 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3551 ///
3552 /// match map.raw_entry_mut().from_key(&"a") {
3553 /// RawEntryMut::Vacant(_) => panic!(),
3554 /// RawEntryMut::Occupied(o) => assert_eq!(o.key(), &"a")
3555 /// }
3556 /// ```
3557 #[cfg_attr(feature = "inline-more", inline)]
3558 pub fn key(&self) -> &K {
3559 unsafe { &self.elem.as_ref().0 }
3560 }
3561
3562 /// Gets a mutable reference to the key in the entry.
3563 ///
3564 /// # Examples
3565 ///
3566 /// ```
3567 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3568 /// use std::rc::Rc;
3569 ///
3570 /// let key_one = Rc::new("a");
3571 /// let key_two = Rc::new("a");
3572 ///
3573 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3574 /// map.insert(key_one.clone(), 10);
3575 ///
3576 /// assert_eq!(map[&key_one], 10);
3577 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3578 ///
3579 /// match map.raw_entry_mut().from_key(&key_one) {
3580 /// RawEntryMut::Vacant(_) => panic!(),
3581 /// RawEntryMut::Occupied(mut o) => {
3582 /// *o.key_mut() = key_two.clone();
3583 /// }
3584 /// }
3585 /// assert_eq!(map[&key_two], 10);
3586 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3587 /// ```
3588 #[cfg_attr(feature = "inline-more", inline)]
3589 pub fn key_mut(&mut self) -> &mut K {
3590 unsafe { &mut self.elem.as_mut().0 }
3591 }
3592
3593 /// Converts the entry into a mutable reference to the key in the entry
3594 /// with a lifetime bound to the map itself.
3595 ///
3596 /// # Examples
3597 ///
3598 /// ```
3599 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3600 /// use std::rc::Rc;
3601 ///
3602 /// let key_one = Rc::new("a");
3603 /// let key_two = Rc::new("a");
3604 ///
3605 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3606 /// map.insert(key_one.clone(), 10);
3607 ///
3608 /// assert_eq!(map[&key_one], 10);
3609 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3610 ///
3611 /// let inside_key: &mut Rc<&str>;
3612 ///
3613 /// match map.raw_entry_mut().from_key(&key_one) {
3614 /// RawEntryMut::Vacant(_) => panic!(),
3615 /// RawEntryMut::Occupied(o) => inside_key = o.into_key(),
3616 /// }
3617 /// *inside_key = key_two.clone();
3618 ///
3619 /// assert_eq!(map[&key_two], 10);
3620 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3621 /// ```
3622 #[cfg_attr(feature = "inline-more", inline)]
3623 pub fn into_key(self) -> &'a mut K {
3624 unsafe { &mut self.elem.as_mut().0 }
3625 }
3626
3627 /// Gets a reference to the value in the entry.
3628 ///
3629 /// # Examples
3630 ///
3631 /// ```
3632 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3633 ///
3634 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3635 ///
3636 /// match map.raw_entry_mut().from_key(&"a") {
3637 /// RawEntryMut::Vacant(_) => panic!(),
3638 /// RawEntryMut::Occupied(o) => assert_eq!(o.get(), &100),
3639 /// }
3640 /// ```
3641 #[cfg_attr(feature = "inline-more", inline)]
3642 pub fn get(&self) -> &V {
3643 unsafe { &self.elem.as_ref().1 }
3644 }
3645
3646 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
3647 /// with a lifetime bound to the map itself.
3648 ///
3649 /// # Examples
3650 ///
3651 /// ```
3652 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3653 ///
3654 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3655 ///
3656 /// let value: &mut u32;
3657 ///
3658 /// match map.raw_entry_mut().from_key(&"a") {
3659 /// RawEntryMut::Vacant(_) => panic!(),
3660 /// RawEntryMut::Occupied(o) => value = o.into_mut(),
3661 /// }
3662 /// *value += 900;
3663 ///
3664 /// assert_eq!(map[&"a"], 1000);
3665 /// ```
3666 #[cfg_attr(feature = "inline-more", inline)]
3667 pub fn into_mut(self) -> &'a mut V {
3668 unsafe { &mut self.elem.as_mut().1 }
3669 }
3670
3671 /// Gets a mutable reference to the value in the entry.
3672 ///
3673 /// # Examples
3674 ///
3675 /// ```
3676 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3677 ///
3678 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3679 ///
3680 /// match map.raw_entry_mut().from_key(&"a") {
3681 /// RawEntryMut::Vacant(_) => panic!(),
3682 /// RawEntryMut::Occupied(mut o) => *o.get_mut() += 900,
3683 /// }
3684 ///
3685 /// assert_eq!(map[&"a"], 1000);
3686 /// ```
3687 #[cfg_attr(feature = "inline-more", inline)]
3688 pub fn get_mut(&mut self) -> &mut V {
3689 unsafe { &mut self.elem.as_mut().1 }
3690 }
3691
3692 /// Gets a reference to the key and value in the entry.
3693 ///
3694 /// # Examples
3695 ///
3696 /// ```
3697 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3698 ///
3699 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3700 ///
3701 /// match map.raw_entry_mut().from_key(&"a") {
3702 /// RawEntryMut::Vacant(_) => panic!(),
3703 /// RawEntryMut::Occupied(o) => assert_eq!(o.get_key_value(), (&"a", &100)),
3704 /// }
3705 /// ```
3706 #[cfg_attr(feature = "inline-more", inline)]
3707 pub fn get_key_value(&self) -> (&K, &V) {
3708 unsafe {
3709 let (key, value) = self.elem.as_ref();
3710 (key, value)
3711 }
3712 }
3713
3714 /// Gets a mutable reference to the key and value in the entry.
3715 ///
3716 /// # Examples
3717 ///
3718 /// ```
3719 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3720 /// use std::rc::Rc;
3721 ///
3722 /// let key_one = Rc::new("a");
3723 /// let key_two = Rc::new("a");
3724 ///
3725 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3726 /// map.insert(key_one.clone(), 10);
3727 ///
3728 /// assert_eq!(map[&key_one], 10);
3729 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3730 ///
3731 /// match map.raw_entry_mut().from_key(&key_one) {
3732 /// RawEntryMut::Vacant(_) => panic!(),
3733 /// RawEntryMut::Occupied(mut o) => {
3734 /// let (inside_key, inside_value) = o.get_key_value_mut();
3735 /// *inside_key = key_two.clone();
3736 /// *inside_value = 100;
3737 /// }
3738 /// }
3739 /// assert_eq!(map[&key_two], 100);
3740 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3741 /// ```
3742 #[cfg_attr(feature = "inline-more", inline)]
3743 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
3744 unsafe {
3745 let &mut (ref mut key, ref mut value) = self.elem.as_mut();
3746 (key, value)
3747 }
3748 }
3749
3750 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
3751 /// with a lifetime bound to the map itself.
3752 ///
3753 /// # Examples
3754 ///
3755 /// ```
3756 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3757 /// use std::rc::Rc;
3758 ///
3759 /// let key_one = Rc::new("a");
3760 /// let key_two = Rc::new("a");
3761 ///
3762 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3763 /// map.insert(key_one.clone(), 10);
3764 ///
3765 /// assert_eq!(map[&key_one], 10);
3766 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3767 ///
3768 /// let inside_key: &mut Rc<&str>;
3769 /// let inside_value: &mut u32;
3770 /// match map.raw_entry_mut().from_key(&key_one) {
3771 /// RawEntryMut::Vacant(_) => panic!(),
3772 /// RawEntryMut::Occupied(o) => {
3773 /// let tuple = o.into_key_value();
3774 /// inside_key = tuple.0;
3775 /// inside_value = tuple.1;
3776 /// }
3777 /// }
3778 /// *inside_key = key_two.clone();
3779 /// *inside_value = 100;
3780 /// assert_eq!(map[&key_two], 100);
3781 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3782 /// ```
3783 #[cfg_attr(feature = "inline-more", inline)]
3784 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
3785 unsafe {
3786 let &mut (ref mut key, ref mut value) = self.elem.as_mut();
3787 (key, value)
3788 }
3789 }
3790
3791 /// Sets the value of the entry, and returns the entry's old value.
3792 ///
3793 /// # Examples
3794 ///
3795 /// ```
3796 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3797 ///
3798 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3799 ///
3800 /// match map.raw_entry_mut().from_key(&"a") {
3801 /// RawEntryMut::Vacant(_) => panic!(),
3802 /// RawEntryMut::Occupied(mut o) => assert_eq!(o.insert(1000), 100),
3803 /// }
3804 ///
3805 /// assert_eq!(map[&"a"], 1000);
3806 /// ```
3807 #[cfg_attr(feature = "inline-more", inline)]
3808 pub fn insert(&mut self, value: V) -> V {
3809 mem::replace(self.get_mut(), value)
3810 }
3811
3812 /// Sets the value of the entry, and returns the entry's old value.
3813 ///
3814 /// # Examples
3815 ///
3816 /// ```
3817 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3818 /// use std::rc::Rc;
3819 ///
3820 /// let key_one = Rc::new("a");
3821 /// let key_two = Rc::new("a");
3822 ///
3823 /// let mut map: HashMap<Rc<&str>, u32> = HashMap::new();
3824 /// map.insert(key_one.clone(), 10);
3825 ///
3826 /// assert_eq!(map[&key_one], 10);
3827 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
3828 ///
3829 /// match map.raw_entry_mut().from_key(&key_one) {
3830 /// RawEntryMut::Vacant(_) => panic!(),
3831 /// RawEntryMut::Occupied(mut o) => {
3832 /// let old_key = o.insert_key(key_two.clone());
3833 /// assert!(Rc::ptr_eq(&old_key, &key_one));
3834 /// }
3835 /// }
3836 /// assert_eq!(map[&key_two], 10);
3837 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
3838 /// ```
3839 #[cfg_attr(feature = "inline-more", inline)]
3840 pub fn insert_key(&mut self, key: K) -> K {
3841 mem::replace(self.key_mut(), key)
3842 }
3843
3844 /// Takes the value out of the entry, and returns it.
3845 ///
3846 /// # Examples
3847 ///
3848 /// ```
3849 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3850 ///
3851 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3852 ///
3853 /// match map.raw_entry_mut().from_key(&"a") {
3854 /// RawEntryMut::Vacant(_) => panic!(),
3855 /// RawEntryMut::Occupied(o) => assert_eq!(o.remove(), 100),
3856 /// }
3857 /// assert_eq!(map.get(&"a"), None);
3858 /// ```
3859 #[cfg_attr(feature = "inline-more", inline)]
3860 pub fn remove(self) -> V {
3861 self.remove_entry().1
3862 }
3863
3864 /// Take the ownership of the key and value from the map.
3865 ///
3866 /// # Examples
3867 ///
3868 /// ```
3869 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3870 ///
3871 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3872 ///
3873 /// match map.raw_entry_mut().from_key(&"a") {
3874 /// RawEntryMut::Vacant(_) => panic!(),
3875 /// RawEntryMut::Occupied(o) => assert_eq!(o.remove_entry(), ("a", 100)),
3876 /// }
3877 /// assert_eq!(map.get(&"a"), None);
3878 /// ```
3879 #[cfg_attr(feature = "inline-more", inline)]
3880 pub fn remove_entry(self) -> (K, V) {
3881 unsafe { self.table.remove(self.elem).0 }
3882 }
3883
3884 /// Provides shared access to the key and owned access to the value of
3885 /// the entry and allows to replace or remove it based on the
3886 /// value of the returned option.
3887 ///
3888 /// # Examples
3889 ///
3890 /// ```
3891 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3892 ///
3893 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3894 ///
3895 /// let raw_entry = match map.raw_entry_mut().from_key(&"a") {
3896 /// RawEntryMut::Vacant(_) => panic!(),
3897 /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| {
3898 /// assert_eq!(k, &"a");
3899 /// assert_eq!(v, 100);
3900 /// Some(v + 900)
3901 /// }),
3902 /// };
3903 /// let raw_entry = match raw_entry {
3904 /// RawEntryMut::Vacant(_) => panic!(),
3905 /// RawEntryMut::Occupied(o) => o.replace_entry_with(|k, v| {
3906 /// assert_eq!(k, &"a");
3907 /// assert_eq!(v, 1000);
3908 /// None
3909 /// }),
3910 /// };
3911 /// match raw_entry {
3912 /// RawEntryMut::Vacant(_) => { },
3913 /// RawEntryMut::Occupied(_) => panic!(),
3914 /// };
3915 /// assert_eq!(map.get(&"a"), None);
3916 /// ```
3917 #[cfg_attr(feature = "inline-more", inline)]
3918 pub fn replace_entry_with<F>(self, f: F) -> RawEntryMut<'a, K, V, S, A>
3919 where
3920 F: FnOnce(&K, V) -> Option<V>,
3921 {
3922 unsafe {
3923 let still_occupied = self
3924 .table
3925 .replace_bucket_with(self.elem.clone(), |(key, value)| {
3926 f(&key, value).map(|new_value| (key, new_value))
3927 });
3928
3929 if still_occupied {
3930 RawEntryMut::Occupied(self)
3931 } else {
3932 RawEntryMut::Vacant(RawVacantEntryMut {
3933 table: self.table,
3934 hash_builder: self.hash_builder,
3935 })
3936 }
3937 }
3938 }
3939}
3940
3941impl<'a, K, V, S, A: Allocator> RawVacantEntryMut<'a, K, V, S, A> {
3942 /// Sets the value of the entry with the VacantEntry's key,
3943 /// and returns a mutable reference to it.
3944 ///
3945 /// # Examples
3946 ///
3947 /// ```
3948 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3949 ///
3950 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3951 ///
3952 /// match map.raw_entry_mut().from_key(&"c") {
3953 /// RawEntryMut::Occupied(_) => panic!(),
3954 /// RawEntryMut::Vacant(v) => assert_eq!(v.insert("c", 300), (&mut "c", &mut 300)),
3955 /// }
3956 ///
3957 /// assert_eq!(map[&"c"], 300);
3958 /// ```
3959 #[cfg_attr(feature = "inline-more", inline)]
3960 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
3961 where
3962 K: Hash,
3963 S: BuildHasher,
3964 {
3965 let hash = make_hash::<K, S>(self.hash_builder, &key);
3966 self.insert_hashed_nocheck(hash, key, value)
3967 }
3968
3969 /// Sets the value of the entry with the VacantEntry's key,
3970 /// and returns a mutable reference to it.
3971 ///
3972 /// # Examples
3973 ///
3974 /// ```
3975 /// use core::hash::{BuildHasher, Hash};
3976 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
3977 ///
3978 /// fn compute_hash<K: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &K) -> u64 {
3979 /// use core::hash::Hasher;
3980 /// let mut state = hash_builder.build_hasher();
3981 /// key.hash(&mut state);
3982 /// state.finish()
3983 /// }
3984 ///
3985 /// let mut map: HashMap<&str, u32> = [("a", 100), ("b", 200)].into();
3986 /// let key = "c";
3987 /// let hash = compute_hash(map.hasher(), &key);
3988 ///
3989 /// match map.raw_entry_mut().from_key_hashed_nocheck(hash, &key) {
3990 /// RawEntryMut::Occupied(_) => panic!(),
3991 /// RawEntryMut::Vacant(v) => assert_eq!(
3992 /// v.insert_hashed_nocheck(hash, key, 300),
3993 /// (&mut "c", &mut 300)
3994 /// ),
3995 /// }
3996 ///
3997 /// assert_eq!(map[&"c"], 300);
3998 /// ```
3999 #[cfg_attr(feature = "inline-more", inline)]
4000 #[allow(clippy::shadow_unrelated)]
4001 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V)
4002 where
4003 K: Hash,
4004 S: BuildHasher,
4005 {
4006 let &mut (ref mut k, ref mut v) = self.table.insert_entry(
4007 hash,
4008 (key, value),
4009 make_hasher::<_, V, S>(self.hash_builder),
4010 );
4011 (k, v)
4012 }
4013
4014 /// Set the value of an entry with a custom hasher function.
4015 ///
4016 /// # Examples
4017 ///
4018 /// ```
4019 /// use core::hash::{BuildHasher, Hash};
4020 /// use hashbrown::hash_map::{HashMap, RawEntryMut};
4021 ///
4022 /// fn make_hasher<K, S>(hash_builder: &S) -> impl Fn(&K) -> u64 + '_
4023 /// where
4024 /// K: Hash + ?Sized,
4025 /// S: BuildHasher,
4026 /// {
4027 /// move |key: &K| {
4028 /// use core::hash::Hasher;
4029 /// let mut state = hash_builder.build_hasher();
4030 /// key.hash(&mut state);
4031 /// state.finish()
4032 /// }
4033 /// }
4034 ///
4035 /// let mut map: HashMap<&str, u32> = HashMap::new();
4036 /// let key = "a";
4037 /// let hash_builder = map.hasher().clone();
4038 /// let hash = make_hasher(&hash_builder)(&key);
4039 ///
4040 /// match map.raw_entry_mut().from_hash(hash, |q| q == &key) {
4041 /// RawEntryMut::Occupied(_) => panic!(),
4042 /// RawEntryMut::Vacant(v) => assert_eq!(
4043 /// v.insert_with_hasher(hash, key, 100, make_hasher(&hash_builder)),
4044 /// (&mut "a", &mut 100)
4045 /// ),
4046 /// }
4047 /// map.extend([("b", 200), ("c", 300), ("d", 400), ("e", 500), ("f", 600)]);
4048 /// assert_eq!(map[&"a"], 100);
4049 /// ```
4050 #[cfg_attr(feature = "inline-more", inline)]
4051 pub fn insert_with_hasher<H>(
4052 self,
4053 hash: u64,
4054 key: K,
4055 value: V,
4056 hasher: H,
4057 ) -> (&'a mut K, &'a mut V)
4058 where
4059 H: Fn(&K) -> u64,
4060 {
4061 let &mut (ref mut k, ref mut v) = self
4062 .table
4063 .insert_entry(hash, (key, value), |x| hasher(&x.0));
4064 (k, v)
4065 }
4066
4067 #[cfg_attr(feature = "inline-more", inline)]
4068 fn insert_entry(self, key: K, value: V) -> RawOccupiedEntryMut<'a, K, V, S, A>
4069 where
4070 K: Hash,
4071 S: BuildHasher,
4072 {
4073 let hash = make_hash::<K, S>(self.hash_builder, &key);
4074 let elem = self.table.insert(
4075 hash,
4076 (key, value),
4077 make_hasher::<_, V, S>(self.hash_builder),
4078 );
4079 RawOccupiedEntryMut {
4080 elem,
4081 table: self.table,
4082 hash_builder: self.hash_builder,
4083 }
4084 }
4085}
4086
4087impl<K, V, S, A: Allocator> Debug for RawEntryBuilderMut<'_, K, V, S, A> {
4088 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4089 f.debug_struct("RawEntryBuilder").finish()
4090 }
4091}
4092
4093impl<K: Debug, V: Debug, S, A: Allocator> Debug for RawEntryMut<'_, K, V, S, A> {
4094 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4095 match *self {
4096 RawEntryMut::Vacant(ref v: &RawVacantEntryMut<'_, K, …, …, …>) => f.debug_tuple("RawEntry").field(v).finish(),
4097 RawEntryMut::Occupied(ref o: &RawOccupiedEntryMut<'_, …, …, …, …>) => f.debug_tuple("RawEntry").field(o).finish(),
4098 }
4099 }
4100}
4101
4102impl<K: Debug, V: Debug, S, A: Allocator> Debug for RawOccupiedEntryMut<'_, K, V, S, A> {
4103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4104 f.debug_struct("RawOccupiedEntryMut")
4105 .field("key", self.key())
4106 .field("value", self.get())
4107 .finish()
4108 }
4109}
4110
4111impl<K, V, S, A: Allocator> Debug for RawVacantEntryMut<'_, K, V, S, A> {
4112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4113 f.debug_struct("RawVacantEntryMut").finish()
4114 }
4115}
4116
4117impl<K, V, S, A: Allocator> Debug for RawEntryBuilder<'_, K, V, S, A> {
4118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4119 f.debug_struct("RawEntryBuilder").finish()
4120 }
4121}
4122
4123/// A view into a single entry in a map, which may either be vacant or occupied.
4124///
4125/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
4126///
4127/// [`HashMap`]: struct.HashMap.html
4128/// [`entry`]: struct.HashMap.html#method.entry
4129///
4130/// # Examples
4131///
4132/// ```
4133/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
4134///
4135/// let mut map = HashMap::new();
4136/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
4137/// assert_eq!(map.len(), 3);
4138///
4139/// // Existing key (insert)
4140/// let entry: Entry<_, _, _> = map.entry("a");
4141/// let _raw_o: OccupiedEntry<_, _, _> = entry.insert(1);
4142/// assert_eq!(map.len(), 3);
4143/// // Nonexistent key (insert)
4144/// map.entry("d").insert(4);
4145///
4146/// // Existing key (or_insert)
4147/// let v = map.entry("b").or_insert(2);
4148/// assert_eq!(std::mem::replace(v, 2), 20);
4149/// // Nonexistent key (or_insert)
4150/// map.entry("e").or_insert(5);
4151///
4152/// // Existing key (or_insert_with)
4153/// let v = map.entry("c").or_insert_with(|| 3);
4154/// assert_eq!(std::mem::replace(v, 3), 30);
4155/// // Nonexistent key (or_insert_with)
4156/// map.entry("f").or_insert_with(|| 6);
4157///
4158/// println!("Our HashMap: {:?}", map);
4159///
4160/// let mut vec: Vec<_> = map.iter().map(|(&k, &v)| (k, v)).collect();
4161/// // The `Iter` iterator produces items in arbitrary order, so the
4162/// // items must be sorted to test them against a sorted array.
4163/// vec.sort_unstable();
4164/// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]);
4165/// ```
4166pub enum Entry<'a, K, V, S, A = Global>
4167where
4168 A: Allocator,
4169{
4170 /// An occupied entry.
4171 ///
4172 /// # Examples
4173 ///
4174 /// ```
4175 /// use hashbrown::hash_map::{Entry, HashMap};
4176 /// let mut map: HashMap<_, _> = [("a", 100), ("b", 200)].into();
4177 ///
4178 /// match map.entry("a") {
4179 /// Entry::Vacant(_) => unreachable!(),
4180 /// Entry::Occupied(_) => { }
4181 /// }
4182 /// ```
4183 Occupied(OccupiedEntry<'a, K, V, S, A>),
4184
4185 /// A vacant entry.
4186 ///
4187 /// # Examples
4188 ///
4189 /// ```
4190 /// use hashbrown::hash_map::{Entry, HashMap};
4191 /// let mut map: HashMap<&str, i32> = HashMap::new();
4192 ///
4193 /// match map.entry("a") {
4194 /// Entry::Occupied(_) => unreachable!(),
4195 /// Entry::Vacant(_) => { }
4196 /// }
4197 /// ```
4198 Vacant(VacantEntry<'a, K, V, S, A>),
4199}
4200
4201impl<K: Debug, V: Debug, S, A: Allocator> Debug for Entry<'_, K, V, S, A> {
4202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4203 match *self {
4204 Entry::Vacant(ref v: &VacantEntry<'_, K, V, S, …>) => f.debug_tuple("Entry").field(v).finish(),
4205 Entry::Occupied(ref o: &OccupiedEntry<'_, K, V, …, …>) => f.debug_tuple("Entry").field(o).finish(),
4206 }
4207 }
4208}
4209
4210/// A view into an occupied entry in a `HashMap`.
4211/// It is part of the [`Entry`] enum.
4212///
4213/// [`Entry`]: enum.Entry.html
4214///
4215/// # Examples
4216///
4217/// ```
4218/// use hashbrown::hash_map::{Entry, HashMap, OccupiedEntry};
4219///
4220/// let mut map = HashMap::new();
4221/// map.extend([("a", 10), ("b", 20), ("c", 30)]);
4222///
4223/// let _entry_o: OccupiedEntry<_, _, _> = map.entry("a").insert(100);
4224/// assert_eq!(map.len(), 3);
4225///
4226/// // Existing key (insert and update)
4227/// match map.entry("a") {
4228/// Entry::Vacant(_) => unreachable!(),
4229/// Entry::Occupied(mut view) => {
4230/// assert_eq!(view.get(), &100);
4231/// let v = view.get_mut();
4232/// *v *= 10;
4233/// assert_eq!(view.insert(1111), 1000);
4234/// }
4235/// }
4236///
4237/// assert_eq!(map[&"a"], 1111);
4238/// assert_eq!(map.len(), 3);
4239///
4240/// // Existing key (take)
4241/// match map.entry("c") {
4242/// Entry::Vacant(_) => unreachable!(),
4243/// Entry::Occupied(view) => {
4244/// assert_eq!(view.remove_entry(), ("c", 30));
4245/// }
4246/// }
4247/// assert_eq!(map.get(&"c"), None);
4248/// assert_eq!(map.len(), 2);
4249/// ```
4250pub struct OccupiedEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
4251 hash: u64,
4252 key: Option<K>,
4253 elem: Bucket<(K, V)>,
4254 table: &'a mut HashMap<K, V, S, A>,
4255}
4256
4257unsafe impl<K, V, S, A> Send for OccupiedEntry<'_, K, V, S, A>
4258where
4259 K: Send,
4260 V: Send,
4261 S: Send,
4262 A: Send + Allocator,
4263{
4264}
4265unsafe impl<K, V, S, A> Sync for OccupiedEntry<'_, K, V, S, A>
4266where
4267 K: Sync,
4268 V: Sync,
4269 S: Sync,
4270 A: Sync + Allocator,
4271{
4272}
4273
4274impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedEntry<'_, K, V, S, A> {
4275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4276 f.debug_struct("OccupiedEntry")
4277 .field("key", self.key())
4278 .field("value", self.get())
4279 .finish()
4280 }
4281}
4282
4283/// A view into a vacant entry in a `HashMap`.
4284/// It is part of the [`Entry`] enum.
4285///
4286/// [`Entry`]: enum.Entry.html
4287///
4288/// # Examples
4289///
4290/// ```
4291/// use hashbrown::hash_map::{Entry, HashMap, VacantEntry};
4292///
4293/// let mut map = HashMap::<&str, i32>::new();
4294///
4295/// let entry_v: VacantEntry<_, _, _> = match map.entry("a") {
4296/// Entry::Vacant(view) => view,
4297/// Entry::Occupied(_) => unreachable!(),
4298/// };
4299/// entry_v.insert(10);
4300/// assert!(map[&"a"] == 10 && map.len() == 1);
4301///
4302/// // Nonexistent key (insert and update)
4303/// match map.entry("b") {
4304/// Entry::Occupied(_) => unreachable!(),
4305/// Entry::Vacant(view) => {
4306/// let value = view.insert(2);
4307/// assert_eq!(*value, 2);
4308/// *value = 20;
4309/// }
4310/// }
4311/// assert!(map[&"b"] == 20 && map.len() == 2);
4312/// ```
4313pub struct VacantEntry<'a, K, V, S = DefaultHashBuilder, A: Allocator = Global> {
4314 hash: u64,
4315 key: K,
4316 table: &'a mut HashMap<K, V, S, A>,
4317}
4318
4319impl<K: Debug, V, S, A: Allocator> Debug for VacantEntry<'_, K, V, S, A> {
4320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4321 f.debug_tuple("VacantEntry").field(self.key()).finish()
4322 }
4323}
4324
4325/// A view into a single entry in a map, which may either be vacant or occupied,
4326/// with any borrowed form of the map's key type.
4327///
4328///
4329/// This `enum` is constructed from the [`entry_ref`] method on [`HashMap`].
4330///
4331/// [`Hash`] and [`Eq`] on the borrowed form of the map's key type *must* match those
4332/// for the key type. It also require that key may be constructed from the borrowed
4333/// form through the [`From`] trait.
4334///
4335/// [`HashMap`]: struct.HashMap.html
4336/// [`entry_ref`]: struct.HashMap.html#method.entry_ref
4337/// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
4338/// [`Hash`]: https://doc.rust-lang.org/std/hash/trait.Hash.html
4339/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
4340///
4341/// # Examples
4342///
4343/// ```
4344/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntryRef};
4345///
4346/// let mut map = HashMap::new();
4347/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
4348/// assert_eq!(map.len(), 3);
4349///
4350/// // Existing key (insert)
4351/// let key = String::from("a");
4352/// let entry: EntryRef<_, _, _, _> = map.entry_ref(&key);
4353/// let _raw_o: OccupiedEntryRef<_, _, _, _> = entry.insert(1);
4354/// assert_eq!(map.len(), 3);
4355/// // Nonexistent key (insert)
4356/// map.entry_ref("d").insert(4);
4357///
4358/// // Existing key (or_insert)
4359/// let v = map.entry_ref("b").or_insert(2);
4360/// assert_eq!(std::mem::replace(v, 2), 20);
4361/// // Nonexistent key (or_insert)
4362/// map.entry_ref("e").or_insert(5);
4363///
4364/// // Existing key (or_insert_with)
4365/// let v = map.entry_ref("c").or_insert_with(|| 3);
4366/// assert_eq!(std::mem::replace(v, 3), 30);
4367/// // Nonexistent key (or_insert_with)
4368/// map.entry_ref("f").or_insert_with(|| 6);
4369///
4370/// println!("Our HashMap: {:?}", map);
4371///
4372/// for (key, value) in ["a", "b", "c", "d", "e", "f"].into_iter().zip(1..=6) {
4373/// assert_eq!(map[key], value)
4374/// }
4375/// assert_eq!(map.len(), 6);
4376/// ```
4377pub enum EntryRef<'a, 'b, K, Q: ?Sized, V, S, A = Global>
4378where
4379 A: Allocator,
4380{
4381 /// An occupied entry.
4382 ///
4383 /// # Examples
4384 ///
4385 /// ```
4386 /// use hashbrown::hash_map::{EntryRef, HashMap};
4387 /// let mut map: HashMap<_, _> = [("a".to_owned(), 100), ("b".into(), 200)].into();
4388 ///
4389 /// match map.entry_ref("a") {
4390 /// EntryRef::Vacant(_) => unreachable!(),
4391 /// EntryRef::Occupied(_) => { }
4392 /// }
4393 /// ```
4394 Occupied(OccupiedEntryRef<'a, 'b, K, Q, V, S, A>),
4395
4396 /// A vacant entry.
4397 ///
4398 /// # Examples
4399 ///
4400 /// ```
4401 /// use hashbrown::hash_map::{EntryRef, HashMap};
4402 /// let mut map: HashMap<String, i32> = HashMap::new();
4403 ///
4404 /// match map.entry_ref("a") {
4405 /// EntryRef::Occupied(_) => unreachable!(),
4406 /// EntryRef::Vacant(_) => { }
4407 /// }
4408 /// ```
4409 Vacant(VacantEntryRef<'a, 'b, K, Q, V, S, A>),
4410}
4411
4412impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator> Debug
4413 for EntryRef<'_, '_, K, Q, V, S, A>
4414{
4415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4416 match *self {
4417 EntryRef::Vacant(ref v: &VacantEntryRef<'_, '_, K, …, …, …, …>) => f.debug_tuple("EntryRef").field(v).finish(),
4418 EntryRef::Occupied(ref o: &OccupiedEntryRef<'_, '_, …, …, …, …, …>) => f.debug_tuple("EntryRef").field(o).finish(),
4419 }
4420 }
4421}
4422
4423enum KeyOrRef<'a, K, Q: ?Sized> {
4424 Borrowed(&'a Q),
4425 Owned(K),
4426}
4427
4428impl<'a, K, Q: ?Sized> KeyOrRef<'a, K, Q> {
4429 fn into_owned(self) -> K
4430 where
4431 K: From<&'a Q>,
4432 {
4433 match self {
4434 Self::Borrowed(borrowed: &Q) => borrowed.into(),
4435 Self::Owned(owned: K) => owned,
4436 }
4437 }
4438}
4439
4440impl<'a, K: Borrow<Q>, Q: ?Sized> AsRef<Q> for KeyOrRef<'a, K, Q> {
4441 fn as_ref(&self) -> &Q {
4442 match self {
4443 Self::Borrowed(borrowed: &&Q) => borrowed,
4444 Self::Owned(owned: &K) => owned.borrow(),
4445 }
4446 }
4447}
4448
4449/// A view into an occupied entry in a `HashMap`.
4450/// It is part of the [`EntryRef`] enum.
4451///
4452/// [`EntryRef`]: enum.EntryRef.html
4453///
4454/// # Examples
4455///
4456/// ```
4457/// use hashbrown::hash_map::{EntryRef, HashMap, OccupiedEntryRef};
4458///
4459/// let mut map = HashMap::new();
4460/// map.extend([("a".to_owned(), 10), ("b".into(), 20), ("c".into(), 30)]);
4461///
4462/// let key = String::from("a");
4463/// let _entry_o: OccupiedEntryRef<_, _, _, _> = map.entry_ref(&key).insert(100);
4464/// assert_eq!(map.len(), 3);
4465///
4466/// // Existing key (insert and update)
4467/// match map.entry_ref("a") {
4468/// EntryRef::Vacant(_) => unreachable!(),
4469/// EntryRef::Occupied(mut view) => {
4470/// assert_eq!(view.get(), &100);
4471/// let v = view.get_mut();
4472/// *v *= 10;
4473/// assert_eq!(view.insert(1111), 1000);
4474/// }
4475/// }
4476///
4477/// assert_eq!(map["a"], 1111);
4478/// assert_eq!(map.len(), 3);
4479///
4480/// // Existing key (take)
4481/// match map.entry_ref("c") {
4482/// EntryRef::Vacant(_) => unreachable!(),
4483/// EntryRef::Occupied(view) => {
4484/// assert_eq!(view.remove_entry(), ("c".to_owned(), 30));
4485/// }
4486/// }
4487/// assert_eq!(map.get("c"), None);
4488/// assert_eq!(map.len(), 2);
4489/// ```
4490pub struct OccupiedEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> {
4491 hash: u64,
4492 key: Option<KeyOrRef<'b, K, Q>>,
4493 elem: Bucket<(K, V)>,
4494 table: &'a mut HashMap<K, V, S, A>,
4495}
4496
4497unsafe impl<'a, 'b, K, Q, V, S, A> Send for OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
4498where
4499 K: Send,
4500 Q: Sync + ?Sized,
4501 V: Send,
4502 S: Send,
4503 A: Send + Allocator,
4504{
4505}
4506unsafe impl<'a, 'b, K, Q, V, S, A> Sync for OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
4507where
4508 K: Sync,
4509 Q: Sync + ?Sized,
4510 V: Sync,
4511 S: Sync,
4512 A: Sync + Allocator,
4513{
4514}
4515
4516impl<K: Borrow<Q>, Q: ?Sized + Debug, V: Debug, S, A: Allocator> Debug
4517 for OccupiedEntryRef<'_, '_, K, Q, V, S, A>
4518{
4519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4520 f.debug_struct("OccupiedEntryRef")
4521 .field("key", &self.key().borrow())
4522 .field("value", &self.get())
4523 .finish()
4524 }
4525}
4526
4527/// A view into a vacant entry in a `HashMap`.
4528/// It is part of the [`EntryRef`] enum.
4529///
4530/// [`EntryRef`]: enum.EntryRef.html
4531///
4532/// # Examples
4533///
4534/// ```
4535/// use hashbrown::hash_map::{EntryRef, HashMap, VacantEntryRef};
4536///
4537/// let mut map = HashMap::<String, i32>::new();
4538///
4539/// let entry_v: VacantEntryRef<_, _, _, _> = match map.entry_ref("a") {
4540/// EntryRef::Vacant(view) => view,
4541/// EntryRef::Occupied(_) => unreachable!(),
4542/// };
4543/// entry_v.insert(10);
4544/// assert!(map["a"] == 10 && map.len() == 1);
4545///
4546/// // Nonexistent key (insert and update)
4547/// match map.entry_ref("b") {
4548/// EntryRef::Occupied(_) => unreachable!(),
4549/// EntryRef::Vacant(view) => {
4550/// let value = view.insert(2);
4551/// assert_eq!(*value, 2);
4552/// *value = 20;
4553/// }
4554/// }
4555/// assert!(map["b"] == 20 && map.len() == 2);
4556/// ```
4557pub struct VacantEntryRef<'a, 'b, K, Q: ?Sized, V, S, A: Allocator = Global> {
4558 hash: u64,
4559 key: KeyOrRef<'b, K, Q>,
4560 table: &'a mut HashMap<K, V, S, A>,
4561}
4562
4563impl<K: Borrow<Q>, Q: ?Sized + Debug, V, S, A: Allocator> Debug
4564 for VacantEntryRef<'_, '_, K, Q, V, S, A>
4565{
4566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4567 f.debug_tuple("VacantEntryRef").field(&self.key()).finish()
4568 }
4569}
4570
4571/// The error returned by [`try_insert`](HashMap::try_insert) when the key already exists.
4572///
4573/// Contains the occupied entry, and the value that was not inserted.
4574///
4575/// # Examples
4576///
4577/// ```
4578/// use hashbrown::hash_map::{HashMap, OccupiedError};
4579///
4580/// let mut map: HashMap<_, _> = [("a", 10), ("b", 20)].into();
4581///
4582/// // try_insert method returns mutable reference to the value if keys are vacant,
4583/// // but if the map did have key present, nothing is updated, and the provided
4584/// // value is returned inside `Err(_)` variant
4585/// match map.try_insert("a", 100) {
4586/// Err(OccupiedError { mut entry, value }) => {
4587/// assert_eq!(entry.key(), &"a");
4588/// assert_eq!(value, 100);
4589/// assert_eq!(entry.insert(100), 10)
4590/// }
4591/// _ => unreachable!(),
4592/// }
4593/// assert_eq!(map[&"a"], 100);
4594/// ```
4595pub struct OccupiedError<'a, K, V, S, A: Allocator = Global> {
4596 /// The entry in the map that was already occupied.
4597 pub entry: OccupiedEntry<'a, K, V, S, A>,
4598 /// The value which was not inserted, because the entry was already occupied.
4599 pub value: V,
4600}
4601
4602impl<K: Debug, V: Debug, S, A: Allocator> Debug for OccupiedError<'_, K, V, S, A> {
4603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4604 f.debug_struct("OccupiedError")
4605 .field("key", self.entry.key())
4606 .field("old_value", self.entry.get())
4607 .field("new_value", &self.value)
4608 .finish()
4609 }
4610}
4611
4612impl<'a, K: Debug, V: Debug, S, A: Allocator> fmt::Display for OccupiedError<'a, K, V, S, A> {
4613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4614 write!(
4615 f,
4616 "failed to insert {:?}, key {:?} already exists with value {:?}",
4617 self.value,
4618 self.entry.key(),
4619 self.entry.get(),
4620 )
4621 }
4622}
4623
4624impl<'a, K, V, S, A: Allocator> IntoIterator for &'a HashMap<K, V, S, A> {
4625 type Item = (&'a K, &'a V);
4626 type IntoIter = Iter<'a, K, V>;
4627
4628 /// Creates an iterator over the entries of a `HashMap` in arbitrary order.
4629 /// The iterator element type is `(&'a K, &'a V)`.
4630 ///
4631 /// Return the same `Iter` struct as by the [`iter`] method on [`HashMap`].
4632 ///
4633 /// [`iter`]: struct.HashMap.html#method.iter
4634 /// [`HashMap`]: struct.HashMap.html
4635 ///
4636 /// # Examples
4637 ///
4638 /// ```
4639 /// use hashbrown::HashMap;
4640 /// let map_one: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].into();
4641 /// let mut map_two = HashMap::new();
4642 ///
4643 /// for (key, value) in &map_one {
4644 /// println!("Key: {}, Value: {}", key, value);
4645 /// map_two.insert_unique_unchecked(*key, *value);
4646 /// }
4647 ///
4648 /// assert_eq!(map_one, map_two);
4649 /// ```
4650 #[cfg_attr(feature = "inline-more", inline)]
4651 fn into_iter(self) -> Iter<'a, K, V> {
4652 self.iter()
4653 }
4654}
4655
4656impl<'a, K, V, S, A: Allocator> IntoIterator for &'a mut HashMap<K, V, S, A> {
4657 type Item = (&'a K, &'a mut V);
4658 type IntoIter = IterMut<'a, K, V>;
4659
4660 /// Creates an iterator over the entries of a `HashMap` in arbitrary order
4661 /// with mutable references to the values. The iterator element type is
4662 /// `(&'a K, &'a mut V)`.
4663 ///
4664 /// Return the same `IterMut` struct as by the [`iter_mut`] method on
4665 /// [`HashMap`].
4666 ///
4667 /// [`iter_mut`]: struct.HashMap.html#method.iter_mut
4668 /// [`HashMap`]: struct.HashMap.html
4669 ///
4670 /// # Examples
4671 ///
4672 /// ```
4673 /// use hashbrown::HashMap;
4674 /// let mut map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
4675 ///
4676 /// for (key, value) in &mut map {
4677 /// println!("Key: {}, Value: {}", key, value);
4678 /// *value *= 2;
4679 /// }
4680 ///
4681 /// let mut vec = map.iter().collect::<Vec<_>>();
4682 /// // The `Iter` iterator produces items in arbitrary order, so the
4683 /// // items must be sorted to test them against a sorted array.
4684 /// vec.sort_unstable();
4685 /// assert_eq!(vec, [(&"a", &2), (&"b", &4), (&"c", &6)]);
4686 /// ```
4687 #[cfg_attr(feature = "inline-more", inline)]
4688 fn into_iter(self) -> IterMut<'a, K, V> {
4689 self.iter_mut()
4690 }
4691}
4692
4693impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A> {
4694 type Item = (K, V);
4695 type IntoIter = IntoIter<K, V, A>;
4696
4697 /// Creates a consuming iterator, that is, one that moves each key-value
4698 /// pair out of the map in arbitrary order. The map cannot be used after
4699 /// calling this.
4700 ///
4701 /// # Examples
4702 ///
4703 /// ```
4704 /// use hashbrown::HashMap;
4705 ///
4706 /// let map: HashMap<_, _> = [("a", 1), ("b", 2), ("c", 3)].into();
4707 ///
4708 /// // Not possible with .iter()
4709 /// let mut vec: Vec<(&str, i32)> = map.into_iter().collect();
4710 /// // The `IntoIter` iterator produces items in arbitrary order, so
4711 /// // the items must be sorted to test them against a sorted array.
4712 /// vec.sort_unstable();
4713 /// assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
4714 /// ```
4715 #[cfg_attr(feature = "inline-more", inline)]
4716 fn into_iter(self) -> IntoIter<K, V, A> {
4717 IntoIter {
4718 inner: self.table.into_iter(),
4719 }
4720 }
4721}
4722
4723impl<'a, K, V> Iterator for Iter<'a, K, V> {
4724 type Item = (&'a K, &'a V);
4725
4726 #[cfg_attr(feature = "inline-more", inline)]
4727 fn next(&mut self) -> Option<(&'a K, &'a V)> {
4728 // Avoid `Option::map` because it bloats LLVM IR.
4729 match self.inner.next() {
4730 Some(x) => unsafe {
4731 let r = x.as_ref();
4732 Some((&r.0, &r.1))
4733 },
4734 None => None,
4735 }
4736 }
4737 #[cfg_attr(feature = "inline-more", inline)]
4738 fn size_hint(&self) -> (usize, Option<usize>) {
4739 self.inner.size_hint()
4740 }
4741 #[cfg_attr(feature = "inline-more", inline)]
4742 fn fold<B, F>(self, init: B, mut f: F) -> B
4743 where
4744 Self: Sized,
4745 F: FnMut(B, Self::Item) -> B,
4746 {
4747 self.inner.fold(init, |acc, x| unsafe {
4748 let (k, v) = x.as_ref();
4749 f(acc, (k, v))
4750 })
4751 }
4752}
4753impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
4754 #[cfg_attr(feature = "inline-more", inline)]
4755 fn len(&self) -> usize {
4756 self.inner.len()
4757 }
4758}
4759
4760impl<K, V> FusedIterator for Iter<'_, K, V> {}
4761
4762impl<'a, K, V> Iterator for IterMut<'a, K, V> {
4763 type Item = (&'a K, &'a mut V);
4764
4765 #[cfg_attr(feature = "inline-more", inline)]
4766 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
4767 // Avoid `Option::map` because it bloats LLVM IR.
4768 match self.inner.next() {
4769 Some(x) => unsafe {
4770 let r = x.as_mut();
4771 Some((&r.0, &mut r.1))
4772 },
4773 None => None,
4774 }
4775 }
4776 #[cfg_attr(feature = "inline-more", inline)]
4777 fn size_hint(&self) -> (usize, Option<usize>) {
4778 self.inner.size_hint()
4779 }
4780 #[cfg_attr(feature = "inline-more", inline)]
4781 fn fold<B, F>(self, init: B, mut f: F) -> B
4782 where
4783 Self: Sized,
4784 F: FnMut(B, Self::Item) -> B,
4785 {
4786 self.inner.fold(init, |acc, x| unsafe {
4787 let (k, v) = x.as_mut();
4788 f(acc, (k, v))
4789 })
4790 }
4791}
4792impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
4793 #[cfg_attr(feature = "inline-more", inline)]
4794 fn len(&self) -> usize {
4795 self.inner.len()
4796 }
4797}
4798impl<K, V> FusedIterator for IterMut<'_, K, V> {}
4799
4800impl<K, V> fmt::Debug for IterMut<'_, K, V>
4801where
4802 K: fmt::Debug,
4803 V: fmt::Debug,
4804{
4805 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4806 f.debug_list().entries(self.iter()).finish()
4807 }
4808}
4809
4810impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
4811 type Item = (K, V);
4812
4813 #[cfg_attr(feature = "inline-more", inline)]
4814 fn next(&mut self) -> Option<(K, V)> {
4815 self.inner.next()
4816 }
4817 #[cfg_attr(feature = "inline-more", inline)]
4818 fn size_hint(&self) -> (usize, Option<usize>) {
4819 self.inner.size_hint()
4820 }
4821 #[cfg_attr(feature = "inline-more", inline)]
4822 fn fold<B, F>(self, init: B, f: F) -> B
4823 where
4824 Self: Sized,
4825 F: FnMut(B, Self::Item) -> B,
4826 {
4827 self.inner.fold(init, f)
4828 }
4829}
4830impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
4831 #[cfg_attr(feature = "inline-more", inline)]
4832 fn len(&self) -> usize {
4833 self.inner.len()
4834 }
4835}
4836impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
4837
4838impl<K: Debug, V: Debug, A: Allocator> fmt::Debug for IntoIter<K, V, A> {
4839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4840 f.debug_list().entries(self.iter()).finish()
4841 }
4842}
4843
4844impl<'a, K, V> Iterator for Keys<'a, K, V> {
4845 type Item = &'a K;
4846
4847 #[cfg_attr(feature = "inline-more", inline)]
4848 fn next(&mut self) -> Option<&'a K> {
4849 // Avoid `Option::map` because it bloats LLVM IR.
4850 match self.inner.next() {
4851 Some((k, _)) => Some(k),
4852 None => None,
4853 }
4854 }
4855 #[cfg_attr(feature = "inline-more", inline)]
4856 fn size_hint(&self) -> (usize, Option<usize>) {
4857 self.inner.size_hint()
4858 }
4859 #[cfg_attr(feature = "inline-more", inline)]
4860 fn fold<B, F>(self, init: B, mut f: F) -> B
4861 where
4862 Self: Sized,
4863 F: FnMut(B, Self::Item) -> B,
4864 {
4865 self.inner.fold(init, |acc, (k, _)| f(acc, k))
4866 }
4867}
4868impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
4869 #[cfg_attr(feature = "inline-more", inline)]
4870 fn len(&self) -> usize {
4871 self.inner.len()
4872 }
4873}
4874impl<K, V> FusedIterator for Keys<'_, K, V> {}
4875
4876impl<'a, K, V> Iterator for Values<'a, K, V> {
4877 type Item = &'a V;
4878
4879 #[cfg_attr(feature = "inline-more", inline)]
4880 fn next(&mut self) -> Option<&'a V> {
4881 // Avoid `Option::map` because it bloats LLVM IR.
4882 match self.inner.next() {
4883 Some((_, v)) => Some(v),
4884 None => None,
4885 }
4886 }
4887 #[cfg_attr(feature = "inline-more", inline)]
4888 fn size_hint(&self) -> (usize, Option<usize>) {
4889 self.inner.size_hint()
4890 }
4891 #[cfg_attr(feature = "inline-more", inline)]
4892 fn fold<B, F>(self, init: B, mut f: F) -> B
4893 where
4894 Self: Sized,
4895 F: FnMut(B, Self::Item) -> B,
4896 {
4897 self.inner.fold(init, |acc, (_, v)| f(acc, v))
4898 }
4899}
4900impl<K, V> ExactSizeIterator for Values<'_, K, V> {
4901 #[cfg_attr(feature = "inline-more", inline)]
4902 fn len(&self) -> usize {
4903 self.inner.len()
4904 }
4905}
4906impl<K, V> FusedIterator for Values<'_, K, V> {}
4907
4908impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
4909 type Item = &'a mut V;
4910
4911 #[cfg_attr(feature = "inline-more", inline)]
4912 fn next(&mut self) -> Option<&'a mut V> {
4913 // Avoid `Option::map` because it bloats LLVM IR.
4914 match self.inner.next() {
4915 Some((_, v)) => Some(v),
4916 None => None,
4917 }
4918 }
4919 #[cfg_attr(feature = "inline-more", inline)]
4920 fn size_hint(&self) -> (usize, Option<usize>) {
4921 self.inner.size_hint()
4922 }
4923 #[cfg_attr(feature = "inline-more", inline)]
4924 fn fold<B, F>(self, init: B, mut f: F) -> B
4925 where
4926 Self: Sized,
4927 F: FnMut(B, Self::Item) -> B,
4928 {
4929 self.inner.fold(init, |acc, (_, v)| f(acc, v))
4930 }
4931}
4932impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
4933 #[cfg_attr(feature = "inline-more", inline)]
4934 fn len(&self) -> usize {
4935 self.inner.len()
4936 }
4937}
4938impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
4939
4940impl<K, V: Debug> fmt::Debug for ValuesMut<'_, K, V> {
4941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4942 f.debug_list()
4943 .entries(self.inner.iter().map(|(_, val)| val))
4944 .finish()
4945 }
4946}
4947
4948impl<'a, K, V, A: Allocator> Iterator for Drain<'a, K, V, A> {
4949 type Item = (K, V);
4950
4951 #[cfg_attr(feature = "inline-more", inline)]
4952 fn next(&mut self) -> Option<(K, V)> {
4953 self.inner.next()
4954 }
4955 #[cfg_attr(feature = "inline-more", inline)]
4956 fn size_hint(&self) -> (usize, Option<usize>) {
4957 self.inner.size_hint()
4958 }
4959 #[cfg_attr(feature = "inline-more", inline)]
4960 fn fold<B, F>(self, init: B, f: F) -> B
4961 where
4962 Self: Sized,
4963 F: FnMut(B, Self::Item) -> B,
4964 {
4965 self.inner.fold(init, f)
4966 }
4967}
4968impl<K, V, A: Allocator> ExactSizeIterator for Drain<'_, K, V, A> {
4969 #[cfg_attr(feature = "inline-more", inline)]
4970 fn len(&self) -> usize {
4971 self.inner.len()
4972 }
4973}
4974impl<K, V, A: Allocator> FusedIterator for Drain<'_, K, V, A> {}
4975
4976impl<K, V, A> fmt::Debug for Drain<'_, K, V, A>
4977where
4978 K: fmt::Debug,
4979 V: fmt::Debug,
4980 A: Allocator,
4981{
4982 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4983 f.debug_list().entries(self.iter()).finish()
4984 }
4985}
4986
4987impl<'a, K, V, S, A: Allocator> Entry<'a, K, V, S, A> {
4988 /// Sets the value of the entry, and returns an OccupiedEntry.
4989 ///
4990 /// # Examples
4991 ///
4992 /// ```
4993 /// use hashbrown::HashMap;
4994 ///
4995 /// let mut map: HashMap<&str, u32> = HashMap::new();
4996 /// let entry = map.entry("horseyland").insert(37);
4997 ///
4998 /// assert_eq!(entry.key(), &"horseyland");
4999 /// ```
5000 #[cfg_attr(feature = "inline-more", inline)]
5001 pub fn insert(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
5002 where
5003 K: Hash,
5004 S: BuildHasher,
5005 {
5006 match self {
5007 Entry::Occupied(mut entry) => {
5008 entry.insert(value);
5009 entry
5010 }
5011 Entry::Vacant(entry) => entry.insert_entry(value),
5012 }
5013 }
5014
5015 /// Ensures a value is in the entry by inserting the default if empty, and returns
5016 /// a mutable reference to the value in the entry.
5017 ///
5018 /// # Examples
5019 ///
5020 /// ```
5021 /// use hashbrown::HashMap;
5022 ///
5023 /// let mut map: HashMap<&str, u32> = HashMap::new();
5024 ///
5025 /// // nonexistent key
5026 /// map.entry("poneyland").or_insert(3);
5027 /// assert_eq!(map["poneyland"], 3);
5028 ///
5029 /// // existing key
5030 /// *map.entry("poneyland").or_insert(10) *= 2;
5031 /// assert_eq!(map["poneyland"], 6);
5032 /// ```
5033 #[cfg_attr(feature = "inline-more", inline)]
5034 pub fn or_insert(self, default: V) -> &'a mut V
5035 where
5036 K: Hash,
5037 S: BuildHasher,
5038 {
5039 match self {
5040 Entry::Occupied(entry) => entry.into_mut(),
5041 Entry::Vacant(entry) => entry.insert(default),
5042 }
5043 }
5044
5045 /// Ensures a value is in the entry by inserting the result of the default function if empty,
5046 /// and returns a mutable reference to the value in the entry.
5047 ///
5048 /// # Examples
5049 ///
5050 /// ```
5051 /// use hashbrown::HashMap;
5052 ///
5053 /// let mut map: HashMap<&str, u32> = HashMap::new();
5054 ///
5055 /// // nonexistent key
5056 /// map.entry("poneyland").or_insert_with(|| 3);
5057 /// assert_eq!(map["poneyland"], 3);
5058 ///
5059 /// // existing key
5060 /// *map.entry("poneyland").or_insert_with(|| 10) *= 2;
5061 /// assert_eq!(map["poneyland"], 6);
5062 /// ```
5063 #[cfg_attr(feature = "inline-more", inline)]
5064 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
5065 where
5066 K: Hash,
5067 S: BuildHasher,
5068 {
5069 match self {
5070 Entry::Occupied(entry) => entry.into_mut(),
5071 Entry::Vacant(entry) => entry.insert(default()),
5072 }
5073 }
5074
5075 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
5076 /// This method allows for generating key-derived values for insertion by providing the default
5077 /// function a reference to the key that was moved during the `.entry(key)` method call.
5078 ///
5079 /// The reference to the moved key is provided so that cloning or copying the key is
5080 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
5081 ///
5082 /// # Examples
5083 ///
5084 /// ```
5085 /// use hashbrown::HashMap;
5086 ///
5087 /// let mut map: HashMap<&str, usize> = HashMap::new();
5088 ///
5089 /// // nonexistent key
5090 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
5091 /// assert_eq!(map["poneyland"], 9);
5092 ///
5093 /// // existing key
5094 /// *map.entry("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
5095 /// assert_eq!(map["poneyland"], 18);
5096 /// ```
5097 #[cfg_attr(feature = "inline-more", inline)]
5098 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
5099 where
5100 K: Hash,
5101 S: BuildHasher,
5102 {
5103 match self {
5104 Entry::Occupied(entry) => entry.into_mut(),
5105 Entry::Vacant(entry) => {
5106 let value = default(entry.key());
5107 entry.insert(value)
5108 }
5109 }
5110 }
5111
5112 /// Returns a reference to this entry's key.
5113 ///
5114 /// # Examples
5115 ///
5116 /// ```
5117 /// use hashbrown::HashMap;
5118 ///
5119 /// let mut map: HashMap<&str, u32> = HashMap::new();
5120 /// map.entry("poneyland").or_insert(3);
5121 /// // existing key
5122 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
5123 /// // nonexistent key
5124 /// assert_eq!(map.entry("horseland").key(), &"horseland");
5125 /// ```
5126 #[cfg_attr(feature = "inline-more", inline)]
5127 pub fn key(&self) -> &K {
5128 match *self {
5129 Entry::Occupied(ref entry) => entry.key(),
5130 Entry::Vacant(ref entry) => entry.key(),
5131 }
5132 }
5133
5134 /// Provides in-place mutable access to an occupied entry before any
5135 /// potential inserts into the map.
5136 ///
5137 /// # Examples
5138 ///
5139 /// ```
5140 /// use hashbrown::HashMap;
5141 ///
5142 /// let mut map: HashMap<&str, u32> = HashMap::new();
5143 ///
5144 /// map.entry("poneyland")
5145 /// .and_modify(|e| { *e += 1 })
5146 /// .or_insert(42);
5147 /// assert_eq!(map["poneyland"], 42);
5148 ///
5149 /// map.entry("poneyland")
5150 /// .and_modify(|e| { *e += 1 })
5151 /// .or_insert(42);
5152 /// assert_eq!(map["poneyland"], 43);
5153 /// ```
5154 #[cfg_attr(feature = "inline-more", inline)]
5155 pub fn and_modify<F>(self, f: F) -> Self
5156 where
5157 F: FnOnce(&mut V),
5158 {
5159 match self {
5160 Entry::Occupied(mut entry) => {
5161 f(entry.get_mut());
5162 Entry::Occupied(entry)
5163 }
5164 Entry::Vacant(entry) => Entry::Vacant(entry),
5165 }
5166 }
5167
5168 /// Provides shared access to the key and owned access to the value of
5169 /// an occupied entry and allows to replace or remove it based on the
5170 /// value of the returned option.
5171 ///
5172 /// # Examples
5173 ///
5174 /// ```
5175 /// use hashbrown::HashMap;
5176 /// use hashbrown::hash_map::Entry;
5177 ///
5178 /// let mut map: HashMap<&str, u32> = HashMap::new();
5179 ///
5180 /// let entry = map
5181 /// .entry("poneyland")
5182 /// .and_replace_entry_with(|_k, _v| panic!());
5183 ///
5184 /// match entry {
5185 /// Entry::Vacant(e) => {
5186 /// assert_eq!(e.key(), &"poneyland");
5187 /// }
5188 /// Entry::Occupied(_) => panic!(),
5189 /// }
5190 ///
5191 /// map.insert("poneyland", 42);
5192 ///
5193 /// let entry = map
5194 /// .entry("poneyland")
5195 /// .and_replace_entry_with(|k, v| {
5196 /// assert_eq!(k, &"poneyland");
5197 /// assert_eq!(v, 42);
5198 /// Some(v + 1)
5199 /// });
5200 ///
5201 /// match entry {
5202 /// Entry::Occupied(e) => {
5203 /// assert_eq!(e.key(), &"poneyland");
5204 /// assert_eq!(e.get(), &43);
5205 /// }
5206 /// Entry::Vacant(_) => panic!(),
5207 /// }
5208 ///
5209 /// assert_eq!(map["poneyland"], 43);
5210 ///
5211 /// let entry = map
5212 /// .entry("poneyland")
5213 /// .and_replace_entry_with(|_k, _v| None);
5214 ///
5215 /// match entry {
5216 /// Entry::Vacant(e) => assert_eq!(e.key(), &"poneyland"),
5217 /// Entry::Occupied(_) => panic!(),
5218 /// }
5219 ///
5220 /// assert!(!map.contains_key("poneyland"));
5221 /// ```
5222 #[cfg_attr(feature = "inline-more", inline)]
5223 pub fn and_replace_entry_with<F>(self, f: F) -> Self
5224 where
5225 F: FnOnce(&K, V) -> Option<V>,
5226 {
5227 match self {
5228 Entry::Occupied(entry) => entry.replace_entry_with(f),
5229 Entry::Vacant(_) => self,
5230 }
5231 }
5232}
5233
5234impl<'a, K, V: Default, S, A: Allocator> Entry<'a, K, V, S, A> {
5235 /// Ensures a value is in the entry by inserting the default value if empty,
5236 /// and returns a mutable reference to the value in the entry.
5237 ///
5238 /// # Examples
5239 ///
5240 /// ```
5241 /// use hashbrown::HashMap;
5242 ///
5243 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
5244 ///
5245 /// // nonexistent key
5246 /// map.entry("poneyland").or_default();
5247 /// assert_eq!(map["poneyland"], None);
5248 ///
5249 /// map.insert("horseland", Some(3));
5250 ///
5251 /// // existing key
5252 /// assert_eq!(map.entry("horseland").or_default(), &mut Some(3));
5253 /// ```
5254 #[cfg_attr(feature = "inline-more", inline)]
5255 pub fn or_default(self) -> &'a mut V
5256 where
5257 K: Hash,
5258 S: BuildHasher,
5259 {
5260 match self {
5261 Entry::Occupied(entry) => entry.into_mut(),
5262 Entry::Vacant(entry) => entry.insert(Default::default()),
5263 }
5264 }
5265}
5266
5267impl<'a, K, V, S, A: Allocator> OccupiedEntry<'a, K, V, S, A> {
5268 /// Gets a reference to the key in the entry.
5269 ///
5270 /// # Examples
5271 ///
5272 /// ```
5273 /// use hashbrown::hash_map::{Entry, HashMap};
5274 ///
5275 /// let mut map: HashMap<&str, u32> = HashMap::new();
5276 /// map.entry("poneyland").or_insert(12);
5277 ///
5278 /// match map.entry("poneyland") {
5279 /// Entry::Vacant(_) => panic!(),
5280 /// Entry::Occupied(entry) => assert_eq!(entry.key(), &"poneyland"),
5281 /// }
5282 /// ```
5283 #[cfg_attr(feature = "inline-more", inline)]
5284 pub fn key(&self) -> &K {
5285 unsafe { &self.elem.as_ref().0 }
5286 }
5287
5288 /// Take the ownership of the key and value from the map.
5289 /// Keeps the allocated memory for reuse.
5290 ///
5291 /// # Examples
5292 ///
5293 /// ```
5294 /// use hashbrown::HashMap;
5295 /// use hashbrown::hash_map::Entry;
5296 ///
5297 /// let mut map: HashMap<&str, u32> = HashMap::new();
5298 /// // The map is empty
5299 /// assert!(map.is_empty() && map.capacity() == 0);
5300 ///
5301 /// map.entry("poneyland").or_insert(12);
5302 ///
5303 /// if let Entry::Occupied(o) = map.entry("poneyland") {
5304 /// // We delete the entry from the map.
5305 /// assert_eq!(o.remove_entry(), ("poneyland", 12));
5306 /// }
5307 ///
5308 /// assert_eq!(map.contains_key("poneyland"), false);
5309 /// // Now map hold none elements
5310 /// assert!(map.is_empty());
5311 /// ```
5312 #[cfg_attr(feature = "inline-more", inline)]
5313 pub fn remove_entry(self) -> (K, V) {
5314 unsafe { self.table.table.remove(self.elem).0 }
5315 }
5316
5317 /// Gets a reference to the value in the entry.
5318 ///
5319 /// # Examples
5320 ///
5321 /// ```
5322 /// use hashbrown::HashMap;
5323 /// use hashbrown::hash_map::Entry;
5324 ///
5325 /// let mut map: HashMap<&str, u32> = HashMap::new();
5326 /// map.entry("poneyland").or_insert(12);
5327 ///
5328 /// match map.entry("poneyland") {
5329 /// Entry::Vacant(_) => panic!(),
5330 /// Entry::Occupied(entry) => assert_eq!(entry.get(), &12),
5331 /// }
5332 /// ```
5333 #[cfg_attr(feature = "inline-more", inline)]
5334 pub fn get(&self) -> &V {
5335 unsafe { &self.elem.as_ref().1 }
5336 }
5337
5338 /// Gets a mutable reference to the value in the entry.
5339 ///
5340 /// If you need a reference to the `OccupiedEntry` which may outlive the
5341 /// destruction of the `Entry` value, see [`into_mut`].
5342 ///
5343 /// [`into_mut`]: #method.into_mut
5344 ///
5345 /// # Examples
5346 ///
5347 /// ```
5348 /// use hashbrown::HashMap;
5349 /// use hashbrown::hash_map::Entry;
5350 ///
5351 /// let mut map: HashMap<&str, u32> = HashMap::new();
5352 /// map.entry("poneyland").or_insert(12);
5353 ///
5354 /// assert_eq!(map["poneyland"], 12);
5355 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
5356 /// *o.get_mut() += 10;
5357 /// assert_eq!(*o.get(), 22);
5358 ///
5359 /// // We can use the same Entry multiple times.
5360 /// *o.get_mut() += 2;
5361 /// }
5362 ///
5363 /// assert_eq!(map["poneyland"], 24);
5364 /// ```
5365 #[cfg_attr(feature = "inline-more", inline)]
5366 pub fn get_mut(&mut self) -> &mut V {
5367 unsafe { &mut self.elem.as_mut().1 }
5368 }
5369
5370 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
5371 /// with a lifetime bound to the map itself.
5372 ///
5373 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
5374 ///
5375 /// [`get_mut`]: #method.get_mut
5376 ///
5377 /// # Examples
5378 ///
5379 /// ```
5380 /// use hashbrown::hash_map::{Entry, HashMap};
5381 ///
5382 /// let mut map: HashMap<&str, u32> = HashMap::new();
5383 /// map.entry("poneyland").or_insert(12);
5384 ///
5385 /// assert_eq!(map["poneyland"], 12);
5386 ///
5387 /// let value: &mut u32;
5388 /// match map.entry("poneyland") {
5389 /// Entry::Occupied(entry) => value = entry.into_mut(),
5390 /// Entry::Vacant(_) => panic!(),
5391 /// }
5392 /// *value += 10;
5393 ///
5394 /// assert_eq!(map["poneyland"], 22);
5395 /// ```
5396 #[cfg_attr(feature = "inline-more", inline)]
5397 pub fn into_mut(self) -> &'a mut V {
5398 unsafe { &mut self.elem.as_mut().1 }
5399 }
5400
5401 /// Sets the value of the entry, and returns the entry's old value.
5402 ///
5403 /// # Examples
5404 ///
5405 /// ```
5406 /// use hashbrown::HashMap;
5407 /// use hashbrown::hash_map::Entry;
5408 ///
5409 /// let mut map: HashMap<&str, u32> = HashMap::new();
5410 /// map.entry("poneyland").or_insert(12);
5411 ///
5412 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
5413 /// assert_eq!(o.insert(15), 12);
5414 /// }
5415 ///
5416 /// assert_eq!(map["poneyland"], 15);
5417 /// ```
5418 #[cfg_attr(feature = "inline-more", inline)]
5419 pub fn insert(&mut self, value: V) -> V {
5420 mem::replace(self.get_mut(), value)
5421 }
5422
5423 /// Takes the value out of the entry, and returns it.
5424 /// Keeps the allocated memory for reuse.
5425 ///
5426 /// # Examples
5427 ///
5428 /// ```
5429 /// use hashbrown::HashMap;
5430 /// use hashbrown::hash_map::Entry;
5431 ///
5432 /// let mut map: HashMap<&str, u32> = HashMap::new();
5433 /// // The map is empty
5434 /// assert!(map.is_empty() && map.capacity() == 0);
5435 ///
5436 /// map.entry("poneyland").or_insert(12);
5437 ///
5438 /// if let Entry::Occupied(o) = map.entry("poneyland") {
5439 /// assert_eq!(o.remove(), 12);
5440 /// }
5441 ///
5442 /// assert_eq!(map.contains_key("poneyland"), false);
5443 /// // Now map hold none elements
5444 /// assert!(map.is_empty());
5445 /// ```
5446 #[cfg_attr(feature = "inline-more", inline)]
5447 pub fn remove(self) -> V {
5448 self.remove_entry().1
5449 }
5450
5451 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
5452 /// the key used to create this entry.
5453 ///
5454 /// # Panics
5455 ///
5456 /// Will panic if this OccupiedEntry was created through [`Entry::insert`].
5457 ///
5458 /// # Examples
5459 ///
5460 /// ```
5461 /// use hashbrown::hash_map::{Entry, HashMap};
5462 /// use std::rc::Rc;
5463 ///
5464 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
5465 /// let key_one = Rc::new("Stringthing".to_string());
5466 /// let key_two = Rc::new("Stringthing".to_string());
5467 ///
5468 /// map.insert(key_one.clone(), 15);
5469 /// assert!(Rc::strong_count(&key_one) == 2 && Rc::strong_count(&key_two) == 1);
5470 ///
5471 /// match map.entry(key_two.clone()) {
5472 /// Entry::Occupied(entry) => {
5473 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
5474 /// assert!(Rc::ptr_eq(&key_one, &old_key) && old_value == 15);
5475 /// }
5476 /// Entry::Vacant(_) => panic!(),
5477 /// }
5478 ///
5479 /// assert!(Rc::strong_count(&key_one) == 1 && Rc::strong_count(&key_two) == 2);
5480 /// assert_eq!(map[&"Stringthing".to_owned()], 16);
5481 /// ```
5482 #[cfg_attr(feature = "inline-more", inline)]
5483 pub fn replace_entry(self, value: V) -> (K, V) {
5484 let entry = unsafe { self.elem.as_mut() };
5485
5486 let old_key = mem::replace(&mut entry.0, self.key.unwrap());
5487 let old_value = mem::replace(&mut entry.1, value);
5488
5489 (old_key, old_value)
5490 }
5491
5492 /// Replaces the key in the hash map with the key used to create this entry.
5493 ///
5494 /// # Panics
5495 ///
5496 /// Will panic if this OccupiedEntry was created through [`Entry::insert`].
5497 ///
5498 /// # Examples
5499 ///
5500 /// ```
5501 /// use hashbrown::hash_map::{Entry, HashMap};
5502 /// use std::rc::Rc;
5503 ///
5504 /// let mut map: HashMap<Rc<String>, usize> = HashMap::with_capacity(6);
5505 /// let mut keys_one: Vec<Rc<String>> = Vec::with_capacity(6);
5506 /// let mut keys_two: Vec<Rc<String>> = Vec::with_capacity(6);
5507 ///
5508 /// for (value, key) in ["a", "b", "c", "d", "e", "f"].into_iter().enumerate() {
5509 /// let rc_key = Rc::new(key.to_owned());
5510 /// keys_one.push(rc_key.clone());
5511 /// map.insert(rc_key.clone(), value);
5512 /// keys_two.push(Rc::new(key.to_owned()));
5513 /// }
5514 ///
5515 /// assert!(
5516 /// keys_one.iter().all(|key| Rc::strong_count(key) == 2)
5517 /// && keys_two.iter().all(|key| Rc::strong_count(key) == 1)
5518 /// );
5519 ///
5520 /// reclaim_memory(&mut map, &keys_two);
5521 ///
5522 /// assert!(
5523 /// keys_one.iter().all(|key| Rc::strong_count(key) == 1)
5524 /// && keys_two.iter().all(|key| Rc::strong_count(key) == 2)
5525 /// );
5526 ///
5527 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, usize>, keys: &[Rc<String>]) {
5528 /// for key in keys {
5529 /// if let Entry::Occupied(entry) = map.entry(key.clone()) {
5530 /// // Replaces the entry's key with our version of it in `keys`.
5531 /// entry.replace_key();
5532 /// }
5533 /// }
5534 /// }
5535 /// ```
5536 #[cfg_attr(feature = "inline-more", inline)]
5537 pub fn replace_key(self) -> K {
5538 let entry = unsafe { self.elem.as_mut() };
5539 mem::replace(&mut entry.0, self.key.unwrap())
5540 }
5541
5542 /// Provides shared access to the key and owned access to the value of
5543 /// the entry and allows to replace or remove it based on the
5544 /// value of the returned option.
5545 ///
5546 /// # Examples
5547 ///
5548 /// ```
5549 /// use hashbrown::HashMap;
5550 /// use hashbrown::hash_map::Entry;
5551 ///
5552 /// let mut map: HashMap<&str, u32> = HashMap::new();
5553 /// map.insert("poneyland", 42);
5554 ///
5555 /// let entry = match map.entry("poneyland") {
5556 /// Entry::Occupied(e) => {
5557 /// e.replace_entry_with(|k, v| {
5558 /// assert_eq!(k, &"poneyland");
5559 /// assert_eq!(v, 42);
5560 /// Some(v + 1)
5561 /// })
5562 /// }
5563 /// Entry::Vacant(_) => panic!(),
5564 /// };
5565 ///
5566 /// match entry {
5567 /// Entry::Occupied(e) => {
5568 /// assert_eq!(e.key(), &"poneyland");
5569 /// assert_eq!(e.get(), &43);
5570 /// }
5571 /// Entry::Vacant(_) => panic!(),
5572 /// }
5573 ///
5574 /// assert_eq!(map["poneyland"], 43);
5575 ///
5576 /// let entry = match map.entry("poneyland") {
5577 /// Entry::Occupied(e) => e.replace_entry_with(|_k, _v| None),
5578 /// Entry::Vacant(_) => panic!(),
5579 /// };
5580 ///
5581 /// match entry {
5582 /// Entry::Vacant(e) => {
5583 /// assert_eq!(e.key(), &"poneyland");
5584 /// }
5585 /// Entry::Occupied(_) => panic!(),
5586 /// }
5587 ///
5588 /// assert!(!map.contains_key("poneyland"));
5589 /// ```
5590 #[cfg_attr(feature = "inline-more", inline)]
5591 pub fn replace_entry_with<F>(self, f: F) -> Entry<'a, K, V, S, A>
5592 where
5593 F: FnOnce(&K, V) -> Option<V>,
5594 {
5595 unsafe {
5596 let mut spare_key = None;
5597
5598 self.table
5599 .table
5600 .replace_bucket_with(self.elem.clone(), |(key, value)| {
5601 if let Some(new_value) = f(&key, value) {
5602 Some((key, new_value))
5603 } else {
5604 spare_key = Some(key);
5605 None
5606 }
5607 });
5608
5609 if let Some(key) = spare_key {
5610 Entry::Vacant(VacantEntry {
5611 hash: self.hash,
5612 key,
5613 table: self.table,
5614 })
5615 } else {
5616 Entry::Occupied(self)
5617 }
5618 }
5619 }
5620}
5621
5622impl<'a, K, V, S, A: Allocator> VacantEntry<'a, K, V, S, A> {
5623 /// Gets a reference to the key that would be used when inserting a value
5624 /// through the `VacantEntry`.
5625 ///
5626 /// # Examples
5627 ///
5628 /// ```
5629 /// use hashbrown::HashMap;
5630 ///
5631 /// let mut map: HashMap<&str, u32> = HashMap::new();
5632 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
5633 /// ```
5634 #[cfg_attr(feature = "inline-more", inline)]
5635 pub fn key(&self) -> &K {
5636 &self.key
5637 }
5638
5639 /// Take ownership of the key.
5640 ///
5641 /// # Examples
5642 ///
5643 /// ```
5644 /// use hashbrown::hash_map::{Entry, HashMap};
5645 ///
5646 /// let mut map: HashMap<&str, u32> = HashMap::new();
5647 ///
5648 /// match map.entry("poneyland") {
5649 /// Entry::Occupied(_) => panic!(),
5650 /// Entry::Vacant(v) => assert_eq!(v.into_key(), "poneyland"),
5651 /// }
5652 /// ```
5653 #[cfg_attr(feature = "inline-more", inline)]
5654 pub fn into_key(self) -> K {
5655 self.key
5656 }
5657
5658 /// Sets the value of the entry with the VacantEntry's key,
5659 /// and returns a mutable reference to it.
5660 ///
5661 /// # Examples
5662 ///
5663 /// ```
5664 /// use hashbrown::HashMap;
5665 /// use hashbrown::hash_map::Entry;
5666 ///
5667 /// let mut map: HashMap<&str, u32> = HashMap::new();
5668 ///
5669 /// if let Entry::Vacant(o) = map.entry("poneyland") {
5670 /// o.insert(37);
5671 /// }
5672 /// assert_eq!(map["poneyland"], 37);
5673 /// ```
5674 #[cfg_attr(feature = "inline-more", inline)]
5675 pub fn insert(self, value: V) -> &'a mut V
5676 where
5677 K: Hash,
5678 S: BuildHasher,
5679 {
5680 let table = &mut self.table.table;
5681 let entry = table.insert_entry(
5682 self.hash,
5683 (self.key, value),
5684 make_hasher::<_, V, S>(&self.table.hash_builder),
5685 );
5686 &mut entry.1
5687 }
5688
5689 #[cfg_attr(feature = "inline-more", inline)]
5690 pub(crate) fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, S, A>
5691 where
5692 K: Hash,
5693 S: BuildHasher,
5694 {
5695 let elem = self.table.table.insert(
5696 self.hash,
5697 (self.key, value),
5698 make_hasher::<_, V, S>(&self.table.hash_builder),
5699 );
5700 OccupiedEntry {
5701 hash: self.hash,
5702 key: None,
5703 elem,
5704 table: self.table,
5705 }
5706 }
5707}
5708
5709impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
5710 /// Sets the value of the entry, and returns an OccupiedEntryRef.
5711 ///
5712 /// # Examples
5713 ///
5714 /// ```
5715 /// use hashbrown::HashMap;
5716 ///
5717 /// let mut map: HashMap<String, u32> = HashMap::new();
5718 /// let entry = map.entry_ref("horseyland").insert(37);
5719 ///
5720 /// assert_eq!(entry.key(), "horseyland");
5721 /// ```
5722 #[cfg_attr(feature = "inline-more", inline)]
5723 pub fn insert(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
5724 where
5725 K: Hash + From<&'b Q>,
5726 S: BuildHasher,
5727 {
5728 match self {
5729 EntryRef::Occupied(mut entry) => {
5730 entry.insert(value);
5731 entry
5732 }
5733 EntryRef::Vacant(entry) => entry.insert_entry(value),
5734 }
5735 }
5736
5737 /// Ensures a value is in the entry by inserting the default if empty, and returns
5738 /// a mutable reference to the value in the entry.
5739 ///
5740 /// # Examples
5741 ///
5742 /// ```
5743 /// use hashbrown::HashMap;
5744 ///
5745 /// let mut map: HashMap<String, u32> = HashMap::new();
5746 ///
5747 /// // nonexistent key
5748 /// map.entry_ref("poneyland").or_insert(3);
5749 /// assert_eq!(map["poneyland"], 3);
5750 ///
5751 /// // existing key
5752 /// *map.entry_ref("poneyland").or_insert(10) *= 2;
5753 /// assert_eq!(map["poneyland"], 6);
5754 /// ```
5755 #[cfg_attr(feature = "inline-more", inline)]
5756 pub fn or_insert(self, default: V) -> &'a mut V
5757 where
5758 K: Hash + From<&'b Q>,
5759 S: BuildHasher,
5760 {
5761 match self {
5762 EntryRef::Occupied(entry) => entry.into_mut(),
5763 EntryRef::Vacant(entry) => entry.insert(default),
5764 }
5765 }
5766
5767 /// Ensures a value is in the entry by inserting the result of the default function if empty,
5768 /// and returns a mutable reference to the value in the entry.
5769 ///
5770 /// # Examples
5771 ///
5772 /// ```
5773 /// use hashbrown::HashMap;
5774 ///
5775 /// let mut map: HashMap<String, u32> = HashMap::new();
5776 ///
5777 /// // nonexistent key
5778 /// map.entry_ref("poneyland").or_insert_with(|| 3);
5779 /// assert_eq!(map["poneyland"], 3);
5780 ///
5781 /// // existing key
5782 /// *map.entry_ref("poneyland").or_insert_with(|| 10) *= 2;
5783 /// assert_eq!(map["poneyland"], 6);
5784 /// ```
5785 #[cfg_attr(feature = "inline-more", inline)]
5786 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V
5787 where
5788 K: Hash + From<&'b Q>,
5789 S: BuildHasher,
5790 {
5791 match self {
5792 EntryRef::Occupied(entry) => entry.into_mut(),
5793 EntryRef::Vacant(entry) => entry.insert(default()),
5794 }
5795 }
5796
5797 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
5798 /// This method allows for generating key-derived values for insertion by providing the default
5799 /// function an access to the borrower form of the key.
5800 ///
5801 /// # Examples
5802 ///
5803 /// ```
5804 /// use hashbrown::HashMap;
5805 ///
5806 /// let mut map: HashMap<String, usize> = HashMap::new();
5807 ///
5808 /// // nonexistent key
5809 /// map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count());
5810 /// assert_eq!(map["poneyland"], 9);
5811 ///
5812 /// // existing key
5813 /// *map.entry_ref("poneyland").or_insert_with_key(|key| key.chars().count() * 10) *= 2;
5814 /// assert_eq!(map["poneyland"], 18);
5815 /// ```
5816 #[cfg_attr(feature = "inline-more", inline)]
5817 pub fn or_insert_with_key<F: FnOnce(&Q) -> V>(self, default: F) -> &'a mut V
5818 where
5819 K: Hash + Borrow<Q> + From<&'b Q>,
5820 S: BuildHasher,
5821 {
5822 match self {
5823 EntryRef::Occupied(entry) => entry.into_mut(),
5824 EntryRef::Vacant(entry) => {
5825 let value = default(entry.key.as_ref());
5826 entry.insert(value)
5827 }
5828 }
5829 }
5830
5831 /// Returns a reference to this entry's key.
5832 ///
5833 /// # Examples
5834 ///
5835 /// ```
5836 /// use hashbrown::HashMap;
5837 ///
5838 /// let mut map: HashMap<String, u32> = HashMap::new();
5839 /// map.entry_ref("poneyland").or_insert(3);
5840 /// // existing key
5841 /// assert_eq!(map.entry_ref("poneyland").key(), "poneyland");
5842 /// // nonexistent key
5843 /// assert_eq!(map.entry_ref("horseland").key(), "horseland");
5844 /// ```
5845 #[cfg_attr(feature = "inline-more", inline)]
5846 pub fn key(&self) -> &Q
5847 where
5848 K: Borrow<Q>,
5849 {
5850 match *self {
5851 EntryRef::Occupied(ref entry) => entry.key().borrow(),
5852 EntryRef::Vacant(ref entry) => entry.key(),
5853 }
5854 }
5855
5856 /// Provides in-place mutable access to an occupied entry before any
5857 /// potential inserts into the map.
5858 ///
5859 /// # Examples
5860 ///
5861 /// ```
5862 /// use hashbrown::HashMap;
5863 ///
5864 /// let mut map: HashMap<String, u32> = HashMap::new();
5865 ///
5866 /// map.entry_ref("poneyland")
5867 /// .and_modify(|e| { *e += 1 })
5868 /// .or_insert(42);
5869 /// assert_eq!(map["poneyland"], 42);
5870 ///
5871 /// map.entry_ref("poneyland")
5872 /// .and_modify(|e| { *e += 1 })
5873 /// .or_insert(42);
5874 /// assert_eq!(map["poneyland"], 43);
5875 /// ```
5876 #[cfg_attr(feature = "inline-more", inline)]
5877 pub fn and_modify<F>(self, f: F) -> Self
5878 where
5879 F: FnOnce(&mut V),
5880 {
5881 match self {
5882 EntryRef::Occupied(mut entry) => {
5883 f(entry.get_mut());
5884 EntryRef::Occupied(entry)
5885 }
5886 EntryRef::Vacant(entry) => EntryRef::Vacant(entry),
5887 }
5888 }
5889
5890 /// Provides shared access to the key and owned access to the value of
5891 /// an occupied entry and allows to replace or remove it based on the
5892 /// value of the returned option.
5893 ///
5894 /// # Examples
5895 ///
5896 /// ```
5897 /// use hashbrown::HashMap;
5898 /// use hashbrown::hash_map::EntryRef;
5899 ///
5900 /// let mut map: HashMap<String, u32> = HashMap::new();
5901 ///
5902 /// let entry = map
5903 /// .entry_ref("poneyland")
5904 /// .and_replace_entry_with(|_k, _v| panic!());
5905 ///
5906 /// match entry {
5907 /// EntryRef::Vacant(e) => {
5908 /// assert_eq!(e.key(), "poneyland");
5909 /// }
5910 /// EntryRef::Occupied(_) => panic!(),
5911 /// }
5912 ///
5913 /// map.insert("poneyland".to_string(), 42);
5914 ///
5915 /// let entry = map
5916 /// .entry_ref("poneyland")
5917 /// .and_replace_entry_with(|k, v| {
5918 /// assert_eq!(k, "poneyland");
5919 /// assert_eq!(v, 42);
5920 /// Some(v + 1)
5921 /// });
5922 ///
5923 /// match entry {
5924 /// EntryRef::Occupied(e) => {
5925 /// assert_eq!(e.key(), "poneyland");
5926 /// assert_eq!(e.get(), &43);
5927 /// }
5928 /// EntryRef::Vacant(_) => panic!(),
5929 /// }
5930 ///
5931 /// assert_eq!(map["poneyland"], 43);
5932 ///
5933 /// let entry = map
5934 /// .entry_ref("poneyland")
5935 /// .and_replace_entry_with(|_k, _v| None);
5936 ///
5937 /// match entry {
5938 /// EntryRef::Vacant(e) => assert_eq!(e.key(), "poneyland"),
5939 /// EntryRef::Occupied(_) => panic!(),
5940 /// }
5941 ///
5942 /// assert!(!map.contains_key("poneyland"));
5943 /// ```
5944 #[cfg_attr(feature = "inline-more", inline)]
5945 pub fn and_replace_entry_with<F>(self, f: F) -> Self
5946 where
5947 F: FnOnce(&K, V) -> Option<V>,
5948 {
5949 match self {
5950 EntryRef::Occupied(entry) => entry.replace_entry_with(f),
5951 EntryRef::Vacant(_) => self,
5952 }
5953 }
5954}
5955
5956impl<'a, 'b, K, Q: ?Sized, V: Default, S, A: Allocator> EntryRef<'a, 'b, K, Q, V, S, A> {
5957 /// Ensures a value is in the entry by inserting the default value if empty,
5958 /// and returns a mutable reference to the value in the entry.
5959 ///
5960 /// # Examples
5961 ///
5962 /// ```
5963 /// use hashbrown::HashMap;
5964 ///
5965 /// let mut map: HashMap<String, Option<u32>> = HashMap::new();
5966 ///
5967 /// // nonexistent key
5968 /// map.entry_ref("poneyland").or_default();
5969 /// assert_eq!(map["poneyland"], None);
5970 ///
5971 /// map.insert("horseland".to_string(), Some(3));
5972 ///
5973 /// // existing key
5974 /// assert_eq!(map.entry_ref("horseland").or_default(), &mut Some(3));
5975 /// ```
5976 #[cfg_attr(feature = "inline-more", inline)]
5977 pub fn or_default(self) -> &'a mut V
5978 where
5979 K: Hash + From<&'b Q>,
5980 S: BuildHasher,
5981 {
5982 match self {
5983 EntryRef::Occupied(entry) => entry.into_mut(),
5984 EntryRef::Vacant(entry) => entry.insert(Default::default()),
5985 }
5986 }
5987}
5988
5989impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> OccupiedEntryRef<'a, 'b, K, Q, V, S, A> {
5990 /// Gets a reference to the key in the entry.
5991 ///
5992 /// # Examples
5993 ///
5994 /// ```
5995 /// use hashbrown::hash_map::{EntryRef, HashMap};
5996 ///
5997 /// let mut map: HashMap<String, u32> = HashMap::new();
5998 /// map.entry_ref("poneyland").or_insert(12);
5999 ///
6000 /// match map.entry_ref("poneyland") {
6001 /// EntryRef::Vacant(_) => panic!(),
6002 /// EntryRef::Occupied(entry) => assert_eq!(entry.key(), "poneyland"),
6003 /// }
6004 /// ```
6005 #[cfg_attr(feature = "inline-more", inline)]
6006 pub fn key(&self) -> &K {
6007 unsafe { &self.elem.as_ref().0 }
6008 }
6009
6010 /// Take the ownership of the key and value from the map.
6011 /// Keeps the allocated memory for reuse.
6012 ///
6013 /// # Examples
6014 ///
6015 /// ```
6016 /// use hashbrown::HashMap;
6017 /// use hashbrown::hash_map::EntryRef;
6018 ///
6019 /// let mut map: HashMap<String, u32> = HashMap::new();
6020 /// // The map is empty
6021 /// assert!(map.is_empty() && map.capacity() == 0);
6022 ///
6023 /// map.entry_ref("poneyland").or_insert(12);
6024 ///
6025 /// if let EntryRef::Occupied(o) = map.entry_ref("poneyland") {
6026 /// // We delete the entry from the map.
6027 /// assert_eq!(o.remove_entry(), ("poneyland".to_owned(), 12));
6028 /// }
6029 ///
6030 /// assert_eq!(map.contains_key("poneyland"), false);
6031 /// // Now map hold none elements but capacity is equal to the old one
6032 /// assert!(map.is_empty());
6033 /// ```
6034 #[cfg_attr(feature = "inline-more", inline)]
6035 pub fn remove_entry(self) -> (K, V) {
6036 unsafe { self.table.table.remove(self.elem).0 }
6037 }
6038
6039 /// Gets a reference to the value in the entry.
6040 ///
6041 /// # Examples
6042 ///
6043 /// ```
6044 /// use hashbrown::HashMap;
6045 /// use hashbrown::hash_map::EntryRef;
6046 ///
6047 /// let mut map: HashMap<String, u32> = HashMap::new();
6048 /// map.entry_ref("poneyland").or_insert(12);
6049 ///
6050 /// match map.entry_ref("poneyland") {
6051 /// EntryRef::Vacant(_) => panic!(),
6052 /// EntryRef::Occupied(entry) => assert_eq!(entry.get(), &12),
6053 /// }
6054 /// ```
6055 #[cfg_attr(feature = "inline-more", inline)]
6056 pub fn get(&self) -> &V {
6057 unsafe { &self.elem.as_ref().1 }
6058 }
6059
6060 /// Gets a mutable reference to the value in the entry.
6061 ///
6062 /// If you need a reference to the `OccupiedEntryRef` which may outlive the
6063 /// destruction of the `EntryRef` value, see [`into_mut`].
6064 ///
6065 /// [`into_mut`]: #method.into_mut
6066 ///
6067 /// # Examples
6068 ///
6069 /// ```
6070 /// use hashbrown::HashMap;
6071 /// use hashbrown::hash_map::EntryRef;
6072 ///
6073 /// let mut map: HashMap<String, u32> = HashMap::new();
6074 /// map.entry_ref("poneyland").or_insert(12);
6075 ///
6076 /// assert_eq!(map["poneyland"], 12);
6077 /// if let EntryRef::Occupied(mut o) = map.entry_ref("poneyland") {
6078 /// *o.get_mut() += 10;
6079 /// assert_eq!(*o.get(), 22);
6080 ///
6081 /// // We can use the same Entry multiple times.
6082 /// *o.get_mut() += 2;
6083 /// }
6084 ///
6085 /// assert_eq!(map["poneyland"], 24);
6086 /// ```
6087 #[cfg_attr(feature = "inline-more", inline)]
6088 pub fn get_mut(&mut self) -> &mut V {
6089 unsafe { &mut self.elem.as_mut().1 }
6090 }
6091
6092 /// Converts the OccupiedEntryRef into a mutable reference to the value in the entry
6093 /// with a lifetime bound to the map itself.
6094 ///
6095 /// If you need multiple references to the `OccupiedEntryRef`, see [`get_mut`].
6096 ///
6097 /// [`get_mut`]: #method.get_mut
6098 ///
6099 /// # Examples
6100 ///
6101 /// ```
6102 /// use hashbrown::hash_map::{EntryRef, HashMap};
6103 ///
6104 /// let mut map: HashMap<String, u32> = HashMap::new();
6105 /// map.entry_ref("poneyland").or_insert(12);
6106 ///
6107 /// let value: &mut u32;
6108 /// match map.entry_ref("poneyland") {
6109 /// EntryRef::Occupied(entry) => value = entry.into_mut(),
6110 /// EntryRef::Vacant(_) => panic!(),
6111 /// }
6112 /// *value += 10;
6113 ///
6114 /// assert_eq!(map["poneyland"], 22);
6115 /// ```
6116 #[cfg_attr(feature = "inline-more", inline)]
6117 pub fn into_mut(self) -> &'a mut V {
6118 unsafe { &mut self.elem.as_mut().1 }
6119 }
6120
6121 /// Sets the value of the entry, and returns the entry's old value.
6122 ///
6123 /// # Examples
6124 ///
6125 /// ```
6126 /// use hashbrown::HashMap;
6127 /// use hashbrown::hash_map::EntryRef;
6128 ///
6129 /// let mut map: HashMap<String, u32> = HashMap::new();
6130 /// map.entry_ref("poneyland").or_insert(12);
6131 ///
6132 /// if let EntryRef::Occupied(mut o) = map.entry_ref("poneyland") {
6133 /// assert_eq!(o.insert(15), 12);
6134 /// }
6135 ///
6136 /// assert_eq!(map["poneyland"], 15);
6137 /// ```
6138 #[cfg_attr(feature = "inline-more", inline)]
6139 pub fn insert(&mut self, value: V) -> V {
6140 mem::replace(self.get_mut(), value)
6141 }
6142
6143 /// Takes the value out of the entry, and returns it.
6144 /// Keeps the allocated memory for reuse.
6145 ///
6146 /// # Examples
6147 ///
6148 /// ```
6149 /// use hashbrown::HashMap;
6150 /// use hashbrown::hash_map::EntryRef;
6151 ///
6152 /// let mut map: HashMap<String, u32> = HashMap::new();
6153 /// // The map is empty
6154 /// assert!(map.is_empty() && map.capacity() == 0);
6155 ///
6156 /// map.entry_ref("poneyland").or_insert(12);
6157 ///
6158 /// if let EntryRef::Occupied(o) = map.entry_ref("poneyland") {
6159 /// assert_eq!(o.remove(), 12);
6160 /// }
6161 ///
6162 /// assert_eq!(map.contains_key("poneyland"), false);
6163 /// // Now map hold none elements but capacity is equal to the old one
6164 /// assert!(map.is_empty());
6165 /// ```
6166 #[cfg_attr(feature = "inline-more", inline)]
6167 pub fn remove(self) -> V {
6168 self.remove_entry().1
6169 }
6170
6171 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
6172 /// the key used to create this entry.
6173 ///
6174 /// # Panics
6175 ///
6176 /// Will panic if this OccupiedEntryRef was created through [`EntryRef::insert`].
6177 ///
6178 /// # Examples
6179 ///
6180 /// ```
6181 /// use hashbrown::hash_map::{EntryRef, HashMap};
6182 /// use std::rc::Rc;
6183 ///
6184 /// let mut map: HashMap<Rc<str>, u32> = HashMap::new();
6185 /// let key: Rc<str> = Rc::from("Stringthing");
6186 ///
6187 /// map.insert(key.clone(), 15);
6188 /// assert_eq!(Rc::strong_count(&key), 2);
6189 ///
6190 /// match map.entry_ref("Stringthing") {
6191 /// EntryRef::Occupied(entry) => {
6192 /// let (old_key, old_value): (Rc<str>, u32) = entry.replace_entry(16);
6193 /// assert!(Rc::ptr_eq(&key, &old_key) && old_value == 15);
6194 /// }
6195 /// EntryRef::Vacant(_) => panic!(),
6196 /// }
6197 ///
6198 /// assert_eq!(Rc::strong_count(&key), 1);
6199 /// assert_eq!(map["Stringthing"], 16);
6200 /// ```
6201 #[cfg_attr(feature = "inline-more", inline)]
6202 pub fn replace_entry(self, value: V) -> (K, V)
6203 where
6204 K: From<&'b Q>,
6205 {
6206 let entry = unsafe { self.elem.as_mut() };
6207
6208 let old_key = mem::replace(&mut entry.0, self.key.unwrap().into_owned());
6209 let old_value = mem::replace(&mut entry.1, value);
6210
6211 (old_key, old_value)
6212 }
6213
6214 /// Replaces the key in the hash map with the key used to create this entry.
6215 ///
6216 /// # Panics
6217 ///
6218 /// Will panic if this OccupiedEntryRef was created through [`EntryRef::insert`].
6219 ///
6220 /// # Examples
6221 ///
6222 /// ```
6223 /// use hashbrown::hash_map::{EntryRef, HashMap};
6224 /// use std::rc::Rc;
6225 ///
6226 /// let mut map: HashMap<Rc<str>, usize> = HashMap::with_capacity(6);
6227 /// let mut keys: Vec<Rc<str>> = Vec::with_capacity(6);
6228 ///
6229 /// for (value, key) in ["a", "b", "c", "d", "e", "f"].into_iter().enumerate() {
6230 /// let rc_key: Rc<str> = Rc::from(key);
6231 /// keys.push(rc_key.clone());
6232 /// map.insert(rc_key.clone(), value);
6233 /// }
6234 ///
6235 /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 2));
6236 ///
6237 /// // It doesn't matter that we kind of use a vector with the same keys,
6238 /// // because all keys will be newly created from the references
6239 /// reclaim_memory(&mut map, &keys);
6240 ///
6241 /// assert!(keys.iter().all(|key| Rc::strong_count(key) == 1));
6242 ///
6243 /// fn reclaim_memory(map: &mut HashMap<Rc<str>, usize>, keys: &[Rc<str>]) {
6244 /// for key in keys {
6245 /// if let EntryRef::Occupied(entry) = map.entry_ref(key.as_ref()) {
6246 /// // Replaces the entry's key with our version of it in `keys`.
6247 /// entry.replace_key();
6248 /// }
6249 /// }
6250 /// }
6251 /// ```
6252 #[cfg_attr(feature = "inline-more", inline)]
6253 pub fn replace_key(self) -> K
6254 where
6255 K: From<&'b Q>,
6256 {
6257 let entry = unsafe { self.elem.as_mut() };
6258 mem::replace(&mut entry.0, self.key.unwrap().into_owned())
6259 }
6260
6261 /// Provides shared access to the key and owned access to the value of
6262 /// the entry and allows to replace or remove it based on the
6263 /// value of the returned option.
6264 ///
6265 /// # Examples
6266 ///
6267 /// ```
6268 /// use hashbrown::HashMap;
6269 /// use hashbrown::hash_map::EntryRef;
6270 ///
6271 /// let mut map: HashMap<String, u32> = HashMap::new();
6272 /// map.insert("poneyland".to_string(), 42);
6273 ///
6274 /// let entry = match map.entry_ref("poneyland") {
6275 /// EntryRef::Occupied(e) => {
6276 /// e.replace_entry_with(|k, v| {
6277 /// assert_eq!(k, "poneyland");
6278 /// assert_eq!(v, 42);
6279 /// Some(v + 1)
6280 /// })
6281 /// }
6282 /// EntryRef::Vacant(_) => panic!(),
6283 /// };
6284 ///
6285 /// match entry {
6286 /// EntryRef::Occupied(e) => {
6287 /// assert_eq!(e.key(), "poneyland");
6288 /// assert_eq!(e.get(), &43);
6289 /// }
6290 /// EntryRef::Vacant(_) => panic!(),
6291 /// }
6292 ///
6293 /// assert_eq!(map["poneyland"], 43);
6294 ///
6295 /// let entry = match map.entry_ref("poneyland") {
6296 /// EntryRef::Occupied(e) => e.replace_entry_with(|_k, _v| None),
6297 /// EntryRef::Vacant(_) => panic!(),
6298 /// };
6299 ///
6300 /// match entry {
6301 /// EntryRef::Vacant(e) => {
6302 /// assert_eq!(e.key(), "poneyland");
6303 /// }
6304 /// EntryRef::Occupied(_) => panic!(),
6305 /// }
6306 ///
6307 /// assert!(!map.contains_key("poneyland"));
6308 /// ```
6309 #[cfg_attr(feature = "inline-more", inline)]
6310 pub fn replace_entry_with<F>(self, f: F) -> EntryRef<'a, 'b, K, Q, V, S, A>
6311 where
6312 F: FnOnce(&K, V) -> Option<V>,
6313 {
6314 unsafe {
6315 let mut spare_key = None;
6316
6317 self.table
6318 .table
6319 .replace_bucket_with(self.elem.clone(), |(key, value)| {
6320 if let Some(new_value) = f(&key, value) {
6321 Some((key, new_value))
6322 } else {
6323 spare_key = Some(KeyOrRef::Owned(key));
6324 None
6325 }
6326 });
6327
6328 if let Some(key) = spare_key {
6329 EntryRef::Vacant(VacantEntryRef {
6330 hash: self.hash,
6331 key,
6332 table: self.table,
6333 })
6334 } else {
6335 EntryRef::Occupied(self)
6336 }
6337 }
6338 }
6339}
6340
6341impl<'a, 'b, K, Q: ?Sized, V, S, A: Allocator> VacantEntryRef<'a, 'b, K, Q, V, S, A> {
6342 /// Gets a reference to the key that would be used when inserting a value
6343 /// through the `VacantEntryRef`.
6344 ///
6345 /// # Examples
6346 ///
6347 /// ```
6348 /// use hashbrown::HashMap;
6349 ///
6350 /// let mut map: HashMap<String, u32> = HashMap::new();
6351 /// let key: &str = "poneyland";
6352 /// assert_eq!(map.entry_ref(key).key(), "poneyland");
6353 /// ```
6354 #[cfg_attr(feature = "inline-more", inline)]
6355 pub fn key(&self) -> &Q
6356 where
6357 K: Borrow<Q>,
6358 {
6359 self.key.as_ref()
6360 }
6361
6362 /// Take ownership of the key.
6363 ///
6364 /// # Examples
6365 ///
6366 /// ```
6367 /// use hashbrown::hash_map::{EntryRef, HashMap};
6368 ///
6369 /// let mut map: HashMap<String, u32> = HashMap::new();
6370 /// let key: &str = "poneyland";
6371 ///
6372 /// match map.entry_ref(key) {
6373 /// EntryRef::Occupied(_) => panic!(),
6374 /// EntryRef::Vacant(v) => assert_eq!(v.into_key(), "poneyland".to_owned()),
6375 /// }
6376 /// ```
6377 #[cfg_attr(feature = "inline-more", inline)]
6378 pub fn into_key(self) -> K
6379 where
6380 K: From<&'b Q>,
6381 {
6382 self.key.into_owned()
6383 }
6384
6385 /// Sets the value of the entry with the VacantEntryRef's key,
6386 /// and returns a mutable reference to it.
6387 ///
6388 /// # Examples
6389 ///
6390 /// ```
6391 /// use hashbrown::HashMap;
6392 /// use hashbrown::hash_map::EntryRef;
6393 ///
6394 /// let mut map: HashMap<String, u32> = HashMap::new();
6395 /// let key: &str = "poneyland";
6396 ///
6397 /// if let EntryRef::Vacant(o) = map.entry_ref(key) {
6398 /// o.insert(37);
6399 /// }
6400 /// assert_eq!(map["poneyland"], 37);
6401 /// ```
6402 #[cfg_attr(feature = "inline-more", inline)]
6403 pub fn insert(self, value: V) -> &'a mut V
6404 where
6405 K: Hash + From<&'b Q>,
6406 S: BuildHasher,
6407 {
6408 let table = &mut self.table.table;
6409 let entry = table.insert_entry(
6410 self.hash,
6411 (self.key.into_owned(), value),
6412 make_hasher::<_, V, S>(&self.table.hash_builder),
6413 );
6414 &mut entry.1
6415 }
6416
6417 #[cfg_attr(feature = "inline-more", inline)]
6418 fn insert_entry(self, value: V) -> OccupiedEntryRef<'a, 'b, K, Q, V, S, A>
6419 where
6420 K: Hash + From<&'b Q>,
6421 S: BuildHasher,
6422 {
6423 let elem = self.table.table.insert(
6424 self.hash,
6425 (self.key.into_owned(), value),
6426 make_hasher::<_, V, S>(&self.table.hash_builder),
6427 );
6428 OccupiedEntryRef {
6429 hash: self.hash,
6430 key: None,
6431 elem,
6432 table: self.table,
6433 }
6434 }
6435}
6436
6437impl<K, V, S, A> FromIterator<(K, V)> for HashMap<K, V, S, A>
6438where
6439 K: Eq + Hash,
6440 S: BuildHasher + Default,
6441 A: Default + Allocator,
6442{
6443 #[cfg_attr(feature = "inline-more", inline)]
6444 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
6445 let iter = iter.into_iter();
6446 let mut map: HashMap =
6447 Self::with_capacity_and_hasher_in(capacity:iter.size_hint().0, S::default(), A::default());
6448 iter.for_each(|(k: K, v: V)| {
6449 map.insert(k, v);
6450 });
6451 map
6452 }
6453}
6454
6455/// Inserts all new key-values from the iterator and replaces values with existing
6456/// keys with new values returned from the iterator.
6457impl<K, V, S, A> Extend<(K, V)> for HashMap<K, V, S, A>
6458where
6459 K: Eq + Hash,
6460 S: BuildHasher,
6461 A: Allocator,
6462{
6463 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
6464 /// Replace values with existing keys with new values returned from the iterator.
6465 ///
6466 /// # Examples
6467 ///
6468 /// ```
6469 /// use hashbrown::hash_map::HashMap;
6470 ///
6471 /// let mut map = HashMap::new();
6472 /// map.insert(1, 100);
6473 ///
6474 /// let some_iter = [(1, 1), (2, 2)].into_iter();
6475 /// map.extend(some_iter);
6476 /// // Replace values with existing keys with new values returned from the iterator.
6477 /// // So that the map.get(&1) doesn't return Some(&100).
6478 /// assert_eq!(map.get(&1), Some(&1));
6479 ///
6480 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
6481 /// map.extend(some_vec);
6482 ///
6483 /// let some_arr = [(5, 5), (6, 6)];
6484 /// map.extend(some_arr);
6485 /// let old_map_len = map.len();
6486 ///
6487 /// // You can also extend from another HashMap
6488 /// let mut new_map = HashMap::new();
6489 /// new_map.extend(map);
6490 /// assert_eq!(new_map.len(), old_map_len);
6491 ///
6492 /// let mut vec: Vec<_> = new_map.into_iter().collect();
6493 /// // The `IntoIter` iterator produces items in arbitrary order, so the
6494 /// // items must be sorted to test them against a sorted array.
6495 /// vec.sort_unstable();
6496 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
6497 /// ```
6498 #[cfg_attr(feature = "inline-more", inline)]
6499 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
6500 // Keys may be already present or show multiple times in the iterator.
6501 // Reserve the entire hint lower bound if the map is empty.
6502 // Otherwise reserve half the hint (rounded up), so the map
6503 // will only resize twice in the worst case.
6504 let iter = iter.into_iter();
6505 let reserve = if self.is_empty() {
6506 iter.size_hint().0
6507 } else {
6508 (iter.size_hint().0 + 1) / 2
6509 };
6510 self.reserve(reserve);
6511 iter.for_each(move |(k, v)| {
6512 self.insert(k, v);
6513 });
6514 }
6515
6516 #[inline]
6517 #[cfg(feature = "nightly")]
6518 fn extend_one(&mut self, (k, v): (K, V)) {
6519 self.insert(k, v);
6520 }
6521
6522 #[inline]
6523 #[cfg(feature = "nightly")]
6524 fn extend_reserve(&mut self, additional: usize) {
6525 // Keys may be already present or show multiple times in the iterator.
6526 // Reserve the entire hint lower bound if the map is empty.
6527 // Otherwise reserve half the hint (rounded up), so the map
6528 // will only resize twice in the worst case.
6529 let reserve = if self.is_empty() {
6530 additional
6531 } else {
6532 (additional + 1) / 2
6533 };
6534 self.reserve(reserve);
6535 }
6536}
6537
6538/// Inserts all new key-values from the iterator and replaces values with existing
6539/// keys with new values returned from the iterator.
6540impl<'a, K, V, S, A> Extend<(&'a K, &'a V)> for HashMap<K, V, S, A>
6541where
6542 K: Eq + Hash + Copy,
6543 V: Copy,
6544 S: BuildHasher,
6545 A: Allocator,
6546{
6547 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
6548 /// Replace values with existing keys with new values returned from the iterator.
6549 /// The keys and values must implement [`Copy`] trait.
6550 ///
6551 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
6552 ///
6553 /// # Examples
6554 ///
6555 /// ```
6556 /// use hashbrown::hash_map::HashMap;
6557 ///
6558 /// let mut map = HashMap::new();
6559 /// map.insert(1, 100);
6560 ///
6561 /// let arr = [(1, 1), (2, 2)];
6562 /// let some_iter = arr.iter().map(|(k, v)| (k, v));
6563 /// map.extend(some_iter);
6564 /// // Replace values with existing keys with new values returned from the iterator.
6565 /// // So that the map.get(&1) doesn't return Some(&100).
6566 /// assert_eq!(map.get(&1), Some(&1));
6567 ///
6568 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
6569 /// map.extend(some_vec.iter().map(|(k, v)| (k, v)));
6570 ///
6571 /// let some_arr = [(5, 5), (6, 6)];
6572 /// map.extend(some_arr.iter().map(|(k, v)| (k, v)));
6573 ///
6574 /// // You can also extend from another HashMap
6575 /// let mut new_map = HashMap::new();
6576 /// new_map.extend(&map);
6577 /// assert_eq!(new_map, map);
6578 ///
6579 /// let mut vec: Vec<_> = new_map.into_iter().collect();
6580 /// // The `IntoIter` iterator produces items in arbitrary order, so the
6581 /// // items must be sorted to test them against a sorted array.
6582 /// vec.sort_unstable();
6583 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
6584 /// ```
6585 #[cfg_attr(feature = "inline-more", inline)]
6586 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
6587 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
6588 }
6589
6590 #[inline]
6591 #[cfg(feature = "nightly")]
6592 fn extend_one(&mut self, (k, v): (&'a K, &'a V)) {
6593 self.insert(*k, *v);
6594 }
6595
6596 #[inline]
6597 #[cfg(feature = "nightly")]
6598 fn extend_reserve(&mut self, additional: usize) {
6599 Extend::<(K, V)>::extend_reserve(self, additional);
6600 }
6601}
6602
6603/// Inserts all new key-values from the iterator and replaces values with existing
6604/// keys with new values returned from the iterator.
6605impl<'a, K, V, S, A> Extend<&'a (K, V)> for HashMap<K, V, S, A>
6606where
6607 K: Eq + Hash + Copy,
6608 V: Copy,
6609 S: BuildHasher,
6610 A: Allocator,
6611{
6612 /// Inserts all new key-values from the iterator to existing `HashMap<K, V, S, A>`.
6613 /// Replace values with existing keys with new values returned from the iterator.
6614 /// The keys and values must implement [`Copy`] trait.
6615 ///
6616 /// [`Copy`]: https://doc.rust-lang.org/core/marker/trait.Copy.html
6617 ///
6618 /// # Examples
6619 ///
6620 /// ```
6621 /// use hashbrown::hash_map::HashMap;
6622 ///
6623 /// let mut map = HashMap::new();
6624 /// map.insert(1, 100);
6625 ///
6626 /// let arr = [(1, 1), (2, 2)];
6627 /// let some_iter = arr.iter();
6628 /// map.extend(some_iter);
6629 /// // Replace values with existing keys with new values returned from the iterator.
6630 /// // So that the map.get(&1) doesn't return Some(&100).
6631 /// assert_eq!(map.get(&1), Some(&1));
6632 ///
6633 /// let some_vec: Vec<_> = vec![(3, 3), (4, 4)];
6634 /// map.extend(&some_vec);
6635 ///
6636 /// let some_arr = [(5, 5), (6, 6)];
6637 /// map.extend(&some_arr);
6638 ///
6639 /// let mut vec: Vec<_> = map.into_iter().collect();
6640 /// // The `IntoIter` iterator produces items in arbitrary order, so the
6641 /// // items must be sorted to test them against a sorted array.
6642 /// vec.sort_unstable();
6643 /// assert_eq!(vec, [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]);
6644 /// ```
6645 #[cfg_attr(feature = "inline-more", inline)]
6646 fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T) {
6647 self.extend(iter.into_iter().map(|&(key, value)| (key, value)));
6648 }
6649
6650 #[inline]
6651 #[cfg(feature = "nightly")]
6652 fn extend_one(&mut self, &(k, v): &'a (K, V)) {
6653 self.insert(k, v);
6654 }
6655
6656 #[inline]
6657 #[cfg(feature = "nightly")]
6658 fn extend_reserve(&mut self, additional: usize) {
6659 Extend::<(K, V)>::extend_reserve(self, additional);
6660 }
6661}
6662
6663#[allow(dead_code)]
6664fn assert_covariance() {
6665 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
6666 v
6667 }
6668 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
6669 v
6670 }
6671 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
6672 v
6673 }
6674 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
6675 v
6676 }
6677 fn into_iter_key<'new, A: Allocator>(
6678 v: IntoIter<&'static str, u8, A>,
6679 ) -> IntoIter<&'new str, u8, A> {
6680 v
6681 }
6682 fn into_iter_val<'new, A: Allocator>(
6683 v: IntoIter<u8, &'static str, A>,
6684 ) -> IntoIter<u8, &'new str, A> {
6685 v
6686 }
6687 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
6688 v
6689 }
6690 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
6691 v
6692 }
6693 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
6694 v
6695 }
6696 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
6697 v
6698 }
6699 fn drain<'new>(
6700 d: Drain<'static, &'static str, &'static str>,
6701 ) -> Drain<'new, &'new str, &'new str> {
6702 d
6703 }
6704}
6705
6706#[cfg(test)]
6707mod test_map {
6708 use super::DefaultHashBuilder;
6709 use super::Entry::{Occupied, Vacant};
6710 use super::EntryRef;
6711 use super::{HashMap, RawEntryMut};
6712 use alloc::string::{String, ToString};
6713 use alloc::sync::Arc;
6714 use allocator_api2::alloc::{AllocError, Allocator, Global};
6715 use core::alloc::Layout;
6716 use core::ptr::NonNull;
6717 use core::sync::atomic::{AtomicI8, Ordering};
6718 use rand::{rngs::SmallRng, Rng, SeedableRng};
6719 use std::borrow::ToOwned;
6720 use std::cell::RefCell;
6721 use std::usize;
6722 use std::vec::Vec;
6723
6724 #[test]
6725 fn test_zero_capacities() {
6726 type HM = HashMap<i32, i32>;
6727
6728 let m = HM::new();
6729 assert_eq!(m.capacity(), 0);
6730
6731 let m = HM::default();
6732 assert_eq!(m.capacity(), 0);
6733
6734 let m = HM::with_hasher(DefaultHashBuilder::default());
6735 assert_eq!(m.capacity(), 0);
6736
6737 let m = HM::with_capacity(0);
6738 assert_eq!(m.capacity(), 0);
6739
6740 let m = HM::with_capacity_and_hasher(0, DefaultHashBuilder::default());
6741 assert_eq!(m.capacity(), 0);
6742
6743 let mut m = HM::new();
6744 m.insert(1, 1);
6745 m.insert(2, 2);
6746 m.remove(&1);
6747 m.remove(&2);
6748 m.shrink_to_fit();
6749 assert_eq!(m.capacity(), 0);
6750
6751 let mut m = HM::new();
6752 m.reserve(0);
6753 assert_eq!(m.capacity(), 0);
6754 }
6755
6756 #[test]
6757 fn test_create_capacity_zero() {
6758 let mut m = HashMap::with_capacity(0);
6759
6760 assert!(m.insert(1, 1).is_none());
6761
6762 assert!(m.contains_key(&1));
6763 assert!(!m.contains_key(&0));
6764 }
6765
6766 #[test]
6767 fn test_insert() {
6768 let mut m = HashMap::new();
6769 assert_eq!(m.len(), 0);
6770 assert!(m.insert(1, 2).is_none());
6771 assert_eq!(m.len(), 1);
6772 assert!(m.insert(2, 4).is_none());
6773 assert_eq!(m.len(), 2);
6774 assert_eq!(*m.get(&1).unwrap(), 2);
6775 assert_eq!(*m.get(&2).unwrap(), 4);
6776 }
6777
6778 #[test]
6779 fn test_clone() {
6780 let mut m = HashMap::new();
6781 assert_eq!(m.len(), 0);
6782 assert!(m.insert(1, 2).is_none());
6783 assert_eq!(m.len(), 1);
6784 assert!(m.insert(2, 4).is_none());
6785 assert_eq!(m.len(), 2);
6786 #[allow(clippy::redundant_clone)]
6787 let m2 = m.clone();
6788 assert_eq!(*m2.get(&1).unwrap(), 2);
6789 assert_eq!(*m2.get(&2).unwrap(), 4);
6790 assert_eq!(m2.len(), 2);
6791 }
6792
6793 #[test]
6794 fn test_clone_from() {
6795 let mut m = HashMap::new();
6796 let mut m2 = HashMap::new();
6797 assert_eq!(m.len(), 0);
6798 assert!(m.insert(1, 2).is_none());
6799 assert_eq!(m.len(), 1);
6800 assert!(m.insert(2, 4).is_none());
6801 assert_eq!(m.len(), 2);
6802 m2.clone_from(&m);
6803 assert_eq!(*m2.get(&1).unwrap(), 2);
6804 assert_eq!(*m2.get(&2).unwrap(), 4);
6805 assert_eq!(m2.len(), 2);
6806 }
6807
6808 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
6809
6810 #[derive(Hash, PartialEq, Eq)]
6811 struct Droppable {
6812 k: usize,
6813 }
6814
6815 impl Droppable {
6816 fn new(k: usize) -> Droppable {
6817 DROP_VECTOR.with(|slot| {
6818 slot.borrow_mut()[k] += 1;
6819 });
6820
6821 Droppable { k }
6822 }
6823 }
6824
6825 impl Drop for Droppable {
6826 fn drop(&mut self) {
6827 DROP_VECTOR.with(|slot| {
6828 slot.borrow_mut()[self.k] -= 1;
6829 });
6830 }
6831 }
6832
6833 impl Clone for Droppable {
6834 fn clone(&self) -> Self {
6835 Droppable::new(self.k)
6836 }
6837 }
6838
6839 #[test]
6840 fn test_drops() {
6841 DROP_VECTOR.with(|slot| {
6842 *slot.borrow_mut() = vec![0; 200];
6843 });
6844
6845 {
6846 let mut m = HashMap::new();
6847
6848 DROP_VECTOR.with(|v| {
6849 for i in 0..200 {
6850 assert_eq!(v.borrow()[i], 0);
6851 }
6852 });
6853
6854 for i in 0..100 {
6855 let d1 = Droppable::new(i);
6856 let d2 = Droppable::new(i + 100);
6857 m.insert(d1, d2);
6858 }
6859
6860 DROP_VECTOR.with(|v| {
6861 for i in 0..200 {
6862 assert_eq!(v.borrow()[i], 1);
6863 }
6864 });
6865
6866 for i in 0..50 {
6867 let k = Droppable::new(i);
6868 let v = m.remove(&k);
6869
6870 assert!(v.is_some());
6871
6872 DROP_VECTOR.with(|v| {
6873 assert_eq!(v.borrow()[i], 1);
6874 assert_eq!(v.borrow()[i + 100], 1);
6875 });
6876 }
6877
6878 DROP_VECTOR.with(|v| {
6879 for i in 0..50 {
6880 assert_eq!(v.borrow()[i], 0);
6881 assert_eq!(v.borrow()[i + 100], 0);
6882 }
6883
6884 for i in 50..100 {
6885 assert_eq!(v.borrow()[i], 1);
6886 assert_eq!(v.borrow()[i + 100], 1);
6887 }
6888 });
6889 }
6890
6891 DROP_VECTOR.with(|v| {
6892 for i in 0..200 {
6893 assert_eq!(v.borrow()[i], 0);
6894 }
6895 });
6896 }
6897
6898 #[test]
6899 fn test_into_iter_drops() {
6900 DROP_VECTOR.with(|v| {
6901 *v.borrow_mut() = vec![0; 200];
6902 });
6903
6904 let hm = {
6905 let mut hm = HashMap::new();
6906
6907 DROP_VECTOR.with(|v| {
6908 for i in 0..200 {
6909 assert_eq!(v.borrow()[i], 0);
6910 }
6911 });
6912
6913 for i in 0..100 {
6914 let d1 = Droppable::new(i);
6915 let d2 = Droppable::new(i + 100);
6916 hm.insert(d1, d2);
6917 }
6918
6919 DROP_VECTOR.with(|v| {
6920 for i in 0..200 {
6921 assert_eq!(v.borrow()[i], 1);
6922 }
6923 });
6924
6925 hm
6926 };
6927
6928 // By the way, ensure that cloning doesn't screw up the dropping.
6929 drop(hm.clone());
6930
6931 {
6932 let mut half = hm.into_iter().take(50);
6933
6934 DROP_VECTOR.with(|v| {
6935 for i in 0..200 {
6936 assert_eq!(v.borrow()[i], 1);
6937 }
6938 });
6939
6940 for _ in half.by_ref() {}
6941
6942 DROP_VECTOR.with(|v| {
6943 let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
6944
6945 let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
6946
6947 assert_eq!(nk, 50);
6948 assert_eq!(nv, 50);
6949 });
6950 };
6951
6952 DROP_VECTOR.with(|v| {
6953 for i in 0..200 {
6954 assert_eq!(v.borrow()[i], 0);
6955 }
6956 });
6957 }
6958
6959 #[test]
6960 fn test_empty_remove() {
6961 let mut m: HashMap<i32, bool> = HashMap::new();
6962 assert_eq!(m.remove(&0), None);
6963 }
6964
6965 #[test]
6966 fn test_empty_entry() {
6967 let mut m: HashMap<i32, bool> = HashMap::new();
6968 match m.entry(0) {
6969 Occupied(_) => panic!(),
6970 Vacant(_) => {}
6971 }
6972 assert!(*m.entry(0).or_insert(true));
6973 assert_eq!(m.len(), 1);
6974 }
6975
6976 #[test]
6977 fn test_empty_entry_ref() {
6978 let mut m: HashMap<std::string::String, bool> = HashMap::new();
6979 match m.entry_ref("poneyland") {
6980 EntryRef::Occupied(_) => panic!(),
6981 EntryRef::Vacant(_) => {}
6982 }
6983 assert!(*m.entry_ref("poneyland").or_insert(true));
6984 assert_eq!(m.len(), 1);
6985 }
6986
6987 #[test]
6988 fn test_empty_iter() {
6989 let mut m: HashMap<i32, bool> = HashMap::new();
6990 assert_eq!(m.drain().next(), None);
6991 assert_eq!(m.keys().next(), None);
6992 assert_eq!(m.values().next(), None);
6993 assert_eq!(m.values_mut().next(), None);
6994 assert_eq!(m.iter().next(), None);
6995 assert_eq!(m.iter_mut().next(), None);
6996 assert_eq!(m.len(), 0);
6997 assert!(m.is_empty());
6998 assert_eq!(m.into_iter().next(), None);
6999 }
7000
7001 #[test]
7002 #[cfg_attr(miri, ignore)] // FIXME: takes too long
7003 fn test_lots_of_insertions() {
7004 let mut m = HashMap::new();
7005
7006 // Try this a few times to make sure we never screw up the hashmap's
7007 // internal state.
7008 for _ in 0..10 {
7009 assert!(m.is_empty());
7010
7011 for i in 1..1001 {
7012 assert!(m.insert(i, i).is_none());
7013
7014 for j in 1..=i {
7015 let r = m.get(&j);
7016 assert_eq!(r, Some(&j));
7017 }
7018
7019 for j in i + 1..1001 {
7020 let r = m.get(&j);
7021 assert_eq!(r, None);
7022 }
7023 }
7024
7025 for i in 1001..2001 {
7026 assert!(!m.contains_key(&i));
7027 }
7028
7029 // remove forwards
7030 for i in 1..1001 {
7031 assert!(m.remove(&i).is_some());
7032
7033 for j in 1..=i {
7034 assert!(!m.contains_key(&j));
7035 }
7036
7037 for j in i + 1..1001 {
7038 assert!(m.contains_key(&j));
7039 }
7040 }
7041
7042 for i in 1..1001 {
7043 assert!(!m.contains_key(&i));
7044 }
7045
7046 for i in 1..1001 {
7047 assert!(m.insert(i, i).is_none());
7048 }
7049
7050 // remove backwards
7051 for i in (1..1001).rev() {
7052 assert!(m.remove(&i).is_some());
7053
7054 for j in i..1001 {
7055 assert!(!m.contains_key(&j));
7056 }
7057
7058 for j in 1..i {
7059 assert!(m.contains_key(&j));
7060 }
7061 }
7062 }
7063 }
7064
7065 #[test]
7066 fn test_find_mut() {
7067 let mut m = HashMap::new();
7068 assert!(m.insert(1, 12).is_none());
7069 assert!(m.insert(2, 8).is_none());
7070 assert!(m.insert(5, 14).is_none());
7071 let new = 100;
7072 match m.get_mut(&5) {
7073 None => panic!(),
7074 Some(x) => *x = new,
7075 }
7076 assert_eq!(m.get(&5), Some(&new));
7077 }
7078
7079 #[test]
7080 fn test_insert_overwrite() {
7081 let mut m = HashMap::new();
7082 assert!(m.insert(1, 2).is_none());
7083 assert_eq!(*m.get(&1).unwrap(), 2);
7084 assert!(m.insert(1, 3).is_some());
7085 assert_eq!(*m.get(&1).unwrap(), 3);
7086 }
7087
7088 #[test]
7089 fn test_insert_conflicts() {
7090 let mut m = HashMap::with_capacity(4);
7091 assert!(m.insert(1, 2).is_none());
7092 assert!(m.insert(5, 3).is_none());
7093 assert!(m.insert(9, 4).is_none());
7094 assert_eq!(*m.get(&9).unwrap(), 4);
7095 assert_eq!(*m.get(&5).unwrap(), 3);
7096 assert_eq!(*m.get(&1).unwrap(), 2);
7097 }
7098
7099 #[test]
7100 fn test_conflict_remove() {
7101 let mut m = HashMap::with_capacity(4);
7102 assert!(m.insert(1, 2).is_none());
7103 assert_eq!(*m.get(&1).unwrap(), 2);
7104 assert!(m.insert(5, 3).is_none());
7105 assert_eq!(*m.get(&1).unwrap(), 2);
7106 assert_eq!(*m.get(&5).unwrap(), 3);
7107 assert!(m.insert(9, 4).is_none());
7108 assert_eq!(*m.get(&1).unwrap(), 2);
7109 assert_eq!(*m.get(&5).unwrap(), 3);
7110 assert_eq!(*m.get(&9).unwrap(), 4);
7111 assert!(m.remove(&1).is_some());
7112 assert_eq!(*m.get(&9).unwrap(), 4);
7113 assert_eq!(*m.get(&5).unwrap(), 3);
7114 }
7115
7116 #[test]
7117 fn test_insert_unique_unchecked() {
7118 let mut map = HashMap::new();
7119 let (k1, v1) = map.insert_unique_unchecked(10, 11);
7120 assert_eq!((&10, &mut 11), (k1, v1));
7121 let (k2, v2) = map.insert_unique_unchecked(20, 21);
7122 assert_eq!((&20, &mut 21), (k2, v2));
7123 assert_eq!(Some(&11), map.get(&10));
7124 assert_eq!(Some(&21), map.get(&20));
7125 assert_eq!(None, map.get(&30));
7126 }
7127
7128 #[test]
7129 fn test_is_empty() {
7130 let mut m = HashMap::with_capacity(4);
7131 assert!(m.insert(1, 2).is_none());
7132 assert!(!m.is_empty());
7133 assert!(m.remove(&1).is_some());
7134 assert!(m.is_empty());
7135 }
7136
7137 #[test]
7138 fn test_remove() {
7139 let mut m = HashMap::new();
7140 m.insert(1, 2);
7141 assert_eq!(m.remove(&1), Some(2));
7142 assert_eq!(m.remove(&1), None);
7143 }
7144
7145 #[test]
7146 fn test_remove_entry() {
7147 let mut m = HashMap::new();
7148 m.insert(1, 2);
7149 assert_eq!(m.remove_entry(&1), Some((1, 2)));
7150 assert_eq!(m.remove(&1), None);
7151 }
7152
7153 #[test]
7154 fn test_iterate() {
7155 let mut m = HashMap::with_capacity(4);
7156 for i in 0..32 {
7157 assert!(m.insert(i, i * 2).is_none());
7158 }
7159 assert_eq!(m.len(), 32);
7160
7161 let mut observed: u32 = 0;
7162
7163 for (k, v) in &m {
7164 assert_eq!(*v, *k * 2);
7165 observed |= 1 << *k;
7166 }
7167 assert_eq!(observed, 0xFFFF_FFFF);
7168 }
7169
7170 #[test]
7171 fn test_keys() {
7172 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
7173 let map: HashMap<_, _> = vec.into_iter().collect();
7174 let keys: Vec<_> = map.keys().copied().collect();
7175 assert_eq!(keys.len(), 3);
7176 assert!(keys.contains(&1));
7177 assert!(keys.contains(&2));
7178 assert!(keys.contains(&3));
7179 }
7180
7181 #[test]
7182 fn test_values() {
7183 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
7184 let map: HashMap<_, _> = vec.into_iter().collect();
7185 let values: Vec<_> = map.values().copied().collect();
7186 assert_eq!(values.len(), 3);
7187 assert!(values.contains(&'a'));
7188 assert!(values.contains(&'b'));
7189 assert!(values.contains(&'c'));
7190 }
7191
7192 #[test]
7193 fn test_values_mut() {
7194 let vec = vec![(1, 1), (2, 2), (3, 3)];
7195 let mut map: HashMap<_, _> = vec.into_iter().collect();
7196 for value in map.values_mut() {
7197 *value *= 2;
7198 }
7199 let values: Vec<_> = map.values().copied().collect();
7200 assert_eq!(values.len(), 3);
7201 assert!(values.contains(&2));
7202 assert!(values.contains(&4));
7203 assert!(values.contains(&6));
7204 }
7205
7206 #[test]
7207 fn test_into_keys() {
7208 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
7209 let map: HashMap<_, _> = vec.into_iter().collect();
7210 let keys: Vec<_> = map.into_keys().collect();
7211
7212 assert_eq!(keys.len(), 3);
7213 assert!(keys.contains(&1));
7214 assert!(keys.contains(&2));
7215 assert!(keys.contains(&3));
7216 }
7217
7218 #[test]
7219 fn test_into_values() {
7220 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
7221 let map: HashMap<_, _> = vec.into_iter().collect();
7222 let values: Vec<_> = map.into_values().collect();
7223
7224 assert_eq!(values.len(), 3);
7225 assert!(values.contains(&'a'));
7226 assert!(values.contains(&'b'));
7227 assert!(values.contains(&'c'));
7228 }
7229
7230 #[test]
7231 fn test_find() {
7232 let mut m = HashMap::new();
7233 assert!(m.get(&1).is_none());
7234 m.insert(1, 2);
7235 match m.get(&1) {
7236 None => panic!(),
7237 Some(v) => assert_eq!(*v, 2),
7238 }
7239 }
7240
7241 #[test]
7242 fn test_eq() {
7243 let mut m1 = HashMap::new();
7244 m1.insert(1, 2);
7245 m1.insert(2, 3);
7246 m1.insert(3, 4);
7247
7248 let mut m2 = HashMap::new();
7249 m2.insert(1, 2);
7250 m2.insert(2, 3);
7251
7252 assert!(m1 != m2);
7253
7254 m2.insert(3, 4);
7255
7256 assert_eq!(m1, m2);
7257 }
7258
7259 #[test]
7260 fn test_show() {
7261 let mut map = HashMap::new();
7262 let empty: HashMap<i32, i32> = HashMap::new();
7263
7264 map.insert(1, 2);
7265 map.insert(3, 4);
7266
7267 let map_str = format!("{map:?}");
7268
7269 assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
7270 assert_eq!(format!("{empty:?}"), "{}");
7271 }
7272
7273 #[test]
7274 fn test_expand() {
7275 let mut m = HashMap::new();
7276
7277 assert_eq!(m.len(), 0);
7278 assert!(m.is_empty());
7279
7280 let mut i = 0;
7281 let old_raw_cap = m.raw_capacity();
7282 while old_raw_cap == m.raw_capacity() {
7283 m.insert(i, i);
7284 i += 1;
7285 }
7286
7287 assert_eq!(m.len(), i);
7288 assert!(!m.is_empty());
7289 }
7290
7291 #[test]
7292 fn test_behavior_resize_policy() {
7293 let mut m = HashMap::new();
7294
7295 assert_eq!(m.len(), 0);
7296 assert_eq!(m.raw_capacity(), 1);
7297 assert!(m.is_empty());
7298
7299 m.insert(0, 0);
7300 m.remove(&0);
7301 assert!(m.is_empty());
7302 let initial_raw_cap = m.raw_capacity();
7303 m.reserve(initial_raw_cap);
7304 let raw_cap = m.raw_capacity();
7305
7306 assert_eq!(raw_cap, initial_raw_cap * 2);
7307
7308 let mut i = 0;
7309 for _ in 0..raw_cap * 3 / 4 {
7310 m.insert(i, i);
7311 i += 1;
7312 }
7313 // three quarters full
7314
7315 assert_eq!(m.len(), i);
7316 assert_eq!(m.raw_capacity(), raw_cap);
7317
7318 for _ in 0..raw_cap / 4 {
7319 m.insert(i, i);
7320 i += 1;
7321 }
7322 // half full
7323
7324 let new_raw_cap = m.raw_capacity();
7325 assert_eq!(new_raw_cap, raw_cap * 2);
7326
7327 for _ in 0..raw_cap / 2 - 1 {
7328 i -= 1;
7329 m.remove(&i);
7330 assert_eq!(m.raw_capacity(), new_raw_cap);
7331 }
7332 // A little more than one quarter full.
7333 m.shrink_to_fit();
7334 assert_eq!(m.raw_capacity(), raw_cap);
7335 // again, a little more than half full
7336 for _ in 0..raw_cap / 2 {
7337 i -= 1;
7338 m.remove(&i);
7339 }
7340 m.shrink_to_fit();
7341
7342 assert_eq!(m.len(), i);
7343 assert!(!m.is_empty());
7344 assert_eq!(m.raw_capacity(), initial_raw_cap);
7345 }
7346
7347 #[test]
7348 fn test_reserve_shrink_to_fit() {
7349 let mut m = HashMap::new();
7350 m.insert(0, 0);
7351 m.remove(&0);
7352 assert!(m.capacity() >= m.len());
7353 for i in 0..128 {
7354 m.insert(i, i);
7355 }
7356 m.reserve(256);
7357
7358 let usable_cap = m.capacity();
7359 for i in 128..(128 + 256) {
7360 m.insert(i, i);
7361 assert_eq!(m.capacity(), usable_cap);
7362 }
7363
7364 for i in 100..(128 + 256) {
7365 assert_eq!(m.remove(&i), Some(i));
7366 }
7367 m.shrink_to_fit();
7368
7369 assert_eq!(m.len(), 100);
7370 assert!(!m.is_empty());
7371 assert!(m.capacity() >= m.len());
7372
7373 for i in 0..100 {
7374 assert_eq!(m.remove(&i), Some(i));
7375 }
7376 m.shrink_to_fit();
7377 m.insert(0, 0);
7378
7379 assert_eq!(m.len(), 1);
7380 assert!(m.capacity() >= m.len());
7381 assert_eq!(m.remove(&0), Some(0));
7382 }
7383
7384 #[test]
7385 fn test_from_iter() {
7386 let xs = [(1, 1), (2, 2), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7387
7388 let map: HashMap<_, _> = xs.iter().copied().collect();
7389
7390 for &(k, v) in &xs {
7391 assert_eq!(map.get(&k), Some(&v));
7392 }
7393
7394 assert_eq!(map.iter().len(), xs.len() - 1);
7395 }
7396
7397 #[test]
7398 fn test_size_hint() {
7399 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7400
7401 let map: HashMap<_, _> = xs.iter().copied().collect();
7402
7403 let mut iter = map.iter();
7404
7405 for _ in iter.by_ref().take(3) {}
7406
7407 assert_eq!(iter.size_hint(), (3, Some(3)));
7408 }
7409
7410 #[test]
7411 fn test_iter_len() {
7412 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7413
7414 let map: HashMap<_, _> = xs.iter().copied().collect();
7415
7416 let mut iter = map.iter();
7417
7418 for _ in iter.by_ref().take(3) {}
7419
7420 assert_eq!(iter.len(), 3);
7421 }
7422
7423 #[test]
7424 fn test_mut_size_hint() {
7425 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7426
7427 let mut map: HashMap<_, _> = xs.iter().copied().collect();
7428
7429 let mut iter = map.iter_mut();
7430
7431 for _ in iter.by_ref().take(3) {}
7432
7433 assert_eq!(iter.size_hint(), (3, Some(3)));
7434 }
7435
7436 #[test]
7437 fn test_iter_mut_len() {
7438 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
7439
7440 let mut map: HashMap<_, _> = xs.iter().copied().collect();
7441
7442 let mut iter = map.iter_mut();
7443
7444 for _ in iter.by_ref().take(3) {}
7445
7446 assert_eq!(iter.len(), 3);
7447 }
7448
7449 #[test]
7450 fn test_index() {
7451 let mut map = HashMap::new();
7452
7453 map.insert(1, 2);
7454 map.insert(2, 1);
7455 map.insert(3, 4);
7456
7457 assert_eq!(map[&2], 1);
7458 }
7459
7460 #[test]
7461 #[should_panic]
7462 fn test_index_nonexistent() {
7463 let mut map = HashMap::new();
7464
7465 map.insert(1, 2);
7466 map.insert(2, 1);
7467 map.insert(3, 4);
7468
7469 #[allow(clippy::no_effect)] // false positive lint
7470 map[&4];
7471 }
7472
7473 #[test]
7474 fn test_entry() {
7475 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
7476
7477 let mut map: HashMap<_, _> = xs.iter().copied().collect();
7478
7479 // Existing key (insert)
7480 match map.entry(1) {
7481 Vacant(_) => unreachable!(),
7482 Occupied(mut view) => {
7483 assert_eq!(view.get(), &10);
7484 assert_eq!(view.insert(100), 10);
7485 }
7486 }
7487 assert_eq!(map.get(&1).unwrap(), &100);
7488 assert_eq!(map.len(), 6);
7489
7490 // Existing key (update)
7491 match map.entry(2) {
7492 Vacant(_) => unreachable!(),
7493 Occupied(mut view) => {
7494 let v = view.get_mut();
7495 let new_v = (*v) * 10;
7496 *v = new_v;
7497 }
7498 }
7499 assert_eq!(map.get(&2).unwrap(), &200);
7500 assert_eq!(map.len(), 6);
7501
7502 // Existing key (take)
7503 match map.entry(3) {
7504 Vacant(_) => unreachable!(),
7505 Occupied(view) => {
7506 assert_eq!(view.remove(), 30);
7507 }
7508 }
7509 assert_eq!(map.get(&3), None);
7510 assert_eq!(map.len(), 5);
7511
7512 // Inexistent key (insert)
7513 match map.entry(10) {
7514 Occupied(_) => unreachable!(),
7515 Vacant(view) => {
7516 assert_eq!(*view.insert(1000), 1000);
7517 }
7518 }
7519 assert_eq!(map.get(&10).unwrap(), &1000);
7520 assert_eq!(map.len(), 6);
7521 }
7522
7523 #[test]
7524 fn test_entry_ref() {
7525 let xs = [
7526 ("One".to_owned(), 10),
7527 ("Two".to_owned(), 20),
7528 ("Three".to_owned(), 30),
7529 ("Four".to_owned(), 40),
7530 ("Five".to_owned(), 50),
7531 ("Six".to_owned(), 60),
7532 ];
7533
7534 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
7535
7536 // Existing key (insert)
7537 match map.entry_ref("One") {
7538 EntryRef::Vacant(_) => unreachable!(),
7539 EntryRef::Occupied(mut view) => {
7540 assert_eq!(view.get(), &10);
7541 assert_eq!(view.insert(100), 10);
7542 }
7543 }
7544 assert_eq!(map.get("One").unwrap(), &100);
7545 assert_eq!(map.len(), 6);
7546
7547 // Existing key (update)
7548 match map.entry_ref("Two") {
7549 EntryRef::Vacant(_) => unreachable!(),
7550 EntryRef::Occupied(mut view) => {
7551 let v = view.get_mut();
7552 let new_v = (*v) * 10;
7553 *v = new_v;
7554 }
7555 }
7556 assert_eq!(map.get("Two").unwrap(), &200);
7557 assert_eq!(map.len(), 6);
7558
7559 // Existing key (take)
7560 match map.entry_ref("Three") {
7561 EntryRef::Vacant(_) => unreachable!(),
7562 EntryRef::Occupied(view) => {
7563 assert_eq!(view.remove(), 30);
7564 }
7565 }
7566 assert_eq!(map.get("Three"), None);
7567 assert_eq!(map.len(), 5);
7568
7569 // Inexistent key (insert)
7570 match map.entry_ref("Ten") {
7571 EntryRef::Occupied(_) => unreachable!(),
7572 EntryRef::Vacant(view) => {
7573 assert_eq!(*view.insert(1000), 1000);
7574 }
7575 }
7576 assert_eq!(map.get("Ten").unwrap(), &1000);
7577 assert_eq!(map.len(), 6);
7578 }
7579
7580 #[test]
7581 fn test_entry_take_doesnt_corrupt() {
7582 #![allow(deprecated)] //rand
7583 // Test for #19292
7584 fn check(m: &HashMap<i32, ()>) {
7585 for k in m.keys() {
7586 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
7587 }
7588 }
7589
7590 let mut m = HashMap::new();
7591
7592 let mut rng = {
7593 let seed = u64::from_le_bytes(*b"testseed");
7594 SmallRng::seed_from_u64(seed)
7595 };
7596
7597 // Populate the map with some items.
7598 for _ in 0..50 {
7599 let x = rng.gen_range(-10..10);
7600 m.insert(x, ());
7601 }
7602
7603 for _ in 0..1000 {
7604 let x = rng.gen_range(-10..10);
7605 match m.entry(x) {
7606 Vacant(_) => {}
7607 Occupied(e) => {
7608 e.remove();
7609 }
7610 }
7611
7612 check(&m);
7613 }
7614 }
7615
7616 #[test]
7617 fn test_entry_ref_take_doesnt_corrupt() {
7618 #![allow(deprecated)] //rand
7619 // Test for #19292
7620 fn check(m: &HashMap<std::string::String, ()>) {
7621 for k in m.keys() {
7622 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
7623 }
7624 }
7625
7626 let mut m = HashMap::new();
7627
7628 let mut rng = {
7629 let seed = u64::from_le_bytes(*b"testseed");
7630 SmallRng::seed_from_u64(seed)
7631 };
7632
7633 // Populate the map with some items.
7634 for _ in 0..50 {
7635 let mut x = std::string::String::with_capacity(1);
7636 x.push(rng.gen_range('a'..='z'));
7637 m.insert(x, ());
7638 }
7639
7640 for _ in 0..1000 {
7641 let mut x = std::string::String::with_capacity(1);
7642 x.push(rng.gen_range('a'..='z'));
7643 match m.entry_ref(x.as_str()) {
7644 EntryRef::Vacant(_) => {}
7645 EntryRef::Occupied(e) => {
7646 e.remove();
7647 }
7648 }
7649
7650 check(&m);
7651 }
7652 }
7653
7654 #[test]
7655 fn test_extend_ref_k_ref_v() {
7656 let mut a = HashMap::new();
7657 a.insert(1, "one");
7658 let mut b = HashMap::new();
7659 b.insert(2, "two");
7660 b.insert(3, "three");
7661
7662 a.extend(&b);
7663
7664 assert_eq!(a.len(), 3);
7665 assert_eq!(a[&1], "one");
7666 assert_eq!(a[&2], "two");
7667 assert_eq!(a[&3], "three");
7668 }
7669
7670 #[test]
7671 #[allow(clippy::needless_borrow)]
7672 fn test_extend_ref_kv_tuple() {
7673 use std::ops::AddAssign;
7674 let mut a = HashMap::new();
7675 a.insert(0, 0);
7676
7677 fn create_arr<T: AddAssign<T> + Copy, const N: usize>(start: T, step: T) -> [(T, T); N] {
7678 let mut outs: [(T, T); N] = [(start, start); N];
7679 let mut element = step;
7680 outs.iter_mut().skip(1).for_each(|(k, v)| {
7681 *k += element;
7682 *v += element;
7683 element += step;
7684 });
7685 outs
7686 }
7687
7688 let for_iter: Vec<_> = (0..100).map(|i| (i, i)).collect();
7689 let iter = for_iter.iter();
7690 let vec: Vec<_> = (100..200).map(|i| (i, i)).collect();
7691 a.extend(iter);
7692 a.extend(&vec);
7693 a.extend(create_arr::<i32, 100>(200, 1));
7694
7695 assert_eq!(a.len(), 300);
7696
7697 for item in 0..300 {
7698 assert_eq!(a[&item], item);
7699 }
7700 }
7701
7702 #[test]
7703 fn test_capacity_not_less_than_len() {
7704 let mut a = HashMap::new();
7705 let mut item = 0;
7706
7707 for _ in 0..116 {
7708 a.insert(item, 0);
7709 item += 1;
7710 }
7711
7712 assert!(a.capacity() > a.len());
7713
7714 let free = a.capacity() - a.len();
7715 for _ in 0..free {
7716 a.insert(item, 0);
7717 item += 1;
7718 }
7719
7720 assert_eq!(a.len(), a.capacity());
7721
7722 // Insert at capacity should cause allocation.
7723 a.insert(item, 0);
7724 assert!(a.capacity() > a.len());
7725 }
7726
7727 #[test]
7728 fn test_occupied_entry_key() {
7729 let mut a = HashMap::new();
7730 let key = "hello there";
7731 let value = "value goes here";
7732 assert!(a.is_empty());
7733 a.insert(key, value);
7734 assert_eq!(a.len(), 1);
7735 assert_eq!(a[key], value);
7736
7737 match a.entry(key) {
7738 Vacant(_) => panic!(),
7739 Occupied(e) => assert_eq!(key, *e.key()),
7740 }
7741 assert_eq!(a.len(), 1);
7742 assert_eq!(a[key], value);
7743 }
7744
7745 #[test]
7746 fn test_occupied_entry_ref_key() {
7747 let mut a = HashMap::new();
7748 let key = "hello there";
7749 let value = "value goes here";
7750 assert!(a.is_empty());
7751 a.insert(key.to_owned(), value);
7752 assert_eq!(a.len(), 1);
7753 assert_eq!(a[key], value);
7754
7755 match a.entry_ref(key) {
7756 EntryRef::Vacant(_) => panic!(),
7757 EntryRef::Occupied(e) => assert_eq!(key, e.key()),
7758 }
7759 assert_eq!(a.len(), 1);
7760 assert_eq!(a[key], value);
7761 }
7762
7763 #[test]
7764 fn test_vacant_entry_key() {
7765 let mut a = HashMap::new();
7766 let key = "hello there";
7767 let value = "value goes here";
7768
7769 assert!(a.is_empty());
7770 match a.entry(key) {
7771 Occupied(_) => panic!(),
7772 Vacant(e) => {
7773 assert_eq!(key, *e.key());
7774 e.insert(value);
7775 }
7776 }
7777 assert_eq!(a.len(), 1);
7778 assert_eq!(a[key], value);
7779 }
7780
7781 #[test]
7782 fn test_vacant_entry_ref_key() {
7783 let mut a: HashMap<std::string::String, &str> = HashMap::new();
7784 let key = "hello there";
7785 let value = "value goes here";
7786
7787 assert!(a.is_empty());
7788 match a.entry_ref(key) {
7789 EntryRef::Occupied(_) => panic!(),
7790 EntryRef::Vacant(e) => {
7791 assert_eq!(key, e.key());
7792 e.insert(value);
7793 }
7794 }
7795 assert_eq!(a.len(), 1);
7796 assert_eq!(a[key], value);
7797 }
7798
7799 #[test]
7800 fn test_occupied_entry_replace_entry_with() {
7801 let mut a = HashMap::new();
7802
7803 let key = "a key";
7804 let value = "an initial value";
7805 let new_value = "a new value";
7806
7807 let entry = a.entry(key).insert(value).replace_entry_with(|k, v| {
7808 assert_eq!(k, &key);
7809 assert_eq!(v, value);
7810 Some(new_value)
7811 });
7812
7813 match entry {
7814 Occupied(e) => {
7815 assert_eq!(e.key(), &key);
7816 assert_eq!(e.get(), &new_value);
7817 }
7818 Vacant(_) => panic!(),
7819 }
7820
7821 assert_eq!(a[key], new_value);
7822 assert_eq!(a.len(), 1);
7823
7824 let entry = match a.entry(key) {
7825 Occupied(e) => e.replace_entry_with(|k, v| {
7826 assert_eq!(k, &key);
7827 assert_eq!(v, new_value);
7828 None
7829 }),
7830 Vacant(_) => panic!(),
7831 };
7832
7833 match entry {
7834 Vacant(e) => assert_eq!(e.key(), &key),
7835 Occupied(_) => panic!(),
7836 }
7837
7838 assert!(!a.contains_key(key));
7839 assert_eq!(a.len(), 0);
7840 }
7841
7842 #[test]
7843 fn test_occupied_entry_ref_replace_entry_with() {
7844 let mut a: HashMap<std::string::String, &str> = HashMap::new();
7845
7846 let key = "a key";
7847 let value = "an initial value";
7848 let new_value = "a new value";
7849
7850 let entry = a.entry_ref(key).insert(value).replace_entry_with(|k, v| {
7851 assert_eq!(k, key);
7852 assert_eq!(v, value);
7853 Some(new_value)
7854 });
7855
7856 match entry {
7857 EntryRef::Occupied(e) => {
7858 assert_eq!(e.key(), key);
7859 assert_eq!(e.get(), &new_value);
7860 }
7861 EntryRef::Vacant(_) => panic!(),
7862 }
7863
7864 assert_eq!(a[key], new_value);
7865 assert_eq!(a.len(), 1);
7866
7867 let entry = match a.entry_ref(key) {
7868 EntryRef::Occupied(e) => e.replace_entry_with(|k, v| {
7869 assert_eq!(k, key);
7870 assert_eq!(v, new_value);
7871 None
7872 }),
7873 EntryRef::Vacant(_) => panic!(),
7874 };
7875
7876 match entry {
7877 EntryRef::Vacant(e) => assert_eq!(e.key(), key),
7878 EntryRef::Occupied(_) => panic!(),
7879 }
7880
7881 assert!(!a.contains_key(key));
7882 assert_eq!(a.len(), 0);
7883 }
7884
7885 #[test]
7886 fn test_entry_and_replace_entry_with() {
7887 let mut a = HashMap::new();
7888
7889 let key = "a key";
7890 let value = "an initial value";
7891 let new_value = "a new value";
7892
7893 let entry = a.entry(key).and_replace_entry_with(|_, _| panic!());
7894
7895 match entry {
7896 Vacant(e) => assert_eq!(e.key(), &key),
7897 Occupied(_) => panic!(),
7898 }
7899
7900 a.insert(key, value);
7901
7902 let entry = a.entry(key).and_replace_entry_with(|k, v| {
7903 assert_eq!(k, &key);
7904 assert_eq!(v, value);
7905 Some(new_value)
7906 });
7907
7908 match entry {
7909 Occupied(e) => {
7910 assert_eq!(e.key(), &key);
7911 assert_eq!(e.get(), &new_value);
7912 }
7913 Vacant(_) => panic!(),
7914 }
7915
7916 assert_eq!(a[key], new_value);
7917 assert_eq!(a.len(), 1);
7918
7919 let entry = a.entry(key).and_replace_entry_with(|k, v| {
7920 assert_eq!(k, &key);
7921 assert_eq!(v, new_value);
7922 None
7923 });
7924
7925 match entry {
7926 Vacant(e) => assert_eq!(e.key(), &key),
7927 Occupied(_) => panic!(),
7928 }
7929
7930 assert!(!a.contains_key(key));
7931 assert_eq!(a.len(), 0);
7932 }
7933
7934 #[test]
7935 fn test_entry_ref_and_replace_entry_with() {
7936 let mut a = HashMap::new();
7937
7938 let key = "a key";
7939 let value = "an initial value";
7940 let new_value = "a new value";
7941
7942 let entry = a.entry_ref(key).and_replace_entry_with(|_, _| panic!());
7943
7944 match entry {
7945 EntryRef::Vacant(e) => assert_eq!(e.key(), key),
7946 EntryRef::Occupied(_) => panic!(),
7947 }
7948
7949 a.insert(key.to_owned(), value);
7950
7951 let entry = a.entry_ref(key).and_replace_entry_with(|k, v| {
7952 assert_eq!(k, key);
7953 assert_eq!(v, value);
7954 Some(new_value)
7955 });
7956
7957 match entry {
7958 EntryRef::Occupied(e) => {
7959 assert_eq!(e.key(), key);
7960 assert_eq!(e.get(), &new_value);
7961 }
7962 EntryRef::Vacant(_) => panic!(),
7963 }
7964
7965 assert_eq!(a[key], new_value);
7966 assert_eq!(a.len(), 1);
7967
7968 let entry = a.entry_ref(key).and_replace_entry_with(|k, v| {
7969 assert_eq!(k, key);
7970 assert_eq!(v, new_value);
7971 None
7972 });
7973
7974 match entry {
7975 EntryRef::Vacant(e) => assert_eq!(e.key(), key),
7976 EntryRef::Occupied(_) => panic!(),
7977 }
7978
7979 assert!(!a.contains_key(key));
7980 assert_eq!(a.len(), 0);
7981 }
7982
7983 #[test]
7984 fn test_raw_occupied_entry_replace_entry_with() {
7985 let mut a = HashMap::new();
7986
7987 let key = "a key";
7988 let value = "an initial value";
7989 let new_value = "a new value";
7990
7991 let entry = a
7992 .raw_entry_mut()
7993 .from_key(&key)
7994 .insert(key, value)
7995 .replace_entry_with(|k, v| {
7996 assert_eq!(k, &key);
7997 assert_eq!(v, value);
7998 Some(new_value)
7999 });
8000
8001 match entry {
8002 RawEntryMut::Occupied(e) => {
8003 assert_eq!(e.key(), &key);
8004 assert_eq!(e.get(), &new_value);
8005 }
8006 RawEntryMut::Vacant(_) => panic!(),
8007 }
8008
8009 assert_eq!(a[key], new_value);
8010 assert_eq!(a.len(), 1);
8011
8012 let entry = match a.raw_entry_mut().from_key(&key) {
8013 RawEntryMut::Occupied(e) => e.replace_entry_with(|k, v| {
8014 assert_eq!(k, &key);
8015 assert_eq!(v, new_value);
8016 None
8017 }),
8018 RawEntryMut::Vacant(_) => panic!(),
8019 };
8020
8021 match entry {
8022 RawEntryMut::Vacant(_) => {}
8023 RawEntryMut::Occupied(_) => panic!(),
8024 }
8025
8026 assert!(!a.contains_key(key));
8027 assert_eq!(a.len(), 0);
8028 }
8029
8030 #[test]
8031 fn test_raw_entry_and_replace_entry_with() {
8032 let mut a = HashMap::new();
8033
8034 let key = "a key";
8035 let value = "an initial value";
8036 let new_value = "a new value";
8037
8038 let entry = a
8039 .raw_entry_mut()
8040 .from_key(&key)
8041 .and_replace_entry_with(|_, _| panic!());
8042
8043 match entry {
8044 RawEntryMut::Vacant(_) => {}
8045 RawEntryMut::Occupied(_) => panic!(),
8046 }
8047
8048 a.insert(key, value);
8049
8050 let entry = a
8051 .raw_entry_mut()
8052 .from_key(&key)
8053 .and_replace_entry_with(|k, v| {
8054 assert_eq!(k, &key);
8055 assert_eq!(v, value);
8056 Some(new_value)
8057 });
8058
8059 match entry {
8060 RawEntryMut::Occupied(e) => {
8061 assert_eq!(e.key(), &key);
8062 assert_eq!(e.get(), &new_value);
8063 }
8064 RawEntryMut::Vacant(_) => panic!(),
8065 }
8066
8067 assert_eq!(a[key], new_value);
8068 assert_eq!(a.len(), 1);
8069
8070 let entry = a
8071 .raw_entry_mut()
8072 .from_key(&key)
8073 .and_replace_entry_with(|k, v| {
8074 assert_eq!(k, &key);
8075 assert_eq!(v, new_value);
8076 None
8077 });
8078
8079 match entry {
8080 RawEntryMut::Vacant(_) => {}
8081 RawEntryMut::Occupied(_) => panic!(),
8082 }
8083
8084 assert!(!a.contains_key(key));
8085 assert_eq!(a.len(), 0);
8086 }
8087
8088 #[test]
8089 fn test_replace_entry_with_doesnt_corrupt() {
8090 #![allow(deprecated)] //rand
8091 // Test for #19292
8092 fn check(m: &HashMap<i32, ()>) {
8093 for k in m.keys() {
8094 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
8095 }
8096 }
8097
8098 let mut m = HashMap::new();
8099
8100 let mut rng = {
8101 let seed = u64::from_le_bytes(*b"testseed");
8102 SmallRng::seed_from_u64(seed)
8103 };
8104
8105 // Populate the map with some items.
8106 for _ in 0..50 {
8107 let x = rng.gen_range(-10..10);
8108 m.insert(x, ());
8109 }
8110
8111 for _ in 0..1000 {
8112 let x = rng.gen_range(-10..10);
8113 m.entry(x).and_replace_entry_with(|_, _| None);
8114 check(&m);
8115 }
8116 }
8117
8118 #[test]
8119 fn test_replace_entry_ref_with_doesnt_corrupt() {
8120 #![allow(deprecated)] //rand
8121 // Test for #19292
8122 fn check(m: &HashMap<std::string::String, ()>) {
8123 for k in m.keys() {
8124 assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
8125 }
8126 }
8127
8128 let mut m = HashMap::new();
8129
8130 let mut rng = {
8131 let seed = u64::from_le_bytes(*b"testseed");
8132 SmallRng::seed_from_u64(seed)
8133 };
8134
8135 // Populate the map with some items.
8136 for _ in 0..50 {
8137 let mut x = std::string::String::with_capacity(1);
8138 x.push(rng.gen_range('a'..='z'));
8139 m.insert(x, ());
8140 }
8141
8142 for _ in 0..1000 {
8143 let mut x = std::string::String::with_capacity(1);
8144 x.push(rng.gen_range('a'..='z'));
8145 m.entry_ref(x.as_str()).and_replace_entry_with(|_, _| None);
8146 check(&m);
8147 }
8148 }
8149
8150 #[test]
8151 fn test_retain() {
8152 let mut map: HashMap<i32, i32> = (0..100).map(|x| (x, x * 10)).collect();
8153
8154 map.retain(|&k, _| k % 2 == 0);
8155 assert_eq!(map.len(), 50);
8156 assert_eq!(map[&2], 20);
8157 assert_eq!(map[&4], 40);
8158 assert_eq!(map[&6], 60);
8159 }
8160
8161 #[test]
8162 fn test_extract_if() {
8163 {
8164 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
8165 let drained = map.extract_if(|&k, _| k % 2 == 0);
8166 let mut out = drained.collect::<Vec<_>>();
8167 out.sort_unstable();
8168 assert_eq!(vec![(0, 0), (2, 20), (4, 40), (6, 60)], out);
8169 assert_eq!(map.len(), 4);
8170 }
8171 {
8172 let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x * 10)).collect();
8173 map.extract_if(|&k, _| k % 2 == 0).for_each(drop);
8174 assert_eq!(map.len(), 4);
8175 }
8176 }
8177
8178 #[test]
8179 #[cfg_attr(miri, ignore)] // FIXME: no OOM signalling (https://github.com/rust-lang/miri/issues/613)
8180 fn test_try_reserve() {
8181 use crate::TryReserveError::{AllocError, CapacityOverflow};
8182
8183 const MAX_ISIZE: usize = isize::MAX as usize;
8184
8185 let mut empty_bytes: HashMap<u8, u8> = HashMap::new();
8186
8187 if let Err(CapacityOverflow) = empty_bytes.try_reserve(usize::MAX) {
8188 } else {
8189 panic!("usize::MAX should trigger an overflow!");
8190 }
8191
8192 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_ISIZE) {
8193 } else {
8194 panic!("isize::MAX should trigger an overflow!");
8195 }
8196
8197 if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_ISIZE / 5) {
8198 } else {
8199 // This may succeed if there is enough free memory. Attempt to
8200 // allocate a few more hashmaps to ensure the allocation will fail.
8201 let mut empty_bytes2: HashMap<u8, u8> = HashMap::new();
8202 let _ = empty_bytes2.try_reserve(MAX_ISIZE / 5);
8203 let mut empty_bytes3: HashMap<u8, u8> = HashMap::new();
8204 let _ = empty_bytes3.try_reserve(MAX_ISIZE / 5);
8205 let mut empty_bytes4: HashMap<u8, u8> = HashMap::new();
8206 if let Err(AllocError { .. }) = empty_bytes4.try_reserve(MAX_ISIZE / 5) {
8207 } else {
8208 panic!("isize::MAX / 5 should trigger an OOM!");
8209 }
8210 }
8211 }
8212
8213 #[test]
8214 fn test_raw_entry() {
8215 use super::RawEntryMut::{Occupied, Vacant};
8216
8217 let xs = [(1_i32, 10_i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
8218
8219 let mut map: HashMap<_, _> = xs.iter().copied().collect();
8220
8221 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
8222 super::make_hash::<i32, _>(map.hasher(), &k)
8223 };
8224
8225 // Existing key (insert)
8226 match map.raw_entry_mut().from_key(&1) {
8227 Vacant(_) => unreachable!(),
8228 Occupied(mut view) => {
8229 assert_eq!(view.get(), &10);
8230 assert_eq!(view.insert(100), 10);
8231 }
8232 }
8233 let hash1 = compute_hash(&map, 1);
8234 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
8235 assert_eq!(
8236 map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(),
8237 (&1, &100)
8238 );
8239 assert_eq!(
8240 map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(),
8241 (&1, &100)
8242 );
8243 assert_eq!(map.len(), 6);
8244
8245 // Existing key (update)
8246 match map.raw_entry_mut().from_key(&2) {
8247 Vacant(_) => unreachable!(),
8248 Occupied(mut view) => {
8249 let v = view.get_mut();
8250 let new_v = (*v) * 10;
8251 *v = new_v;
8252 }
8253 }
8254 let hash2 = compute_hash(&map, 2);
8255 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
8256 assert_eq!(
8257 map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(),
8258 (&2, &200)
8259 );
8260 assert_eq!(
8261 map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(),
8262 (&2, &200)
8263 );
8264 assert_eq!(map.len(), 6);
8265
8266 // Existing key (take)
8267 let hash3 = compute_hash(&map, 3);
8268 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
8269 Vacant(_) => unreachable!(),
8270 Occupied(view) => {
8271 assert_eq!(view.remove_entry(), (3, 30));
8272 }
8273 }
8274 assert_eq!(map.raw_entry().from_key(&3), None);
8275 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
8276 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
8277 assert_eq!(map.len(), 5);
8278
8279 // Nonexistent key (insert)
8280 match map.raw_entry_mut().from_key(&10) {
8281 Occupied(_) => unreachable!(),
8282 Vacant(view) => {
8283 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
8284 }
8285 }
8286 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
8287 assert_eq!(map.len(), 6);
8288
8289 // Ensure all lookup methods produce equivalent results.
8290 for k in 0..12 {
8291 let hash = compute_hash(&map, k);
8292 let v = map.get(&k).copied();
8293 let kv = v.as_ref().map(|v| (&k, v));
8294
8295 assert_eq!(map.raw_entry().from_key(&k), kv);
8296 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
8297 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
8298
8299 match map.raw_entry_mut().from_key(&k) {
8300 Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
8301 Vacant(_) => assert_eq!(v, None),
8302 }
8303 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
8304 Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
8305 Vacant(_) => assert_eq!(v, None),
8306 }
8307 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
8308 Occupied(o) => assert_eq!(Some(o.get_key_value()), kv),
8309 Vacant(_) => assert_eq!(v, None),
8310 }
8311 }
8312 }
8313
8314 #[test]
8315 fn test_key_without_hash_impl() {
8316 #[derive(Debug)]
8317 struct IntWrapper(u64);
8318
8319 let mut m: HashMap<IntWrapper, (), ()> = HashMap::default();
8320 {
8321 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none());
8322 }
8323 {
8324 let vacant_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) {
8325 RawEntryMut::Occupied(..) => panic!("Found entry for key 0"),
8326 RawEntryMut::Vacant(e) => e,
8327 };
8328 vacant_entry.insert_with_hasher(0, IntWrapper(0), (), |k| k.0);
8329 }
8330 {
8331 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some());
8332 assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_none());
8333 assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
8334 }
8335 {
8336 let vacant_entry = match m.raw_entry_mut().from_hash(1, |k| k.0 == 1) {
8337 RawEntryMut::Occupied(..) => panic!("Found entry for key 1"),
8338 RawEntryMut::Vacant(e) => e,
8339 };
8340 vacant_entry.insert_with_hasher(1, IntWrapper(1), (), |k| k.0);
8341 }
8342 {
8343 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_some());
8344 assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some());
8345 assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
8346 }
8347 {
8348 let occupied_entry = match m.raw_entry_mut().from_hash(0, |k| k.0 == 0) {
8349 RawEntryMut::Occupied(e) => e,
8350 RawEntryMut::Vacant(..) => panic!("Couldn't find entry for key 0"),
8351 };
8352 occupied_entry.remove();
8353 }
8354 assert!(m.raw_entry().from_hash(0, |k| k.0 == 0).is_none());
8355 assert!(m.raw_entry().from_hash(1, |k| k.0 == 1).is_some());
8356 assert!(m.raw_entry().from_hash(2, |k| k.0 == 2).is_none());
8357 }
8358
8359 #[test]
8360 #[cfg(feature = "raw")]
8361 fn test_into_iter_refresh() {
8362 #[cfg(miri)]
8363 const N: usize = 32;
8364 #[cfg(not(miri))]
8365 const N: usize = 128;
8366
8367 let mut rng = rand::thread_rng();
8368 for n in 0..N {
8369 let mut map = HashMap::new();
8370 for i in 0..n {
8371 assert!(map.insert(i, 2 * i).is_none());
8372 }
8373 let hash_builder = map.hasher().clone();
8374
8375 let mut it = unsafe { map.table.iter() };
8376 assert_eq!(it.len(), n);
8377
8378 let mut i = 0;
8379 let mut left = n;
8380 let mut removed = Vec::new();
8381 loop {
8382 // occasionally remove some elements
8383 if i < n && rng.gen_bool(0.1) {
8384 let hash_value = super::make_hash(&hash_builder, &i);
8385
8386 unsafe {
8387 let e = map.table.find(hash_value, |q| q.0.eq(&i));
8388 if let Some(e) = e {
8389 it.reflect_remove(&e);
8390 let t = map.table.remove(e).0;
8391 removed.push(t);
8392 left -= 1;
8393 } else {
8394 assert!(removed.contains(&(i, 2 * i)), "{i} not in {removed:?}");
8395 let e = map.table.insert(
8396 hash_value,
8397 (i, 2 * i),
8398 super::make_hasher::<_, usize, _>(&hash_builder),
8399 );
8400 it.reflect_insert(&e);
8401 if let Some(p) = removed.iter().position(|e| e == &(i, 2 * i)) {
8402 removed.swap_remove(p);
8403 }
8404 left += 1;
8405 }
8406 }
8407 }
8408
8409 let e = it.next();
8410 if e.is_none() {
8411 break;
8412 }
8413 assert!(i < n);
8414 let t = unsafe { e.unwrap().as_ref() };
8415 assert!(!removed.contains(t));
8416 let (key, value) = t;
8417 assert_eq!(*value, 2 * key);
8418 i += 1;
8419 }
8420 assert!(i <= n);
8421
8422 // just for safety:
8423 assert_eq!(map.table.len(), left);
8424 }
8425 }
8426
8427 #[test]
8428 fn test_const_with_hasher() {
8429 use core::hash::BuildHasher;
8430 use std::collections::hash_map::DefaultHasher;
8431
8432 #[derive(Clone)]
8433 struct MyHasher;
8434 impl BuildHasher for MyHasher {
8435 type Hasher = DefaultHasher;
8436
8437 fn build_hasher(&self) -> DefaultHasher {
8438 DefaultHasher::new()
8439 }
8440 }
8441
8442 const EMPTY_MAP: HashMap<u32, std::string::String, MyHasher> =
8443 HashMap::with_hasher(MyHasher);
8444
8445 let mut map = EMPTY_MAP;
8446 map.insert(17, "seventeen".to_owned());
8447 assert_eq!("seventeen", map[&17]);
8448 }
8449
8450 #[test]
8451 fn test_get_each_mut() {
8452 let mut map = HashMap::new();
8453 map.insert("foo".to_owned(), 0);
8454 map.insert("bar".to_owned(), 10);
8455 map.insert("baz".to_owned(), 20);
8456 map.insert("qux".to_owned(), 30);
8457
8458 let xs = map.get_many_mut(["foo", "qux"]);
8459 assert_eq!(xs, Some([&mut 0, &mut 30]));
8460
8461 let xs = map.get_many_mut(["foo", "dud"]);
8462 assert_eq!(xs, None);
8463
8464 let xs = map.get_many_mut(["foo", "foo"]);
8465 assert_eq!(xs, None);
8466
8467 let ys = map.get_many_key_value_mut(["bar", "baz"]);
8468 assert_eq!(
8469 ys,
8470 Some([(&"bar".to_owned(), &mut 10), (&"baz".to_owned(), &mut 20),]),
8471 );
8472
8473 let ys = map.get_many_key_value_mut(["bar", "dip"]);
8474 assert_eq!(ys, None);
8475
8476 let ys = map.get_many_key_value_mut(["baz", "baz"]);
8477 assert_eq!(ys, None);
8478 }
8479
8480 #[test]
8481 #[should_panic = "panic in drop"]
8482 fn test_clone_from_double_drop() {
8483 #[derive(Clone)]
8484 struct CheckedDrop {
8485 panic_in_drop: bool,
8486 dropped: bool,
8487 }
8488 impl Drop for CheckedDrop {
8489 fn drop(&mut self) {
8490 if self.panic_in_drop {
8491 self.dropped = true;
8492 panic!("panic in drop");
8493 }
8494 if self.dropped {
8495 panic!("double drop");
8496 }
8497 self.dropped = true;
8498 }
8499 }
8500 const DISARMED: CheckedDrop = CheckedDrop {
8501 panic_in_drop: false,
8502 dropped: false,
8503 };
8504 const ARMED: CheckedDrop = CheckedDrop {
8505 panic_in_drop: true,
8506 dropped: false,
8507 };
8508
8509 let mut map1 = HashMap::new();
8510 map1.insert(1, DISARMED);
8511 map1.insert(2, DISARMED);
8512 map1.insert(3, DISARMED);
8513 map1.insert(4, DISARMED);
8514
8515 let mut map2 = HashMap::new();
8516 map2.insert(1, DISARMED);
8517 map2.insert(2, ARMED);
8518 map2.insert(3, DISARMED);
8519 map2.insert(4, DISARMED);
8520
8521 map2.clone_from(&map1);
8522 }
8523
8524 #[test]
8525 #[should_panic = "panic in clone"]
8526 fn test_clone_from_memory_leaks() {
8527 use ::alloc::vec::Vec;
8528
8529 struct CheckedClone {
8530 panic_in_clone: bool,
8531 need_drop: Vec<i32>,
8532 }
8533 impl Clone for CheckedClone {
8534 fn clone(&self) -> Self {
8535 if self.panic_in_clone {
8536 panic!("panic in clone")
8537 }
8538 Self {
8539 panic_in_clone: self.panic_in_clone,
8540 need_drop: self.need_drop.clone(),
8541 }
8542 }
8543 }
8544 let mut map1 = HashMap::new();
8545 map1.insert(
8546 1,
8547 CheckedClone {
8548 panic_in_clone: false,
8549 need_drop: vec![0, 1, 2],
8550 },
8551 );
8552 map1.insert(
8553 2,
8554 CheckedClone {
8555 panic_in_clone: false,
8556 need_drop: vec![3, 4, 5],
8557 },
8558 );
8559 map1.insert(
8560 3,
8561 CheckedClone {
8562 panic_in_clone: true,
8563 need_drop: vec![6, 7, 8],
8564 },
8565 );
8566 let _map2 = map1.clone();
8567 }
8568
8569 struct MyAllocInner {
8570 drop_count: Arc<AtomicI8>,
8571 }
8572
8573 #[derive(Clone)]
8574 struct MyAlloc {
8575 _inner: Arc<MyAllocInner>,
8576 }
8577
8578 impl MyAlloc {
8579 fn new(drop_count: Arc<AtomicI8>) -> Self {
8580 MyAlloc {
8581 _inner: Arc::new(MyAllocInner { drop_count }),
8582 }
8583 }
8584 }
8585
8586 impl Drop for MyAllocInner {
8587 fn drop(&mut self) {
8588 println!("MyAlloc freed.");
8589 self.drop_count.fetch_sub(1, Ordering::SeqCst);
8590 }
8591 }
8592
8593 unsafe impl Allocator for MyAlloc {
8594 fn allocate(&self, layout: Layout) -> std::result::Result<NonNull<[u8]>, AllocError> {
8595 let g = Global;
8596 g.allocate(layout)
8597 }
8598
8599 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
8600 let g = Global;
8601 g.deallocate(ptr, layout)
8602 }
8603 }
8604
8605 #[test]
8606 fn test_hashmap_into_iter_bug() {
8607 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(1));
8608
8609 {
8610 let mut map = HashMap::with_capacity_in(10, MyAlloc::new(dropped.clone()));
8611 for i in 0..10 {
8612 map.entry(i).or_insert_with(|| "i".to_string());
8613 }
8614
8615 for (k, v) in map {
8616 println!("{}, {}", k, v);
8617 }
8618 }
8619
8620 // All allocator clones should already be dropped.
8621 assert_eq!(dropped.load(Ordering::SeqCst), 0);
8622 }
8623
8624 #[derive(Debug)]
8625 struct CheckedCloneDrop<T> {
8626 panic_in_clone: bool,
8627 panic_in_drop: bool,
8628 dropped: bool,
8629 data: T,
8630 }
8631
8632 impl<T> CheckedCloneDrop<T> {
8633 fn new(panic_in_clone: bool, panic_in_drop: bool, data: T) -> Self {
8634 CheckedCloneDrop {
8635 panic_in_clone,
8636 panic_in_drop,
8637 dropped: false,
8638 data,
8639 }
8640 }
8641 }
8642
8643 impl<T: Clone> Clone for CheckedCloneDrop<T> {
8644 fn clone(&self) -> Self {
8645 if self.panic_in_clone {
8646 panic!("panic in clone")
8647 }
8648 Self {
8649 panic_in_clone: self.panic_in_clone,
8650 panic_in_drop: self.panic_in_drop,
8651 dropped: self.dropped,
8652 data: self.data.clone(),
8653 }
8654 }
8655 }
8656
8657 impl<T> Drop for CheckedCloneDrop<T> {
8658 fn drop(&mut self) {
8659 if self.panic_in_drop {
8660 self.dropped = true;
8661 panic!("panic in drop");
8662 }
8663 if self.dropped {
8664 panic!("double drop");
8665 }
8666 self.dropped = true;
8667 }
8668 }
8669
8670 /// Return hashmap with predefined distribution of elements.
8671 /// All elements will be located in the same order as elements
8672 /// returned by iterator.
8673 ///
8674 /// This function does not panic, but returns an error as a `String`
8675 /// to distinguish between a test panic and an error in the input data.
8676 fn get_test_map<I, T, A>(
8677 iter: I,
8678 mut fun: impl FnMut(u64) -> T,
8679 alloc: A,
8680 ) -> Result<HashMap<u64, CheckedCloneDrop<T>, DefaultHashBuilder, A>, String>
8681 where
8682 I: Iterator<Item = (bool, bool)> + Clone + ExactSizeIterator,
8683 A: Allocator,
8684 T: PartialEq + core::fmt::Debug,
8685 {
8686 use crate::scopeguard::guard;
8687
8688 let mut map: HashMap<u64, CheckedCloneDrop<T>, _, A> =
8689 HashMap::with_capacity_in(iter.size_hint().0, alloc);
8690 {
8691 let mut guard = guard(&mut map, |map| {
8692 for (_, value) in map.iter_mut() {
8693 value.panic_in_drop = false
8694 }
8695 });
8696
8697 let mut count = 0;
8698 // Hash and Key must be equal to each other for controlling the elements placement.
8699 for (panic_in_clone, panic_in_drop) in iter.clone() {
8700 if core::mem::needs_drop::<T>() && panic_in_drop {
8701 return Err(String::from(
8702 "panic_in_drop can be set with a type that doesn't need to be dropped",
8703 ));
8704 }
8705 guard.table.insert(
8706 count,
8707 (
8708 count,
8709 CheckedCloneDrop::new(panic_in_clone, panic_in_drop, fun(count)),
8710 ),
8711 |(k, _)| *k,
8712 );
8713 count += 1;
8714 }
8715
8716 // Let's check that all elements are located as we wanted
8717 let mut check_count = 0;
8718 for ((key, value), (panic_in_clone, panic_in_drop)) in guard.iter().zip(iter) {
8719 if *key != check_count {
8720 return Err(format!(
8721 "key != check_count,\nkey: `{}`,\ncheck_count: `{}`",
8722 key, check_count
8723 ));
8724 }
8725 if value.dropped
8726 || value.panic_in_clone != panic_in_clone
8727 || value.panic_in_drop != panic_in_drop
8728 || value.data != fun(check_count)
8729 {
8730 return Err(format!(
8731 "Value is not equal to expected,\nvalue: `{:?}`,\nexpected: \
8732 `CheckedCloneDrop {{ panic_in_clone: {}, panic_in_drop: {}, dropped: {}, data: {:?} }}`",
8733 value, panic_in_clone, panic_in_drop, false, fun(check_count)
8734 ));
8735 }
8736 check_count += 1;
8737 }
8738
8739 if guard.len() != check_count as usize {
8740 return Err(format!(
8741 "map.len() != check_count,\nmap.len(): `{}`,\ncheck_count: `{}`",
8742 guard.len(),
8743 check_count
8744 ));
8745 }
8746
8747 if count != check_count {
8748 return Err(format!(
8749 "count != check_count,\ncount: `{}`,\ncheck_count: `{}`",
8750 count, check_count
8751 ));
8752 }
8753 core::mem::forget(guard);
8754 }
8755 Ok(map)
8756 }
8757
8758 const DISARMED: bool = false;
8759 const ARMED: bool = true;
8760
8761 const ARMED_FLAGS: [bool; 8] = [
8762 DISARMED, DISARMED, DISARMED, ARMED, DISARMED, DISARMED, DISARMED, DISARMED,
8763 ];
8764
8765 const DISARMED_FLAGS: [bool; 8] = [
8766 DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED, DISARMED,
8767 ];
8768
8769 #[test]
8770 #[should_panic = "panic in clone"]
8771 fn test_clone_memory_leaks_and_double_drop_one() {
8772 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
8773
8774 {
8775 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
8776
8777 let map: HashMap<u64, CheckedCloneDrop<Vec<u64>>, DefaultHashBuilder, MyAlloc> =
8778 match get_test_map(
8779 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
8780 |n| vec![n],
8781 MyAlloc::new(dropped.clone()),
8782 ) {
8783 Ok(map) => map,
8784 Err(msg) => panic!("{msg}"),
8785 };
8786
8787 // Clone should normally clone a few elements, and then (when the
8788 // clone function panics), deallocate both its own memory, memory
8789 // of `dropped: Arc<AtomicI8>` and the memory of already cloned
8790 // elements (Vec<i32> memory inside CheckedCloneDrop).
8791 let _map2 = map.clone();
8792 }
8793 }
8794
8795 #[test]
8796 #[should_panic = "panic in drop"]
8797 fn test_clone_memory_leaks_and_double_drop_two() {
8798 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
8799
8800 {
8801 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
8802
8803 let map: HashMap<u64, CheckedCloneDrop<u64>, DefaultHashBuilder, _> = match get_test_map(
8804 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
8805 |n| n,
8806 MyAlloc::new(dropped.clone()),
8807 ) {
8808 Ok(map) => map,
8809 Err(msg) => panic!("{msg}"),
8810 };
8811
8812 let mut map2 = match get_test_map(
8813 DISARMED_FLAGS.into_iter().zip(ARMED_FLAGS),
8814 |n| n,
8815 MyAlloc::new(dropped.clone()),
8816 ) {
8817 Ok(map) => map,
8818 Err(msg) => panic!("{msg}"),
8819 };
8820
8821 // The `clone_from` should try to drop the elements of `map2` without
8822 // double drop and leaking the allocator. Elements that have not been
8823 // dropped leak their memory.
8824 map2.clone_from(&map);
8825 }
8826 }
8827
8828 /// We check that we have a working table if the clone operation from another
8829 /// thread ended in a panic (when buckets of maps are equal to each other).
8830 #[test]
8831 fn test_catch_panic_clone_from_when_len_is_equal() {
8832 use std::thread;
8833
8834 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
8835
8836 {
8837 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
8838
8839 let mut map = match get_test_map(
8840 DISARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
8841 |n| vec![n],
8842 MyAlloc::new(dropped.clone()),
8843 ) {
8844 Ok(map) => map,
8845 Err(msg) => panic!("{msg}"),
8846 };
8847
8848 thread::scope(|s| {
8849 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
8850 let scope_map =
8851 match get_test_map(ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS), |n| vec![n * 2], MyAlloc::new(dropped.clone())) {
8852 Ok(map) => map,
8853 Err(msg) => return msg,
8854 };
8855 if map.table.buckets() != scope_map.table.buckets() {
8856 return format!(
8857 "map.table.buckets() != scope_map.table.buckets(),\nleft: `{}`,\nright: `{}`",
8858 map.table.buckets(), scope_map.table.buckets()
8859 );
8860 }
8861 map.clone_from(&scope_map);
8862 "We must fail the cloning!!!".to_owned()
8863 });
8864 if let Ok(msg) = result.join() {
8865 panic!("{msg}")
8866 }
8867 });
8868
8869 // Let's check that all iterators work fine and do not return elements
8870 // (especially `RawIterRange`, which does not depend on the number of
8871 // elements in the table, but looks directly at the control bytes)
8872 //
8873 // SAFETY: We know for sure that `RawTable` will outlive
8874 // the returned `RawIter / RawIterRange` iterator.
8875 assert_eq!(map.len(), 0);
8876 assert_eq!(map.iter().count(), 0);
8877 assert_eq!(unsafe { map.table.iter().count() }, 0);
8878 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
8879
8880 for idx in 0..map.table.buckets() {
8881 let idx = idx as u64;
8882 assert!(
8883 map.table.find(idx, |(k, _)| *k == idx).is_none(),
8884 "Index: {idx}"
8885 );
8886 }
8887 }
8888
8889 // All allocator clones should already be dropped.
8890 assert_eq!(dropped.load(Ordering::SeqCst), 0);
8891 }
8892
8893 /// We check that we have a working table if the clone operation from another
8894 /// thread ended in a panic (when buckets of maps are not equal to each other).
8895 #[test]
8896 fn test_catch_panic_clone_from_when_len_is_not_equal() {
8897 use std::thread;
8898
8899 let dropped: Arc<AtomicI8> = Arc::new(AtomicI8::new(2));
8900
8901 {
8902 assert_eq!(ARMED_FLAGS.len(), DISARMED_FLAGS.len());
8903
8904 let mut map = match get_test_map(
8905 [DISARMED].into_iter().zip([DISARMED]),
8906 |n| vec![n],
8907 MyAlloc::new(dropped.clone()),
8908 ) {
8909 Ok(map) => map,
8910 Err(msg) => panic!("{msg}"),
8911 };
8912
8913 thread::scope(|s| {
8914 let result: thread::ScopedJoinHandle<'_, String> = s.spawn(|| {
8915 let scope_map = match get_test_map(
8916 ARMED_FLAGS.into_iter().zip(DISARMED_FLAGS),
8917 |n| vec![n * 2],
8918 MyAlloc::new(dropped.clone()),
8919 ) {
8920 Ok(map) => map,
8921 Err(msg) => return msg,
8922 };
8923 if map.table.buckets() == scope_map.table.buckets() {
8924 return format!(
8925 "map.table.buckets() == scope_map.table.buckets(): `{}`",
8926 map.table.buckets()
8927 );
8928 }
8929 map.clone_from(&scope_map);
8930 "We must fail the cloning!!!".to_owned()
8931 });
8932 if let Ok(msg) = result.join() {
8933 panic!("{msg}")
8934 }
8935 });
8936
8937 // Let's check that all iterators work fine and do not return elements
8938 // (especially `RawIterRange`, which does not depend on the number of
8939 // elements in the table, but looks directly at the control bytes)
8940 //
8941 // SAFETY: We know for sure that `RawTable` will outlive
8942 // the returned `RawIter / RawIterRange` iterator.
8943 assert_eq!(map.len(), 0);
8944 assert_eq!(map.iter().count(), 0);
8945 assert_eq!(unsafe { map.table.iter().count() }, 0);
8946 assert_eq!(unsafe { map.table.iter().iter.count() }, 0);
8947
8948 for idx in 0..map.table.buckets() {
8949 let idx = idx as u64;
8950 assert!(
8951 map.table.find(idx, |(k, _)| *k == idx).is_none(),
8952 "Index: {idx}"
8953 );
8954 }
8955 }
8956
8957 // All allocator clones should already be dropped.
8958 assert_eq!(dropped.load(Ordering::SeqCst), 0);
8959 }
8960}
8961