Debian Codegraph @

debian/missing-sources/hashbrown-0.13.2/src/map.rs

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