]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/map.rs
Do not show `::constructor` on tuple struct diagnostics
[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`]
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     /// Deprecated, renamed to `remove_entry`
2021     #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2022     #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2023     pub fn remove_pair(self) -> (K, V) {
2024         self.remove_entry()
2025     }
2026
2027     /// Take the ownership of the key and value from the map.
2028     ///
2029     /// # Examples
2030     ///
2031     /// ```
2032     /// use std::collections::HashMap;
2033     /// use std::collections::hash_map::Entry;
2034     ///
2035     /// let mut map: HashMap<&str, u32> = HashMap::new();
2036     /// map.entry("poneyland").or_insert(12);
2037     ///
2038     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2039     ///     // We delete the entry from the map.
2040     ///     o.remove_entry();
2041     /// }
2042     ///
2043     /// assert_eq!(map.contains_key("poneyland"), false);
2044     /// ```
2045     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2046     pub fn remove_entry(self) -> (K, V) {
2047         let (k, v, _) = pop_internal(self.elem);
2048         (k, v)
2049     }
2050
2051     /// Gets a reference to the value in the entry.
2052     ///
2053     /// # Examples
2054     ///
2055     /// ```
2056     /// use std::collections::HashMap;
2057     /// use std::collections::hash_map::Entry;
2058     ///
2059     /// let mut map: HashMap<&str, u32> = HashMap::new();
2060     /// map.entry("poneyland").or_insert(12);
2061     ///
2062     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2063     ///     assert_eq!(o.get(), &12);
2064     /// }
2065     /// ```
2066     #[stable(feature = "rust1", since = "1.0.0")]
2067     pub fn get(&self) -> &V {
2068         self.elem.read().1
2069     }
2070
2071     /// Gets a mutable reference to the value in the entry.
2072     ///
2073     /// # Examples
2074     ///
2075     /// ```
2076     /// use std::collections::HashMap;
2077     /// use std::collections::hash_map::Entry;
2078     ///
2079     /// let mut map: HashMap<&str, u32> = HashMap::new();
2080     /// map.entry("poneyland").or_insert(12);
2081     ///
2082     /// assert_eq!(map["poneyland"], 12);
2083     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2084     ///      *o.get_mut() += 10;
2085     /// }
2086     ///
2087     /// assert_eq!(map["poneyland"], 22);
2088     /// ```
2089     #[stable(feature = "rust1", since = "1.0.0")]
2090     pub fn get_mut(&mut self) -> &mut V {
2091         self.elem.read_mut().1
2092     }
2093
2094     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
2095     /// with a lifetime bound to the map itself.
2096     ///
2097     /// # Examples
2098     ///
2099     /// ```
2100     /// use std::collections::HashMap;
2101     /// use std::collections::hash_map::Entry;
2102     ///
2103     /// let mut map: HashMap<&str, u32> = HashMap::new();
2104     /// map.entry("poneyland").or_insert(12);
2105     ///
2106     /// assert_eq!(map["poneyland"], 12);
2107     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2108     ///     *o.into_mut() += 10;
2109     /// }
2110     ///
2111     /// assert_eq!(map["poneyland"], 22);
2112     /// ```
2113     #[stable(feature = "rust1", since = "1.0.0")]
2114     pub fn into_mut(self) -> &'a mut V {
2115         self.elem.into_mut_refs().1
2116     }
2117
2118     /// Sets the value of the entry, and returns the entry's old value.
2119     ///
2120     /// # Examples
2121     ///
2122     /// ```
2123     /// use std::collections::HashMap;
2124     /// use std::collections::hash_map::Entry;
2125     ///
2126     /// let mut map: HashMap<&str, u32> = HashMap::new();
2127     /// map.entry("poneyland").or_insert(12);
2128     ///
2129     /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2130     ///     assert_eq!(o.insert(15), 12);
2131     /// }
2132     ///
2133     /// assert_eq!(map["poneyland"], 15);
2134     /// ```
2135     #[stable(feature = "rust1", since = "1.0.0")]
2136     pub fn insert(&mut self, mut value: V) -> V {
2137         let old_value = self.get_mut();
2138         mem::swap(&mut value, old_value);
2139         value
2140     }
2141
2142     /// Takes the value out of the entry, and returns it.
2143     ///
2144     /// # Examples
2145     ///
2146     /// ```
2147     /// use std::collections::HashMap;
2148     /// use std::collections::hash_map::Entry;
2149     ///
2150     /// let mut map: HashMap<&str, u32> = HashMap::new();
2151     /// map.entry("poneyland").or_insert(12);
2152     ///
2153     /// if let Entry::Occupied(o) = map.entry("poneyland") {
2154     ///     assert_eq!(o.remove(), 12);
2155     /// }
2156     ///
2157     /// assert_eq!(map.contains_key("poneyland"), false);
2158     /// ```
2159     #[stable(feature = "rust1", since = "1.0.0")]
2160     pub fn remove(self) -> V {
2161         pop_internal(self.elem).1
2162     }
2163
2164     /// Returns a key that was used for search.
2165     ///
2166     /// The key was retained for further use.
2167     fn take_key(&mut self) -> Option<K> {
2168         self.key.take()
2169     }
2170 }
2171
2172 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
2173     /// Gets a reference to the key that would be used when inserting a value
2174     /// through the `VacantEntry`.
2175     ///
2176     /// # Examples
2177     ///
2178     /// ```
2179     /// use std::collections::HashMap;
2180     ///
2181     /// let mut map: HashMap<&str, u32> = HashMap::new();
2182     /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2183     /// ```
2184     #[stable(feature = "map_entry_keys", since = "1.10.0")]
2185     pub fn key(&self) -> &K {
2186         &self.key
2187     }
2188
2189     /// Take ownership of the key.
2190     ///
2191     /// # Examples
2192     ///
2193     /// ```
2194     /// use std::collections::HashMap;
2195     /// use std::collections::hash_map::Entry;
2196     ///
2197     /// let mut map: HashMap<&str, u32> = HashMap::new();
2198     ///
2199     /// if let Entry::Vacant(v) = map.entry("poneyland") {
2200     ///     v.into_key();
2201     /// }
2202     /// ```
2203     #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2204     pub fn into_key(self) -> K {
2205         self.key
2206     }
2207
2208     /// Sets the value of the entry with the VacantEntry's key,
2209     /// and returns a mutable reference to it.
2210     ///
2211     /// # Examples
2212     ///
2213     /// ```
2214     /// use std::collections::HashMap;
2215     /// use std::collections::hash_map::Entry;
2216     ///
2217     /// let mut map: HashMap<&str, u32> = HashMap::new();
2218     ///
2219     /// if let Entry::Vacant(o) = map.entry("poneyland") {
2220     ///     o.insert(37);
2221     /// }
2222     /// assert_eq!(map["poneyland"], 37);
2223     /// ```
2224     #[stable(feature = "rust1", since = "1.0.0")]
2225     pub fn insert(self, value: V) -> &'a mut V {
2226         let b = match self.elem {
2227             NeqElem(mut bucket, disp) => {
2228                 if disp >= DISPLACEMENT_THRESHOLD {
2229                     bucket.table_mut().set_tag(true);
2230                 }
2231                 robin_hood(bucket, disp, self.hash, self.key, value)
2232             },
2233             NoElem(mut bucket, disp) => {
2234                 if disp >= DISPLACEMENT_THRESHOLD {
2235                     bucket.table_mut().set_tag(true);
2236                 }
2237                 bucket.put(self.hash, self.key, value)
2238             },
2239         };
2240         b.into_mut_refs().1
2241     }
2242
2243     // Only used for InPlacement insert. Avoid unnecessary value copy.
2244     // The value remains uninitialized.
2245     unsafe fn insert_key(self) -> FullBucketMut<'a, K, V> {
2246         match self.elem {
2247             NeqElem(mut bucket, disp) => {
2248                 if disp >= DISPLACEMENT_THRESHOLD {
2249                     bucket.table_mut().set_tag(true);
2250                 }
2251                 let uninit = mem::uninitialized();
2252                 robin_hood(bucket, disp, self.hash, self.key, uninit)
2253             },
2254             NoElem(mut bucket, disp) => {
2255                 if disp >= DISPLACEMENT_THRESHOLD {
2256                     bucket.table_mut().set_tag(true);
2257                 }
2258                 bucket.put_key(self.hash, self.key)
2259             },
2260         }
2261     }
2262 }
2263
2264 #[stable(feature = "rust1", since = "1.0.0")]
2265 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
2266     where K: Eq + Hash,
2267           S: BuildHasher + Default
2268 {
2269     fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
2270         let mut map = HashMap::with_hasher(Default::default());
2271         map.extend(iter);
2272         map
2273     }
2274 }
2275
2276 #[stable(feature = "rust1", since = "1.0.0")]
2277 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
2278     where K: Eq + Hash,
2279           S: BuildHasher
2280 {
2281     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2282         // Keys may be already present or show multiple times in the iterator.
2283         // Reserve the entire hint lower bound if the map is empty.
2284         // Otherwise reserve half the hint (rounded up), so the map
2285         // will only resize twice in the worst case.
2286         let iter = iter.into_iter();
2287         let reserve = if self.is_empty() {
2288             iter.size_hint().0
2289         } else {
2290             (iter.size_hint().0 + 1) / 2
2291         };
2292         self.reserve(reserve);
2293         for (k, v) in iter {
2294             self.insert(k, v);
2295         }
2296     }
2297 }
2298
2299 #[stable(feature = "hash_extend_copy", since = "1.4.0")]
2300 impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
2301     where K: Eq + Hash + Copy,
2302           V: Copy,
2303           S: BuildHasher
2304 {
2305     fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
2306         self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2307     }
2308 }
2309
2310 /// `RandomState` is the default state for [`HashMap`] types.
2311 ///
2312 /// A particular instance `RandomState` will create the same instances of
2313 /// [`Hasher`], but the hashers created by two different `RandomState`
2314 /// instances are unlikely to produce the same result for the same values.
2315 ///
2316 /// [`HashMap`]: struct.HashMap.html
2317 /// [`Hasher`]: ../../hash/trait.Hasher.html
2318 ///
2319 /// # Examples
2320 ///
2321 /// ```
2322 /// use std::collections::HashMap;
2323 /// use std::collections::hash_map::RandomState;
2324 ///
2325 /// let s = RandomState::new();
2326 /// let mut map = HashMap::with_hasher(s);
2327 /// map.insert(1, 2);
2328 /// ```
2329 #[derive(Clone)]
2330 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2331 pub struct RandomState {
2332     k0: u64,
2333     k1: u64,
2334 }
2335
2336 impl RandomState {
2337     /// Constructs a new `RandomState` that is initialized with random keys.
2338     ///
2339     /// # Examples
2340     ///
2341     /// ```
2342     /// use std::collections::hash_map::RandomState;
2343     ///
2344     /// let s = RandomState::new();
2345     /// ```
2346     #[inline]
2347     #[allow(deprecated)]
2348     // rand
2349     #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2350     pub fn new() -> RandomState {
2351         // Historically this function did not cache keys from the OS and instead
2352         // simply always called `rand::thread_rng().gen()` twice. In #31356 it
2353         // was discovered, however, that because we re-seed the thread-local RNG
2354         // from the OS periodically that this can cause excessive slowdown when
2355         // many hash maps are created on a thread. To solve this performance
2356         // trap we cache the first set of randomly generated keys per-thread.
2357         //
2358         // Later in #36481 it was discovered that exposing a deterministic
2359         // iteration order allows a form of DOS attack. To counter that we
2360         // increment one of the seeds on every RandomState creation, giving
2361         // every corresponding HashMap a different iteration order.
2362         thread_local!(static KEYS: Cell<(u64, u64)> = {
2363             let r = rand::OsRng::new();
2364             let mut r = r.expect("failed to create an OS RNG");
2365             Cell::new((r.gen(), r.gen()))
2366         });
2367
2368         KEYS.with(|keys| {
2369             let (k0, k1) = keys.get();
2370             keys.set((k0.wrapping_add(1), k1));
2371             RandomState { k0: k0, k1: k1 }
2372         })
2373     }
2374 }
2375
2376 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2377 impl BuildHasher for RandomState {
2378     type Hasher = DefaultHasher;
2379     #[inline]
2380     #[allow(deprecated)]
2381     fn build_hasher(&self) -> DefaultHasher {
2382         DefaultHasher(SipHasher13::new_with_keys(self.k0, self.k1))
2383     }
2384 }
2385
2386 /// The default [`Hasher`] used by [`RandomState`].
2387 ///
2388 /// The internal algorithm is not specified, and so it and its hashes should
2389 /// not be relied upon over releases.
2390 ///
2391 /// [`RandomState`]: struct.RandomState.html
2392 /// [`Hasher`]: ../../hash/trait.Hasher.html
2393 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2394 #[allow(deprecated)]
2395 #[derive(Debug)]
2396 pub struct DefaultHasher(SipHasher13);
2397
2398 impl DefaultHasher {
2399     /// Creates a new `DefaultHasher`.
2400     ///
2401     /// This hasher is not guaranteed to be the same as all other
2402     /// `DefaultHasher` instances, but is the same as all other `DefaultHasher`
2403     /// instances created through `new` or `default`.
2404     #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2405     #[allow(deprecated)]
2406     pub fn new() -> DefaultHasher {
2407         DefaultHasher(SipHasher13::new_with_keys(0, 0))
2408     }
2409 }
2410
2411 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2412 impl Default for DefaultHasher {
2413     /// Creates a new `DefaultHasher` using [`new`]. See its documentation for more.
2414     ///
2415     /// [`new`]: #method.new
2416     fn default() -> DefaultHasher {
2417         DefaultHasher::new()
2418     }
2419 }
2420
2421 #[stable(feature = "hashmap_default_hasher", since = "1.13.0")]
2422 impl Hasher for DefaultHasher {
2423     #[inline]
2424     fn write(&mut self, msg: &[u8]) {
2425         self.0.write(msg)
2426     }
2427
2428     #[inline]
2429     fn finish(&self) -> u64 {
2430         self.0.finish()
2431     }
2432 }
2433
2434 #[stable(feature = "hashmap_build_hasher", since = "1.7.0")]
2435 impl Default for RandomState {
2436     /// Constructs a new `RandomState`.
2437     #[inline]
2438     fn default() -> RandomState {
2439         RandomState::new()
2440     }
2441 }
2442
2443 #[stable(feature = "std_debug", since = "1.16.0")]
2444 impl fmt::Debug for RandomState {
2445     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2446         f.pad("RandomState { .. }")
2447     }
2448 }
2449
2450 impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
2451     where K: Eq + Hash + Borrow<Q>,
2452           S: BuildHasher,
2453           Q: Eq + Hash
2454 {
2455     type Key = K;
2456
2457     fn get(&self, key: &Q) -> Option<&K> {
2458         self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0)
2459     }
2460
2461     fn take(&mut self, key: &Q) -> Option<K> {
2462         if self.table.size() == 0 {
2463             return None;
2464         }
2465
2466         self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0)
2467     }
2468
2469     fn replace(&mut self, key: K) -> Option<K> {
2470         self.reserve(1);
2471
2472         match self.entry(key) {
2473             Occupied(mut occupied) => {
2474                 let key = occupied.take_key().unwrap();
2475                 Some(mem::replace(occupied.elem.read_mut().0, key))
2476             }
2477             Vacant(vacant) => {
2478                 vacant.insert(());
2479                 None
2480             }
2481         }
2482     }
2483 }
2484
2485 #[allow(dead_code)]
2486 fn assert_covariance() {
2487     fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> {
2488         v
2489     }
2490     fn map_val<'new>(v: HashMap<u8, &'static str>) -> HashMap<u8, &'new str> {
2491         v
2492     }
2493     fn iter_key<'a, 'new>(v: Iter<'a, &'static str, u8>) -> Iter<'a, &'new str, u8> {
2494         v
2495     }
2496     fn iter_val<'a, 'new>(v: Iter<'a, u8, &'static str>) -> Iter<'a, u8, &'new str> {
2497         v
2498     }
2499     fn into_iter_key<'new>(v: IntoIter<&'static str, u8>) -> IntoIter<&'new str, u8> {
2500         v
2501     }
2502     fn into_iter_val<'new>(v: IntoIter<u8, &'static str>) -> IntoIter<u8, &'new str> {
2503         v
2504     }
2505     fn keys_key<'a, 'new>(v: Keys<'a, &'static str, u8>) -> Keys<'a, &'new str, u8> {
2506         v
2507     }
2508     fn keys_val<'a, 'new>(v: Keys<'a, u8, &'static str>) -> Keys<'a, u8, &'new str> {
2509         v
2510     }
2511     fn values_key<'a, 'new>(v: Values<'a, &'static str, u8>) -> Values<'a, &'new str, u8> {
2512         v
2513     }
2514     fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
2515         v
2516     }
2517     fn drain<'new>(d: Drain<'static, &'static str, &'static str>)
2518                    -> Drain<'new, &'new str, &'new str> {
2519         d
2520     }
2521 }
2522
2523 #[cfg(test)]
2524 mod test_map {
2525     use super::HashMap;
2526     use super::Entry::{Occupied, Vacant};
2527     use super::RandomState;
2528     use cell::RefCell;
2529     use rand::{thread_rng, Rng};
2530     use panic;
2531
2532     #[test]
2533     fn test_zero_capacities() {
2534         type HM = HashMap<i32, i32>;
2535
2536         let m = HM::new();
2537         assert_eq!(m.capacity(), 0);
2538
2539         let m = HM::default();
2540         assert_eq!(m.capacity(), 0);
2541
2542         let m = HM::with_hasher(RandomState::new());
2543         assert_eq!(m.capacity(), 0);
2544
2545         let m = HM::with_capacity(0);
2546         assert_eq!(m.capacity(), 0);
2547
2548         let m = HM::with_capacity_and_hasher(0, RandomState::new());
2549         assert_eq!(m.capacity(), 0);
2550
2551         let mut m = HM::new();
2552         m.insert(1, 1);
2553         m.insert(2, 2);
2554         m.remove(&1);
2555         m.remove(&2);
2556         m.shrink_to_fit();
2557         assert_eq!(m.capacity(), 0);
2558
2559         let mut m = HM::new();
2560         m.reserve(0);
2561         assert_eq!(m.capacity(), 0);
2562     }
2563
2564     #[test]
2565     fn test_create_capacity_zero() {
2566         let mut m = HashMap::with_capacity(0);
2567
2568         assert!(m.insert(1, 1).is_none());
2569
2570         assert!(m.contains_key(&1));
2571         assert!(!m.contains_key(&0));
2572     }
2573
2574     #[test]
2575     fn test_insert() {
2576         let mut m = HashMap::new();
2577         assert_eq!(m.len(), 0);
2578         assert!(m.insert(1, 2).is_none());
2579         assert_eq!(m.len(), 1);
2580         assert!(m.insert(2, 4).is_none());
2581         assert_eq!(m.len(), 2);
2582         assert_eq!(*m.get(&1).unwrap(), 2);
2583         assert_eq!(*m.get(&2).unwrap(), 4);
2584     }
2585
2586     #[test]
2587     fn test_clone() {
2588         let mut m = HashMap::new();
2589         assert_eq!(m.len(), 0);
2590         assert!(m.insert(1, 2).is_none());
2591         assert_eq!(m.len(), 1);
2592         assert!(m.insert(2, 4).is_none());
2593         assert_eq!(m.len(), 2);
2594         let m2 = m.clone();
2595         assert_eq!(*m2.get(&1).unwrap(), 2);
2596         assert_eq!(*m2.get(&2).unwrap(), 4);
2597         assert_eq!(m2.len(), 2);
2598     }
2599
2600     thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }
2601
2602     #[derive(Hash, PartialEq, Eq)]
2603     struct Dropable {
2604         k: usize,
2605     }
2606
2607     impl Dropable {
2608         fn new(k: usize) -> Dropable {
2609             DROP_VECTOR.with(|slot| {
2610                 slot.borrow_mut()[k] += 1;
2611             });
2612
2613             Dropable { k: k }
2614         }
2615     }
2616
2617     impl Drop for Dropable {
2618         fn drop(&mut self) {
2619             DROP_VECTOR.with(|slot| {
2620                 slot.borrow_mut()[self.k] -= 1;
2621             });
2622         }
2623     }
2624
2625     impl Clone for Dropable {
2626         fn clone(&self) -> Dropable {
2627             Dropable::new(self.k)
2628         }
2629     }
2630
2631     #[test]
2632     fn test_drops() {
2633         DROP_VECTOR.with(|slot| {
2634             *slot.borrow_mut() = vec![0; 200];
2635         });
2636
2637         {
2638             let mut m = HashMap::new();
2639
2640             DROP_VECTOR.with(|v| {
2641                 for i in 0..200 {
2642                     assert_eq!(v.borrow()[i], 0);
2643                 }
2644             });
2645
2646             for i in 0..100 {
2647                 let d1 = Dropable::new(i);
2648                 let d2 = Dropable::new(i + 100);
2649                 m.insert(d1, d2);
2650             }
2651
2652             DROP_VECTOR.with(|v| {
2653                 for i in 0..200 {
2654                     assert_eq!(v.borrow()[i], 1);
2655                 }
2656             });
2657
2658             for i in 0..50 {
2659                 let k = Dropable::new(i);
2660                 let v = m.remove(&k);
2661
2662                 assert!(v.is_some());
2663
2664                 DROP_VECTOR.with(|v| {
2665                     assert_eq!(v.borrow()[i], 1);
2666                     assert_eq!(v.borrow()[i+100], 1);
2667                 });
2668             }
2669
2670             DROP_VECTOR.with(|v| {
2671                 for i in 0..50 {
2672                     assert_eq!(v.borrow()[i], 0);
2673                     assert_eq!(v.borrow()[i+100], 0);
2674                 }
2675
2676                 for i in 50..100 {
2677                     assert_eq!(v.borrow()[i], 1);
2678                     assert_eq!(v.borrow()[i+100], 1);
2679                 }
2680             });
2681         }
2682
2683         DROP_VECTOR.with(|v| {
2684             for i in 0..200 {
2685                 assert_eq!(v.borrow()[i], 0);
2686             }
2687         });
2688     }
2689
2690     #[test]
2691     fn test_into_iter_drops() {
2692         DROP_VECTOR.with(|v| {
2693             *v.borrow_mut() = vec![0; 200];
2694         });
2695
2696         let hm = {
2697             let mut hm = HashMap::new();
2698
2699             DROP_VECTOR.with(|v| {
2700                 for i in 0..200 {
2701                     assert_eq!(v.borrow()[i], 0);
2702                 }
2703             });
2704
2705             for i in 0..100 {
2706                 let d1 = Dropable::new(i);
2707                 let d2 = Dropable::new(i + 100);
2708                 hm.insert(d1, d2);
2709             }
2710
2711             DROP_VECTOR.with(|v| {
2712                 for i in 0..200 {
2713                     assert_eq!(v.borrow()[i], 1);
2714                 }
2715             });
2716
2717             hm
2718         };
2719
2720         // By the way, ensure that cloning doesn't screw up the dropping.
2721         drop(hm.clone());
2722
2723         {
2724             let mut half = hm.into_iter().take(50);
2725
2726             DROP_VECTOR.with(|v| {
2727                 for i in 0..200 {
2728                     assert_eq!(v.borrow()[i], 1);
2729                 }
2730             });
2731
2732             for _ in half.by_ref() {}
2733
2734             DROP_VECTOR.with(|v| {
2735                 let nk = (0..100)
2736                     .filter(|&i| v.borrow()[i] == 1)
2737                     .count();
2738
2739                 let nv = (0..100)
2740                     .filter(|&i| v.borrow()[i + 100] == 1)
2741                     .count();
2742
2743                 assert_eq!(nk, 50);
2744                 assert_eq!(nv, 50);
2745             });
2746         };
2747
2748         DROP_VECTOR.with(|v| {
2749             for i in 0..200 {
2750                 assert_eq!(v.borrow()[i], 0);
2751             }
2752         });
2753     }
2754
2755     #[test]
2756     fn test_empty_remove() {
2757         let mut m: HashMap<isize, bool> = HashMap::new();
2758         assert_eq!(m.remove(&0), None);
2759     }
2760
2761     #[test]
2762     fn test_empty_entry() {
2763         let mut m: HashMap<isize, bool> = HashMap::new();
2764         match m.entry(0) {
2765             Occupied(_) => panic!(),
2766             Vacant(_) => {}
2767         }
2768         assert!(*m.entry(0).or_insert(true));
2769         assert_eq!(m.len(), 1);
2770     }
2771
2772     #[test]
2773     fn test_empty_iter() {
2774         let mut m: HashMap<isize, bool> = HashMap::new();
2775         assert_eq!(m.drain().next(), None);
2776         assert_eq!(m.keys().next(), None);
2777         assert_eq!(m.values().next(), None);
2778         assert_eq!(m.values_mut().next(), None);
2779         assert_eq!(m.iter().next(), None);
2780         assert_eq!(m.iter_mut().next(), None);
2781         assert_eq!(m.len(), 0);
2782         assert!(m.is_empty());
2783         assert_eq!(m.into_iter().next(), None);
2784     }
2785
2786     #[test]
2787     fn test_lots_of_insertions() {
2788         let mut m = HashMap::new();
2789
2790         // Try this a few times to make sure we never screw up the hashmap's
2791         // internal state.
2792         for _ in 0..10 {
2793             assert!(m.is_empty());
2794
2795             for i in 1..1001 {
2796                 assert!(m.insert(i, i).is_none());
2797
2798                 for j in 1..i + 1 {
2799                     let r = m.get(&j);
2800                     assert_eq!(r, Some(&j));
2801                 }
2802
2803                 for j in i + 1..1001 {
2804                     let r = m.get(&j);
2805                     assert_eq!(r, None);
2806                 }
2807             }
2808
2809             for i in 1001..2001 {
2810                 assert!(!m.contains_key(&i));
2811             }
2812
2813             // remove forwards
2814             for i in 1..1001 {
2815                 assert!(m.remove(&i).is_some());
2816
2817                 for j in 1..i + 1 {
2818                     assert!(!m.contains_key(&j));
2819                 }
2820
2821                 for j in i + 1..1001 {
2822                     assert!(m.contains_key(&j));
2823                 }
2824             }
2825
2826             for i in 1..1001 {
2827                 assert!(!m.contains_key(&i));
2828             }
2829
2830             for i in 1..1001 {
2831                 assert!(m.insert(i, i).is_none());
2832             }
2833
2834             // remove backwards
2835             for i in (1..1001).rev() {
2836                 assert!(m.remove(&i).is_some());
2837
2838                 for j in i..1001 {
2839                     assert!(!m.contains_key(&j));
2840                 }
2841
2842                 for j in 1..i {
2843                     assert!(m.contains_key(&j));
2844                 }
2845             }
2846         }
2847     }
2848
2849     #[test]
2850     fn test_find_mut() {
2851         let mut m = HashMap::new();
2852         assert!(m.insert(1, 12).is_none());
2853         assert!(m.insert(2, 8).is_none());
2854         assert!(m.insert(5, 14).is_none());
2855         let new = 100;
2856         match m.get_mut(&5) {
2857             None => panic!(),
2858             Some(x) => *x = new,
2859         }
2860         assert_eq!(m.get(&5), Some(&new));
2861     }
2862
2863     #[test]
2864     fn test_insert_overwrite() {
2865         let mut m = HashMap::new();
2866         assert!(m.insert(1, 2).is_none());
2867         assert_eq!(*m.get(&1).unwrap(), 2);
2868         assert!(!m.insert(1, 3).is_none());
2869         assert_eq!(*m.get(&1).unwrap(), 3);
2870     }
2871
2872     #[test]
2873     fn test_insert_conflicts() {
2874         let mut m = HashMap::with_capacity(4);
2875         assert!(m.insert(1, 2).is_none());
2876         assert!(m.insert(5, 3).is_none());
2877         assert!(m.insert(9, 4).is_none());
2878         assert_eq!(*m.get(&9).unwrap(), 4);
2879         assert_eq!(*m.get(&5).unwrap(), 3);
2880         assert_eq!(*m.get(&1).unwrap(), 2);
2881     }
2882
2883     #[test]
2884     fn test_conflict_remove() {
2885         let mut m = HashMap::with_capacity(4);
2886         assert!(m.insert(1, 2).is_none());
2887         assert_eq!(*m.get(&1).unwrap(), 2);
2888         assert!(m.insert(5, 3).is_none());
2889         assert_eq!(*m.get(&1).unwrap(), 2);
2890         assert_eq!(*m.get(&5).unwrap(), 3);
2891         assert!(m.insert(9, 4).is_none());
2892         assert_eq!(*m.get(&1).unwrap(), 2);
2893         assert_eq!(*m.get(&5).unwrap(), 3);
2894         assert_eq!(*m.get(&9).unwrap(), 4);
2895         assert!(m.remove(&1).is_some());
2896         assert_eq!(*m.get(&9).unwrap(), 4);
2897         assert_eq!(*m.get(&5).unwrap(), 3);
2898     }
2899
2900     #[test]
2901     fn test_is_empty() {
2902         let mut m = HashMap::with_capacity(4);
2903         assert!(m.insert(1, 2).is_none());
2904         assert!(!m.is_empty());
2905         assert!(m.remove(&1).is_some());
2906         assert!(m.is_empty());
2907     }
2908
2909     #[test]
2910     fn test_pop() {
2911         let mut m = HashMap::new();
2912         m.insert(1, 2);
2913         assert_eq!(m.remove(&1), Some(2));
2914         assert_eq!(m.remove(&1), None);
2915     }
2916
2917     #[test]
2918     fn test_iterate() {
2919         let mut m = HashMap::with_capacity(4);
2920         for i in 0..32 {
2921             assert!(m.insert(i, i*2).is_none());
2922         }
2923         assert_eq!(m.len(), 32);
2924
2925         let mut observed: u32 = 0;
2926
2927         for (k, v) in &m {
2928             assert_eq!(*v, *k * 2);
2929             observed |= 1 << *k;
2930         }
2931         assert_eq!(observed, 0xFFFF_FFFF);
2932     }
2933
2934     #[test]
2935     fn test_keys() {
2936         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2937         let map: HashMap<_, _> = vec.into_iter().collect();
2938         let keys: Vec<_> = map.keys().cloned().collect();
2939         assert_eq!(keys.len(), 3);
2940         assert!(keys.contains(&1));
2941         assert!(keys.contains(&2));
2942         assert!(keys.contains(&3));
2943     }
2944
2945     #[test]
2946     fn test_values() {
2947         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
2948         let map: HashMap<_, _> = vec.into_iter().collect();
2949         let values: Vec<_> = map.values().cloned().collect();
2950         assert_eq!(values.len(), 3);
2951         assert!(values.contains(&'a'));
2952         assert!(values.contains(&'b'));
2953         assert!(values.contains(&'c'));
2954     }
2955
2956     #[test]
2957     fn test_values_mut() {
2958         let vec = vec![(1, 1), (2, 2), (3, 3)];
2959         let mut map: HashMap<_, _> = vec.into_iter().collect();
2960         for value in map.values_mut() {
2961             *value = (*value) * 2
2962         }
2963         let values: Vec<_> = map.values().cloned().collect();
2964         assert_eq!(values.len(), 3);
2965         assert!(values.contains(&2));
2966         assert!(values.contains(&4));
2967         assert!(values.contains(&6));
2968     }
2969
2970     #[test]
2971     fn test_find() {
2972         let mut m = HashMap::new();
2973         assert!(m.get(&1).is_none());
2974         m.insert(1, 2);
2975         match m.get(&1) {
2976             None => panic!(),
2977             Some(v) => assert_eq!(*v, 2),
2978         }
2979     }
2980
2981     #[test]
2982     fn test_eq() {
2983         let mut m1 = HashMap::new();
2984         m1.insert(1, 2);
2985         m1.insert(2, 3);
2986         m1.insert(3, 4);
2987
2988         let mut m2 = HashMap::new();
2989         m2.insert(1, 2);
2990         m2.insert(2, 3);
2991
2992         assert!(m1 != m2);
2993
2994         m2.insert(3, 4);
2995
2996         assert_eq!(m1, m2);
2997     }
2998
2999     #[test]
3000     fn test_show() {
3001         let mut map = HashMap::new();
3002         let empty: HashMap<i32, i32> = HashMap::new();
3003
3004         map.insert(1, 2);
3005         map.insert(3, 4);
3006
3007         let map_str = format!("{:?}", map);
3008
3009         assert!(map_str == "{1: 2, 3: 4}" ||
3010                 map_str == "{3: 4, 1: 2}");
3011         assert_eq!(format!("{:?}", empty), "{}");
3012     }
3013
3014     #[test]
3015     fn test_expand() {
3016         let mut m = HashMap::new();
3017
3018         assert_eq!(m.len(), 0);
3019         assert!(m.is_empty());
3020
3021         let mut i = 0;
3022         let old_raw_cap = m.raw_capacity();
3023         while old_raw_cap == m.raw_capacity() {
3024             m.insert(i, i);
3025             i += 1;
3026         }
3027
3028         assert_eq!(m.len(), i);
3029         assert!(!m.is_empty());
3030     }
3031
3032     #[test]
3033     fn test_behavior_resize_policy() {
3034         let mut m = HashMap::new();
3035
3036         assert_eq!(m.len(), 0);
3037         assert_eq!(m.raw_capacity(), 0);
3038         assert!(m.is_empty());
3039
3040         m.insert(0, 0);
3041         m.remove(&0);
3042         assert!(m.is_empty());
3043         let initial_raw_cap = m.raw_capacity();
3044         m.reserve(initial_raw_cap);
3045         let raw_cap = m.raw_capacity();
3046
3047         assert_eq!(raw_cap, initial_raw_cap * 2);
3048
3049         let mut i = 0;
3050         for _ in 0..raw_cap * 3 / 4 {
3051             m.insert(i, i);
3052             i += 1;
3053         }
3054         // three quarters full
3055
3056         assert_eq!(m.len(), i);
3057         assert_eq!(m.raw_capacity(), raw_cap);
3058
3059         for _ in 0..raw_cap / 4 {
3060             m.insert(i, i);
3061             i += 1;
3062         }
3063         // half full
3064
3065         let new_raw_cap = m.raw_capacity();
3066         assert_eq!(new_raw_cap, raw_cap * 2);
3067
3068         for _ in 0..raw_cap / 2 - 1 {
3069             i -= 1;
3070             m.remove(&i);
3071             assert_eq!(m.raw_capacity(), new_raw_cap);
3072         }
3073         // A little more than one quarter full.
3074         m.shrink_to_fit();
3075         assert_eq!(m.raw_capacity(), raw_cap);
3076         // again, a little more than half full
3077         for _ in 0..raw_cap / 2 - 1 {
3078             i -= 1;
3079             m.remove(&i);
3080         }
3081         m.shrink_to_fit();
3082
3083         assert_eq!(m.len(), i);
3084         assert!(!m.is_empty());
3085         assert_eq!(m.raw_capacity(), initial_raw_cap);
3086     }
3087
3088     #[test]
3089     fn test_reserve_shrink_to_fit() {
3090         let mut m = HashMap::new();
3091         m.insert(0, 0);
3092         m.remove(&0);
3093         assert!(m.capacity() >= m.len());
3094         for i in 0..128 {
3095             m.insert(i, i);
3096         }
3097         m.reserve(256);
3098
3099         let usable_cap = m.capacity();
3100         for i in 128..(128 + 256) {
3101             m.insert(i, i);
3102             assert_eq!(m.capacity(), usable_cap);
3103         }
3104
3105         for i in 100..(128 + 256) {
3106             assert_eq!(m.remove(&i), Some(i));
3107         }
3108         m.shrink_to_fit();
3109
3110         assert_eq!(m.len(), 100);
3111         assert!(!m.is_empty());
3112         assert!(m.capacity() >= m.len());
3113
3114         for i in 0..100 {
3115             assert_eq!(m.remove(&i), Some(i));
3116         }
3117         m.shrink_to_fit();
3118         m.insert(0, 0);
3119
3120         assert_eq!(m.len(), 1);
3121         assert!(m.capacity() >= m.len());
3122         assert_eq!(m.remove(&0), Some(0));
3123     }
3124
3125     #[test]
3126     fn test_from_iter() {
3127         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3128
3129         let map: HashMap<_, _> = xs.iter().cloned().collect();
3130
3131         for &(k, v) in &xs {
3132             assert_eq!(map.get(&k), Some(&v));
3133         }
3134     }
3135
3136     #[test]
3137     fn test_size_hint() {
3138         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3139
3140         let map: HashMap<_, _> = xs.iter().cloned().collect();
3141
3142         let mut iter = map.iter();
3143
3144         for _ in iter.by_ref().take(3) {}
3145
3146         assert_eq!(iter.size_hint(), (3, Some(3)));
3147     }
3148
3149     #[test]
3150     fn test_iter_len() {
3151         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3152
3153         let map: HashMap<_, _> = xs.iter().cloned().collect();
3154
3155         let mut iter = map.iter();
3156
3157         for _ in iter.by_ref().take(3) {}
3158
3159         assert_eq!(iter.len(), 3);
3160     }
3161
3162     #[test]
3163     fn test_mut_size_hint() {
3164         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3165
3166         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3167
3168         let mut iter = map.iter_mut();
3169
3170         for _ in iter.by_ref().take(3) {}
3171
3172         assert_eq!(iter.size_hint(), (3, Some(3)));
3173     }
3174
3175     #[test]
3176     fn test_iter_mut_len() {
3177         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
3178
3179         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3180
3181         let mut iter = map.iter_mut();
3182
3183         for _ in iter.by_ref().take(3) {}
3184
3185         assert_eq!(iter.len(), 3);
3186     }
3187
3188     #[test]
3189     fn test_index() {
3190         let mut map = HashMap::new();
3191
3192         map.insert(1, 2);
3193         map.insert(2, 1);
3194         map.insert(3, 4);
3195
3196         assert_eq!(map[&2], 1);
3197     }
3198
3199     #[test]
3200     #[should_panic]
3201     fn test_index_nonexistent() {
3202         let mut map = HashMap::new();
3203
3204         map.insert(1, 2);
3205         map.insert(2, 1);
3206         map.insert(3, 4);
3207
3208         map[&4];
3209     }
3210
3211     #[test]
3212     fn test_entry() {
3213         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
3214
3215         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
3216
3217         // Existing key (insert)
3218         match map.entry(1) {
3219             Vacant(_) => unreachable!(),
3220             Occupied(mut view) => {
3221                 assert_eq!(view.get(), &10);
3222                 assert_eq!(view.insert(100), 10);
3223             }
3224         }
3225         assert_eq!(map.get(&1).unwrap(), &100);
3226         assert_eq!(map.len(), 6);
3227
3228
3229         // Existing key (update)
3230         match map.entry(2) {
3231             Vacant(_) => unreachable!(),
3232             Occupied(mut view) => {
3233                 let v = view.get_mut();
3234                 let new_v = (*v) * 10;
3235                 *v = new_v;
3236             }
3237         }
3238         assert_eq!(map.get(&2).unwrap(), &200);
3239         assert_eq!(map.len(), 6);
3240
3241         // Existing key (take)
3242         match map.entry(3) {
3243             Vacant(_) => unreachable!(),
3244             Occupied(view) => {
3245                 assert_eq!(view.remove(), 30);
3246             }
3247         }
3248         assert_eq!(map.get(&3), None);
3249         assert_eq!(map.len(), 5);
3250
3251
3252         // Inexistent key (insert)
3253         match map.entry(10) {
3254             Occupied(_) => unreachable!(),
3255             Vacant(view) => {
3256                 assert_eq!(*view.insert(1000), 1000);
3257             }
3258         }
3259         assert_eq!(map.get(&10).unwrap(), &1000);
3260         assert_eq!(map.len(), 6);
3261     }
3262
3263     #[test]
3264     fn test_entry_take_doesnt_corrupt() {
3265         #![allow(deprecated)] //rand
3266         // Test for #19292
3267         fn check(m: &HashMap<isize, ()>) {
3268             for k in m.keys() {
3269                 assert!(m.contains_key(k),
3270                         "{} is in keys() but not in the map?", k);
3271             }
3272         }
3273
3274         let mut m = HashMap::new();
3275         let mut rng = thread_rng();
3276
3277         // Populate the map with some items.
3278         for _ in 0..50 {
3279             let x = rng.gen_range(-10, 10);
3280             m.insert(x, ());
3281         }
3282
3283         for i in 0..1000 {
3284             let x = rng.gen_range(-10, 10);
3285             match m.entry(x) {
3286                 Vacant(_) => {}
3287                 Occupied(e) => {
3288                     println!("{}: remove {}", i, x);
3289                     e.remove();
3290                 }
3291             }
3292
3293             check(&m);
3294         }
3295     }
3296
3297     #[test]
3298     fn test_extend_ref() {
3299         let mut a = HashMap::new();
3300         a.insert(1, "one");
3301         let mut b = HashMap::new();
3302         b.insert(2, "two");
3303         b.insert(3, "three");
3304
3305         a.extend(&b);
3306
3307         assert_eq!(a.len(), 3);
3308         assert_eq!(a[&1], "one");
3309         assert_eq!(a[&2], "two");
3310         assert_eq!(a[&3], "three");
3311     }
3312
3313     #[test]
3314     fn test_capacity_not_less_than_len() {
3315         let mut a = HashMap::new();
3316         let mut item = 0;
3317
3318         for _ in 0..116 {
3319             a.insert(item, 0);
3320             item += 1;
3321         }
3322
3323         assert!(a.capacity() > a.len());
3324
3325         let free = a.capacity() - a.len();
3326         for _ in 0..free {
3327             a.insert(item, 0);
3328             item += 1;
3329         }
3330
3331         assert_eq!(a.len(), a.capacity());
3332
3333         // Insert at capacity should cause allocation.
3334         a.insert(item, 0);
3335         assert!(a.capacity() > a.len());
3336     }
3337
3338     #[test]
3339     fn test_occupied_entry_key() {
3340         let mut a = HashMap::new();
3341         let key = "hello there";
3342         let value = "value goes here";
3343         assert!(a.is_empty());
3344         a.insert(key.clone(), value.clone());
3345         assert_eq!(a.len(), 1);
3346         assert_eq!(a[key], value);
3347
3348         match a.entry(key.clone()) {
3349             Vacant(_) => panic!(),
3350             Occupied(e) => assert_eq!(key, *e.key()),
3351         }
3352         assert_eq!(a.len(), 1);
3353         assert_eq!(a[key], value);
3354     }
3355
3356     #[test]
3357     fn test_vacant_entry_key() {
3358         let mut a = HashMap::new();
3359         let key = "hello there";
3360         let value = "value goes here";
3361
3362         assert!(a.is_empty());
3363         match a.entry(key.clone()) {
3364             Occupied(_) => panic!(),
3365             Vacant(e) => {
3366                 assert_eq!(key, *e.key());
3367                 e.insert(value.clone());
3368             }
3369         }
3370         assert_eq!(a.len(), 1);
3371         assert_eq!(a[key], value);
3372     }
3373
3374     #[test]
3375     fn test_retain() {
3376         let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect();
3377
3378         map.retain(|&k, _| k % 2 == 0);
3379         assert_eq!(map.len(), 50);
3380         assert_eq!(map[&2], 20);
3381         assert_eq!(map[&4], 40);
3382         assert_eq!(map[&6], 60);
3383     }
3384
3385     #[test]
3386     fn test_adaptive() {
3387         const TEST_LEN: usize = 5000;
3388         // by cloning we get maps with the same hasher seed
3389         let mut first = HashMap::new();
3390         let mut second = first.clone();
3391         first.extend((0..TEST_LEN).map(|i| (i, i)));
3392         second.extend((TEST_LEN..TEST_LEN * 2).map(|i| (i, i)));
3393
3394         for (&k, &v) in &second {
3395             let prev_cap = first.capacity();
3396             let expect_grow = first.len() == prev_cap;
3397             first.insert(k, v);
3398             if !expect_grow && first.capacity() != prev_cap {
3399                 return;
3400             }
3401         }
3402         panic!("Adaptive early resize failed");
3403     }
3404
3405     #[test]
3406     fn test_placement_in() {
3407         let mut map = HashMap::new();
3408         map.extend((0..10).map(|i| (i, i)));
3409
3410         map.entry(100) <- 100;
3411         assert_eq!(map[&100], 100);
3412
3413         map.entry(0) <- 10;
3414         assert_eq!(map[&0], 10);
3415
3416         assert_eq!(map.len(), 11);
3417     }
3418
3419     #[test]
3420     fn test_placement_panic() {
3421         let mut map = HashMap::new();
3422         map.extend((0..10).map(|i| (i, i)));
3423
3424         fn mkpanic() -> usize { panic!() }
3425
3426         // modify existing key
3427         // when panic happens, previous key is removed.
3428         let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(0) <- mkpanic(); }));
3429         assert_eq!(map.len(), 9);
3430         assert!(!map.contains_key(&0));
3431
3432         // add new key
3433         let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { map.entry(100) <- mkpanic(); }));
3434         assert_eq!(map.len(), 9);
3435         assert!(!map.contains_key(&100));
3436     }
3437
3438     #[test]
3439     fn test_placement_drop() {
3440         // correctly drop
3441         struct TestV<'a>(&'a mut bool);
3442         impl<'a> Drop for TestV<'a> {
3443             fn drop(&mut self) {
3444                 if !*self.0 { panic!("value double drop!"); } // no double drop
3445                 *self.0 = false;
3446             }
3447         }
3448
3449         fn makepanic<'a>() -> TestV<'a> { panic!() }
3450
3451         let mut can_drop = true;
3452         let mut hm = HashMap::new();
3453         hm.insert(0, TestV(&mut can_drop));
3454         let _ = panic::catch_unwind(panic::AssertUnwindSafe(|| { hm.entry(0) <- makepanic(); }));
3455         assert_eq!(hm.len(), 0);
3456     }
3457 }