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