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