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