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