Coverage Report

Created: 2025-07-11 06:05

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