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