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