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