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