rayon_hash/std_hash/map.rs
1use self::Entry::*;
2use self::VacantEntryState::*;
3
4use crate::alloc::CollectionAllocErr;
5#[cfg(rayon_hash_unstable)]
6use crate::intrinsics::unlikely;
7use std::borrow::Borrow;
8use std::cmp::max;
9use std::fmt::{self, Debug};
10use std::hash::{Hash, BuildHasher};
11#[cfg(rayon_hash_unstable)]
12use std::hash::Hasher;
13use std::iter::{FromIterator, FusedIterator};
14use std::mem::{self, replace};
15use std::ops::{Deref, Index};
16#[cfg(rayon_hash_unstable)]
17use std::ops::DerefMut;
18
19pub use std::collections::hash_map::{DefaultHasher, RandomState};
20
21use super::table::{self, Bucket, EmptyBucket, Fallibility, FullBucket, FullBucketMut, RawTable,
22 SafeHash};
23use super::table::BucketState::{Empty, Full};
24use super::table::Fallibility::{Fallible, Infallible};
25
26const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two
27
28/// The default behavior of HashMap implements a maximum load factor of 90.9%.
29#[derive(Clone)]
30struct DefaultResizePolicy;
31
32impl DefaultResizePolicy {
33 #[inline]
34 fn new() -> DefaultResizePolicy {
35 DefaultResizePolicy
36 }
37
38 /// A hash map's "capacity" is the number of elements it can hold without
39 /// being resized. Its "raw capacity" is the number of slots required to
40 /// provide that capacity, accounting for maximum loading. The raw capacity
41 /// is always zero or a power of two.
42 #[inline]
43 fn try_raw_capacity(&self, len: usize) -> Result<usize, CollectionAllocErr> {
44 if len == 0 {
45 Ok(0)
46 } else {
47 // 1. Account for loading: `raw_capacity >= len * 1.1`.
48 // 2. Ensure it is a power of two.
49 // 3. Ensure it is at least the minimum size.
50 let mut raw_cap = len.checked_mul(11)
51 .map(|l| l / 10)
52 .and_then(|l| l.checked_next_power_of_two())
53 .ok_or(CollectionAllocErr::CapacityOverflow)?;
54
55 raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
56 Ok(raw_cap)
57 }
58 }
59
60 #[inline]
61 fn raw_capacity(&self, len: usize) -> usize {
62 self.try_raw_capacity(len).expect("raw_capacity overflow")
63 }
64
65 /// The capacity of the given raw capacity.
66 #[inline]
67 fn capacity(&self, raw_cap: usize) -> usize {
68 // This doesn't have to be checked for overflow since allocation size
69 // in bytes will overflow earlier than multiplication by 10.
70 //
71 // As per https://github.com/rust-lang/rust/pull/30991 this is updated
72 // to be: (raw_cap * den + den - 1) / num
73 (raw_cap * 10 + 10 - 1) / 11
74 }
75}
76
77// The main performance trick in this hashmap is called Robin Hood Hashing.
78// It gains its excellent performance from one essential operation:
79//
80// If an insertion collides with an existing element, and that element's
81// "probe distance" (how far away the element is from its ideal location)
82// is higher than how far we've already probed, swap the elements.
83//
84// This massively lowers variance in probe distance, and allows us to get very
85// high load factors with good performance. The 90% load factor I use is rather
86// conservative.
87//
88// > Why a load factor of approximately 90%?
89//
90// In general, all the distances to initial buckets will converge on the mean.
91// At a load factor of α, the odds of finding the target bucket after k
92// probes is approximately 1-α^k. If we set this equal to 50% (since we converge
93// on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
94// this down to make the math easier on the CPU and avoid its FPU.
95// Since on average we start the probing in the middle of a cache line, this
96// strategy pulls in two cache lines of hashes on every lookup. I think that's
97// pretty good, but if you want to trade off some space, it could go down to one
98// cache line on average with an α of 0.84.
99//
100// > Wait, what? Where did you get 1-α^k from?
101//
102// On the first probe, your odds of a collision with an existing element is α.
103// The odds of doing this twice in a row is approximately α^2. For three times,
104// α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
105// colliding after k tries is 1-α^k.
106//
107// The paper from 1986 cited below mentions an implementation which keeps track
108// of the distance-to-initial-bucket histogram. This approach is not suitable
109// for modern architectures because it requires maintaining an internal data
110// structure. This allows very good first guesses, but we are most concerned
111// with guessing entire cache lines, not individual indexes. Furthermore, array
112// accesses are no longer linear and in one direction, as we have now. There
113// is also memory and cache pressure that this would entail that would be very
114// difficult to properly see in a microbenchmark.
115//
116// ## Future Improvements (FIXME!)
117//
118// Allow the load factor to be changed dynamically and/or at initialization.
119//
120// Also, would it be possible for us to reuse storage when growing the
121// underlying table? This is exactly the use case for 'realloc', and may
122// be worth exploring.
123//
124// ## Future Optimizations (FIXME!)
125//
126// Another possible design choice that I made without any real reason is
127// parameterizing the raw table over keys and values. Technically, all we need
128// is the size and alignment of keys and values, and the code should be just as
129// efficient (well, we might need one for power-of-two size and one for not...).
130// This has the potential to reduce code bloat in rust executables, without
131// really losing anything except 4 words (key size, key alignment, val size,
132// val alignment) which can be passed in to every call of a `RawTable` function.
133// This would definitely be an avenue worth exploring if people start complaining
134// about the size of rust executables.
135//
136// Annotate exceedingly likely branches in `table::make_hash`
137// and `search_hashed` to reduce instruction cache pressure
138// and mispredictions once it becomes possible (blocked on issue #11092).
139//
140// Shrinking the table could simply reallocate in place after moving buckets
141// to the first half.
142//
143// The growth algorithm (fragment of the Proof of Correctness)
144// --------------------
145//
146// The growth algorithm is basically a fast path of the naive reinsertion-
147// during-resize algorithm. Other paths should never be taken.
148//
149// Consider growing a robin hood hashtable of capacity n. Normally, we do this
150// by allocating a new table of capacity `2n`, and then individually reinsert
151// each element in the old table into the new one. This guarantees that the
152// new table is a valid robin hood hashtable with all the desired statistical
153// properties. Remark that the order we reinsert the elements in should not
154// matter. For simplicity and efficiency, we will consider only linear
155// reinsertions, which consist of reinserting all elements in the old table
156// into the new one by increasing order of index. However we will not be
157// starting our reinsertions from index 0 in general. If we start from index
158// i, for the purpose of reinsertion we will consider all elements with real
159// index j < i to have virtual index n + j.
160//
161// Our hash generation scheme consists of generating a 64-bit hash and
162// truncating the most significant bits. When moving to the new table, we
163// simply introduce a new bit to the front of the hash. Therefore, if an
164// element has ideal index i in the old table, it can have one of two ideal
165// locations in the new table. If the new bit is 0, then the new ideal index
166// is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
167// we are producing two independent tables of size n, and for each element we
168// independently choose which table to insert it into with equal probability.
169// However, rather than wrapping around themselves on overflowing their
170// indexes, the first table overflows into the second, and the second into the
171// first. Visually, our new table will look something like:
172//
173// [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
174//
175// Where x's are elements inserted into the first table, y's are elements
176// inserted into the second, and _'s are empty sections. We now define a few
177// key concepts that we will use later. Note that this is a very abstract
178// perspective of the table. A real resized table would be at least half
179// empty.
180//
181// Theorem: A linear robin hood reinsertion from the first ideal element
182// produces identical results to a linear naive reinsertion from the same
183// element.
184//
185// FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
186//
187// Adaptive early resizing
188// ----------------------
189// To protect against degenerate performance scenarios (including DOS attacks),
190// the implementation includes an adaptive behavior that can resize the map
191// early (before its capacity is exceeded) when suspiciously long probe sequences
192// are encountered.
193//
194// With this algorithm in place it would be possible to turn a CPU attack into
195// a memory attack due to the aggressive resizing. To prevent that the
196// adaptive behavior only triggers when the map is at least half full.
197// This reduces the effectiveness of the algorithm but also makes it completely safe.
198//
199// The previous safety measure also prevents degenerate interactions with
200// really bad quality hash algorithms that can make normal inputs look like a
201// DOS attack.
202//
203const DISPLACEMENT_THRESHOLD: usize = 128;
204//
205// The threshold of 128 is chosen to minimize the chance of exceeding it.
206// In particular, we want that chance to be less than 10^-8 with a load of 90%.
207// For displacement, the smallest constant that fits our needs is 90,
208// so we round that up to 128.
209//
210// At a load factor of α, the odds of finding the target bucket after exactly n
211// unsuccessful probes[1] are
212//
213// Pr_α{displacement = n} =
214// (1 - α) / α * ∑_{k≥1} e^(-kα) * (kα)^(k+n) / (k + n)! * (1 - kα / (k + n + 1))
215//
216// We use this formula to find the probability of triggering the adaptive behavior
217//
218// Pr_0.909{displacement > 128} = 1.601 * 10^-11
219//
220// 1. Alfredo Viola (2005). Distributional analysis of Robin Hood linear probing
221// hashing with buckets.
222
223/// A hash map implemented with linear probing and Robin Hood bucket stealing.
224///
225/// By default, `HashMap` uses a hashing algorithm selected to provide
226/// resistance against HashDoS attacks. The algorithm is randomly seeded, and a
227/// reasonable best-effort is made to generate this seed from a high quality,
228/// secure source of randomness provided by the host without blocking the
229/// program. Because of this, the randomness of the seed depends on the output
230/// quality of the system's random number generator when the seed is created.
231/// In particular, seeds generated when the system's entropy pool is abnormally
232/// low such as during system boot may be of a lower quality.
233///
234/// The default hashing algorithm is currently SipHash 1-3, though this is
235/// subject to change at any point in the future. While its performance is very
236/// competitive for medium sized keys, other hashing algorithms will outperform
237/// it for small keys such as integers as well as large keys such as long
238/// strings, though those algorithms will typically *not* protect against
239/// attacks such as HashDoS.
240///
241/// The hashing algorithm can be replaced on a per-`HashMap` basis using the
242/// [`default`], [`with_hasher`], and [`with_capacity_and_hasher`] methods. Many
243/// alternative algorithms are available on crates.io, such as the [`fnv`] crate.
244///
245/// It is required that the keys implement the [`Eq`] and [`Hash`] traits, although
246/// this can frequently be achieved by using `#[derive(PartialEq, Eq, Hash)]`.
247/// If you implement these yourself, it is important that the following
248/// property holds:
249///
250/// ```text
251/// k1 == k2 -> hash(k1) == hash(k2)
252/// ```
253///
254/// In other words, if two keys are equal, their hashes must be equal.
255///
256/// It is a logic error for a key to be modified in such a way that the key's
257/// hash, as determined by the [`Hash`] trait, or its equality, as determined by
258/// the [`Eq`] trait, changes while it is in the map. This is normally only
259/// possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
260///
261/// Relevant papers/articles:
262///
263/// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
264/// 2. Emmanuel Goossaert. ["Robin Hood
265/// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
266/// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
267/// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
268///
269/// # Examples
270///
271/// ```
272/// use rayon_hash::HashMap;
273///
274/// // Type inference lets us omit an explicit type signature (which
275/// // would be `HashMap<String, String>` in this example).
276/// let mut book_reviews = HashMap::new();
277///
278/// // Review some books.
279/// book_reviews.insert(
280/// "Adventures of Huckleberry Finn".to_string(),
281/// "My favorite book.".to_string(),
282/// );
283/// book_reviews.insert(
284/// "Grimms' Fairy Tales".to_string(),
285/// "Masterpiece.".to_string(),
286/// );
287/// book_reviews.insert(
288/// "Pride and Prejudice".to_string(),
289/// "Very enjoyable.".to_string(),
290/// );
291/// book_reviews.insert(
292/// "The Adventures of Sherlock Holmes".to_string(),
293/// "Eye lyked it alot.".to_string(),
294/// );
295///
296/// // Check for a specific one.
297/// // When collections store owned values (String), they can still be
298/// // queried using references (&str).
299/// if !book_reviews.contains_key("Les Misérables") {
300/// println!("We've got {} reviews, but Les Misérables ain't one.",
301/// book_reviews.len());
302/// }
303///
304/// // oops, this review has a lot of spelling mistakes, let's delete it.
305/// book_reviews.remove("The Adventures of Sherlock Holmes");
306///
307/// // Look up the values associated with some keys.
308/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
309/// for &book in &to_find {
310/// match book_reviews.get(book) {
311/// Some(review) => println!("{}: {}", book, review),
312/// None => println!("{} is unreviewed.", book)
313/// }
314/// }
315///
316/// // Look up the value for a key (will panic if the key is not found).
317/// println!("Review for Jane: {}", book_reviews["Pride and Prejudice"]);
318///
319/// // Iterate over everything.
320/// for (book, review) in &book_reviews {
321/// println!("{}: \"{}\"", book, review);
322/// }
323/// ```
324///
325/// `HashMap` also implements an [`Entry API`](#method.entry), which allows
326/// for more complex methods of getting, setting, updating and removing keys and
327/// their values:
328///
329/// ```
330/// use rayon_hash::HashMap;
331///
332/// // type inference lets us omit an explicit type signature (which
333/// // would be `HashMap<&str, u8>` in this example).
334/// let mut player_stats = HashMap::new();
335///
336/// fn random_stat_buff() -> u8 {
337/// // could actually return some random value here - let's just return
338/// // some fixed value for now
339/// 42
340/// }
341///
342/// // insert a key only if it doesn't already exist
343/// player_stats.entry("health").or_insert(100);
344///
345/// // insert a key using a function that provides a new value only if it
346/// // doesn't already exist
347/// player_stats.entry("defence").or_insert_with(random_stat_buff);
348///
349/// // update a key, guarding against the key possibly not being set
350/// let stat = player_stats.entry("attack").or_insert(100);
351/// *stat += random_stat_buff();
352/// ```
353///
354/// The easiest way to use `HashMap` with a custom key type is to derive [`Eq`] and [`Hash`].
355/// We must also derive [`PartialEq`].
356///
357/// [`Eq`]: ../../std/cmp/trait.Eq.html
358/// [`Hash`]: ../../std/hash/trait.Hash.html
359/// [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
360/// [`RefCell`]: ../../std/cell/struct.RefCell.html
361/// [`Cell`]: ../../std/cell/struct.Cell.html
362/// [`default`]: #method.default
363/// [`with_hasher`]: #method.with_hasher
364/// [`with_capacity_and_hasher`]: #method.with_capacity_and_hasher
365/// [`fnv`]: https://crates.io/crates/fnv
366///
367/// ```
368/// use rayon_hash::HashMap;
369///
370/// #[derive(Hash, Eq, PartialEq, Debug)]
371/// struct Viking {
372/// name: String,
373/// country: String,
374/// }
375///
376/// impl Viking {
377/// /// Creates a new Viking.
378/// fn new(name: &str, country: &str) -> Viking {
379/// Viking { name: name.to_string(), country: country.to_string() }
380/// }
381/// }
382///
383/// // Use a HashMap to store the vikings' health points.
384/// let mut vikings = HashMap::new();
385///
386/// vikings.insert(Viking::new("Einar", "Norway"), 25);
387/// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
388/// vikings.insert(Viking::new("Harald", "Iceland"), 12);
389///
390/// // Use derived implementation to print the status of the vikings.
391/// for (viking, health) in &vikings {
392/// println!("{:?} has {} hp", viking, health);
393/// }
394/// ```
395///
396/// A `HashMap` with fixed list of elements can be initialized from an array:
397///
398/// ```
399/// use rayon_hash::HashMap;
400///
401/// fn main() {
402/// let timber_resources: HashMap<&str, i32> =
403/// [("Norway", 100),
404/// ("Denmark", 50),
405/// ("Iceland", 10)]
406/// .iter().cloned().collect();
407/// // use the values stored in map
408/// }
409/// ```
410
411#[derive(Clone)]
412// #[stable(feature = "rust1", since = "1.0.0")]
413pub struct HashMap<K, V, S = RandomState> {
414 // All hashes are keyed on these values, to prevent hash collision attacks.
415 hash_builder: S,
416
417 pub(crate) table: RawTable<K, V>,
418
419 resize_policy: DefaultResizePolicy,
420}
421
422/// Search for a pre-hashed key.
423/// If you don't already know the hash, use search or search_mut instead
424#[inline]
425fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, is_match: F) -> InternalEntry<K, V, M>
426 where M: Deref<Target = RawTable<K, V>>,
427 F: FnMut(&K) -> bool
428{
429 // This is the only function where capacity can be zero. To avoid
430 // undefined behavior when Bucket::new gets the raw bucket in this
431 // case, immediately return the appropriate search result.
432 if table.capacity() == 0 {
433 return InternalEntry::TableIsEmpty;
434 }
435
436 search_hashed_nonempty(table, hash, is_match, true)
437}
438
439/// Search for a pre-hashed key when the hash map is known to be non-empty.
440#[inline]
441fn search_hashed_nonempty<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
442 compare_hashes: bool)
443 -> InternalEntry<K, V, M>
444 where M: Deref<Target = RawTable<K, V>>,
445 F: FnMut(&K) -> bool
446{
447 // Do not check the capacity as an extra branch could slow the lookup.
448
449 let size = table.size();
450 let mut probe = Bucket::new(table, hash);
451 let mut displacement = 0;
452
453 loop {
454 let full = match probe.peek() {
455 Empty(bucket) => {
456 // Found a hole!
457 return InternalEntry::Vacant {
458 hash,
459 elem: NoElem(bucket, displacement),
460 };
461 }
462 Full(bucket) => bucket,
463 };
464
465 let probe_displacement = full.displacement();
466
467 if probe_displacement < displacement {
468 // Found a luckier bucket than me.
469 // We can finish the search early if we hit any bucket
470 // with a lower distance to initial bucket than we've probed.
471 return InternalEntry::Vacant {
472 hash,
473 elem: NeqElem(full, probe_displacement),
474 };
475 }
476
477 // If the hash doesn't match, it can't be this one..
478 if !compare_hashes || hash == full.hash() {
479 // If the key doesn't match, it can't be this one..
480 if is_match(full.read().0) {
481 return InternalEntry::Occupied { elem: full };
482 }
483 }
484 displacement += 1;
485 probe = full.next();
486 debug_assert!(displacement <= size);
487 }
488}
489
490/// Same as `search_hashed_nonempty` but for mutable access.
491#[inline]
492#[cfg(rayon_hash_unstable)]
493fn search_hashed_nonempty_mut<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F,
494 compare_hashes: bool)
495 -> InternalEntry<K, V, M>
496 where M: DerefMut<Target = RawTable<K, V>>,
497 F: FnMut(&K) -> bool
498{
499 // Do not check the capacity as an extra branch could slow the lookup.
500
501 let size = table.size();
502 let mut probe = Bucket::new(table, hash);
503 let mut displacement = 0;
504
505 loop {
506 let mut full = match probe.peek() {
507 Empty(bucket) => {
508 // Found a hole!
509 return InternalEntry::Vacant {
510 hash,
511 elem: NoElem(bucket, displacement),
512 };
513 }
514 Full(bucket) => bucket,
515 };
516
517 let probe_displacement = full.displacement();
518
519 if probe_displacement < displacement {
520 // Found a luckier bucket than me.
521 // We can finish the search early if we hit any bucket
522 // with a lower distance to initial bucket than we've probed.
523 return InternalEntry::Vacant {
524 hash,
525 elem: NeqElem(full, probe_displacement),
526 };
527 }
528
529 // If the hash doesn't match, it can't be this one..
530 if hash == full.hash() || !compare_hashes {
531 // If the key doesn't match, it can't be this one..
532 if is_match(full.read_mut().0) {
533 return InternalEntry::Occupied { elem: full };
534 }
535 }
536 displacement += 1;
537 probe = full.next();
538 debug_assert!(displacement <= size);
539 }
540}
541
542fn pop_internal<K, V>(starting_bucket: FullBucketMut<'_, K, V>)
543 -> (K, V, &mut RawTable<K, V>)
544{
545 let (empty, retkey, retval) = starting_bucket.take();
546 let mut gap = match empty.gap_peek() {
547 Ok(b) => b,
548 Err(b) => return (retkey, retval, b.into_table()),
549 };
550
551 while gap.full().displacement() != 0 {
552 gap = match gap.shift() {
553 Ok(b) => b,
554 Err(b) => {
555 return (retkey, retval, b.into_table());
556 },
557 };
558 }
559
560 // Now we've done all our shifting. Return the value we grabbed earlier.
561 (retkey, retval, gap.into_table())
562}
563
564/// Performs robin hood bucket stealing at the given `bucket`. You must
565/// also pass that bucket's displacement so we don't have to recalculate it.
566///
567/// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable.
568fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
569 mut displacement: usize,
570 mut hash: SafeHash,
571 mut key: K,
572 mut val: V)
573 -> FullBucketMut<'a, K, V> {
574 let size = bucket.table().size();
575 let raw_capacity = bucket.table().capacity();
576 // There can be at most `size - dib` buckets to displace, because
577 // in the worst case, there are `size` elements and we already are
578 // `displacement` buckets away from the initial one.
579 let idx_end = (bucket.index() + size - bucket.displacement()) % raw_capacity;
580 // Save the *starting point*.
581 let mut bucket = bucket.stash();
582
583 loop {
584 let (old_hash, old_key, old_val) = bucket.replace(hash, key, val);
585 hash = old_hash;
586 key = old_key;
587 val = old_val;
588
589 loop {
590 displacement += 1;
591 let probe = bucket.next();
592 debug_assert!(probe.index() != idx_end);
593
594 let full_bucket = match probe.peek() {
595 Empty(bucket) => {
596 // Found a hole!
597 let bucket = bucket.put(hash, key, val);
598 // Now that it's stolen, just read the value's pointer
599 // right out of the table! Go back to the *starting point*.
600 //
601 // This use of `into_table` is misleading. It turns the
602 // bucket, which is a FullBucket on top of a
603 // FullBucketMut, into just one FullBucketMut. The "table"
604 // refers to the inner FullBucketMut in this context.
605 return bucket.into_table();
606 }
607 Full(bucket) => bucket,
608 };
609
610 let probe_displacement = full_bucket.displacement();
611
612 bucket = full_bucket;
613
614 // Robin hood! Steal the spot.
615 if probe_displacement < displacement {
616 displacement = probe_displacement;
617 break;
618 }
619 }
620 }
621}
622
623impl<K, V, S> HashMap<K, V, S>
624 where K: Eq + Hash,
625 S: BuildHasher
626{
627 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
628 where X: Hash
629 {
630 table::make_hash(&self.hash_builder, x)
631 }
632
633 /// Search for a key, yielding the index if it's found in the hashtable.
634 /// If you already have the hash for the key lying around, or if you need an
635 /// InternalEntry, use search_hashed or search_hashed_nonempty.
636 #[inline]
637 fn search<'a, Q: ?Sized>(&'a self, q: &Q)
638 -> Option<FullBucket<K, V, &'a RawTable<K, V>>>
639 where K: Borrow<Q>,
640 Q: Eq + Hash
641 {
642 if self.is_empty() {
643 return None;
644 }
645
646 let hash = self.make_hash(q);
647 search_hashed_nonempty(&self.table, hash, |k| q.eq(k.borrow()), true)
648 .into_occupied_bucket()
649 }
650
651 #[inline]
652 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q)
653 -> Option<FullBucket<K, V, &'a mut RawTable<K, V>>>
654 where K: Borrow<Q>,
655 Q: Eq + Hash
656 {
657 if self.is_empty() {
658 return None;
659 }
660
661 let hash = self.make_hash(q);
662 search_hashed_nonempty(&mut self.table, hash, |k| q.eq(k.borrow()), true)
663 .into_occupied_bucket()
664 }
665
666 // The caller should ensure that invariants by Robin Hood Hashing hold
667 // and that there's space in the underlying table.
668 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
669 let mut buckets = Bucket::new(&mut self.table, hash);
670 let start_index = buckets.index();
671
672 loop {
673 // We don't need to compare hashes for value swap.
674 // Not even DIBs for Robin Hood.
675 buckets = match buckets.peek() {
676 Empty(empty) => {
677 empty.put(hash, k, v);
678 return;
679 }
680 Full(b) => b.into_bucket(),
681 };
682 buckets.next();
683 debug_assert!(buckets.index() != start_index);
684 }
685 }
686}
687
688impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
689 /// Creates an empty `HashMap`.
690 ///
691 /// The hash map is initially created with a capacity of 0, so it will not allocate until it
692 /// is first inserted into.
693 ///
694 /// # Examples
695 ///
696 /// ```
697 /// use rayon_hash::HashMap;
698 /// let mut map: HashMap<&str, i32> = HashMap::new();
699 /// ```
700 #[inline]
701 // #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn new() -> HashMap<K, V, RandomState> {
703 Default::default()
704 }
705
706 /// Creates an empty `HashMap` with the specified capacity.
707 ///
708 /// The hash map will be able to hold at least `capacity` elements without
709 /// reallocating. If `capacity` is 0, the hash map will not allocate.
710 ///
711 /// # Examples
712 ///
713 /// ```
714 /// use rayon_hash::HashMap;
715 /// let mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
716 /// ```
717 #[inline]
718 // #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
720 HashMap::with_capacity_and_hasher(capacity, Default::default())
721 }
722}
723
724impl<K, V, S> HashMap<K, V, S> {
725 /// Returns the number of elements the map can hold without reallocating.
726 ///
727 /// This number is a lower bound; the `HashMap<K, V>` might be able to hold
728 /// more, but is guaranteed to be able to hold at least this many.
729 ///
730 /// # Examples
731 ///
732 /// ```
733 /// use rayon_hash::HashMap;
734 /// let map: HashMap<i32, i32> = HashMap::with_capacity(100);
735 /// assert!(map.capacity() >= 100);
736 /// ```
737 #[inline]
738 // #[stable(feature = "rust1", since = "1.0.0")]
739 pub fn capacity(&self) -> usize {
740 self.resize_policy.capacity(self.raw_capacity())
741 }
742
743 /// Returns the hash map's raw capacity.
744 #[inline]
745 fn raw_capacity(&self) -> usize {
746 self.table.capacity()
747 }
748
749 /// An iterator visiting all keys in arbitrary order.
750 /// The iterator element type is `&'a K`.
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// use rayon_hash::HashMap;
756 ///
757 /// let mut map = HashMap::new();
758 /// map.insert("a", 1);
759 /// map.insert("b", 2);
760 /// map.insert("c", 3);
761 ///
762 /// for key in map.keys() {
763 /// println!("{}", key);
764 /// }
765 /// ```
766 // #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn keys(&self) -> Keys<'_, K, V> {
768 Keys { inner: self.iter() }
769 }
770
771 /// An iterator visiting all values in arbitrary order.
772 /// The iterator element type is `&'a V`.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// use rayon_hash::HashMap;
778 ///
779 /// let mut map = HashMap::new();
780 /// map.insert("a", 1);
781 /// map.insert("b", 2);
782 /// map.insert("c", 3);
783 ///
784 /// for val in map.values() {
785 /// println!("{}", val);
786 /// }
787 /// ```
788 // #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn values(&self) -> Values<'_, K, V> {
790 Values { inner: self.iter() }
791 }
792
793 /// An iterator visiting all values mutably in arbitrary order.
794 /// The iterator element type is `&'a mut V`.
795 ///
796 /// # Examples
797 ///
798 /// ```
799 /// use rayon_hash::HashMap;
800 ///
801 /// let mut map = HashMap::new();
802 ///
803 /// map.insert("a", 1);
804 /// map.insert("b", 2);
805 /// map.insert("c", 3);
806 ///
807 /// for val in map.values_mut() {
808 /// *val = *val + 10;
809 /// }
810 ///
811 /// for val in map.values() {
812 /// println!("{}", val);
813 /// }
814 /// ```
815 // #[stable(feature = "map_values_mut", since = "1.10.0")]
816 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
817 ValuesMut { inner: self.iter_mut() }
818 }
819
820 /// An iterator visiting all key-value pairs in arbitrary order.
821 /// The iterator element type is `(&'a K, &'a V)`.
822 ///
823 /// # Examples
824 ///
825 /// ```
826 /// use rayon_hash::HashMap;
827 ///
828 /// let mut map = HashMap::new();
829 /// map.insert("a", 1);
830 /// map.insert("b", 2);
831 /// map.insert("c", 3);
832 ///
833 /// for (key, val) in map.iter() {
834 /// println!("key: {} val: {}", key, val);
835 /// }
836 /// ```
837 // #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn iter(&self) -> Iter<'_, K, V> {
839 Iter { inner: self.table.iter() }
840 }
841
842 /// An iterator visiting all key-value pairs in arbitrary order,
843 /// with mutable references to the values.
844 /// The iterator element type is `(&'a K, &'a mut V)`.
845 ///
846 /// # Examples
847 ///
848 /// ```
849 /// use rayon_hash::HashMap;
850 ///
851 /// let mut map = HashMap::new();
852 /// map.insert("a", 1);
853 /// map.insert("b", 2);
854 /// map.insert("c", 3);
855 ///
856 /// // Update all values
857 /// for (_, val) in map.iter_mut() {
858 /// *val *= 2;
859 /// }
860 ///
861 /// for (key, val) in &map {
862 /// println!("key: {} val: {}", key, val);
863 /// }
864 /// ```
865 // #[stable(feature = "rust1", since = "1.0.0")]
866 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
867 IterMut { inner: self.table.iter_mut() }
868 }
869
870 /// Returns the number of elements in the map.
871 ///
872 /// # Examples
873 ///
874 /// ```
875 /// use rayon_hash::HashMap;
876 ///
877 /// let mut a = HashMap::new();
878 /// assert_eq!(a.len(), 0);
879 /// a.insert(1, "a");
880 /// assert_eq!(a.len(), 1);
881 /// ```
882 // #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn len(&self) -> usize {
884 self.table.size()
885 }
886
887 /// Returns `true` if the map contains no elements.
888 ///
889 /// # Examples
890 ///
891 /// ```
892 /// use rayon_hash::HashMap;
893 ///
894 /// let mut a = HashMap::new();
895 /// assert!(a.is_empty());
896 /// a.insert(1, "a");
897 /// assert!(!a.is_empty());
898 /// ```
899 #[inline]
900 // #[stable(feature = "rust1", since = "1.0.0")]
901 pub fn is_empty(&self) -> bool {
902 self.len() == 0
903 }
904
905 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
906 /// allocated memory for reuse.
907 ///
908 /// # Examples
909 ///
910 /// ```
911 /// use rayon_hash::HashMap;
912 ///
913 /// let mut a = HashMap::new();
914 /// a.insert(1, "a");
915 /// a.insert(2, "b");
916 ///
917 /// for (k, v) in a.drain().take(1) {
918 /// assert!(k == 1 || k == 2);
919 /// assert!(v == "a" || v == "b");
920 /// }
921 ///
922 /// assert!(a.is_empty());
923 /// ```
924 #[inline]
925 // #[stable(feature = "drain", since = "1.6.0")]
926 pub fn drain(&mut self) -> Drain<'_, K, V> {
927 Drain { inner: self.table.drain() }
928 }
929
930 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
931 /// for reuse.
932 ///
933 /// # Examples
934 ///
935 /// ```
936 /// use rayon_hash::HashMap;
937 ///
938 /// let mut a = HashMap::new();
939 /// a.insert(1, "a");
940 /// a.clear();
941 /// assert!(a.is_empty());
942 /// ```
943 // #[stable(feature = "rust1", since = "1.0.0")]
944 #[inline]
945 pub fn clear(&mut self) {
946 self.drain();
947 }
948}
949
950impl<K, V, S> HashMap<K, V, S>
951 where K: Eq + Hash,
952 S: BuildHasher
953{
954 /// Creates an empty `HashMap` which will use the given hash builder to hash
955 /// keys.
956 ///
957 /// The created map has the default initial capacity.
958 ///
959 /// Warning: `hash_builder` is normally randomly generated, and
960 /// is designed to allow HashMaps to be resistant to attacks that
961 /// cause many collisions and very poor performance. Setting it
962 /// manually using this function can expose a DoS attack vector.
963 ///
964 /// # Examples
965 ///
966 /// ```
967 /// use rayon_hash::HashMap;
968 /// use rayon_hash::hash_map::RandomState;
969 ///
970 /// let s = RandomState::new();
971 /// let mut map = HashMap::with_hasher(s);
972 /// map.insert(1, 2);
973 /// ```
974 #[inline]
975 // #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
976 pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> {
977 HashMap {
978 hash_builder,
979 resize_policy: DefaultResizePolicy::new(),
980 table: RawTable::new(0),
981 }
982 }
983
984 /// Creates an empty `HashMap` with the specified capacity, using `hash_builder`
985 /// to hash the keys.
986 ///
987 /// The hash map will be able to hold at least `capacity` elements without
988 /// reallocating. If `capacity` is 0, the hash map will not allocate.
989 ///
990 /// Warning: `hash_builder` is normally randomly generated, and
991 /// is designed to allow HashMaps to be resistant to attacks that
992 /// cause many collisions and very poor performance. Setting it
993 /// manually using this function can expose a DoS attack vector.
994 ///
995 /// # Examples
996 ///
997 /// ```
998 /// use rayon_hash::HashMap;
999 /// use rayon_hash::hash_map::RandomState;
1000 ///
1001 /// let s = RandomState::new();
1002 /// let mut map = HashMap::with_capacity_and_hasher(10, s);
1003 /// map.insert(1, 2);
1004 /// ```
1005 #[inline]
1006 // #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
1007 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
1008 let resize_policy = DefaultResizePolicy::new();
1009 let raw_cap = resize_policy.raw_capacity(capacity);
1010 HashMap {
1011 hash_builder,
1012 resize_policy,
1013 table: RawTable::new(raw_cap),
1014 }
1015 }
1016
1017 /// Returns a reference to the map's [`BuildHasher`].
1018 ///
1019 /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
1020 ///
1021 /// # Examples
1022 ///
1023 /// ```
1024 /// use rayon_hash::HashMap;
1025 /// use rayon_hash::hash_map::RandomState;
1026 ///
1027 /// let hasher = RandomState::new();
1028 /// let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
1029 /// let hasher: &RandomState = map.hasher();
1030 /// ```
1031 // #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
1032 pub fn hasher(&self) -> &S {
1033 &self.hash_builder
1034 }
1035
1036 /// Reserves capacity for at least `additional` more elements to be inserted
1037 /// in the `HashMap`. The collection may reserve more space to avoid
1038 /// frequent reallocations.
1039 ///
1040 /// # Panics
1041 ///
1042 /// Panics if the new allocation size overflows [`usize`].
1043 ///
1044 /// [`usize`]: ../../std/primitive.usize.html
1045 ///
1046 /// # Examples
1047 ///
1048 /// ```
1049 /// use rayon_hash::HashMap;
1050 /// let mut map: HashMap<&str, i32> = HashMap::new();
1051 /// map.reserve(10);
1052 /// ```
1053 #[inline]
1054 // #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn reserve(&mut self, additional: usize) {
1056 match self.reserve_internal(additional, Infallible) {
1057 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
1058 Err(CollectionAllocErr::AllocErr) => unreachable!(),
1059 Ok(()) => { /* yay */ }
1060 }
1061 }
1062
1063 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1064 /// in the given `HashMap<K,V>`. The collection may reserve more space to avoid
1065 /// frequent reallocations.
1066 ///
1067 /// # Errors
1068 ///
1069 /// If the capacity overflows, or the allocator reports a failure, then an error
1070 /// is returned.
1071 ///
1072 /// # Examples
1073 ///
1074 /// ```
1075 /// use rayon_hash::HashMap;
1076 /// let mut map: HashMap<&str, isize> = HashMap::new();
1077 /// map.try_reserve(10).expect("why is the test harness OOMing on 10 bytes?");
1078 /// ```
1079 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
1080 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1081 self.reserve_internal(additional, Fallible)
1082 }
1083
1084 #[inline]
1085 fn reserve_internal(&mut self, additional: usize, fallibility: Fallibility)
1086 -> Result<(), CollectionAllocErr> {
1087
1088 let remaining = self.capacity() - self.len(); // this can't overflow
1089 if remaining < additional {
1090 let min_cap = self.len()
1091 .checked_add(additional)
1092 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1093 let raw_cap = self.resize_policy.try_raw_capacity(min_cap)?;
1094 self.try_resize(raw_cap, fallibility)?;
1095 } else if self.table.tag() && remaining <= self.len() {
1096 // Probe sequence is too long and table is half full,
1097 // resize early to reduce probing length.
1098 let new_capacity = self.table.capacity() * 2;
1099 self.try_resize(new_capacity, fallibility)?;
1100 }
1101 Ok(())
1102 }
1103
1104 /// Resizes the internal vectors to a new capacity. It's your
1105 /// responsibility to:
1106 /// 1) Ensure `new_raw_cap` is enough for all the elements, accounting
1107 /// for the load factor.
1108 /// 2) Ensure `new_raw_cap` is a power of two or zero.
1109 #[inline(never)]
1110 #[cold]
1111 fn try_resize(
1112 &mut self,
1113 new_raw_cap: usize,
1114 fallibility: Fallibility,
1115 ) -> Result<(), CollectionAllocErr> {
1116 assert!(self.table.size() <= new_raw_cap);
1117 assert!(new_raw_cap.is_power_of_two() || new_raw_cap == 0);
1118
1119 let mut old_table = replace(
1120 &mut self.table,
1121 match fallibility {
1122 Infallible => RawTable::new(new_raw_cap),
1123 Fallible => RawTable::try_new(new_raw_cap)?,
1124 }
1125 );
1126 let old_size = old_table.size();
1127
1128 if old_table.size() == 0 {
1129 return Ok(());
1130 }
1131
1132 let mut bucket = Bucket::head_bucket(&mut old_table);
1133
1134 // This is how the buckets might be laid out in memory:
1135 // ($ marks an initialized bucket)
1136 // ________________
1137 // |$$$_$$$$$$_$$$$$|
1138 //
1139 // But we've skipped the entire initial cluster of buckets
1140 // and will continue iteration in this order:
1141 // ________________
1142 // |$$$$$$_$$$$$
1143 // ^ wrap around once end is reached
1144 // ________________
1145 // $$$_____________|
1146 // ^ exit once table.size == 0
1147 loop {
1148 bucket = match bucket.peek() {
1149 Full(bucket) => {
1150 let h = bucket.hash();
1151 let (b, k, v) = bucket.take();
1152 self.insert_hashed_ordered(h, k, v);
1153 if b.table().size() == 0 {
1154 break;
1155 }
1156 b.into_bucket()
1157 }
1158 Empty(b) => b.into_bucket(),
1159 };
1160 bucket.next();
1161 }
1162
1163 assert_eq!(self.table.size(), old_size);
1164 Ok(())
1165 }
1166
1167 /// Shrinks the capacity of the map as much as possible. It will drop
1168 /// down as much as possible while maintaining the internal rules
1169 /// and possibly leaving some space in accordance with the resize policy.
1170 ///
1171 /// # Examples
1172 ///
1173 /// ```
1174 /// use rayon_hash::HashMap;
1175 ///
1176 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1177 /// map.insert(1, 2);
1178 /// map.insert(3, 4);
1179 /// assert!(map.capacity() >= 100);
1180 /// map.shrink_to_fit();
1181 /// assert!(map.capacity() >= 2);
1182 /// ```
1183 // #[stable(feature = "rust1", since = "1.0.0")]
1184 pub fn shrink_to_fit(&mut self) {
1185 let new_raw_cap = self.resize_policy.raw_capacity(self.len());
1186 if self.raw_capacity() != new_raw_cap {
1187 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1188 let old_size = old_table.size();
1189
1190 // Shrink the table. Naive algorithm for resizing:
1191 for (h, k, v) in old_table.into_iter() {
1192 self.insert_hashed_nocheck(h, k, v);
1193 }
1194
1195 debug_assert_eq!(self.table.size(), old_size);
1196 }
1197 }
1198
1199 /// Shrinks the capacity of the map with a lower limit. It will drop
1200 /// down no lower than the supplied limit while maintaining the internal rules
1201 /// and possibly leaving some space in accordance with the resize policy.
1202 ///
1203 /// Panics if the current capacity is smaller than the supplied
1204 /// minimum capacity.
1205 ///
1206 /// # Examples
1207 ///
1208 /// ```
1209 /// use rayon_hash::HashMap;
1210 ///
1211 /// let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
1212 /// map.insert(1, 2);
1213 /// map.insert(3, 4);
1214 /// assert!(map.capacity() >= 100);
1215 /// map.shrink_to(10);
1216 /// assert!(map.capacity() >= 10);
1217 /// map.shrink_to(0);
1218 /// assert!(map.capacity() >= 2);
1219 /// ```
1220 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
1221 pub fn shrink_to(&mut self, min_capacity: usize) {
1222 assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity");
1223
1224 let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity));
1225 if self.raw_capacity() != new_raw_cap {
1226 let old_table = replace(&mut self.table, RawTable::new(new_raw_cap));
1227 let old_size = old_table.size();
1228
1229 // Shrink the table. Naive algorithm for resizing:
1230 for (h, k, v) in old_table.into_iter() {
1231 self.insert_hashed_nocheck(h, k, v);
1232 }
1233
1234 debug_assert_eq!(self.table.size(), old_size);
1235 }
1236 }
1237
1238 /// Insert a pre-hashed key-value pair, without first checking
1239 /// that there's enough room in the buckets. Returns a reference to the
1240 /// newly insert value.
1241 ///
1242 /// If the key already exists, the hashtable will be returned untouched
1243 /// and a reference to the existing element will be returned.
1244 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> Option<V> {
1245 let entry = search_hashed(&mut self.table, hash, |key| *key == k).into_entry(k);
1246 match entry {
1247 Some(Occupied(mut elem)) => Some(elem.insert(v)),
1248 Some(Vacant(elem)) => {
1249 elem.insert(v);
1250 None
1251 }
1252 None => unreachable!(),
1253 }
1254 }
1255
1256 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1257 ///
1258 /// # Examples
1259 ///
1260 /// ```
1261 /// use rayon_hash::HashMap;
1262 ///
1263 /// let mut letters = HashMap::new();
1264 ///
1265 /// for ch in "a short treatise on fungi".chars() {
1266 /// let counter = letters.entry(ch).or_insert(0);
1267 /// *counter += 1;
1268 /// }
1269 ///
1270 /// assert_eq!(letters[&'s'], 2);
1271 /// assert_eq!(letters[&'t'], 3);
1272 /// assert_eq!(letters[&'u'], 1);
1273 /// assert_eq!(letters.get(&'y'), None);
1274 /// ```
1275 // #[stable(feature = "rust1", since = "1.0.0")]
1276 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1277 // Gotta resize now.
1278 self.reserve(1);
1279 let hash = self.make_hash(&key);
1280 search_hashed(&mut self.table, hash, |q| q.eq(&key))
1281 .into_entry(key).expect("unreachable")
1282 }
1283
1284 /// Returns a reference to the value corresponding to the key.
1285 ///
1286 /// The key may be any borrowed form of the map's key type, but
1287 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1288 /// the key type.
1289 ///
1290 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1291 /// [`Hash`]: ../../std/hash/trait.Hash.html
1292 ///
1293 /// # Examples
1294 ///
1295 /// ```
1296 /// use rayon_hash::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 // #[stable(feature = "rust1", since = "1.0.0")]
1304 #[inline]
1305 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1306 where K: Borrow<Q>,
1307 Q: Hash + Eq
1308 {
1309 self.search(k).map(|bucket| bucket.into_refs().1)
1310 }
1311
1312 /// Returns the key-value pair corresponding to the supplied key.
1313 ///
1314 /// The supplied key may be any borrowed form of the map's key type, but
1315 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1316 /// the key type.
1317 ///
1318 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1319 /// [`Hash`]: ../../std/hash/trait.Hash.html
1320 ///
1321 /// # Examples
1322 ///
1323 /// ```
1324 /// use rayon_hash::HashMap;
1325 ///
1326 /// let mut map = HashMap::new();
1327 /// map.insert(1, "a");
1328 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
1329 /// assert_eq!(map.get_key_value(&2), None);
1330 /// ```
1331 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "map_get_key_value", issue = "49347")]
1332 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
1333 where K: Borrow<Q>,
1334 Q: Hash + Eq
1335 {
1336 self.search(k).map(|bucket| bucket.into_refs())
1337 }
1338
1339 /// Returns `true` if the map contains a value for the specified key.
1340 ///
1341 /// The key may be any borrowed form of the map's key type, but
1342 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1343 /// the key type.
1344 ///
1345 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1346 /// [`Hash`]: ../../std/hash/trait.Hash.html
1347 ///
1348 /// # Examples
1349 ///
1350 /// ```
1351 /// use rayon_hash::HashMap;
1352 ///
1353 /// let mut map = HashMap::new();
1354 /// map.insert(1, "a");
1355 /// assert_eq!(map.contains_key(&1), true);
1356 /// assert_eq!(map.contains_key(&2), false);
1357 /// ```
1358 // #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1360 where K: Borrow<Q>,
1361 Q: Hash + Eq
1362 {
1363 self.search(k).is_some()
1364 }
1365
1366 /// Returns a mutable reference to the value corresponding to the key.
1367 ///
1368 /// The key may be any borrowed form of the map's key type, but
1369 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1370 /// the key type.
1371 ///
1372 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1373 /// [`Hash`]: ../../std/hash/trait.Hash.html
1374 ///
1375 /// # Examples
1376 ///
1377 /// ```
1378 /// use rayon_hash::HashMap;
1379 ///
1380 /// let mut map = HashMap::new();
1381 /// map.insert(1, "a");
1382 /// if let Some(x) = map.get_mut(&1) {
1383 /// *x = "b";
1384 /// }
1385 /// assert_eq!(map[&1], "b");
1386 /// ```
1387 // #[stable(feature = "rust1", since = "1.0.0")]
1388 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1389 where K: Borrow<Q>,
1390 Q: Hash + Eq
1391 {
1392 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1393 }
1394
1395 /// Inserts a key-value pair into the map.
1396 ///
1397 /// If the map did not have this key present, [`None`] is returned.
1398 ///
1399 /// If the map did have this key present, the value is updated, and the old
1400 /// value is returned. The key is not updated, though; this matters for
1401 /// types that can be `==` without being identical. See the [module-level
1402 /// documentation] for more.
1403 ///
1404 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1405 /// [module-level documentation]: index.html#insert-and-complex-keys
1406 ///
1407 /// # Examples
1408 ///
1409 /// ```
1410 /// use rayon_hash::HashMap;
1411 ///
1412 /// let mut map = HashMap::new();
1413 /// assert_eq!(map.insert(37, "a"), None);
1414 /// assert_eq!(map.is_empty(), false);
1415 ///
1416 /// map.insert(37, "b");
1417 /// assert_eq!(map.insert(37, "c"), Some("b"));
1418 /// assert_eq!(map[&37], "c");
1419 /// ```
1420 // #[stable(feature = "rust1", since = "1.0.0")]
1421 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1422 let hash = self.make_hash(&k);
1423 self.reserve(1);
1424 self.insert_hashed_nocheck(hash, k, v)
1425 }
1426
1427 /// Removes a key from the map, returning the value at the key if the key
1428 /// was previously in the map.
1429 ///
1430 /// The key may be any borrowed form of the map's key type, but
1431 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1432 /// the key type.
1433 ///
1434 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1435 /// [`Hash`]: ../../std/hash/trait.Hash.html
1436 ///
1437 /// # Examples
1438 ///
1439 /// ```
1440 /// use rayon_hash::HashMap;
1441 ///
1442 /// let mut map = HashMap::new();
1443 /// map.insert(1, "a");
1444 /// assert_eq!(map.remove(&1), Some("a"));
1445 /// assert_eq!(map.remove(&1), None);
1446 /// ```
1447 // #[stable(feature = "rust1", since = "1.0.0")]
1448 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1449 where K: Borrow<Q>,
1450 Q: Hash + Eq
1451 {
1452 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1453 }
1454
1455 /// Removes a key from the map, returning the stored key and value if the
1456 /// key was previously in the map.
1457 ///
1458 /// The key may be any borrowed form of the map's key type, but
1459 /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for
1460 /// the key type.
1461 ///
1462 /// [`Eq`]: ../../std/cmp/trait.Eq.html
1463 /// [`Hash`]: ../../std/hash/trait.Hash.html
1464 ///
1465 /// # Examples
1466 ///
1467 /// ```
1468 /// use rayon_hash::HashMap;
1469 ///
1470 /// # fn main() {
1471 /// let mut map = HashMap::new();
1472 /// map.insert(1, "a");
1473 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1474 /// assert_eq!(map.remove(&1), None);
1475 /// # }
1476 /// ```
1477 // #[stable(feature = "hash_map_remove_entry", since = "1.27.0")]
1478 pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)>
1479 where K: Borrow<Q>,
1480 Q: Hash + Eq
1481 {
1482 self.search_mut(k)
1483 .map(|bucket| {
1484 let (k, v, _) = pop_internal(bucket);
1485 (k, v)
1486 })
1487 }
1488
1489 /// Retains only the elements specified by the predicate.
1490 ///
1491 /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`.
1492 ///
1493 /// # Examples
1494 ///
1495 /// ```
1496 /// use rayon_hash::HashMap;
1497 ///
1498 /// let mut map: HashMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
1499 /// map.retain(|&k, _| k % 2 == 0);
1500 /// assert_eq!(map.len(), 4);
1501 /// ```
1502 // #[stable(feature = "retain_hash_collection", since = "1.18.0")]
1503 pub fn retain<F>(&mut self, mut f: F)
1504 where F: FnMut(&K, &mut V) -> bool
1505 {
1506 if self.table.size() == 0 {
1507 return;
1508 }
1509 let mut elems_left = self.table.size();
1510 let mut bucket = Bucket::head_bucket(&mut self.table);
1511 bucket.prev();
1512 let start_index = bucket.index();
1513 while elems_left != 0 {
1514 bucket = match bucket.peek() {
1515 Full(mut full) => {
1516 elems_left -= 1;
1517 let should_remove = {
1518 let (k, v) = full.read_mut();
1519 !f(k, v)
1520 };
1521 if should_remove {
1522 let prev_raw = full.raw();
1523 let (_, _, t) = pop_internal(full);
1524 Bucket::new_from(prev_raw, t)
1525 } else {
1526 full.into_bucket()
1527 }
1528 },
1529 Empty(b) => {
1530 b.into_bucket()
1531 }
1532 };
1533 bucket.prev(); // reverse iteration
1534 debug_assert!(elems_left == 0 || bucket.index() != start_index);
1535 }
1536 }
1537}
1538
1539impl<K, V, S> HashMap<K, V, S>
1540 where K: Eq + Hash,
1541 S: BuildHasher
1542{
1543 /// Creates a raw entry builder for the HashMap.
1544 ///
1545 /// Raw entries provide the lowest level of control for searching and
1546 /// manipulating a map. They must be manually initialized with a hash and
1547 /// then manually searched. After this, insertions into a vacant entry
1548 /// still require an owned key to be provided.
1549 ///
1550 /// Raw entries are useful for such exotic situations as:
1551 ///
1552 /// * Hash memoization
1553 /// * Deferring the creation of an owned key until it is known to be required
1554 /// * Using a search key that doesn't work with the Borrow trait
1555 /// * Using custom comparison logic without newtype wrappers
1556 ///
1557 /// Because raw entries provide much more low-level control, it's much easier
1558 /// to put the HashMap into an inconsistent state which, while memory-safe,
1559 /// will cause the map to produce seemingly random results. Higher-level and
1560 /// more foolproof APIs like `entry` should be preferred when possible.
1561 ///
1562 /// In particular, the hash used to initialized the raw entry must still be
1563 /// consistent with the hash of the key that is ultimately stored in the entry.
1564 /// This is because implementations of HashMap may need to recompute hashes
1565 /// when resizing, at which point only the keys are available.
1566 ///
1567 /// Raw entries give mutable access to the keys. This must not be used
1568 /// to modify how the key would compare or hash, as the map will not re-evaluate
1569 /// where the key should go, meaning the keys may become "lost" if their
1570 /// location does not reflect their state. For instance, if you change a key
1571 /// so that the map now contains keys which compare equal, search may start
1572 /// acting erratically, with two keys randomly masking each other. Implementations
1573 /// are free to assume this doesn't happen (within the limits of memory-safety).
1574 #[inline(always)]
1575 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1576 pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> {
1577 self.reserve(1);
1578 RawEntryBuilderMut { map: self }
1579 }
1580
1581 /// Creates a raw immutable entry builder for the HashMap.
1582 ///
1583 /// Raw entries provide the lowest level of control for searching and
1584 /// manipulating a map. They must be manually initialized with a hash and
1585 /// then manually searched.
1586 ///
1587 /// This is useful for
1588 /// * Hash memoization
1589 /// * Using a search key that doesn't work with the Borrow trait
1590 /// * Using custom comparison logic without newtype wrappers
1591 ///
1592 /// Unless you are in such a situation, higher-level and more foolproof APIs like
1593 /// `get` should be preferred.
1594 ///
1595 /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`.
1596 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1597 pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> {
1598 RawEntryBuilder { map: self }
1599 }
1600}
1601
1602// #[stable(feature = "rust1", since = "1.0.0")]
1603impl<K, V, S> PartialEq for HashMap<K, V, S>
1604 where K: Eq + Hash,
1605 V: PartialEq,
1606 S: BuildHasher
1607{
1608 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1609 if self.len() != other.len() {
1610 return false;
1611 }
1612
1613 self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1614 }
1615}
1616
1617// #[stable(feature = "rust1", since = "1.0.0")]
1618impl<K, V, S> Eq for HashMap<K, V, S>
1619 where K: Eq + Hash,
1620 V: Eq,
1621 S: BuildHasher
1622{
1623}
1624
1625// #[stable(feature = "rust1", since = "1.0.0")]
1626impl<K, V, S> Debug for HashMap<K, V, S>
1627 where K: Eq + Hash + Debug,
1628 V: Debug,
1629 S: BuildHasher
1630{
1631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1632 f.debug_map().entries(self.iter()).finish()
1633 }
1634}
1635
1636// #[stable(feature = "rust1", since = "1.0.0")]
1637impl<K, V, S> Default for HashMap<K, V, S>
1638 where K: Eq + Hash,
1639 S: BuildHasher + Default
1640{
1641 /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
1642 fn default() -> HashMap<K, V, S> {
1643 HashMap::with_hasher(Default::default())
1644 }
1645}
1646
1647// #[stable(feature = "rust1", since = "1.0.0")]
1648impl<K, Q: ?Sized, V, S> Index<&Q> for HashMap<K, V, S>
1649 where K: Eq + Hash + Borrow<Q>,
1650 Q: Eq + Hash,
1651 S: BuildHasher
1652{
1653 type Output = V;
1654
1655 /// Returns a reference to the value corresponding to the supplied key.
1656 ///
1657 /// # Panics
1658 ///
1659 /// Panics if the key is not present in the `HashMap`.
1660 #[inline]
1661 fn index(&self, key: &Q) -> &V {
1662 self.get(key).expect("no entry found for key")
1663 }
1664}
1665
1666/// An iterator over the entries of a `HashMap`.
1667///
1668/// This `struct` is created by the [`iter`] method on [`HashMap`]. See its
1669/// documentation for more.
1670///
1671/// [`iter`]: struct.HashMap.html#method.iter
1672/// [`HashMap`]: struct.HashMap.html
1673// #[stable(feature = "rust1", since = "1.0.0")]
1674pub struct Iter<'a, K: 'a, V: 'a> {
1675 inner: table::Iter<'a, K, V>,
1676}
1677
1678// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1679// #[stable(feature = "rust1", since = "1.0.0")]
1680impl<K, V> Clone for Iter<'_, K, V> {
1681 fn clone(&self) -> Self {
1682 Iter { inner: self.inner.clone() }
1683 }
1684}
1685
1686// #[stable(feature = "std_debug", since = "1.16.0")]
1687impl<K: Debug, V: Debug> fmt::Debug for Iter<'_, K, V> {
1688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1689 f.debug_list()
1690 .entries(self.clone())
1691 .finish()
1692 }
1693}
1694
1695/// A mutable iterator over the entries of a `HashMap`.
1696///
1697/// This `struct` is created by the [`iter_mut`] method on [`HashMap`]. See its
1698/// documentation for more.
1699///
1700/// [`iter_mut`]: struct.HashMap.html#method.iter_mut
1701/// [`HashMap`]: struct.HashMap.html
1702// #[stable(feature = "rust1", since = "1.0.0")]
1703pub struct IterMut<'a, K: 'a, V: 'a> {
1704 inner: table::IterMut<'a, K, V>,
1705}
1706
1707/// An owning iterator over the entries of a `HashMap`.
1708///
1709/// This `struct` is created by the [`into_iter`] method on [`HashMap`][`HashMap`]
1710/// (provided by the `IntoIterator` trait). See its documentation for more.
1711///
1712/// [`into_iter`]: struct.HashMap.html#method.into_iter
1713/// [`HashMap`]: struct.HashMap.html
1714// #[stable(feature = "rust1", since = "1.0.0")]
1715pub struct IntoIter<K, V> {
1716 pub(super) inner: table::IntoIter<K, V>,
1717}
1718
1719/// An iterator over the keys of a `HashMap`.
1720///
1721/// This `struct` is created by the [`keys`] method on [`HashMap`]. See its
1722/// documentation for more.
1723///
1724/// [`keys`]: struct.HashMap.html#method.keys
1725/// [`HashMap`]: struct.HashMap.html
1726// #[stable(feature = "rust1", since = "1.0.0")]
1727pub struct Keys<'a, K: 'a, V: 'a> {
1728 inner: Iter<'a, K, V>,
1729}
1730
1731// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1732// #[stable(feature = "rust1", since = "1.0.0")]
1733impl<K, V> Clone for Keys<'_, K, V> {
1734 fn clone(&self) -> Self {
1735 Keys { inner: self.inner.clone() }
1736 }
1737}
1738
1739// #[stable(feature = "std_debug", since = "1.16.0")]
1740impl<K: Debug, V> fmt::Debug for Keys<'_, K, V> {
1741 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1742 f.debug_list()
1743 .entries(self.clone())
1744 .finish()
1745 }
1746}
1747
1748/// An iterator over the values of a `HashMap`.
1749///
1750/// This `struct` is created by the [`values`] method on [`HashMap`]. See its
1751/// documentation for more.
1752///
1753/// [`values`]: struct.HashMap.html#method.values
1754/// [`HashMap`]: struct.HashMap.html
1755// #[stable(feature = "rust1", since = "1.0.0")]
1756pub struct Values<'a, K: 'a, V: 'a> {
1757 inner: Iter<'a, K, V>,
1758}
1759
1760// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1761// #[stable(feature = "rust1", since = "1.0.0")]
1762impl<K, V> Clone for Values<'_, K, V> {
1763 fn clone(&self) -> Self {
1764 Values { inner: self.inner.clone() }
1765 }
1766}
1767
1768// #[stable(feature = "std_debug", since = "1.16.0")]
1769impl<K, V: Debug> fmt::Debug for Values<'_, K, V> {
1770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1771 f.debug_list()
1772 .entries(self.clone())
1773 .finish()
1774 }
1775}
1776
1777/// A draining iterator over the entries of a `HashMap`.
1778///
1779/// This `struct` is created by the [`drain`] method on [`HashMap`]. See its
1780/// documentation for more.
1781///
1782/// [`drain`]: struct.HashMap.html#method.drain
1783/// [`HashMap`]: struct.HashMap.html
1784// #[stable(feature = "drain", since = "1.6.0")]
1785pub struct Drain<'a, K: 'a, V: 'a> {
1786 pub(super) inner: table::Drain<'a, K, V>,
1787}
1788
1789/// A mutable iterator over the values of a `HashMap`.
1790///
1791/// This `struct` is created by the [`values_mut`] method on [`HashMap`]. See its
1792/// documentation for more.
1793///
1794/// [`values_mut`]: struct.HashMap.html#method.values_mut
1795/// [`HashMap`]: struct.HashMap.html
1796// #[stable(feature = "map_values_mut", since = "1.10.0")]
1797pub struct ValuesMut<'a, K: 'a, V: 'a> {
1798 inner: IterMut<'a, K, V>,
1799}
1800
1801enum InternalEntry<K, V, M> {
1802 Occupied { elem: FullBucket<K, V, M> },
1803 Vacant {
1804 hash: SafeHash,
1805 elem: VacantEntryState<K, V, M>,
1806 },
1807 TableIsEmpty,
1808}
1809
1810impl<K, V, M> InternalEntry<K, V, M> {
1811 #[inline]
1812 fn into_occupied_bucket(self) -> Option<FullBucket<K, V, M>> {
1813 match self {
1814 InternalEntry::Occupied { elem } => Some(elem),
1815 _ => None,
1816 }
1817 }
1818}
1819
1820impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
1821 #[inline]
1822 fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
1823 match self {
1824 InternalEntry::Occupied { elem } => {
1825 Some(Occupied(OccupiedEntry {
1826 key: Some(key),
1827 elem,
1828 }))
1829 }
1830 InternalEntry::Vacant { hash, elem } => {
1831 Some(Vacant(VacantEntry {
1832 hash,
1833 key,
1834 elem,
1835 }))
1836 }
1837 InternalEntry::TableIsEmpty => None,
1838 }
1839 }
1840}
1841
1842/// A builder for computing where in a HashMap a key-value pair would be stored.
1843///
1844/// See the [`HashMap::raw_entry_mut`] docs for usage examples.
1845///
1846/// [`HashMap::raw_entry_mut`]: struct.HashMap.html#method.raw_entry_mut
1847
1848#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1849pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> {
1850 map: &'a mut HashMap<K, V, S>,
1851}
1852
1853/// A view into a single entry in a map, which may either be vacant or occupied.
1854///
1855/// This is a lower-level version of [`Entry`].
1856///
1857/// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`].
1858///
1859/// [`HashMap`]: struct.HashMap.html
1860/// [`Entry`]: enum.Entry.html
1861/// [`raw_entry`]: struct.HashMap.html#method.raw_entry
1862#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1863pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1864 /// An occupied entry.
1865 Occupied(RawOccupiedEntryMut<'a, K, V>),
1866 /// A vacant entry.
1867 Vacant(RawVacantEntryMut<'a, K, V, S>),
1868}
1869
1870/// A view into an occupied entry in a `HashMap`.
1871/// It is part of the [`RawEntryMut`] enum.
1872///
1873/// [`RawEntryMut`]: enum.RawEntryMut.html
1874#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1875pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a> {
1876 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1877}
1878
1879/// A view into a vacant entry in a `HashMap`.
1880/// It is part of the [`RawEntryMut`] enum.
1881///
1882/// [`RawEntryMut`]: enum.RawEntryMut.html
1883#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1884pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> {
1885 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1886 hash_builder: &'a S,
1887}
1888
1889/// A builder for computing where in a HashMap a key-value pair would be stored.
1890///
1891/// See the [`HashMap::raw_entry`] docs for usage examples.
1892///
1893/// [`HashMap::raw_entry`]: struct.HashMap.html#method.raw_entry
1894#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1895pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> {
1896 map: &'a HashMap<K, V, S>,
1897}
1898
1899#[cfg(rayon_hash_unstable)]
1900impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S>
1901 where S: BuildHasher,
1902 K: Eq + Hash,
1903{
1904 /// Creates a `RawEntryMut` from the given key.
1905 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1906 pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S>
1907 where K: Borrow<Q>,
1908 Q: Hash + Eq
1909 {
1910 let mut hasher = self.map.hash_builder.build_hasher();
1911 k.hash(&mut hasher);
1912 self.from_key_hashed_nocheck(hasher.finish(), k)
1913 }
1914
1915 /// Creates a `RawEntryMut` from the given key and its hash.
1916 #[inline]
1917 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1918 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S>
1919 where K: Borrow<Q>,
1920 Q: Eq
1921 {
1922 self.from_hash(hash, |q| q.borrow().eq(k))
1923 }
1924
1925 #[inline]
1926 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> RawEntryMut<'a, K, V, S>
1927 where for<'b> F: FnMut(&'b K) -> bool,
1928 {
1929 match search_hashed_nonempty_mut(&mut self.map.table,
1930 SafeHash::new(hash),
1931 is_match,
1932 compare_hashes) {
1933 InternalEntry::Occupied { elem } => {
1934 RawEntryMut::Occupied(RawOccupiedEntryMut { elem })
1935 }
1936 InternalEntry::Vacant { elem, .. } => {
1937 RawEntryMut::Vacant(RawVacantEntryMut {
1938 elem,
1939 hash_builder: &self.map.hash_builder,
1940 })
1941 }
1942 InternalEntry::TableIsEmpty => {
1943 unreachable!()
1944 }
1945 }
1946 }
1947 /// Creates a `RawEntryMut` from the given hash.
1948 #[inline]
1949 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1950 pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1951 where for<'b> F: FnMut(&'b K) -> bool,
1952 {
1953 self.search(hash, is_match, true)
1954 }
1955
1956 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
1957 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
1958 /// hash.
1959 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1960 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S>
1961 where for<'b> F: FnMut(&'b K) -> bool,
1962 {
1963 self.search(hash, is_match, false)
1964 }
1965}
1966
1967#[cfg(rayon_hash_unstable)]
1968impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S>
1969 where S: BuildHasher,
1970{
1971 /// Access an entry by key.
1972 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1973 pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)>
1974 where K: Borrow<Q>,
1975 Q: Hash + Eq
1976 {
1977 let mut hasher = self.map.hash_builder.build_hasher();
1978 k.hash(&mut hasher);
1979 self.from_key_hashed_nocheck(hasher.finish(), k)
1980 }
1981
1982 /// Access an entry by a key and its hash.
1983 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
1984 pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)>
1985 where K: Borrow<Q>,
1986 Q: Hash + Eq
1987
1988 {
1989 self.from_hash(hash, |q| q.borrow().eq(k))
1990 }
1991
1992 fn search<F>(self, hash: u64, is_match: F, compare_hashes: bool) -> Option<(&'a K, &'a V)>
1993 where F: FnMut(&K) -> bool
1994 {
1995 if unsafe { unlikely(self.map.table.size() == 0) } {
1996 return None;
1997 }
1998 match search_hashed_nonempty(&self.map.table,
1999 SafeHash::new(hash),
2000 is_match,
2001 compare_hashes) {
2002 InternalEntry::Occupied { elem } => Some(elem.into_refs()),
2003 InternalEntry::Vacant { .. } => None,
2004 InternalEntry::TableIsEmpty => unreachable!(),
2005 }
2006 }
2007
2008 /// Access an entry by hash.
2009 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2010 pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2011 where F: FnMut(&K) -> bool
2012 {
2013 self.search(hash, is_match, true)
2014 }
2015
2016 /// Search possible locations for an element with hash `hash` until `is_match` returns true for
2017 /// one of them. There is no guarantee that all keys passed to `is_match` will have the provided
2018 /// hash.
2019 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2020 pub fn search_bucket<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)>
2021 where F: FnMut(&K) -> bool
2022 {
2023 self.search(hash, is_match, false)
2024 }
2025}
2026
2027#[cfg(rayon_hash_unstable)]
2028impl<'a, K, V, S> RawEntryMut<'a, K, V, S> {
2029 /// Ensures a value is in the entry by inserting the default if empty, and returns
2030 /// mutable references to the key and value in the entry.
2031 ///
2032 /// # Examples
2033 ///
2034 /// ```
2035 /// use rayon_hash::HashMap;
2036 ///
2037 /// let mut map: HashMap<&str, u32> = HashMap::new();
2038 ///
2039 /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3);
2040 /// assert_eq!(map["poneyland"], 3);
2041 ///
2042 /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2;
2043 /// assert_eq!(map["poneyland"], 6);
2044 /// ```
2045 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2046 pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V)
2047 where K: Hash,
2048 S: BuildHasher,
2049 {
2050 match self {
2051 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2052 RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val),
2053 }
2054 }
2055
2056 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2057 /// and returns mutable references to the key and value in the entry.
2058 ///
2059 /// # Examples
2060 ///
2061 /// ```
2062 /// use rayon_hash::HashMap;
2063 ///
2064 /// let mut map: HashMap<&str, String> = HashMap::new();
2065 ///
2066 /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| {
2067 /// ("poneyland", "hoho".to_string())
2068 /// });
2069 ///
2070 /// assert_eq!(map["poneyland"], "hoho".to_string());
2071 /// ```
2072 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2073 pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V)
2074 where F: FnOnce() -> (K, V),
2075 K: Hash,
2076 S: BuildHasher,
2077 {
2078 match self {
2079 RawEntryMut::Occupied(entry) => entry.into_key_value(),
2080 RawEntryMut::Vacant(entry) => {
2081 let (k, v) = default();
2082 entry.insert(k, v)
2083 }
2084 }
2085 }
2086
2087 /// Provides in-place mutable access to an occupied entry before any
2088 /// potential inserts into the map.
2089 ///
2090 /// # Examples
2091 ///
2092 /// ```
2093 /// use rayon_hash::HashMap;
2094 ///
2095 /// let mut map: HashMap<&str, u32> = HashMap::new();
2096 ///
2097 /// map.raw_entry_mut()
2098 /// .from_key("poneyland")
2099 /// .and_modify(|_k, v| { *v += 1 })
2100 /// .or_insert("poneyland", 42);
2101 /// assert_eq!(map["poneyland"], 42);
2102 ///
2103 /// map.raw_entry_mut()
2104 /// .from_key("poneyland")
2105 /// .and_modify(|_k, v| { *v += 1 })
2106 /// .or_insert("poneyland", 0);
2107 /// assert_eq!(map["poneyland"], 43);
2108 /// ```
2109 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2110 pub fn and_modify<F>(self, f: F) -> Self
2111 where F: FnOnce(&mut K, &mut V)
2112 {
2113 match self {
2114 RawEntryMut::Occupied(mut entry) => {
2115 {
2116 let (k, v) = entry.get_key_value_mut();
2117 f(k, v);
2118 }
2119 RawEntryMut::Occupied(entry)
2120 },
2121 RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry),
2122 }
2123 }
2124}
2125
2126#[cfg(rayon_hash_unstable)]
2127impl<'a, K, V> RawOccupiedEntryMut<'a, K, V> {
2128 /// Gets a reference to the key in the entry.
2129 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2130 pub fn key(&self) -> &K {
2131 self.elem.read().0
2132 }
2133
2134 /// Gets a mutable reference to the key in the entry.
2135 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2136 pub fn key_mut(&mut self) -> &mut K {
2137 self.elem.read_mut().0
2138 }
2139
2140 /// Converts the entry into a mutable reference to the key in the entry
2141 /// with a lifetime bound to the map itself.
2142 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2143 pub fn into_key(self) -> &'a mut K {
2144 self.elem.into_mut_refs().0
2145 }
2146
2147 /// Gets a reference to the value in the entry.
2148 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2149 pub fn get(&self) -> &V {
2150 self.elem.read().1
2151 }
2152
2153 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2154 /// with a lifetime bound to the map itself.
2155 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2156 pub fn into_mut(self) -> &'a mut V {
2157 self.elem.into_mut_refs().1
2158 }
2159
2160 /// Gets a mutable reference to the value in the entry.
2161 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2162 pub fn get_mut(&mut self) -> &mut V {
2163 self.elem.read_mut().1
2164 }
2165
2166 /// Gets a reference to the key and value in the entry.
2167 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2168 pub fn get_key_value(&mut self) -> (&K, &V) {
2169 self.elem.read()
2170 }
2171
2172 /// Gets a mutable reference to the key and value in the entry.
2173 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2174 pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) {
2175 self.elem.read_mut()
2176 }
2177
2178 /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry
2179 /// with a lifetime bound to the map itself.
2180 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2181 pub fn into_key_value(self) -> (&'a mut K, &'a mut V) {
2182 self.elem.into_mut_refs()
2183 }
2184
2185 /// Sets the value of the entry, and returns the entry's old value.
2186 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2187 pub fn insert(&mut self, value: V) -> V {
2188 mem::replace(self.get_mut(), value)
2189 }
2190
2191 /// Sets the value of the entry, and returns the entry's old value.
2192 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2193 pub fn insert_key(&mut self, key: K) -> K {
2194 mem::replace(self.key_mut(), key)
2195 }
2196
2197 /// Takes the value out of the entry, and returns it.
2198 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2199 pub fn remove(self) -> V {
2200 pop_internal(self.elem).1
2201 }
2202
2203 /// Take the ownership of the key and value from the map.
2204 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2205 pub fn remove_entry(self) -> (K, V) {
2206 let (k, v, _) = pop_internal(self.elem);
2207 (k, v)
2208 }
2209}
2210
2211#[cfg(rayon_hash_unstable)]
2212impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> {
2213 /// Sets the value of the entry with the VacantEntry's key,
2214 /// and returns a mutable reference to it.
2215 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2216 pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V)
2217 where K: Hash,
2218 S: BuildHasher,
2219 {
2220 let mut hasher = self.hash_builder.build_hasher();
2221 key.hash(&mut hasher);
2222 self.insert_hashed_nocheck(hasher.finish(), key, value)
2223 }
2224
2225 /// Sets the value of the entry with the VacantEntry's key,
2226 /// and returns a mutable reference to it.
2227 #[inline]
2228 // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2229 pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) {
2230 let hash = SafeHash::new(hash);
2231 let b = match self.elem {
2232 NeqElem(mut bucket, disp) => {
2233 if disp >= DISPLACEMENT_THRESHOLD {
2234 bucket.table_mut().set_tag(true);
2235 }
2236 robin_hood(bucket, disp, hash, key, value)
2237 },
2238 NoElem(mut bucket, disp) => {
2239 if disp >= DISPLACEMENT_THRESHOLD {
2240 bucket.table_mut().set_tag(true);
2241 }
2242 bucket.put(hash, key, value)
2243 },
2244 };
2245 b.into_mut_refs()
2246 }
2247}
2248
2249#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2250impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> {
2251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2252 f.debug_struct("RawEntryBuilder")
2253 .finish()
2254 }
2255}
2256
2257#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2258impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> {
2259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2260 match *self {
2261 RawEntryMut::Vacant(ref v) => {
2262 f.debug_tuple("RawEntry")
2263 .field(v)
2264 .finish()
2265 }
2266 RawEntryMut::Occupied(ref o) => {
2267 f.debug_tuple("RawEntry")
2268 .field(o)
2269 .finish()
2270 }
2271 }
2272 }
2273}
2274
2275#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2276impl<K: Debug, V: Debug> Debug for RawOccupiedEntryMut<'_, K, V> {
2277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2278 f.debug_struct("RawOccupiedEntryMut")
2279 .field("key", self.key())
2280 .field("value", self.get())
2281 .finish()
2282 }
2283}
2284
2285#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2286impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> {
2287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2288 f.debug_struct("RawVacantEntryMut")
2289 .finish()
2290 }
2291}
2292
2293#[cfg(rayon_hash_unstable)] // #[unstable(feature = "hash_raw_entry", issue = "56167")]
2294impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> {
2295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2296 f.debug_struct("RawEntryBuilder")
2297 .finish()
2298 }
2299}
2300
2301/// A view into a single entry in a map, which may either be vacant or occupied.
2302///
2303/// This `enum` is constructed from the [`entry`] method on [`HashMap`].
2304///
2305/// [`HashMap`]: struct.HashMap.html
2306/// [`entry`]: struct.HashMap.html#method.entry
2307// #[stable(feature = "rust1", since = "1.0.0")]
2308pub enum Entry<'a, K: 'a, V: 'a> {
2309 /// An occupied entry.
2310 // #[stable(feature = "rust1", since = "1.0.0")]
2311 Occupied(// #[stable(feature = "rust1", since = "1.0.0")]
2312 OccupiedEntry<'a, K, V>),
2313
2314 /// A vacant entry.
2315 // #[stable(feature = "rust1", since = "1.0.0")]
2316 Vacant(// #[stable(feature = "rust1", since = "1.0.0")]
2317 VacantEntry<'a, K, V>),
2318}
2319
2320// #[stable(feature= "debug_hash_map", since = "1.12.0")]
2321impl<K: Debug, V: Debug> Debug for Entry<'_, K, V> {
2322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2323 match *self {
2324 Vacant(ref v) => {
2325 f.debug_tuple("Entry")
2326 .field(v)
2327 .finish()
2328 }
2329 Occupied(ref o) => {
2330 f.debug_tuple("Entry")
2331 .field(o)
2332 .finish()
2333 }
2334 }
2335 }
2336}
2337
2338/// A view into an occupied entry in a `HashMap`.
2339/// It is part of the [`Entry`] enum.
2340///
2341/// [`Entry`]: enum.Entry.html
2342// #[stable(feature = "rust1", since = "1.0.0")]
2343pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
2344 key: Option<K>,
2345 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
2346}
2347
2348// #[stable(feature = "rust1", since = "1.0.0")]
2349unsafe impl<'a, K: 'a + Send, V: 'a + Send> Send for OccupiedEntry<'a, K, V> {}
2350// #[stable(feature = "rust1", since = "1.0.0")]
2351unsafe impl<'a, K: 'a + Sync, V: 'a + Sync> Sync for OccupiedEntry<'a, K, V> {}
2352
2353// #[stable(feature= "debug_hash_map", since = "1.12.0")]
2354impl<K: Debug, V: Debug> Debug for OccupiedEntry<'_, K, V> {
2355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2356 f.debug_struct("OccupiedEntry")
2357 .field("key", self.key())
2358 .field("value", self.get())
2359 .finish()
2360 }
2361}
2362
2363/// A view into a vacant entry in a `HashMap`.
2364/// It is part of the [`Entry`] enum.
2365///
2366/// [`Entry`]: enum.Entry.html
2367// #[stable(feature = "rust1", since = "1.0.0")]
2368pub struct VacantEntry<'a, K: 'a, V: 'a> {
2369 hash: SafeHash,
2370 key: K,
2371 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
2372}
2373
2374// #[stable(feature = "rust1", since = "1.0.0")]
2375unsafe impl<'a, K: 'a + Send, V: 'a + Send> Send for VacantEntry<'a, K, V> {}
2376// #[stable(feature = "rust1", since = "1.0.0")]
2377unsafe impl<'a, K: 'a + Sync, V: 'a + Sync> Sync for VacantEntry<'a, K, V> {}
2378
2379// #[stable(feature= "debug_hash_map", since = "1.12.0")]
2380impl<K: Debug, V> Debug for VacantEntry<'_, K, V> {
2381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2382 f.debug_tuple("VacantEntry")
2383 .field(self.key())
2384 .finish()
2385 }
2386}
2387
2388/// Possible states of a VacantEntry.
2389enum VacantEntryState<K, V, M> {
2390 /// The index is occupied, but the key to insert has precedence,
2391 /// and will kick the current one out on insertion.
2392 NeqElem(FullBucket<K, V, M>, usize),
2393 /// The index is genuinely vacant.
2394 NoElem(EmptyBucket<K, V, M>, usize),
2395}
2396
2397// #[stable(feature = "rust1", since = "1.0.0")]
2398impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> {
2399 type Item = (&'a K, &'a V);
2400 type IntoIter = Iter<'a, K, V>;
2401
2402 fn into_iter(self) -> Iter<'a, K, V> {
2403 self.iter()
2404 }
2405}
2406
2407// #[stable(feature = "rust1", since = "1.0.0")]
2408impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> {
2409 type Item = (&'a K, &'a mut V);
2410 type IntoIter = IterMut<'a, K, V>;
2411
2412 fn into_iter(self) -> IterMut<'a, K, V> {
2413 self.iter_mut()
2414 }
2415}
2416
2417// #[stable(feature = "rust1", since = "1.0.0")]
2418impl<K, V, S> IntoIterator for HashMap<K, V, S> {
2419 type Item = (K, V);
2420 type IntoIter = IntoIter<K, V>;
2421
2422 /// Creates a consuming iterator, that is, one that moves each key-value
2423 /// pair out of the map in arbitrary order. The map cannot be used after
2424 /// calling this.
2425 ///
2426 /// # Examples
2427 ///
2428 /// ```
2429 /// use rayon_hash::HashMap;
2430 ///
2431 /// let mut map = HashMap::new();
2432 /// map.insert("a", 1);
2433 /// map.insert("b", 2);
2434 /// map.insert("c", 3);
2435 ///
2436 /// // Not possible with .iter()
2437 /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
2438 /// ```
2439 fn into_iter(self) -> IntoIter<K, V> {
2440 IntoIter { inner: self.table.into_iter() }
2441 }
2442}
2443
2444// #[stable(feature = "rust1", since = "1.0.0")]
2445impl<'a, K, V> Iterator for Iter<'a, K, V> {
2446 type Item = (&'a K, &'a V);
2447
2448 #[inline]
2449 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2450 self.inner.next()
2451 }
2452 #[inline]
2453 fn size_hint(&self) -> (usize, Option<usize>) {
2454 self.inner.size_hint()
2455 }
2456}
2457// #[stable(feature = "rust1", since = "1.0.0")]
2458impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
2459 #[inline]
2460 fn len(&self) -> usize {
2461 self.inner.len()
2462 }
2463}
2464
2465// #[stable(feature = "fused", since = "1.26.0")]
2466impl<K, V> FusedIterator for Iter<'_, K, V> {}
2467
2468// #[stable(feature = "rust1", since = "1.0.0")]
2469impl<'a, K, V> Iterator for IterMut<'a, K, V> {
2470 type Item = (&'a K, &'a mut V);
2471
2472 #[inline]
2473 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2474 self.inner.next()
2475 }
2476 #[inline]
2477 fn size_hint(&self) -> (usize, Option<usize>) {
2478 self.inner.size_hint()
2479 }
2480}
2481// #[stable(feature = "rust1", since = "1.0.0")]
2482impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
2483 #[inline]
2484 fn len(&self) -> usize {
2485 self.inner.len()
2486 }
2487}
2488// #[stable(feature = "fused", since = "1.26.0")]
2489impl<K, V> FusedIterator for IterMut<'_, K, V> {}
2490
2491// #[stable(feature = "std_debug", since = "1.16.0")]
2492impl<K, V> fmt::Debug for IterMut<'_, K, V>
2493 where K: fmt::Debug,
2494 V: fmt::Debug,
2495{
2496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2497 f.debug_list()
2498 .entries(self.inner.iter())
2499 .finish()
2500 }
2501}
2502
2503// #[stable(feature = "rust1", since = "1.0.0")]
2504impl<K, V> Iterator for IntoIter<K, V> {
2505 type Item = (K, V);
2506
2507 #[inline]
2508 fn next(&mut self) -> Option<(K, V)> {
2509 self.inner.next().map(|(_, k, v)| (k, v))
2510 }
2511 #[inline]
2512 fn size_hint(&self) -> (usize, Option<usize>) {
2513 self.inner.size_hint()
2514 }
2515}
2516// #[stable(feature = "rust1", since = "1.0.0")]
2517impl<K, V> ExactSizeIterator for IntoIter<K, V> {
2518 #[inline]
2519 fn len(&self) -> usize {
2520 self.inner.len()
2521 }
2522}
2523// #[stable(feature = "fused", since = "1.26.0")]
2524impl<K, V> FusedIterator for IntoIter<K, V> {}
2525
2526// #[stable(feature = "std_debug", since = "1.16.0")]
2527impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
2528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2529 f.debug_list()
2530 .entries(self.inner.iter())
2531 .finish()
2532 }
2533}
2534
2535// #[stable(feature = "rust1", since = "1.0.0")]
2536impl<'a, K, V> Iterator for Keys<'a, K, V> {
2537 type Item = &'a K;
2538
2539 #[inline]
2540 fn next(&mut self) -> Option<(&'a K)> {
2541 self.inner.next().map(|(k, _)| k)
2542 }
2543 #[inline]
2544 fn size_hint(&self) -> (usize, Option<usize>) {
2545 self.inner.size_hint()
2546 }
2547}
2548// #[stable(feature = "rust1", since = "1.0.0")]
2549impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2550 #[inline]
2551 fn len(&self) -> usize {
2552 self.inner.len()
2553 }
2554}
2555// #[stable(feature = "fused", since = "1.26.0")]
2556impl<K, V> FusedIterator for Keys<'_, K, V> {}
2557
2558// #[stable(feature = "rust1", since = "1.0.0")]
2559impl<'a, K, V> Iterator for Values<'a, K, V> {
2560 type Item = &'a V;
2561
2562 #[inline]
2563 fn next(&mut self) -> Option<(&'a V)> {
2564 self.inner.next().map(|(_, v)| v)
2565 }
2566 #[inline]
2567 fn size_hint(&self) -> (usize, Option<usize>) {
2568 self.inner.size_hint()
2569 }
2570}
2571// #[stable(feature = "rust1", since = "1.0.0")]
2572impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2573 #[inline]
2574 fn len(&self) -> usize {
2575 self.inner.len()
2576 }
2577}
2578// #[stable(feature = "fused", since = "1.26.0")]
2579impl<K, V> FusedIterator for Values<'_, K, V> {}
2580
2581// #[stable(feature = "map_values_mut", since = "1.10.0")]
2582impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2583 type Item = &'a mut V;
2584
2585 #[inline]
2586 fn next(&mut self) -> Option<(&'a mut V)> {
2587 self.inner.next().map(|(_, v)| v)
2588 }
2589 #[inline]
2590 fn size_hint(&self) -> (usize, Option<usize>) {
2591 self.inner.size_hint()
2592 }
2593}
2594// #[stable(feature = "map_values_mut", since = "1.10.0")]
2595impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2596 #[inline]
2597 fn len(&self) -> usize {
2598 self.inner.len()
2599 }
2600}
2601// #[stable(feature = "fused", since = "1.26.0")]
2602impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2603
2604// #[stable(feature = "std_debug", since = "1.16.0")]
2605impl<K, V> fmt::Debug for ValuesMut<'_, K, V>
2606 where K: fmt::Debug,
2607 V: fmt::Debug,
2608{
2609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2610 f.debug_list()
2611 .entries(self.inner.inner.iter())
2612 .finish()
2613 }
2614}
2615
2616// #[stable(feature = "drain", since = "1.6.0")]
2617impl<'a, K, V> Iterator for Drain<'a, K, V> {
2618 type Item = (K, V);
2619
2620 #[inline]
2621 fn next(&mut self) -> Option<(K, V)> {
2622 self.inner.next().map(|(_, k, v)| (k, v))
2623 }
2624 #[inline]
2625 fn size_hint(&self) -> (usize, Option<usize>) {
2626 self.inner.size_hint()
2627 }
2628}
2629// #[stable(feature = "drain", since = "1.6.0")]
2630impl<K, V> ExactSizeIterator for Drain<'_, K, V> {
2631 #[inline]
2632 fn len(&self) -> usize {
2633 self.inner.len()
2634 }
2635}
2636// #[stable(feature = "fused", since = "1.26.0")]
2637impl<K, V> FusedIterator for Drain<'_, K, V> {}
2638
2639// #[stable(feature = "std_debug", since = "1.16.0")]
2640impl<K, V> fmt::Debug for Drain<'_, K, V>
2641 where K: fmt::Debug,
2642 V: fmt::Debug,
2643{
2644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2645 f.debug_list()
2646 .entries(self.inner.iter())
2647 .finish()
2648 }
2649}
2650
2651impl<'a, K, V> Entry<'a, K, V> {
2652 // #[stable(feature = "rust1", since = "1.0.0")]
2653 /// Ensures a value is in the entry by inserting the default if empty, and returns
2654 /// a mutable reference to the value in the entry.
2655 ///
2656 /// # Examples
2657 ///
2658 /// ```
2659 /// use rayon_hash::HashMap;
2660 ///
2661 /// let mut map: HashMap<&str, u32> = HashMap::new();
2662 ///
2663 /// map.entry("poneyland").or_insert(3);
2664 /// assert_eq!(map["poneyland"], 3);
2665 ///
2666 /// *map.entry("poneyland").or_insert(10) *= 2;
2667 /// assert_eq!(map["poneyland"], 6);
2668 /// ```
2669 pub fn or_insert(self, default: V) -> &'a mut V {
2670 match self {
2671 Occupied(entry) => entry.into_mut(),
2672 Vacant(entry) => entry.insert(default),
2673 }
2674 }
2675
2676 // #[stable(feature = "rust1", since = "1.0.0")]
2677 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2678 /// and returns a mutable reference to the value in the entry.
2679 ///
2680 /// # Examples
2681 ///
2682 /// ```
2683 /// use rayon_hash::HashMap;
2684 ///
2685 /// let mut map: HashMap<&str, String> = HashMap::new();
2686 /// let s = "hoho".to_string();
2687 ///
2688 /// map.entry("poneyland").or_insert_with(|| s);
2689 ///
2690 /// assert_eq!(map["poneyland"], "hoho".to_string());
2691 /// ```
2692 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2693 match self {
2694 Occupied(entry) => entry.into_mut(),
2695 Vacant(entry) => entry.insert(default()),
2696 }
2697 }
2698
2699 /// Returns a reference to this entry's key.
2700 ///
2701 /// # Examples
2702 ///
2703 /// ```
2704 /// use rayon_hash::HashMap;
2705 ///
2706 /// let mut map: HashMap<&str, u32> = HashMap::new();
2707 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2708 /// ```
2709 // #[stable(feature = "map_entry_keys", since = "1.10.0")]
2710 pub fn key(&self) -> &K {
2711 match *self {
2712 Occupied(ref entry) => entry.key(),
2713 Vacant(ref entry) => entry.key(),
2714 }
2715 }
2716
2717 /// Provides in-place mutable access to an occupied entry before any
2718 /// potential inserts into the map.
2719 ///
2720 /// # Examples
2721 ///
2722 /// ```
2723 /// use rayon_hash::HashMap;
2724 ///
2725 /// let mut map: HashMap<&str, u32> = HashMap::new();
2726 ///
2727 /// map.entry("poneyland")
2728 /// .and_modify(|e| { *e += 1 })
2729 /// .or_insert(42);
2730 /// assert_eq!(map["poneyland"], 42);
2731 ///
2732 /// map.entry("poneyland")
2733 /// .and_modify(|e| { *e += 1 })
2734 /// .or_insert(42);
2735 /// assert_eq!(map["poneyland"], 43);
2736 /// ```
2737 // #[stable(feature = "entry_and_modify", since = "1.26.0")]
2738 pub fn and_modify<F>(self, f: F) -> Self
2739 where F: FnOnce(&mut V)
2740 {
2741 match self {
2742 Occupied(mut entry) => {
2743 f(entry.get_mut());
2744 Occupied(entry)
2745 },
2746 Vacant(entry) => Vacant(entry),
2747 }
2748 }
2749
2750}
2751
2752impl<'a, K, V: Default> Entry<'a, K, V> {
2753 // #[stable(feature = "entry_or_default", since = "1.28.0")]
2754 /// Ensures a value is in the entry by inserting the default value if empty,
2755 /// and returns a mutable reference to the value in the entry.
2756 ///
2757 /// # Examples
2758 ///
2759 /// ```
2760 /// # fn main() {
2761 /// use rayon_hash::HashMap;
2762 ///
2763 /// let mut map: HashMap<&str, Option<u32>> = HashMap::new();
2764 /// map.entry("poneyland").or_default();
2765 ///
2766 /// assert_eq!(map["poneyland"], None);
2767 /// # }
2768 /// ```
2769 pub fn or_default(self) -> &'a mut V {
2770 match self {
2771 Occupied(entry) => entry.into_mut(),
2772 Vacant(entry) => entry.insert(Default::default()),
2773 }
2774 }
2775}
2776
2777impl<'a, K, V> OccupiedEntry<'a, K, V> {
2778 /// Gets a reference to the key in the entry.
2779 ///
2780 /// # Examples
2781 ///
2782 /// ```
2783 /// use rayon_hash::HashMap;
2784 ///
2785 /// let mut map: HashMap<&str, u32> = HashMap::new();
2786 /// map.entry("poneyland").or_insert(12);
2787 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2788 /// ```
2789 // #[stable(feature = "map_entry_keys", since = "1.10.0")]
2790 pub fn key(&self) -> &K {
2791 self.elem.read().0
2792 }
2793
2794 /// Take the ownership of the key and value from the map.
2795 ///
2796 /// # Examples
2797 ///
2798 /// ```
2799 /// use rayon_hash::HashMap;
2800 /// use rayon_hash::hash_map::Entry;
2801 ///
2802 /// let mut map: HashMap<&str, u32> = HashMap::new();
2803 /// map.entry("poneyland").or_insert(12);
2804 ///
2805 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2806 /// // We delete the entry from the map.
2807 /// o.remove_entry();
2808 /// }
2809 ///
2810 /// assert_eq!(map.contains_key("poneyland"), false);
2811 /// ```
2812 // #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2813 pub fn remove_entry(self) -> (K, V) {
2814 let (k, v, _) = pop_internal(self.elem);
2815 (k, v)
2816 }
2817
2818 /// Gets a reference to the value in the entry.
2819 ///
2820 /// # Examples
2821 ///
2822 /// ```
2823 /// use rayon_hash::HashMap;
2824 /// use rayon_hash::hash_map::Entry;
2825 ///
2826 /// let mut map: HashMap<&str, u32> = HashMap::new();
2827 /// map.entry("poneyland").or_insert(12);
2828 ///
2829 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2830 /// assert_eq!(o.get(), &12);
2831 /// }
2832 /// ```
2833 // #[stable(feature = "rust1", since = "1.0.0")]
2834 pub fn get(&self) -> &V {
2835 self.elem.read().1
2836 }
2837
2838 /// Gets a mutable reference to the value in the entry.
2839 ///
2840 /// If you need a reference to the `OccupiedEntry` which may outlive the
2841 /// destruction of the `Entry` value, see [`into_mut`].
2842 ///
2843 /// [`into_mut`]: #method.into_mut
2844 ///
2845 /// # Examples
2846 ///
2847 /// ```
2848 /// use rayon_hash::HashMap;
2849 /// use rayon_hash::hash_map::Entry;
2850 ///
2851 /// let mut map: HashMap<&str, u32> = HashMap::new();
2852 /// map.entry("poneyland").or_insert(12);
2853 ///
2854 /// assert_eq!(map["poneyland"], 12);
2855 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2856 /// *o.get_mut() += 10;
2857 /// assert_eq!(*o.get(), 22);
2858 ///
2859 /// // We can use the same Entry multiple times.
2860 /// *o.get_mut() += 2;
2861 /// }
2862 ///
2863 /// assert_eq!(map["poneyland"], 24);
2864 /// ```
2865 // #[stable(feature = "rust1", since = "1.0.0")]
2866 pub fn get_mut(&mut self) -> &mut V {
2867 self.elem.read_mut().1
2868 }
2869
2870 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2871 /// with a lifetime bound to the map itself.
2872 ///
2873 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2874 ///
2875 /// [`get_mut`]: #method.get_mut
2876 ///
2877 /// # Examples
2878 ///
2879 /// ```
2880 /// use rayon_hash::HashMap;
2881 /// use rayon_hash::hash_map::Entry;
2882 ///
2883 /// let mut map: HashMap<&str, u32> = HashMap::new();
2884 /// map.entry("poneyland").or_insert(12);
2885 ///
2886 /// assert_eq!(map["poneyland"], 12);
2887 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2888 /// *o.into_mut() += 10;
2889 /// }
2890 ///
2891 /// assert_eq!(map["poneyland"], 22);
2892 /// ```
2893 // #[stable(feature = "rust1", since = "1.0.0")]
2894 pub fn into_mut(self) -> &'a mut V {
2895 self.elem.into_mut_refs().1
2896 }
2897
2898 /// Sets the value of the entry, and returns the entry's old value.
2899 ///
2900 /// # Examples
2901 ///
2902 /// ```
2903 /// use rayon_hash::HashMap;
2904 /// use rayon_hash::hash_map::Entry;
2905 ///
2906 /// let mut map: HashMap<&str, u32> = HashMap::new();
2907 /// map.entry("poneyland").or_insert(12);
2908 ///
2909 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2910 /// assert_eq!(o.insert(15), 12);
2911 /// }
2912 ///
2913 /// assert_eq!(map["poneyland"], 15);
2914 /// ```
2915 // #[stable(feature = "rust1", since = "1.0.0")]
2916 pub fn insert(&mut self, mut value: V) -> V {
2917 let old_value = self.get_mut();
2918 mem::swap(&mut value, old_value);
2919 value
2920 }
2921
2922 /// Takes the value out of the entry, and returns it.
2923 ///
2924 /// # Examples
2925 ///
2926 /// ```
2927 /// use rayon_hash::HashMap;
2928 /// use rayon_hash::hash_map::Entry;
2929 ///
2930 /// let mut map: HashMap<&str, u32> = HashMap::new();
2931 /// map.entry("poneyland").or_insert(12);
2932 ///
2933 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2934 /// assert_eq!(o.remove(), 12);
2935 /// }
2936 ///
2937 /// assert_eq!(map.contains_key("poneyland"), false);
2938 /// ```
2939 // #[stable(feature = "rust1", since = "1.0.0")]
2940 pub fn remove(self) -> V {
2941 pop_internal(self.elem).1
2942 }
2943
2944 /// Returns a key that was used for search.
2945 ///
2946 /// The key was retained for further use.
2947 fn take_key(&mut self) -> Option<K> {
2948 self.key.take()
2949 }
2950
2951 /// Replaces the entry, returning the old key and value. The new key in the hash map will be
2952 /// the key used to create this entry.
2953 ///
2954 /// # Examples
2955 ///
2956 /// ```
2957 /// use rayon_hash::hash_map::{Entry, HashMap};
2958 /// use std::rc::Rc;
2959 ///
2960 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2961 /// map.insert(Rc::new("Stringthing".to_string()), 15);
2962 ///
2963 /// let my_key = Rc::new("Stringthing".to_string());
2964 ///
2965 /// if let Entry::Occupied(entry) = map.entry(my_key) {
2966 /// // Also replace the key with a handle to our other key.
2967 /// let (old_key, old_value): (Rc<String>, u32) = entry.replace_entry(16);
2968 /// }
2969 ///
2970 /// ```
2971 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "map_entry_replace", issue = "44286")]
2972 pub fn replace_entry(mut self, value: V) -> (K, V) {
2973 let (old_key, old_value) = self.elem.read_mut();
2974
2975 let old_key = mem::replace(old_key, self.key.unwrap());
2976 let old_value = mem::replace(old_value, value);
2977
2978 (old_key, old_value)
2979 }
2980
2981 /// Replaces the key in the hash map with the key used to create this entry.
2982 ///
2983 /// # Examples
2984 ///
2985 /// ```
2986 /// use rayon_hash::hash_map::{Entry, HashMap};
2987 /// use std::rc::Rc;
2988 ///
2989 /// let mut map: HashMap<Rc<String>, u32> = HashMap::new();
2990 /// let mut known_strings: Vec<Rc<String>> = Vec::new();
2991 ///
2992 /// // Initialise known strings, run program, etc.
2993 ///
2994 /// reclaim_memory(&mut map, &known_strings);
2995 ///
2996 /// fn reclaim_memory(map: &mut HashMap<Rc<String>, u32>, known_strings: &[Rc<String>] ) {
2997 /// for s in known_strings {
2998 /// if let Entry::Occupied(entry) = map.entry(s.clone()) {
2999 /// // Replaces the entry's key with our version of it in `known_strings`.
3000 /// entry.replace_key();
3001 /// }
3002 /// }
3003 /// }
3004 /// ```
3005 #[cfg(rayon_hash_unstable)] // #[unstable(feature = "map_entry_replace", issue = "44286")]
3006 pub fn replace_key(mut self) -> K {
3007 let (old_key, _) = self.elem.read_mut();
3008 mem::replace(old_key, self.key.unwrap())
3009 }
3010}
3011
3012impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
3013 /// Gets a reference to the key that would be used when inserting a value
3014 /// through the `VacantEntry`.
3015 ///
3016 /// # Examples
3017 ///
3018 /// ```
3019 /// use rayon_hash::HashMap;
3020 ///
3021 /// let mut map: HashMap<&str, u32> = HashMap::new();
3022 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
3023 /// ```
3024 // #[stable(feature = "map_entry_keys", since = "1.10.0")]
3025 pub fn key(&self) -> &K {
3026 &self.key
3027 }
3028
3029 /// Take ownership of the key.
3030 ///
3031 /// # Examples
3032 ///
3033 /// ```
3034 /// use rayon_hash::HashMap;
3035 /// use rayon_hash::hash_map::Entry;
3036 ///
3037 /// let mut map: HashMap<&str, u32> = HashMap::new();
3038 ///
3039 /// if let Entry::Vacant(v) = map.entry("poneyland") {
3040 /// v.into_key();
3041 /// }
3042 /// ```
3043 // #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
3044 pub fn into_key(self) -> K {
3045 self.key
3046 }
3047
3048 /// Sets the value of the entry with the VacantEntry's key,
3049 /// and returns a mutable reference to it.
3050 ///
3051 /// # Examples
3052 ///
3053 /// ```
3054 /// use rayon_hash::HashMap;
3055 /// use rayon_hash::hash_map::Entry;
3056 ///
3057 /// let mut map: HashMap<&str, u32> = HashMap::new();
3058 ///
3059 /// if let Entry::Vacant(o) = map.entry("poneyland") {
3060 /// o.insert(37);
3061 /// }
3062 /// assert_eq!(map["poneyland"], 37);
3063 /// ```
3064 // #[stable(feature = "rust1", since = "1.0.0")]
3065 pub fn insert(self, value: V) -> &'a mut V {
3066 let b = match self.elem {
3067 NeqElem(mut bucket, disp) => {
3068 if disp >= DISPLACEMENT_THRESHOLD {
3069 bucket.table_mut().set_tag(true);
3070 }
3071 robin_hood(bucket, disp, self.hash, self.key, value)
3072 },
3073 NoElem(mut bucket, disp) => {
3074 if disp >= DISPLACEMENT_THRESHOLD {
3075 bucket.table_mut().set_tag(true);
3076 }
3077 bucket.put(self.hash, self.key, value)
3078 },
3079 };
3080 b.into_mut_refs().1
3081 }
3082}
3083
3084// #[stable(feature = "rust1", since = "1.0.0")]
3085impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
3086 where K: Eq + Hash,
3087 S: BuildHasher + Default
3088{
3089 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
3090 let mut map = HashMap::with_hasher(Default::default());
3091 map.extend(iter);
3092 map
3093 }
3094}
3095
3096// #[stable(feature = "rust1", since = "1.0.0")]
3097impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
3098 where K: Eq + Hash,
3099 S: BuildHasher
3100{
3101 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
3102 // Keys may be already present or show multiple times in the iterator.
3103 // Reserve the entire hint lower bound if the map is empty.
3104 // Otherwise reserve half the hint (rounded up), so the map
3105 // will only resize twice in the worst case.
3106 let iter = iter.into_iter();
3107 let reserve = if self.is_empty() {
3108 iter.size_hint().0
3109 } else {
3110 (iter.size_hint().0 + 1) / 2
3111 };
3112 self.reserve(reserve);
3113 for (k, v) in iter {
3114 self.insert(k, v);
3115 }
3116 }
3117}
3118
3119// #[stable(feature = "hash_extend_copy", since = "1.4.0")]
3120impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
3121 where K: Eq + Hash + Copy,
3122 V: Copy,
3123 S: BuildHasher
3124{
3125 fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
3126 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
3127 }
3128}
3129
3130impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
3131 where K: Eq + Hash + Borrow<Q>,
3132 S: BuildHasher,
3133 Q: Eq + Hash
3134{
3135 type Key = K;
3136
3137 #[inline]
3138 fn get(&self, key: &Q) -> Option<&K> {
3139 self.search(key).map(|bucket| bucket.into_refs().0)
3140 }
3141
3142 fn take(&mut self, key: &Q) -> Option<K> {
3143 self.search_mut(key).map(|bucket| pop_internal(bucket).0)
3144 }
3145
3146 #[inline]
3147 fn replace(&mut self, key: K) -> Option<K> {
3148 self.reserve(1);
3149
3150 match self.entry(key) {
3151 Occupied(mut occupied) => {
3152 let key = occupied.take_key().unwrap();
3153 Some(mem::replace(occupied.elem.read_mut().0, key))
3154 }
3155 Vacant(vacant) => {
3156 vacant.insert(());
3157 None
3158 }
3159 }
3160 }
3161}
3162
3163#[allow(dead_code)]
3164fn assert_covariance() {
3165 fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
3166 v
3167 }
3168 fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
3169 v
3170 }
3171 fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
3172 v
3173 }
3174 fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
3175 v
3176 }
3177 fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
3178 v
3179 }
3180 fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
3181 v
3182 }
3183 fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
3184 v
3185 }
3186 fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
3187 v
3188 }
3189 fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
3190 v
3191 }
3192 fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
3193 v
3194 }
3195 fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
3196 -> Drain<'new, &'new str, &'new str> {
3197 d
3198 }
3199}
3200
3201#[cfg(test)]
3202mod test_map {
3203 use super::HashMap;
3204 use super::Entry::{Occupied, Vacant};
3205 use super::RandomState;
3206 use std::cell::RefCell;
3207 use rand::{thread_rng, Rng};
3208 #[cfg(rayon_hash_unstable)] use crate::alloc::CollectionAllocErr::*;
3209 #[cfg(rayon_hash_unstable)] use std::mem::size_of;
3210 use std::usize;
3211
3212 #[test]
3213 fn test_zero_capacities() {
3214 type HM = HashMap<i32, i32>;
3215
3216 let m = HM::new();
3217 assert_eq!(m.capacity(), 0);
3218
3219 let m = HM::default();
3220 assert_eq!(m.capacity(), 0);
3221
3222 let m = HM::with_hasher(RandomState::new());
3223 assert_eq!(m.capacity(), 0);
3224
3225 let m = HM::with_capacity(0);
3226 assert_eq!(m.capacity(), 0);
3227
3228 let m = HM::with_capacity_and_hasher(0, RandomState::new());
3229 assert_eq!(m.capacity(), 0);
3230
3231 let mut m = HM::new();
3232 m.insert(1, 1);
3233 m.insert(2, 2);
3234 m.remove(&1);
3235 m.remove(&2);
3236 m.shrink_to_fit();
3237 assert_eq!(m.capacity(), 0);
3238
3239 let mut m = HM::new();
3240 m.reserve(0);
3241 assert_eq!(m.capacity(), 0);
3242 }
3243
3244 #[test]
3245 fn test_create_capacity_zero() {
3246 let mut m = HashMap::with_capacity(0);
3247
3248 assert!(m.insert(1, 1).is_none());
3249
3250 assert!(m.contains_key(&1));
3251 assert!(!m.contains_key(&0));
3252 }
3253
3254 #[test]
3255 fn test_insert() {
3256 let mut m = HashMap::new();
3257 assert_eq!(m.len(), 0);
3258 assert!(m.insert(1, 2).is_none());
3259 assert_eq!(m.len(), 1);
3260 assert!(m.insert(2, 4).is_none());
3261 assert_eq!(m.len(), 2);
3262 assert_eq!(*m.get(&1).unwrap(), 2);
3263 assert_eq!(*m.get(&2).unwrap(), 4);
3264 }
3265
3266 #[test]
3267 fn test_clone() {
3268 let mut m = HashMap::new();
3269 assert_eq!(m.len(), 0);
3270 assert!(m.insert(1, 2).is_none());
3271 assert_eq!(m.len(), 1);
3272 assert!(m.insert(2, 4).is_none());
3273 assert_eq!(m.len(), 2);
3274 let m2 = m.clone();
3275 assert_eq!(*m2.get(&1).unwrap(), 2);
3276 assert_eq!(*m2.get(&2).unwrap(), 4);
3277 assert_eq!(m2.len(), 2);
3278 }
3279
3280 thread_local! { static DROP_VECTOR: RefCell<Vec<i32>> = RefCell::new(Vec::new()) }
3281
3282 #[derive(Hash, PartialEq, Eq)]
3283 struct Droppable {
3284 k: usize,
3285 }
3286
3287 impl Droppable {
3288 fn new(k: usize) -> Droppable {
3289 DROP_VECTOR.with(|slot| {
3290 slot.borrow_mut()[k] += 1;
3291 });
3292
3293 Droppable { k }
3294 }
3295 }
3296
3297 impl Drop for Droppable {
3298 fn drop(&mut self) {
3299 DROP_VECTOR.with(|slot| {
3300 slot.borrow_mut()[self.k] -= 1;
3301 });
3302 }
3303 }
3304
3305 impl Clone for Droppable {
3306 fn clone(&self) -> Droppable {
3307 Droppable::new(self.k)
3308 }
3309 }
3310
3311 #[test]
3312 fn test_drops() {
3313 DROP_VECTOR.with(|slot| {
3314 *slot.borrow_mut() = vec![0; 200];
3315 });
3316
3317 {
3318 let mut m = HashMap::new();
3319
3320 DROP_VECTOR.with(|v| {
3321 for i in 0..200 {
3322 assert_eq!(v.borrow()[i], 0);
3323 }
3324 });
3325
3326 for i in 0..100 {
3327 let d1 = Droppable::new(i);
3328 let d2 = Droppable::new(i + 100);
3329 m.insert(d1, d2);
3330 }
3331
3332 DROP_VECTOR.with(|v| {
3333 for i in 0..200 {
3334 assert_eq!(v.borrow()[i], 1);
3335 }
3336 });
3337
3338 for i in 0..50 {
3339 let k = Droppable::new(i);
3340 let v = m.remove(&k);
3341
3342 assert!(v.is_some());
3343
3344 DROP_VECTOR.with(|v| {
3345 assert_eq!(v.borrow()[i], 1);
3346 assert_eq!(v.borrow()[i+100], 1);
3347 });
3348 }
3349
3350 DROP_VECTOR.with(|v| {
3351 for i in 0..50 {
3352 assert_eq!(v.borrow()[i], 0);
3353 assert_eq!(v.borrow()[i+100], 0);
3354 }
3355
3356 for i in 50..100 {
3357 assert_eq!(v.borrow()[i], 1);
3358 assert_eq!(v.borrow()[i+100], 1);
3359 }
3360 });
3361 }
3362
3363 DROP_VECTOR.with(|v| {
3364 for i in 0..200 {
3365 assert_eq!(v.borrow()[i], 0);
3366 }
3367 });
3368 }
3369
3370 #[test]
3371 fn test_into_iter_drops() {
3372 DROP_VECTOR.with(|v| {
3373 *v.borrow_mut() = vec![0; 200];
3374 });
3375
3376 let hm = {
3377 let mut hm = HashMap::new();
3378
3379 DROP_VECTOR.with(|v| {
3380 for i in 0..200 {
3381 assert_eq!(v.borrow()[i], 0);
3382 }
3383 });
3384
3385 for i in 0..100 {
3386 let d1 = Droppable::new(i);
3387 let d2 = Droppable::new(i + 100);
3388 hm.insert(d1, d2);
3389 }
3390
3391 DROP_VECTOR.with(|v| {
3392 for i in 0..200 {
3393 assert_eq!(v.borrow()[i], 1);
3394 }
3395 });
3396
3397 hm
3398 };
3399
3400 // By the way, ensure that cloning doesn't screw up the dropping.
3401 drop(hm.clone());
3402
3403 {
3404 let mut half = hm.into_iter().take(50);
3405
3406 DROP_VECTOR.with(|v| {
3407 for i in 0..200 {
3408 assert_eq!(v.borrow()[i], 1);
3409 }
3410 });
3411
3412 for _ in half.by_ref() {}
3413
3414 DROP_VECTOR.with(|v| {
3415 let nk = (0..100)
3416 .filter(|&i| v.borrow()[i] == 1)
3417 .count();
3418
3419 let nv = (0..100)
3420 .filter(|&i| v.borrow()[i + 100] == 1)
3421 .count();
3422
3423 assert_eq!(nk, 50);
3424 assert_eq!(nv, 50);
3425 });
3426 };
3427
3428 DROP_VECTOR.with(|v| {
3429 for i in 0..200 {
3430 assert_eq!(v.borrow()[i], 0);
3431 }
3432 });
3433 }
3434
3435 #[test]
3436 fn test_empty_remove() {
3437 let mut m: HashMap<i32, bool> = HashMap::new();
3438 assert_eq!(m.remove(&0), None);
3439 }
3440
3441 #[test]
3442 fn test_empty_entry() {
3443 let mut m: HashMap<i32, bool> = HashMap::new();
3444 match m.entry(0) {
3445 Occupied(_) => panic!(),
3446 Vacant(_) => {}
3447 }
3448 assert!(*m.entry(0).or_insert(true));
3449 assert_eq!(m.len(), 1);
3450 }
3451
3452 #[test]
3453 fn test_empty_iter() {
3454 let mut m: HashMap<i32, bool> = HashMap::new();
3455 assert_eq!(m.drain().next(), None);
3456 assert_eq!(m.keys().next(), None);
3457 assert_eq!(m.values().next(), None);
3458 assert_eq!(m.values_mut().next(), None);
3459 assert_eq!(m.iter().next(), None);
3460 assert_eq!(m.iter_mut().next(), None);
3461 assert_eq!(m.len(), 0);
3462 assert!(m.is_empty());
3463 assert_eq!(m.into_iter().next(), None);
3464 }
3465
3466 #[test]
3467 fn test_lots_of_insertions() {
3468 let mut m = HashMap::new();
3469
3470 // Try this a few times to make sure we never screw up the hashmap's
3471 // internal state.
3472 for _ in 0..10 {
3473 assert!(m.is_empty());
3474
3475 for i in 1..1001 {
3476 assert!(m.insert(i, i).is_none());
3477
3478 for j in 1..=i {
3479 let r = m.get(&j);
3480 assert_eq!(r, Some(&j));
3481 }
3482
3483 for j in i + 1..1001 {
3484 let r = m.get(&j);
3485 assert_eq!(r, None);
3486 }
3487 }
3488
3489 for i in 1001..2001 {
3490 assert!(!m.contains_key(&i));
3491 }
3492
3493 // remove forwards
3494 for i in 1..1001 {
3495 assert!(m.remove(&i).is_some());
3496
3497 for j in 1..=i {
3498 assert!(!m.contains_key(&j));
3499 }
3500
3501 for j in i + 1..1001 {
3502 assert!(m.contains_key(&j));
3503 }
3504 }
3505
3506 for i in 1..1001 {
3507 assert!(!m.contains_key(&i));
3508 }
3509
3510 for i in 1..1001 {
3511 assert!(m.insert(i, i).is_none());
3512 }
3513
3514 // remove backwards
3515 for i in (1..1001).rev() {
3516 assert!(m.remove(&i).is_some());
3517
3518 for j in i..1001 {
3519 assert!(!m.contains_key(&j));
3520 }
3521
3522 for j in 1..i {
3523 assert!(m.contains_key(&j));
3524 }
3525 }
3526 }
3527 }
3528
3529 #[test]
3530 fn test_find_mut() {
3531 let mut m = HashMap::new();
3532 assert!(m.insert(1, 12).is_none());
3533 assert!(m.insert(2, 8).is_none());
3534 assert!(m.insert(5, 14).is_none());
3535 let new = 100;
3536 match m.get_mut(&5) {
3537 None => panic!(),
3538 Some(x) => *x = new,
3539 }
3540 assert_eq!(m.get(&5), Some(&new));
3541 }
3542
3543 #[test]
3544 fn test_insert_overwrite() {
3545 let mut m = HashMap::new();
3546 assert!(m.insert(1, 2).is_none());
3547 assert_eq!(*m.get(&1).unwrap(), 2);
3548 assert!(!m.insert(1, 3).is_none());
3549 assert_eq!(*m.get(&1).unwrap(), 3);
3550 }
3551
3552 #[test]
3553 fn test_insert_conflicts() {
3554 let mut m = HashMap::with_capacity(4);
3555 assert!(m.insert(1, 2).is_none());
3556 assert!(m.insert(5, 3).is_none());
3557 assert!(m.insert(9, 4).is_none());
3558 assert_eq!(*m.get(&9).unwrap(), 4);
3559 assert_eq!(*m.get(&5).unwrap(), 3);
3560 assert_eq!(*m.get(&1).unwrap(), 2);
3561 }
3562
3563 #[test]
3564 fn test_conflict_remove() {
3565 let mut m = HashMap::with_capacity(4);
3566 assert!(m.insert(1, 2).is_none());
3567 assert_eq!(*m.get(&1).unwrap(), 2);
3568 assert!(m.insert(5, 3).is_none());
3569 assert_eq!(*m.get(&1).unwrap(), 2);
3570 assert_eq!(*m.get(&5).unwrap(), 3);
3571 assert!(m.insert(9, 4).is_none());
3572 assert_eq!(*m.get(&1).unwrap(), 2);
3573 assert_eq!(*m.get(&5).unwrap(), 3);
3574 assert_eq!(*m.get(&9).unwrap(), 4);
3575 assert!(m.remove(&1).is_some());
3576 assert_eq!(*m.get(&9).unwrap(), 4);
3577 assert_eq!(*m.get(&5).unwrap(), 3);
3578 }
3579
3580 #[test]
3581 fn test_is_empty() {
3582 let mut m = HashMap::with_capacity(4);
3583 assert!(m.insert(1, 2).is_none());
3584 assert!(!m.is_empty());
3585 assert!(m.remove(&1).is_some());
3586 assert!(m.is_empty());
3587 }
3588
3589 #[test]
3590 fn test_remove() {
3591 let mut m = HashMap::new();
3592 m.insert(1, 2);
3593 assert_eq!(m.remove(&1), Some(2));
3594 assert_eq!(m.remove(&1), None);
3595 }
3596
3597 #[test]
3598 #[cfg(rayon_hash_unstable)]
3599 fn test_remove_entry() {
3600 let mut m = HashMap::new();
3601 m.insert(1, 2);
3602 assert_eq!(m.remove_entry(&1), Some((1, 2)));
3603 assert_eq!(m.remove(&1), None);
3604 }
3605
3606 #[test]
3607 fn test_iterate() {
3608 let mut m = HashMap::with_capacity(4);
3609 for i in 0..32 {
3610 assert!(m.insert(i, i*2).is_none());
3611 }
3612 assert_eq!(m.len(), 32);
3613
3614 let mut observed: u32 = 0;
3615
3616 for (k, v) in &m {
3617 assert_eq!(*v, *k * 2);
3618 observed |= 1 << *k;
3619 }
3620 assert_eq!(observed, 0xFFFF_FFFF);
3621 }
3622
3623 #[test]
3624 fn test_keys() {
3625 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3626 let map: HashMap<_, _> = vec.into_iter().collect();
3627 let keys: Vec<_> = map.keys().cloned().collect();
3628 assert_eq!(keys.len(), 3);
3629 assert!(keys.contains(&1));
3630 assert!(keys.contains(&2));
3631 assert!(keys.contains(&3));
3632 }
3633
3634 #[test]
3635 fn test_values() {
3636 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
3637 let map: HashMap<_, _> = vec.into_iter().collect();
3638 let values: Vec<_> = map.values().cloned().collect();
3639 assert_eq!(values.len(), 3);
3640 assert!(values.contains(&'a'));
3641 assert!(values.contains(&'b'));
3642 assert!(values.contains(&'c'));
3643 }
3644
3645 #[test]
3646 fn test_values_mut() {
3647 let vec = vec![(1, 1), (2, 2), (3, 3)];
3648 let mut map: HashMap<_, _> = vec.into_iter().collect();
3649 for value in map.values_mut() {
3650 *value = (*value) * 2
3651 }
3652 let values: Vec<_> = map.values().cloned().collect();
3653 assert_eq!(values.len(), 3);
3654 assert!(values.contains(&2));
3655 assert!(values.contains(&4));
3656 assert!(values.contains(&6));
3657 }
3658
3659 #[test]
3660 fn test_find() {
3661 let mut m = HashMap::new();
3662 assert!(m.get(&1).is_none());
3663 m.insert(1, 2);
3664 match m.get(&1) {
3665 None => panic!(),
3666 Some(v) => assert_eq!(*v, 2),
3667 }
3668 }
3669
3670 #[test]
3671 fn test_eq() {
3672 let mut m1 = HashMap::new();
3673 m1.insert(1, 2);
3674 m1.insert(2, 3);
3675 m1.insert(3, 4);
3676
3677 let mut m2 = HashMap::new();
3678 m2.insert(1, 2);
3679 m2.insert(2, 3);
3680
3681 assert!(m1 != m2);
3682
3683 m2.insert(3, 4);
3684
3685 assert_eq!(m1, m2);
3686 }
3687
3688 #[test]
3689 fn test_show() {
3690 let mut map = HashMap::new();
3691 let empty: HashMap<i32, i32> = HashMap::new();
3692
3693 map.insert(1, 2);
3694 map.insert(3, 4);
3695
3696 let map_str = format!("{:?}", map);
3697
3698 assert!(map_str == "{1: 2, 3: 4}" ||
3699 map_str == "{3: 4, 1: 2}");
3700 assert_eq!(format!("{:?}", empty), "{}");
3701 }
3702
3703 #[test]
3704 fn test_expand() {
3705 let mut m = HashMap::new();
3706
3707 assert_eq!(m.len(), 0);
3708 assert!(m.is_empty());
3709
3710 let mut i = 0;
3711 let old_raw_cap = m.raw_capacity();
3712 while old_raw_cap == m.raw_capacity() {
3713 m.insert(i, i);
3714 i += 1;
3715 }
3716
3717 assert_eq!(m.len(), i);
3718 assert!(!m.is_empty());
3719 }
3720
3721 #[test]
3722 fn test_behavior_resize_policy() {
3723 let mut m = HashMap::new();
3724
3725 assert_eq!(m.len(), 0);
3726 assert_eq!(m.raw_capacity(), 0);
3727 assert!(m.is_empty());
3728
3729 m.insert(0, 0);
3730 m.remove(&0);
3731 assert!(m.is_empty());
3732 let initial_raw_cap = m.raw_capacity();
3733 m.reserve(initial_raw_cap);
3734 let raw_cap = m.raw_capacity();
3735
3736 assert_eq!(raw_cap, initial_raw_cap * 2);
3737
3738 let mut i = 0;
3739 for _ in 0..raw_cap * 3 / 4 {
3740 m.insert(i, i);
3741 i += 1;
3742 }
3743 // three quarters full
3744
3745 assert_eq!(m.len(), i);
3746 assert_eq!(m.raw_capacity(), raw_cap);
3747
3748 for _ in 0..raw_cap / 4 {
3749 m.insert(i, i);
3750 i += 1;
3751 }
3752 // half full
3753
3754 let new_raw_cap = m.raw_capacity();
3755 assert_eq!(new_raw_cap, raw_cap * 2);
3756
3757 for _ in 0..raw_cap / 2 - 1 {
3758 i -= 1;
3759 m.remove(&i);
3760 assert_eq!(m.raw_capacity(), new_raw_cap);
3761 }
3762 // A little more than one quarter full.
3763 m.shrink_to_fit();
3764 assert_eq!(m.raw_capacity(), raw_cap);
3765 // again, a little more than half full
3766 for _ in 0..raw_cap / 2 - 1 {
3767 i -= 1;
3768 m.remove(&i);
3769 }
3770 m.shrink_to_fit();
3771
3772 assert_eq!(m.len(), i);
3773 assert!(!m.is_empty());
3774 assert_eq!(m.raw_capacity(), initial_raw_cap);
3775 }
3776
3777 #[test]
3778 fn test_reserve_shrink_to_fit() {
3779 let mut m = HashMap::new();
3780 m.insert(0, 0);
3781 m.remove(&0);
3782 assert!(m.capacity() >= m.len());
3783 for i in 0..128 {
3784 m.insert(i, i);
3785 }
3786 m.reserve(256);
3787
3788 let usable_cap = m.capacity();
3789 for i in 128..(128 + 256) {
3790 m.insert(i, i);
3791 assert_eq!(m.capacity(), usable_cap);
3792 }
3793
3794 for i in 100..(128 + 256) {
3795 assert_eq!(m.remove(&i), Some(i));
3796 }
3797 m.shrink_to_fit();
3798
3799 assert_eq!(m.len(), 100);
3800 assert!(!m.is_empty());
3801 assert!(m.capacity() >= m.len());
3802
3803 for i in 0..100 {
3804 assert_eq!(m.remove(&i), Some(i));
3805 }
3806 m.shrink_to_fit();
3807 m.insert(0, 0);
3808
3809 assert_eq!(m.len(), 1);
3810 assert!(m.capacity() >= m.len());
3811 assert_eq!(m.remove(&0), Some(0));
3812 }
3813
3814 #[test]
3815 fn test_from_iter() {
3816 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3817
3818 let map: HashMap<_, _> = xs.iter().cloned().collect();
3819
3820 for &(k, v) in &xs {
3821 assert_eq!(map.get(&k), Some(&v));
3822 }
3823 }
3824
3825 #[test]
3826 fn test_size_hint() {
3827 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3828
3829 let map: HashMap<_, _> = xs.iter().cloned().collect();
3830
3831 let mut iter = map.iter();
3832
3833 for _ in iter.by_ref().take(3) {}
3834
3835 assert_eq!(iter.size_hint(), (3, Some(3)));
3836 }
3837
3838 #[test]
3839 fn test_iter_len() {
3840 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3841
3842 let map: HashMap<_, _> = xs.iter().cloned().collect();
3843
3844 let mut iter = map.iter();
3845
3846 for _ in iter.by_ref().take(3) {}
3847
3848 assert_eq!(iter.len(), 3);
3849 }
3850
3851 #[test]
3852 fn test_mut_size_hint() {
3853 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3854
3855 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3856
3857 let mut iter = map.iter_mut();
3858
3859 for _ in iter.by_ref().take(3) {}
3860
3861 assert_eq!(iter.size_hint(), (3, Some(3)));
3862 }
3863
3864 #[test]
3865 fn test_iter_mut_len() {
3866 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3867
3868 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3869
3870 let mut iter = map.iter_mut();
3871
3872 for _ in iter.by_ref().take(3) {}
3873
3874 assert_eq!(iter.len(), 3);
3875 }
3876
3877 #[test]
3878 fn test_index() {
3879 let mut map = HashMap::new();
3880
3881 map.insert(1, 2);
3882 map.insert(2, 1);
3883 map.insert(3, 4);
3884
3885 assert_eq!(map[&2], 1);
3886 }
3887
3888 #[test]
3889 #[should_panic]
3890 fn test_index_nonexistent() {
3891 let mut map = HashMap::new();
3892
3893 map.insert(1, 2);
3894 map.insert(2, 1);
3895 map.insert(3, 4);
3896
3897 map[&4];
3898 }
3899
3900 #[test]
3901 fn test_entry() {
3902 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3903
3904 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3905
3906 // Existing key (insert)
3907 match map.entry(1) {
3908 Vacant(_) => unreachable!(),
3909 Occupied(mut view) => {
3910 assert_eq!(view.get(), &10);
3911 assert_eq!(view.insert(100), 10);
3912 }
3913 }
3914 assert_eq!(map.get(&1).unwrap(), &100);
3915 assert_eq!(map.len(), 6);
3916
3917
3918 // Existing key (update)
3919 match map.entry(2) {
3920 Vacant(_) => unreachable!(),
3921 Occupied(mut view) => {
3922 let v = view.get_mut();
3923 let new_v = (*v) * 10;
3924 *v = new_v;
3925 }
3926 }
3927 assert_eq!(map.get(&2).unwrap(), &200);
3928 assert_eq!(map.len(), 6);
3929
3930 // Existing key (take)
3931 match map.entry(3) {
3932 Vacant(_) => unreachable!(),
3933 Occupied(view) => {
3934 assert_eq!(view.remove(), 30);
3935 }
3936 }
3937 assert_eq!(map.get(&3), None);
3938 assert_eq!(map.len(), 5);
3939
3940
3941 // Inexistent key (insert)
3942 match map.entry(10) {
3943 Occupied(_) => unreachable!(),
3944 Vacant(view) => {
3945 assert_eq!(*view.insert(1000), 1000);
3946 }
3947 }
3948 assert_eq!(map.get(&10).unwrap(), &1000);
3949 assert_eq!(map.len(), 6);
3950 }
3951
3952 #[test]
3953 fn test_entry_take_doesnt_corrupt() {
3954 // Test for #19292
3955 fn check(m: &HashMap<i32, ()>) {
3956 for k in m.keys() {
3957 assert!(m.contains_key(k),
3958 "{} is in keys() but not in the map?", k);
3959 }
3960 }
3961
3962 let mut m = HashMap::new();
3963 let mut rng = thread_rng();
3964
3965 // Populate the map with some items.
3966 for _ in 0..50 {
3967 let x = rng.gen_range(-10, 10);
3968 m.insert(x, ());
3969 }
3970
3971 for _ in 0..1000 {
3972 let x = rng.gen_range(-10, 10);
3973 match m.entry(x) {
3974 Vacant(_) => {}
3975 Occupied(e) => {
3976 e.remove();
3977 }
3978 }
3979
3980 check(&m);
3981 }
3982 }
3983
3984 #[test]
3985 fn test_extend_ref() {
3986 let mut a = HashMap::new();
3987 a.insert(1, "one");
3988 let mut b = HashMap::new();
3989 b.insert(2, "two");
3990 b.insert(3, "three");
3991
3992 a.extend(&b);
3993
3994 assert_eq!(a.len(), 3);
3995 assert_eq!(a[&1], "one");
3996 assert_eq!(a[&2], "two");
3997 assert_eq!(a[&3], "three");
3998 }
3999
4000 #[test]
4001 fn test_capacity_not_less_than_len() {
4002 let mut a = HashMap::new();
4003 let mut item = 0;
4004
4005 for _ in 0..116 {
4006 a.insert(item, 0);
4007 item += 1;
4008 }
4009
4010 assert!(a.capacity() > a.len());
4011
4012 let free = a.capacity() - a.len();
4013 for _ in 0..free {
4014 a.insert(item, 0);
4015 item += 1;
4016 }
4017
4018 assert_eq!(a.len(), a.capacity());
4019
4020 // Insert at capacity should cause allocation.
4021 a.insert(item, 0);
4022 assert!(a.capacity() > a.len());
4023 }
4024
4025 #[test]
4026 fn test_occupied_entry_key() {
4027 let mut a = HashMap::new();
4028 let key = "hello there";
4029 let value = "value goes here";
4030 assert!(a.is_empty());
4031 a.insert(key.clone(), value.clone());
4032 assert_eq!(a.len(), 1);
4033 assert_eq!(a[key], value);
4034
4035 match a.entry(key.clone()) {
4036 Vacant(_) => panic!(),
4037 Occupied(e) => assert_eq!(key, *e.key()),
4038 }
4039 assert_eq!(a.len(), 1);
4040 assert_eq!(a[key], value);
4041 }
4042
4043 #[test]
4044 fn test_vacant_entry_key() {
4045 let mut a = HashMap::new();
4046 let key = "hello there";
4047 let value = "value goes here";
4048
4049 assert!(a.is_empty());
4050 match a.entry(key.clone()) {
4051 Occupied(_) => panic!(),
4052 Vacant(e) => {
4053 assert_eq!(key, *e.key());
4054 e.insert(value.clone());
4055 }
4056 }
4057 assert_eq!(a.len(), 1);
4058 assert_eq!(a[key], value);
4059 }
4060
4061 #[test]
4062 fn test_retain() {
4063 let mut map: HashMap<i32, i32> = (0..100).map(|x|(x, x*10)).collect();
4064
4065 map.retain(|&k, _| k % 2 == 0);
4066 assert_eq!(map.len(), 50);
4067 assert_eq!(map[&2], 20);
4068 assert_eq!(map[&4], 40);
4069 assert_eq!(map[&6], 60);
4070 }
4071
4072 #[test]
4073 fn test_adaptive() {
4074 const TEST_LEN: usize = 5000;
4075 // by cloning we get maps with the same hasher seed
4076 let mut first = HashMap::new();
4077 let mut second = first.clone();
4078 first.extend((0..TEST_LEN).map(|i| (i, i)));
4079 second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
4080
4081 for (&k, &v) in &second {
4082 let prev_cap = first.capacity();
4083 let expect_grow = first.len() == prev_cap;
4084 first.insert(k, v);
4085 if !expect_grow && first.capacity() != prev_cap {
4086 return;
4087 }
4088 }
4089 panic!("Adaptive early resize failed");
4090 }
4091
4092 #[test]
4093 #[cfg(rayon_hash_unstable)]
4094 fn test_try_reserve() {
4095
4096 let mut empty_bytes: HashMap<u8,u8> = HashMap::new();
4097
4098 const MAX_USIZE: usize = usize::MAX;
4099
4100 // HashMap and RawTables use complicated size calculations
4101 // hashes_size is sizeof(HashUint) * capacity;
4102 // pairs_size is sizeof((K. V)) * capacity;
4103 // alignment_hashes_size is 8
4104 // alignment_pairs size is 4
4105 let size_of_multiplier = (size_of::<usize>() + size_of::<(u8, u8)>()).next_power_of_two();
4106 // The following formula is used to calculate the new capacity
4107 let max_no_ovf = ((MAX_USIZE / 11) * 10) / size_of_multiplier - 1;
4108
4109 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
4110 } else { panic!("usize::MAX should trigger an overflow!"); }
4111
4112 if size_of::<usize>() < 8 {
4113 if let Err(CapacityOverflow) = empty_bytes.try_reserve(max_no_ovf) {
4114 } else { panic!("isize::MAX + 1 should trigger a CapacityOverflow!") }
4115 } else {
4116 if let Err(AllocErr) = empty_bytes.try_reserve(max_no_ovf) {
4117 } else { panic!("isize::MAX + 1 should trigger an OOM!") }
4118 }
4119 }
4120
4121 #[test]
4122 #[cfg(rayon_hash_unstable)]
4123 fn test_raw_entry() {
4124 use super::RawEntryMut::{Occupied, Vacant};
4125
4126 let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
4127
4128 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
4129
4130 let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 {
4131 use std::hash::{BuildHasher, Hash, Hasher};
4132
4133 let mut hasher = map.hasher().build_hasher();
4134 k.hash(&mut hasher);
4135 hasher.finish()
4136 };
4137
4138 // Existing key (insert)
4139 match map.raw_entry_mut().from_key(&1) {
4140 Vacant(_) => unreachable!(),
4141 Occupied(mut view) => {
4142 assert_eq!(view.get(), &10);
4143 assert_eq!(view.insert(100), 10);
4144 }
4145 }
4146 let hash1 = compute_hash(&map, 1);
4147 assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100));
4148 assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100));
4149 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100));
4150 assert_eq!(map.raw_entry().search_bucket(hash1, |k| *k == 1).unwrap(), (&1, &100));
4151 assert_eq!(map.len(), 6);
4152
4153 // Existing key (update)
4154 match map.raw_entry_mut().from_key(&2) {
4155 Vacant(_) => unreachable!(),
4156 Occupied(mut view) => {
4157 let v = view.get_mut();
4158 let new_v = (*v) * 10;
4159 *v = new_v;
4160 }
4161 }
4162 let hash2 = compute_hash(&map, 2);
4163 assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200));
4164 assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200));
4165 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200));
4166 assert_eq!(map.raw_entry().search_bucket(hash2, |k| *k == 2).unwrap(), (&2, &200));
4167 assert_eq!(map.len(), 6);
4168
4169 // Existing key (take)
4170 let hash3 = compute_hash(&map, 3);
4171 match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) {
4172 Vacant(_) => unreachable!(),
4173 Occupied(view) => {
4174 assert_eq!(view.remove_entry(), (3, 30));
4175 }
4176 }
4177 assert_eq!(map.raw_entry().from_key(&3), None);
4178 assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None);
4179 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None);
4180 assert_eq!(map.raw_entry().search_bucket(hash3, |k| *k == 3), None);
4181 assert_eq!(map.len(), 5);
4182
4183
4184 // Nonexistent key (insert)
4185 match map.raw_entry_mut().from_key(&10) {
4186 Occupied(_) => unreachable!(),
4187 Vacant(view) => {
4188 assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000));
4189 }
4190 }
4191 assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000));
4192 assert_eq!(map.len(), 6);
4193
4194 // Ensure all lookup methods produce equivalent results.
4195 for k in 0..12 {
4196 let hash = compute_hash(&map, k);
4197 let v = map.get(&k).cloned();
4198 let kv = v.as_ref().map(|v| (&k, v));
4199
4200 assert_eq!(map.raw_entry().from_key(&k), kv);
4201 assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv);
4202 assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv);
4203 assert_eq!(map.raw_entry().search_bucket(hash, |q| *q == k), kv);
4204
4205 match map.raw_entry_mut().from_key(&k) {
4206 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4207 Vacant(_) => assert_eq!(v, None),
4208 }
4209 match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) {
4210 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4211 Vacant(_) => assert_eq!(v, None),
4212 }
4213 match map.raw_entry_mut().from_hash(hash, |q| *q == k) {
4214 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4215 Vacant(_) => assert_eq!(v, None),
4216 }
4217 match map.raw_entry_mut().search_bucket(hash, |q| *q == k) {
4218 Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv),
4219 Vacant(_) => assert_eq!(v, None),
4220 }
4221 }
4222 }
4223
4224}