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