]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/map.rs
Auto merge of #23213 - ipetkov:rustdoc-src-fix, r=huonw
[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 // ignore-lexer-test FIXME #15883
12
13 use self::Entry::*;
14 use self::SearchResult::*;
15 use self::VacantEntryState::*;
16
17 use borrow::Borrow;
18 use clone::Clone;
19 use cmp::{max, Eq, PartialEq};
20 use default::Default;
21 use fmt::{self, Debug};
22 use hash::{Hash, SipHasher};
23 use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map};
24 use marker::Sized;
25 use mem::{self, replace};
26 use ops::{Deref, FnMut, Index, IndexMut};
27 use option::Option::{self, Some, None};
28 use rand::{self, Rng};
29 use result::Result::{self, Ok, Err};
30
31 use super::table::{
32     self,
33     Bucket,
34     EmptyBucket,
35     FullBucket,
36     FullBucketImm,
37     FullBucketMut,
38     RawTable,
39     SafeHash
40 };
41 use super::table::BucketState::{
42     Empty,
43     Full,
44 };
45 use super::state::HashState;
46
47 const INITIAL_LOG2_CAP: usize = 5;
48 #[unstable(feature = "std_misc")]
49 pub const INITIAL_CAPACITY: usize = 1 << INITIAL_LOG2_CAP; // 2^5
50
51 /// The default behavior of HashMap implements a load factor of 90.9%.
52 /// This behavior is characterized by the following condition:
53 ///
54 /// - if size > 0.909 * capacity: grow the map
55 #[derive(Clone)]
56 struct DefaultResizePolicy;
57
58 impl DefaultResizePolicy {
59     fn new() -> DefaultResizePolicy {
60         DefaultResizePolicy
61     }
62
63     #[inline]
64     fn min_capacity(&self, usable_size: usize) -> usize {
65         // Here, we are rephrasing the logic by specifying the lower limit
66         // on capacity:
67         //
68         // - if `cap < size * 1.1`: grow the map
69         usable_size * 11 / 10
70     }
71
72     /// An inverse of `min_capacity`, approximately.
73     #[inline]
74     fn usable_capacity(&self, cap: usize) -> usize {
75         // As the number of entries approaches usable capacity,
76         // min_capacity(size) must be smaller than the internal capacity,
77         // so that the map is not resized:
78         // `min_capacity(usable_capacity(x)) <= x`.
79         // The left-hand side can only be smaller due to flooring by integer
80         // division.
81         //
82         // This doesn't have to be checked for overflow since allocation size
83         // in bytes will overflow earlier than multiplication by 10.
84         cap * 10 / 11
85     }
86 }
87
88 #[test]
89 fn test_resize_policy() {
90     let rp = DefaultResizePolicy;
91     for n in 0..1000 {
92         assert!(rp.min_capacity(rp.usable_capacity(n)) <= n);
93         assert!(rp.usable_capacity(rp.min_capacity(n)) <= n);
94     }
95 }
96
97 // The main performance trick in this hashmap is called Robin Hood Hashing.
98 // It gains its excellent performance from one essential operation:
99 //
100 //    If an insertion collides with an existing element, and that element's
101 //    "probe distance" (how far away the element is from its ideal location)
102 //    is higher than how far we've already probed, swap the elements.
103 //
104 // This massively lowers variance in probe distance, and allows us to get very
105 // high load factors with good performance. The 90% load factor I use is rather
106 // conservative.
107 //
108 // > Why a load factor of approximately 90%?
109 //
110 // In general, all the distances to initial buckets will converge on the mean.
111 // At a load factor of α, the odds of finding the target bucket after k
112 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
113 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), α=0.92. I round
114 // this down to make the math easier on the CPU and avoid its FPU.
115 // Since on average we start the probing in the middle of a cache line, this
116 // strategy pulls in two cache lines of hashes on every lookup. I think that's
117 // pretty good, but if you want to trade off some space, it could go down to one
118 // cache line on average with an α of 0.84.
119 //
120 // > Wait, what? Where did you get 1-α^k from?
121 //
122 // On the first probe, your odds of a collision with an existing element is α.
123 // The odds of doing this twice in a row is approximately α^2. For three times,
124 // α^3, etc. Therefore, the odds of colliding k times is α^k. The odds of NOT
125 // colliding after k tries is 1-α^k.
126 //
127 // The paper from 1986 cited below mentions an implementation which keeps track
128 // of the distance-to-initial-bucket histogram. This approach is not suitable
129 // for modern architectures because it requires maintaining an internal data
130 // structure. This allows very good first guesses, but we are most concerned
131 // with guessing entire cache lines, not individual indexes. Furthermore, array
132 // accesses are no longer linear and in one direction, as we have now. There
133 // is also memory and cache pressure that this would entail that would be very
134 // difficult to properly see in a microbenchmark.
135 //
136 // ## Future Improvements (FIXME!)
137 //
138 // Allow the load factor to be changed dynamically and/or at initialization.
139 //
140 // Also, would it be possible for us to reuse storage when growing the
141 // underlying table? This is exactly the use case for 'realloc', and may
142 // be worth exploring.
143 //
144 // ## Future Optimizations (FIXME!)
145 //
146 // Another possible design choice that I made without any real reason is
147 // parameterizing the raw table over keys and values. Technically, all we need
148 // is the size and alignment of keys and values, and the code should be just as
149 // efficient (well, we might need one for power-of-two size and one for not...).
150 // This has the potential to reduce code bloat in rust executables, without
151 // really losing anything except 4 words (key size, key alignment, val size,
152 // val alignment) which can be passed in to every call of a `RawTable` function.
153 // This would definitely be an avenue worth exploring if people start complaining
154 // about the size of rust executables.
155 //
156 // Annotate exceedingly likely branches in `table::make_hash`
157 // and `search_hashed` to reduce instruction cache pressure
158 // and mispredictions once it becomes possible (blocked on issue #11092).
159 //
160 // Shrinking the table could simply reallocate in place after moving buckets
161 // to the first half.
162 //
163 // The growth algorithm (fragment of the Proof of Correctness)
164 // --------------------
165 //
166 // The growth algorithm is basically a fast path of the naive reinsertion-
167 // during-resize algorithm. Other paths should never be taken.
168 //
169 // Consider growing a robin hood hashtable of capacity n. Normally, we do this
170 // by allocating a new table of capacity `2n`, and then individually reinsert
171 // each element in the old table into the new one. This guarantees that the
172 // new table is a valid robin hood hashtable with all the desired statistical
173 // properties. Remark that the order we reinsert the elements in should not
174 // matter. For simplicity and efficiency, we will consider only linear
175 // reinsertions, which consist of reinserting all elements in the old table
176 // into the new one by increasing order of index. However we will not be
177 // starting our reinsertions from index 0 in general. If we start from index
178 // i, for the purpose of reinsertion we will consider all elements with real
179 // index j < i to have virtual index n + j.
180 //
181 // Our hash generation scheme consists of generating a 64-bit hash and
182 // truncating the most significant bits. When moving to the new table, we
183 // simply introduce a new bit to the front of the hash. Therefore, if an
184 // elements has ideal index i in the old table, it can have one of two ideal
185 // locations in the new table. If the new bit is 0, then the new ideal index
186 // is i. If the new bit is 1, then the new ideal index is n + i. Intuitively,
187 // we are producing two independent tables of size n, and for each element we
188 // independently choose which table to insert it into with equal probability.
189 // However the rather than wrapping around themselves on overflowing their
190 // indexes, the first table overflows into the first, and the first into the
191 // second. Visually, our new table will look something like:
192 //
193 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
194 //
195 // Where x's are elements inserted into the first table, y's are elements
196 // inserted into the second, and _'s are empty sections. We now define a few
197 // key concepts that we will use later. Note that this is a very abstract
198 // perspective of the table. A real resized table would be at least half
199 // empty.
200 //
201 // Theorem: A linear robin hood reinsertion from the first ideal element
202 // produces identical results to a linear naive reinsertion from the same
203 // element.
204 //
205 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
206
207 /// A hash map implementation which uses linear probing with Robin
208 /// Hood bucket stealing.
209 ///
210 /// The hashes are all keyed by the task-local random number generator
211 /// on creation by default. This means that the ordering of the keys is
212 /// randomized, but makes the tables more resistant to
213 /// denial-of-service attacks (Hash DoS). This behaviour can be
214 /// overridden with one of the constructors.
215 ///
216 /// It is required that the keys implement the `Eq` and `Hash` traits, although
217 /// this can frequently be achieved by using `#[derive(Eq, Hash)]`.
218 ///
219 /// It is a logic error for a key to be modified in such a way that the key's
220 /// hash, as determined by the `Hash` trait, or its equality, as determined by
221 /// the `Eq` trait, changes while it is in the map. This is normally only
222 /// possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
223 ///
224 /// Relevant papers/articles:
225 ///
226 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
227 /// 2. Emmanuel Goossaert. ["Robin Hood
228 ///    hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
229 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
230 ///    deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
231 ///
232 /// # Examples
233 ///
234 /// ```
235 /// use std::collections::HashMap;
236 ///
237 /// // type inference lets us omit an explicit type signature (which
238 /// // would be `HashMap<&str, &str>` in this example).
239 /// let mut book_reviews = HashMap::new();
240 ///
241 /// // review some books.
242 /// book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.");
243 /// book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.");
244 /// book_reviews.insert("Pride and Prejudice",               "Very enjoyable.");
245 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
246 ///
247 /// // check for a specific one.
248 /// if !book_reviews.contains_key(&("Les Misérables")) {
249 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
250 ///              book_reviews.len());
251 /// }
252 ///
253 /// // oops, this review has a lot of spelling mistakes, let's delete it.
254 /// book_reviews.remove(&("The Adventures of Sherlock Holmes"));
255 ///
256 /// // look up the values associated with some keys.
257 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
258 /// for book in to_find.iter() {
259 ///     match book_reviews.get(book) {
260 ///         Some(review) => println!("{}: {}", *book, *review),
261 ///         None => println!("{} is unreviewed.", *book)
262 ///     }
263 /// }
264 ///
265 /// // iterate over everything.
266 /// for (book, review) in book_reviews.iter() {
267 ///     println!("{}: \"{}\"", *book, *review);
268 /// }
269 /// ```
270 ///
271 /// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
272 /// We must also derive `PartialEq`.
273 ///
274 /// ```
275 /// use std::collections::HashMap;
276 ///
277 /// #[derive(Hash, Eq, PartialEq, Debug)]
278 /// struct Viking {
279 ///     name: String,
280 ///     country: String,
281 /// }
282 ///
283 /// impl Viking {
284 ///     /// Create a new Viking.
285 ///     fn new(name: &str, country: &str) -> Viking {
286 ///         Viking { name: name.to_string(), country: country.to_string() }
287 ///     }
288 /// }
289 ///
290 /// // Use a HashMap to store the vikings' health points.
291 /// let mut vikings = HashMap::new();
292 ///
293 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
294 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
295 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
296 ///
297 /// // Use derived implementation to print the status of the vikings.
298 /// for (viking, health) in vikings.iter() {
299 ///     println!("{:?} has {} hp", viking, health);
300 /// }
301 /// ```
302 #[derive(Clone)]
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub struct HashMap<K, V, S = RandomState> {
305     // All hashes are keyed on these values, to prevent hash collision attacks.
306     hash_state: S,
307
308     table: RawTable<K, V>,
309
310     resize_policy: DefaultResizePolicy,
311 }
312
313 /// Search for a pre-hashed key.
314 fn search_hashed<K, V, M, F>(table: M,
315                              hash: SafeHash,
316                              mut is_match: F)
317                              -> SearchResult<K, V, M> where
318     M: Deref<Target=RawTable<K, V>>,
319     F: FnMut(&K) -> bool,
320 {
321     // This is the only function where capacity can be zero. To avoid
322     // undefined behaviour when Bucket::new gets the raw bucket in this
323     // case, immediately return the appropriate search result.
324     if table.capacity() == 0 {
325         return TableRef(table);
326     }
327
328     let size = table.size();
329     let mut probe = Bucket::new(table, hash);
330     let ib = probe.index();
331
332     while probe.index() != ib + size {
333         let full = match probe.peek() {
334             Empty(b) => return TableRef(b.into_table()), // hit an empty bucket
335             Full(b) => b
336         };
337
338         if full.distance() + ib < full.index() {
339             // We can finish the search early if we hit any bucket
340             // with a lower distance to initial bucket than we've probed.
341             return TableRef(full.into_table());
342         }
343
344         // If the hash doesn't match, it can't be this one..
345         if hash == full.hash() {
346             // If the key doesn't match, it can't be this one..
347             if is_match(full.read().0) {
348                 return FoundExisting(full);
349             }
350         }
351
352         probe = full.next();
353     }
354
355     TableRef(probe.into_table())
356 }
357
358 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
359     let (empty, retkey, retval) = starting_bucket.take();
360     let mut gap = match empty.gap_peek() {
361         Some(b) => b,
362         None => return (retkey, retval)
363     };
364
365     while gap.full().distance() != 0 {
366         gap = match gap.shift() {
367             Some(b) => b,
368             None => break
369         };
370     }
371
372     // Now we've done all our shifting. Return the value we grabbed earlier.
373     (retkey, retval)
374 }
375
376 /// Perform robin hood bucket stealing at the given `bucket`. You must
377 /// also pass the position of that bucket's initial bucket so we don't have
378 /// to recalculate it.
379 ///
380 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
381 fn robin_hood<'a, K: 'a, V: 'a>(mut bucket: FullBucketMut<'a, K, V>,
382                         mut ib: usize,
383                         mut hash: SafeHash,
384                         mut k: K,
385                         mut v: V)
386                         -> &'a mut V {
387     let starting_index = bucket.index();
388     let size = {
389         let table = bucket.table(); // FIXME "lifetime too short".
390         table.size()
391     };
392     // There can be at most `size - dib` buckets to displace, because
393     // in the worst case, there are `size` elements and we already are
394     // `distance` buckets away from the initial one.
395     let idx_end = starting_index + size - bucket.distance();
396
397     loop {
398         let (old_hash, old_key, old_val) = bucket.replace(hash, k, v);
399         loop {
400             let probe = bucket.next();
401             assert!(probe.index() != idx_end);
402
403             let full_bucket = match probe.peek() {
404                 Empty(bucket) => {
405                     // Found a hole!
406                     let b = bucket.put(old_hash, old_key, old_val);
407                     // Now that it's stolen, just read the value's pointer
408                     // right out of the table!
409                     return Bucket::at_index(b.into_table(), starting_index)
410                                .peek()
411                                .expect_full()
412                                .into_mut_refs()
413                                .1;
414                 },
415                 Full(bucket) => bucket
416             };
417
418             let probe_ib = full_bucket.index() - full_bucket.distance();
419
420             bucket = full_bucket;
421
422             // Robin hood! Steal the spot.
423             if ib < probe_ib {
424                 ib = probe_ib;
425                 hash = old_hash;
426                 k = old_key;
427                 v = old_val;
428                 break;
429             }
430         }
431     }
432 }
433
434 /// A result that works like Option<FullBucket<..>> but preserves
435 /// the reference that grants us access to the table in any case.
436 enum SearchResult<K, V, M> {
437     // This is an entry that holds the given key:
438     FoundExisting(FullBucket<K, V, M>),
439
440     // There was no such entry. The reference is given back:
441     TableRef(M)
442 }
443
444 impl<K, V, M> SearchResult<K, V, M> {
445     fn into_option(self) -> Option<FullBucket<K, V, M>> {
446         match self {
447             FoundExisting(bucket) => Some(bucket),
448             TableRef(_) => None
449         }
450     }
451 }
452
453 impl<K, V, S> HashMap<K, V, S>
454     where K: Eq + Hash, S: HashState
455 {
456     fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash {
457         table::make_hash(&self.hash_state, x)
458     }
459
460     /// Search for a key, yielding the index if it's found in the hashtable.
461     /// If you already have the hash for the key lying around, use
462     /// search_hashed.
463     fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> Option<FullBucketImm<'a, K, V>>
464         where K: Borrow<Q>, Q: Eq + Hash
465     {
466         let hash = self.make_hash(q);
467         search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
468             .into_option()
469     }
470
471     fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> Option<FullBucketMut<'a, K, V>>
472         where K: Borrow<Q>, Q: Eq + Hash
473     {
474         let hash = self.make_hash(q);
475         search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
476             .into_option()
477     }
478
479     // The caller should ensure that invariants by Robin Hood Hashing hold.
480     fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
481         let cap = self.table.capacity();
482         let mut buckets = Bucket::new(&mut self.table, hash);
483         let ib = buckets.index();
484
485         while buckets.index() != ib + cap {
486             // We don't need to compare hashes for value swap.
487             // Not even DIBs for Robin Hood.
488             buckets = match buckets.peek() {
489                 Empty(empty) => {
490                     empty.put(hash, k, v);
491                     return;
492                 }
493                 Full(b) => b.into_bucket()
494             };
495             buckets.next();
496         }
497         panic!("Internal HashMap error: Out of space.");
498     }
499 }
500
501 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
502     /// Create an empty HashMap.
503     ///
504     /// # Examples
505     ///
506     /// ```
507     /// use std::collections::HashMap;
508     /// let mut map: HashMap<&str, int> = HashMap::new();
509     /// ```
510     #[inline]
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub fn new() -> HashMap<K, V, RandomState> {
513         Default::default()
514     }
515
516     /// Creates an empty hash map with the given initial capacity.
517     ///
518     /// # Examples
519     ///
520     /// ```
521     /// use std::collections::HashMap;
522     /// let mut map: HashMap<&str, int> = HashMap::with_capacity(10);
523     /// ```
524     #[inline]
525     #[stable(feature = "rust1", since = "1.0.0")]
526     pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
527         HashMap::with_capacity_and_hash_state(capacity, Default::default())
528     }
529 }
530
531 impl<K, V, S> HashMap<K, V, S>
532     where K: Eq + Hash, S: HashState
533 {
534     /// Creates an empty hashmap which will use the given hasher to hash keys.
535     ///
536     /// The creates map has the default initial capacity.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// use std::collections::HashMap;
542     /// use std::collections::hash_map::RandomState;
543     ///
544     /// let s = RandomState::new();
545     /// let mut map = HashMap::with_hash_state(s);
546     /// map.insert(1, 2);
547     /// ```
548     #[inline]
549     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
550     pub fn with_hash_state(hash_state: S) -> HashMap<K, V, S> {
551         HashMap {
552             hash_state:    hash_state,
553             resize_policy: DefaultResizePolicy::new(),
554             table:         RawTable::new(0),
555         }
556     }
557
558     /// Create an empty HashMap with space for at least `capacity`
559     /// elements, using `hasher` to hash the keys.
560     ///
561     /// Warning: `hasher` is normally randomly generated, and
562     /// is designed to allow HashMaps to be resistant to attacks that
563     /// cause many collisions and very poor performance. Setting it
564     /// manually using this function can expose a DoS attack vector.
565     ///
566     /// # Examples
567     ///
568     /// ```
569     /// use std::collections::HashMap;
570     /// use std::collections::hash_map::RandomState;
571     ///
572     /// let s = RandomState::new();
573     /// let mut map = HashMap::with_capacity_and_hash_state(10, s);
574     /// map.insert(1, 2);
575     /// ```
576     #[inline]
577     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
578     pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
579                                         -> HashMap<K, V, S> {
580         let resize_policy = DefaultResizePolicy::new();
581         let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
582         let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow");
583         assert!(internal_cap >= capacity, "capacity overflow");
584         HashMap {
585             hash_state:    hash_state,
586             resize_policy: resize_policy,
587             table:         RawTable::new(internal_cap),
588         }
589     }
590
591     /// Returns the number of elements the map can hold without reallocating.
592     ///
593     /// # Examples
594     ///
595     /// ```
596     /// use std::collections::HashMap;
597     /// let map: HashMap<int, int> = HashMap::with_capacity(100);
598     /// assert!(map.capacity() >= 100);
599     /// ```
600     #[inline]
601     #[stable(feature = "rust1", since = "1.0.0")]
602     pub fn capacity(&self) -> usize {
603         self.resize_policy.usable_capacity(self.table.capacity())
604     }
605
606     /// Reserves capacity for at least `additional` more elements to be inserted
607     /// in the `HashMap`. The collection may reserve more space to avoid
608     /// frequent reallocations.
609     ///
610     /// # Panics
611     ///
612     /// Panics if the new allocation size overflows `usize`.
613     ///
614     /// # Examples
615     ///
616     /// ```
617     /// use std::collections::HashMap;
618     /// let mut map: HashMap<&str, int> = HashMap::new();
619     /// map.reserve(10);
620     /// ```
621     #[stable(feature = "rust1", since = "1.0.0")]
622     pub fn reserve(&mut self, additional: usize) {
623         let new_size = self.len().checked_add(additional).expect("capacity overflow");
624         let min_cap = self.resize_policy.min_capacity(new_size);
625
626         // An invalid value shouldn't make us run out of space. This includes
627         // an overflow check.
628         assert!(new_size <= min_cap);
629
630         if self.table.capacity() < min_cap {
631             let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
632             self.resize(new_capacity);
633         }
634     }
635
636     /// Resizes the internal vectors to a new capacity. It's your responsibility to:
637     ///   1) Make sure the new capacity is enough for all the elements, accounting
638     ///      for the load factor.
639     ///   2) Ensure new_capacity is a power of two or zero.
640     fn resize(&mut self, new_capacity: usize) {
641         assert!(self.table.size() <= new_capacity);
642         assert!(new_capacity.is_power_of_two() || new_capacity == 0);
643
644         let mut old_table = replace(&mut self.table, RawTable::new(new_capacity));
645         let old_size = old_table.size();
646
647         if old_table.capacity() == 0 || old_table.size() == 0 {
648             return;
649         }
650
651         // Grow the table.
652         // Specialization of the other branch.
653         let mut bucket = Bucket::first(&mut old_table);
654
655         // "So a few of the first shall be last: for many be called,
656         // but few chosen."
657         //
658         // We'll most likely encounter a few buckets at the beginning that
659         // have their initial buckets near the end of the table. They were
660         // placed at the beginning as the probe wrapped around the table
661         // during insertion. We must skip forward to a bucket that won't
662         // get reinserted too early and won't unfairly steal others spot.
663         // This eliminates the need for robin hood.
664         loop {
665             bucket = match bucket.peek() {
666                 Full(full) => {
667                     if full.distance() == 0 {
668                         // This bucket occupies its ideal spot.
669                         // It indicates the start of another "cluster".
670                         bucket = full.into_bucket();
671                         break;
672                     }
673                     // Leaving this bucket in the last cluster for later.
674                     full.into_bucket()
675                 }
676                 Empty(b) => {
677                     // Encountered a hole between clusters.
678                     b.into_bucket()
679                 }
680             };
681             bucket.next();
682         }
683
684         // This is how the buckets might be laid out in memory:
685         // ($ marks an initialized bucket)
686         //  ________________
687         // |$$$_$$$$$$_$$$$$|
688         //
689         // But we've skipped the entire initial cluster of buckets
690         // and will continue iteration in this order:
691         //  ________________
692         //     |$$$$$$_$$$$$
693         //                  ^ wrap around once end is reached
694         //  ________________
695         //  $$$_____________|
696         //    ^ exit once table.size == 0
697         loop {
698             bucket = match bucket.peek() {
699                 Full(bucket) => {
700                     let h = bucket.hash();
701                     let (b, k, v) = bucket.take();
702                     self.insert_hashed_ordered(h, k, v);
703                     {
704                         let t = b.table(); // FIXME "lifetime too short".
705                         if t.size() == 0 { break }
706                     };
707                     b.into_bucket()
708                 }
709                 Empty(b) => b.into_bucket()
710             };
711             bucket.next();
712         }
713
714         assert_eq!(self.table.size(), old_size);
715     }
716
717     /// Shrinks the capacity of the map as much as possible. It will drop
718     /// down as much as possible while maintaining the internal rules
719     /// and possibly leaving some space in accordance with the resize policy.
720     ///
721     /// # Examples
722     ///
723     /// ```
724     /// use std::collections::HashMap;
725     ///
726     /// let mut map: HashMap<int, int> = HashMap::with_capacity(100);
727     /// map.insert(1, 2);
728     /// map.insert(3, 4);
729     /// assert!(map.capacity() >= 100);
730     /// map.shrink_to_fit();
731     /// assert!(map.capacity() >= 2);
732     /// ```
733     #[stable(feature = "rust1", since = "1.0.0")]
734     pub fn shrink_to_fit(&mut self) {
735         let min_capacity = self.resize_policy.min_capacity(self.len());
736         let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY);
737
738         // An invalid value shouldn't make us run out of space.
739         debug_assert!(self.len() <= min_capacity);
740
741         if self.table.capacity() != min_capacity {
742             let old_table = replace(&mut self.table, RawTable::new(min_capacity));
743             let old_size = old_table.size();
744
745             // Shrink the table. Naive algorithm for resizing:
746             for (h, k, v) in old_table.into_iter() {
747                 self.insert_hashed_nocheck(h, k, v);
748             }
749
750             debug_assert_eq!(self.table.size(), old_size);
751         }
752     }
753
754     /// Insert a pre-hashed key-value pair, without first checking
755     /// that there's enough room in the buckets. Returns a reference to the
756     /// newly insert value.
757     ///
758     /// If the key already exists, the hashtable will be returned untouched
759     /// and a reference to the existing element will be returned.
760     fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> &mut V {
761         self.insert_or_replace_with(hash, k, v, |_, _, _| ())
762     }
763
764     fn insert_or_replace_with<'a, F>(&'a mut self,
765                                      hash: SafeHash,
766                                      k: K,
767                                      v: V,
768                                      mut found_existing: F)
769                                      -> &'a mut V where
770         F: FnMut(&mut K, &mut V, V),
771     {
772         // Worst case, we'll find one empty bucket among `size + 1` buckets.
773         let size = self.table.size();
774         let mut probe = Bucket::new(&mut self.table, hash);
775         let ib = probe.index();
776
777         loop {
778             let mut bucket = match probe.peek() {
779                 Empty(bucket) => {
780                     // Found a hole!
781                     return bucket.put(hash, k, v).into_mut_refs().1;
782                 }
783                 Full(bucket) => bucket
784             };
785
786             // hash matches?
787             if bucket.hash() == hash {
788                 // key matches?
789                 if k == *bucket.read_mut().0 {
790                     let (bucket_k, bucket_v) = bucket.into_mut_refs();
791                     debug_assert!(k == *bucket_k);
792                     // Key already exists. Get its reference.
793                     found_existing(bucket_k, bucket_v, v);
794                     return bucket_v;
795                 }
796             }
797
798             let robin_ib = bucket.index() as int - bucket.distance() as int;
799
800             if (ib as int) < robin_ib {
801                 // Found a luckier bucket than me. Better steal his spot.
802                 return robin_hood(bucket, robin_ib as usize, hash, k, v);
803             }
804
805             probe = bucket.next();
806             assert!(probe.index() != ib + size + 1);
807         }
808     }
809
810     /// An iterator visiting all keys in arbitrary order.
811     /// Iterator element type is `&'a K`.
812     ///
813     /// # Examples
814     ///
815     /// ```
816     /// use std::collections::HashMap;
817     ///
818     /// let mut map = HashMap::new();
819     /// map.insert("a", 1);
820     /// map.insert("b", 2);
821     /// map.insert("c", 3);
822     ///
823     /// for key in map.keys() {
824     ///     println!("{}", key);
825     /// }
826     /// ```
827     #[stable(feature = "rust1", since = "1.0.0")]
828     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
829         fn first<A, B>((a, _): (A, B)) -> A { a }
830         let first: fn((&'a K,&'a V)) -> &'a K = first; // coerce to fn ptr
831
832         Keys { inner: self.iter().map(first) }
833     }
834
835     /// An iterator visiting all values in arbitrary order.
836     /// Iterator element type is `&'a V`.
837     ///
838     /// # Examples
839     ///
840     /// ```
841     /// use std::collections::HashMap;
842     ///
843     /// let mut map = HashMap::new();
844     /// map.insert("a", 1);
845     /// map.insert("b", 2);
846     /// map.insert("c", 3);
847     ///
848     /// for val in map.values() {
849     ///     println!("{}", val);
850     /// }
851     /// ```
852     #[stable(feature = "rust1", since = "1.0.0")]
853     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
854         fn second<A, B>((_, b): (A, B)) -> B { b }
855         let second: fn((&'a K,&'a V)) -> &'a V = second; // coerce to fn ptr
856
857         Values { inner: self.iter().map(second) }
858     }
859
860     /// An iterator visiting all key-value pairs in arbitrary order.
861     /// Iterator element type is `(&'a K, &'a V)`.
862     ///
863     /// # Examples
864     ///
865     /// ```
866     /// use std::collections::HashMap;
867     ///
868     /// let mut map = HashMap::new();
869     /// map.insert("a", 1);
870     /// map.insert("b", 2);
871     /// map.insert("c", 3);
872     ///
873     /// for (key, val) in map.iter() {
874     ///     println!("key: {} val: {}", key, val);
875     /// }
876     /// ```
877     #[stable(feature = "rust1", since = "1.0.0")]
878     pub fn iter(&self) -> Iter<K, V> {
879         Iter { inner: self.table.iter() }
880     }
881
882     /// An iterator visiting all key-value pairs in arbitrary order,
883     /// with mutable references to the values.
884     /// Iterator element type is `(&'a K, &'a mut V)`.
885     ///
886     /// # Examples
887     ///
888     /// ```
889     /// use std::collections::HashMap;
890     ///
891     /// let mut map = HashMap::new();
892     /// map.insert("a", 1);
893     /// map.insert("b", 2);
894     /// map.insert("c", 3);
895     ///
896     /// // Update all values
897     /// for (_, val) in map.iter_mut() {
898     ///     *val *= 2;
899     /// }
900     ///
901     /// for (key, val) in map.iter() {
902     ///     println!("key: {} val: {}", key, val);
903     /// }
904     /// ```
905     #[stable(feature = "rust1", since = "1.0.0")]
906     pub fn iter_mut(&mut self) -> IterMut<K, V> {
907         IterMut { inner: self.table.iter_mut() }
908     }
909
910     /// Creates a consuming iterator, that is, one that moves each key-value
911     /// pair out of the map in arbitrary order. The map cannot be used after
912     /// calling this.
913     ///
914     /// # Examples
915     ///
916     /// ```
917     /// use std::collections::HashMap;
918     ///
919     /// let mut map = HashMap::new();
920     /// map.insert("a", 1);
921     /// map.insert("b", 2);
922     /// map.insert("c", 3);
923     ///
924     /// // Not possible with .iter()
925     /// let vec: Vec<(&str, int)> = map.into_iter().collect();
926     /// ```
927     #[stable(feature = "rust1", since = "1.0.0")]
928     pub fn into_iter(self) -> IntoIter<K, V> {
929         fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
930         let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two;
931
932         IntoIter {
933             inner: self.table.into_iter().map(last_two)
934         }
935     }
936
937     /// Gets the given key's corresponding entry in the map for in-place manipulation.
938     #[stable(feature = "rust1", since = "1.0.0")]
939     pub fn entry(&mut self, key: K) -> Entry<K, V> {
940         // Gotta resize now.
941         self.reserve(1);
942
943         let hash = self.make_hash(&key);
944         search_entry_hashed(&mut self.table, hash, key)
945     }
946
947     /// Returns the number of elements in the map.
948     ///
949     /// # Examples
950     ///
951     /// ```
952     /// use std::collections::HashMap;
953     ///
954     /// let mut a = HashMap::new();
955     /// assert_eq!(a.len(), 0);
956     /// a.insert(1, "a");
957     /// assert_eq!(a.len(), 1);
958     /// ```
959     #[stable(feature = "rust1", since = "1.0.0")]
960     pub fn len(&self) -> usize { self.table.size() }
961
962     /// Returns true if the map contains no elements.
963     ///
964     /// # Examples
965     ///
966     /// ```
967     /// use std::collections::HashMap;
968     ///
969     /// let mut a = HashMap::new();
970     /// assert!(a.is_empty());
971     /// a.insert(1, "a");
972     /// assert!(!a.is_empty());
973     /// ```
974     #[inline]
975     #[stable(feature = "rust1", since = "1.0.0")]
976     pub fn is_empty(&self) -> bool { self.len() == 0 }
977
978     /// Clears the map, returning all key-value pairs as an iterator. Keeps the
979     /// allocated memory for reuse.
980     ///
981     /// # Examples
982     ///
983     /// ```
984     /// use std::collections::HashMap;
985     ///
986     /// let mut a = HashMap::new();
987     /// a.insert(1, "a");
988     /// a.insert(2, "b");
989     ///
990     /// for (k, v) in a.drain().take(1) {
991     ///     assert!(k == 1 || k == 2);
992     ///     assert!(v == "a" || v == "b");
993     /// }
994     ///
995     /// assert!(a.is_empty());
996     /// ```
997     #[inline]
998     #[unstable(feature = "std_misc",
999                reason = "matches collection reform specification, waiting for dust to settle")]
1000     pub fn drain(&mut self) -> Drain<K, V> {
1001         fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
1002         let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two; // coerce to fn pointer
1003
1004         Drain {
1005             inner: self.table.drain().map(last_two),
1006         }
1007     }
1008
1009     /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1010     /// for reuse.
1011     ///
1012     /// # Examples
1013     ///
1014     /// ```
1015     /// use std::collections::HashMap;
1016     ///
1017     /// let mut a = HashMap::new();
1018     /// a.insert(1, "a");
1019     /// a.clear();
1020     /// assert!(a.is_empty());
1021     /// ```
1022     #[stable(feature = "rust1", since = "1.0.0")]
1023     #[inline]
1024     pub fn clear(&mut self) {
1025         self.drain();
1026     }
1027
1028     /// Returns a reference to the value corresponding to the key.
1029     ///
1030     /// The key may be any borrowed form of the map's key type, but
1031     /// `Hash` and `Eq` on the borrowed form *must* match those for
1032     /// the key type.
1033     ///
1034     /// # Examples
1035     ///
1036     /// ```
1037     /// use std::collections::HashMap;
1038     ///
1039     /// let mut map = HashMap::new();
1040     /// map.insert(1, "a");
1041     /// assert_eq!(map.get(&1), Some(&"a"));
1042     /// assert_eq!(map.get(&2), None);
1043     /// ```
1044     #[stable(feature = "rust1", since = "1.0.0")]
1045     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1046         where K: Borrow<Q>, Q: Hash + Eq
1047     {
1048         self.search(k).map(|bucket| bucket.into_refs().1)
1049     }
1050
1051     /// Returns true if the map contains a value for the specified key.
1052     ///
1053     /// The key may be any borrowed form of the map's key type, but
1054     /// `Hash` and `Eq` on the borrowed form *must* match those for
1055     /// the key type.
1056     ///
1057     /// # Examples
1058     ///
1059     /// ```
1060     /// use std::collections::HashMap;
1061     ///
1062     /// let mut map = HashMap::new();
1063     /// map.insert(1, "a");
1064     /// assert_eq!(map.contains_key(&1), true);
1065     /// assert_eq!(map.contains_key(&2), false);
1066     /// ```
1067     #[stable(feature = "rust1", since = "1.0.0")]
1068     pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1069         where K: Borrow<Q>, Q: Hash + Eq
1070     {
1071         self.search(k).is_some()
1072     }
1073
1074     /// Returns a mutable reference to the value corresponding to the key.
1075     ///
1076     /// The key may be any borrowed form of the map's key type, but
1077     /// `Hash` and `Eq` on the borrowed form *must* match those for
1078     /// the key type.
1079     ///
1080     /// # Examples
1081     ///
1082     /// ```
1083     /// use std::collections::HashMap;
1084     ///
1085     /// let mut map = HashMap::new();
1086     /// map.insert(1, "a");
1087     /// match map.get_mut(&1) {
1088     ///     Some(x) => *x = "b",
1089     ///     None => (),
1090     /// }
1091     /// assert_eq!(map[1], "b");
1092     /// ```
1093     #[stable(feature = "rust1", since = "1.0.0")]
1094     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1095         where K: Borrow<Q>, Q: Hash + Eq
1096     {
1097         self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1098     }
1099
1100     /// Inserts a key-value pair from the map. If the key already had a value
1101     /// present in the map, that value is returned. Otherwise, `None` is returned.
1102     ///
1103     /// # Examples
1104     ///
1105     /// ```
1106     /// use std::collections::HashMap;
1107     ///
1108     /// let mut map = HashMap::new();
1109     /// assert_eq!(map.insert(37, "a"), None);
1110     /// assert_eq!(map.is_empty(), false);
1111     ///
1112     /// map.insert(37, "b");
1113     /// assert_eq!(map.insert(37, "c"), Some("b"));
1114     /// assert_eq!(map[37], "c");
1115     /// ```
1116     #[stable(feature = "rust1", since = "1.0.0")]
1117     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1118         let hash = self.make_hash(&k);
1119         self.reserve(1);
1120
1121         let mut retval = None;
1122         self.insert_or_replace_with(hash, k, v, |_, val_ref, val| {
1123             retval = Some(replace(val_ref, val));
1124         });
1125         retval
1126     }
1127
1128     /// Removes a key from the map, returning the value at the key if the key
1129     /// was previously in the map.
1130     ///
1131     /// The key may be any borrowed form of the map's key type, but
1132     /// `Hash` and `Eq` on the borrowed form *must* match those for
1133     /// the key type.
1134     ///
1135     /// # Examples
1136     ///
1137     /// ```
1138     /// use std::collections::HashMap;
1139     ///
1140     /// let mut map = HashMap::new();
1141     /// map.insert(1, "a");
1142     /// assert_eq!(map.remove(&1), Some("a"));
1143     /// assert_eq!(map.remove(&1), None);
1144     /// ```
1145     #[stable(feature = "rust1", since = "1.0.0")]
1146     pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1147         where K: Borrow<Q>, Q: Hash + Eq
1148     {
1149         if self.table.size() == 0 {
1150             return None
1151         }
1152
1153         self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1154     }
1155 }
1156
1157 fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHash, k: K)
1158         -> Entry<'a, K, V>
1159 {
1160     // Worst case, we'll find one empty bucket among `size + 1` buckets.
1161     let size = table.size();
1162     let mut probe = Bucket::new(table, hash);
1163     let ib = probe.index();
1164
1165     loop {
1166         let bucket = match probe.peek() {
1167             Empty(bucket) => {
1168                 // Found a hole!
1169                 return Vacant(VacantEntry {
1170                     hash: hash,
1171                     key: k,
1172                     elem: NoElem(bucket),
1173                 });
1174             },
1175             Full(bucket) => bucket
1176         };
1177
1178         // hash matches?
1179         if bucket.hash() == hash {
1180             // key matches?
1181             if k == *bucket.read().0 {
1182                 return Occupied(OccupiedEntry{
1183                     elem: bucket,
1184                 });
1185             }
1186         }
1187
1188         let robin_ib = bucket.index() as int - bucket.distance() as int;
1189
1190         if (ib as int) < robin_ib {
1191             // Found a luckier bucket than me. Better steal his spot.
1192             return Vacant(VacantEntry {
1193                 hash: hash,
1194                 key: k,
1195                 elem: NeqElem(bucket, robin_ib as usize),
1196             });
1197         }
1198
1199         probe = bucket.next();
1200         assert!(probe.index() != ib + size + 1);
1201     }
1202 }
1203
1204 impl<K, V, S> PartialEq for HashMap<K, V, S>
1205     where K: Eq + Hash, V: PartialEq, S: HashState
1206 {
1207     fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1208         if self.len() != other.len() { return false; }
1209
1210         self.iter().all(|(key, value)|
1211             other.get(key).map_or(false, |v| *value == *v)
1212         )
1213     }
1214 }
1215
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<K, V, S> Eq for HashMap<K, V, S>
1218     where K: Eq + Hash, V: Eq, S: HashState
1219 {}
1220
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<K, V, S> Debug for HashMap<K, V, S>
1223     where K: Eq + Hash + Debug, V: Debug, S: HashState
1224 {
1225     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1226         try!(write!(f, "{{"));
1227
1228         for (i, (k, v)) in self.iter().enumerate() {
1229             if i != 0 { try!(write!(f, ", ")); }
1230             try!(write!(f, "{:?}: {:?}", *k, *v));
1231         }
1232
1233         write!(f, "}}")
1234     }
1235 }
1236
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<K, V, S> Default for HashMap<K, V, S>
1239     where K: Eq + Hash,
1240           S: HashState + Default,
1241 {
1242     fn default() -> HashMap<K, V, S> {
1243         HashMap::with_hash_state(Default::default())
1244     }
1245 }
1246
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl<K, Q: ?Sized, V, S> Index<Q> for HashMap<K, V, S>
1249     where K: Eq + Hash + Borrow<Q>,
1250           Q: Eq + Hash,
1251           S: HashState,
1252 {
1253     type Output = V;
1254
1255     #[inline]
1256     fn index<'a>(&'a self, index: &Q) -> &'a V {
1257         self.get(index).expect("no entry found for key")
1258     }
1259 }
1260
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<K, V, S, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S>
1263     where K: Eq + Hash + Borrow<Q>,
1264           Q: Eq + Hash,
1265           S: HashState,
1266 {
1267     #[inline]
1268     fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
1269         self.get_mut(index).expect("no entry found for key")
1270     }
1271 }
1272
1273 /// HashMap iterator.
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 pub struct Iter<'a, K: 'a, V: 'a> {
1276     inner: table::Iter<'a, K, V>
1277 }
1278
1279 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1280 impl<'a, K, V> Clone for Iter<'a, K, V> {
1281     fn clone(&self) -> Iter<'a, K, V> {
1282         Iter {
1283             inner: self.inner.clone()
1284         }
1285     }
1286 }
1287
1288 /// HashMap mutable values iterator.
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 pub struct IterMut<'a, K: 'a, V: 'a> {
1291     inner: table::IterMut<'a, K, V>
1292 }
1293
1294 /// HashMap move iterator.
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 pub struct IntoIter<K, V> {
1297     inner: iter::Map<table::IntoIter<K, V>, fn((SafeHash, K, V)) -> (K, V)>
1298 }
1299
1300 /// HashMap keys iterator.
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 pub struct Keys<'a, K: 'a, V: 'a> {
1303     inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
1304 }
1305
1306 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1307 impl<'a, K, V> Clone for Keys<'a, K, V> {
1308     fn clone(&self) -> Keys<'a, K, V> {
1309         Keys {
1310             inner: self.inner.clone()
1311         }
1312     }
1313 }
1314
1315 /// HashMap values iterator.
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 pub struct Values<'a, K: 'a, V: 'a> {
1318     inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
1319 }
1320
1321 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1322 impl<'a, K, V> Clone for Values<'a, K, V> {
1323     fn clone(&self) -> Values<'a, K, V> {
1324         Values {
1325             inner: self.inner.clone()
1326         }
1327     }
1328 }
1329
1330 /// HashMap drain iterator.
1331 #[unstable(feature = "std_misc",
1332            reason = "matches collection reform specification, waiting for dust to settle")]
1333 pub struct Drain<'a, K: 'a, V: 'a> {
1334     inner: iter::Map<table::Drain<'a, K, V>, fn((SafeHash, K, V)) -> (K, V)>
1335 }
1336
1337 /// A view into a single occupied location in a HashMap.
1338 #[unstable(feature = "std_misc",
1339            reason = "precise API still being fleshed out")]
1340 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1341     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1342 }
1343
1344 /// A view into a single empty location in a HashMap.
1345 #[unstable(feature = "std_misc",
1346            reason = "precise API still being fleshed out")]
1347 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1348     hash: SafeHash,
1349     key: K,
1350     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1351 }
1352
1353 /// A view into a single location in a map, which may be vacant or occupied.
1354 #[unstable(feature = "std_misc",
1355            reason = "precise API still being fleshed out")]
1356 pub enum Entry<'a, K: 'a, V: 'a> {
1357     /// An occupied Entry.
1358     Occupied(OccupiedEntry<'a, K, V>),
1359     /// A vacant Entry.
1360     Vacant(VacantEntry<'a, K, V>),
1361 }
1362
1363 /// Possible states of a VacantEntry.
1364 enum VacantEntryState<K, V, M> {
1365     /// The index is occupied, but the key to insert has precedence,
1366     /// and will kick the current one out on insertion.
1367     NeqElem(FullBucket<K, V, M>, usize),
1368     /// The index is genuinely vacant.
1369     NoElem(EmptyBucket<K, V, M>),
1370 }
1371
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1374     where K: Eq + Hash, S: HashState
1375 {
1376     type Item = (&'a K, &'a V);
1377     type IntoIter = Iter<'a, K, V>;
1378
1379     fn into_iter(self) -> Iter<'a, K, V> {
1380         self.iter()
1381     }
1382 }
1383
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1386     where K: Eq + Hash, S: HashState
1387 {
1388     type Item = (&'a K, &'a mut V);
1389     type IntoIter = IterMut<'a, K, V>;
1390
1391     fn into_iter(mut self) -> IterMut<'a, K, V> {
1392         self.iter_mut()
1393     }
1394 }
1395
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1398     where K: Eq + Hash, S: HashState
1399 {
1400     type Item = (K, V);
1401     type IntoIter = IntoIter<K, V>;
1402
1403     fn into_iter(self) -> IntoIter<K, V> {
1404         self.into_iter()
1405     }
1406 }
1407
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1410     type Item = (&'a K, &'a V);
1411
1412     #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1413     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1414 }
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1417     #[inline] fn len(&self) -> usize { self.inner.len() }
1418 }
1419
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1422     type Item = (&'a K, &'a mut V);
1423
1424     #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1425     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1426 }
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1429     #[inline] fn len(&self) -> usize { self.inner.len() }
1430 }
1431
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<K, V> Iterator for IntoIter<K, V> {
1434     type Item = (K, V);
1435
1436     #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1437     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1438 }
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1441     #[inline] fn len(&self) -> usize { self.inner.len() }
1442 }
1443
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1446     type Item = &'a K;
1447
1448     #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1449     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1450 }
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1453     #[inline] fn len(&self) -> usize { self.inner.len() }
1454 }
1455
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<'a, K, V> Iterator for Values<'a, K, V> {
1458     type Item = &'a V;
1459
1460     #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1461     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1462 }
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1465     #[inline] fn len(&self) -> usize { self.inner.len() }
1466 }
1467
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1470     type Item = (K, V);
1471
1472     #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1473     #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1474 }
1475 #[stable(feature = "rust1", since = "1.0.0")]
1476 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1477     #[inline] fn len(&self) -> usize { self.inner.len() }
1478 }
1479
1480 #[unstable(feature = "std_misc",
1481            reason = "matches collection reform v2 specification, waiting for dust to settle")]
1482 impl<'a, K, V> Entry<'a, K, V> {
1483     /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant.
1484     pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
1485         match self {
1486             Occupied(entry) => Ok(entry.into_mut()),
1487             Vacant(entry) => Err(entry),
1488         }
1489     }
1490 }
1491
1492 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1493     /// Gets a reference to the value in the entry.
1494     #[stable(feature = "rust1", since = "1.0.0")]
1495     pub fn get(&self) -> &V {
1496         self.elem.read().1
1497     }
1498
1499     /// Gets a mutable reference to the value in the entry.
1500     #[stable(feature = "rust1", since = "1.0.0")]
1501     pub fn get_mut(&mut self) -> &mut V {
1502         self.elem.read_mut().1
1503     }
1504
1505     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1506     /// with a lifetime bound to the map itself
1507     #[stable(feature = "rust1", since = "1.0.0")]
1508     pub fn into_mut(self) -> &'a mut V {
1509         self.elem.into_mut_refs().1
1510     }
1511
1512     /// Sets the value of the entry, and returns the entry's old value
1513     #[stable(feature = "rust1", since = "1.0.0")]
1514     pub fn insert(&mut self, mut value: V) -> V {
1515         let old_value = self.get_mut();
1516         mem::swap(&mut value, old_value);
1517         value
1518     }
1519
1520     /// Takes the value out of the entry, and returns it
1521     #[stable(feature = "rust1", since = "1.0.0")]
1522     pub fn remove(self) -> V {
1523         pop_internal(self.elem).1
1524     }
1525 }
1526
1527 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1528     /// Sets the value of the entry with the VacantEntry's key,
1529     /// and returns a mutable reference to it
1530     #[stable(feature = "rust1", since = "1.0.0")]
1531     pub fn insert(self, value: V) -> &'a mut V {
1532         match self.elem {
1533             NeqElem(bucket, ib) => {
1534                 robin_hood(bucket, ib, self.hash, self.key, value)
1535             }
1536             NoElem(bucket) => {
1537                 bucket.put(self.hash, self.key, value).into_mut_refs().1
1538             }
1539         }
1540     }
1541 }
1542
1543 #[stable(feature = "rust1", since = "1.0.0")]
1544 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
1545     where K: Eq + Hash, S: HashState + Default
1546 {
1547     fn from_iter<T: IntoIterator<Item=(K, V)>>(iterable: T) -> HashMap<K, V, S> {
1548         let iter = iterable.into_iter();
1549         let lower = iter.size_hint().0;
1550         let mut map = HashMap::with_capacity_and_hash_state(lower,
1551                                                             Default::default());
1552         map.extend(iter);
1553         map
1554     }
1555 }
1556
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
1559     where K: Eq + Hash, S: HashState
1560 {
1561     fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1562         for (k, v) in iter {
1563             self.insert(k, v);
1564         }
1565     }
1566 }
1567
1568
1569 /// `RandomState` is the default state for `HashMap` types.
1570 ///
1571 /// A particular instance `RandomState` will create the same instances of
1572 /// `Hasher`, but the hashers created by two different `RandomState`
1573 /// instances are unlikely to produce the same result for the same values.
1574 #[derive(Clone)]
1575 #[unstable(feature = "std_misc",
1576            reason = "hashing an hash maps may be altered")]
1577 pub struct RandomState {
1578     k0: u64,
1579     k1: u64,
1580 }
1581
1582 #[unstable(feature = "std_misc",
1583            reason = "hashing an hash maps may be altered")]
1584 impl RandomState {
1585     /// Construct a new `RandomState` that is initialized with random keys.
1586     #[inline]
1587     #[allow(deprecated)]
1588     pub fn new() -> RandomState {
1589         let mut r = rand::thread_rng();
1590         RandomState { k0: r.gen(), k1: r.gen() }
1591     }
1592 }
1593
1594 #[unstable(feature = "std_misc",
1595            reason = "hashing an hash maps may be altered")]
1596 impl HashState for RandomState {
1597     type Hasher = SipHasher;
1598     fn hasher(&self) -> SipHasher {
1599         SipHasher::new_with_keys(self.k0, self.k1)
1600     }
1601 }
1602
1603 #[unstable(feature = "std_misc",
1604            reason = "hashing an hash maps may be altered")]
1605 impl Default for RandomState {
1606     #[inline]
1607     fn default() -> RandomState {
1608         RandomState::new()
1609     }
1610 }
1611
1612 #[cfg(test)]
1613 mod test_map {
1614     use prelude::v1::*;
1615
1616     use super::HashMap;
1617     use super::Entry::{Occupied, Vacant};
1618     use iter::{range_inclusive, range_step_inclusive, repeat};
1619     use cell::RefCell;
1620     use rand::{weak_rng, Rng};
1621
1622     #[test]
1623     fn test_create_capacity_zero() {
1624         let mut m = HashMap::with_capacity(0);
1625
1626         assert!(m.insert(1, 1).is_none());
1627
1628         assert!(m.contains_key(&1));
1629         assert!(!m.contains_key(&0));
1630     }
1631
1632     #[test]
1633     fn test_insert() {
1634         let mut m = HashMap::new();
1635         assert_eq!(m.len(), 0);
1636         assert!(m.insert(1, 2).is_none());
1637         assert_eq!(m.len(), 1);
1638         assert!(m.insert(2, 4).is_none());
1639         assert_eq!(m.len(), 2);
1640         assert_eq!(*m.get(&1).unwrap(), 2);
1641         assert_eq!(*m.get(&2).unwrap(), 4);
1642     }
1643
1644     thread_local! { static DROP_VECTOR: RefCell<Vec<int>> = RefCell::new(Vec::new()) }
1645
1646     #[derive(Hash, PartialEq, Eq)]
1647     struct Dropable {
1648         k: usize
1649     }
1650
1651     impl Dropable {
1652         fn new(k: usize) -> Dropable {
1653             DROP_VECTOR.with(|slot| {
1654                 slot.borrow_mut()[k] += 1;
1655             });
1656
1657             Dropable { k: k }
1658         }
1659     }
1660
1661     impl Drop for Dropable {
1662         fn drop(&mut self) {
1663             DROP_VECTOR.with(|slot| {
1664                 slot.borrow_mut()[self.k] -= 1;
1665             });
1666         }
1667     }
1668
1669     impl Clone for Dropable {
1670         fn clone(&self) -> Dropable {
1671             Dropable::new(self.k)
1672         }
1673     }
1674
1675     #[test]
1676     fn test_drops() {
1677         DROP_VECTOR.with(|slot| {
1678             *slot.borrow_mut() = repeat(0).take(200).collect();
1679         });
1680
1681         {
1682             let mut m = HashMap::new();
1683
1684             DROP_VECTOR.with(|v| {
1685                 for i in 0..200 {
1686                     assert_eq!(v.borrow()[i], 0);
1687                 }
1688             });
1689
1690             for i in 0..100 {
1691                 let d1 = Dropable::new(i);
1692                 let d2 = Dropable::new(i+100);
1693                 m.insert(d1, d2);
1694             }
1695
1696             DROP_VECTOR.with(|v| {
1697                 for i in 0..200 {
1698                     assert_eq!(v.borrow()[i], 1);
1699                 }
1700             });
1701
1702             for i in 0..50 {
1703                 let k = Dropable::new(i);
1704                 let v = m.remove(&k);
1705
1706                 assert!(v.is_some());
1707
1708                 DROP_VECTOR.with(|v| {
1709                     assert_eq!(v.borrow()[i], 1);
1710                     assert_eq!(v.borrow()[i+100], 1);
1711                 });
1712             }
1713
1714             DROP_VECTOR.with(|v| {
1715                 for i in 0..50 {
1716                     assert_eq!(v.borrow()[i], 0);
1717                     assert_eq!(v.borrow()[i+100], 0);
1718                 }
1719
1720                 for i in 50..100 {
1721                     assert_eq!(v.borrow()[i], 1);
1722                     assert_eq!(v.borrow()[i+100], 1);
1723                 }
1724             });
1725         }
1726
1727         DROP_VECTOR.with(|v| {
1728             for i in 0..200 {
1729                 assert_eq!(v.borrow()[i], 0);
1730             }
1731         });
1732     }
1733
1734     #[test]
1735     fn test_move_iter_drops() {
1736         DROP_VECTOR.with(|v| {
1737             *v.borrow_mut() = repeat(0).take(200).collect();
1738         });
1739
1740         let hm = {
1741             let mut hm = HashMap::new();
1742
1743             DROP_VECTOR.with(|v| {
1744                 for i in 0..200 {
1745                     assert_eq!(v.borrow()[i], 0);
1746                 }
1747             });
1748
1749             for i in 0..100 {
1750                 let d1 = Dropable::new(i);
1751                 let d2 = Dropable::new(i+100);
1752                 hm.insert(d1, d2);
1753             }
1754
1755             DROP_VECTOR.with(|v| {
1756                 for i in 0..200 {
1757                     assert_eq!(v.borrow()[i], 1);
1758                 }
1759             });
1760
1761             hm
1762         };
1763
1764         // By the way, ensure that cloning doesn't screw up the dropping.
1765         drop(hm.clone());
1766
1767         {
1768             let mut half = hm.into_iter().take(50);
1769
1770             DROP_VECTOR.with(|v| {
1771                 for i in 0..200 {
1772                     assert_eq!(v.borrow()[i], 1);
1773                 }
1774             });
1775
1776             for _ in half.by_ref() {}
1777
1778             DROP_VECTOR.with(|v| {
1779                 let nk = (0..100).filter(|&i| {
1780                     v.borrow()[i] == 1
1781                 }).count();
1782
1783                 let nv = (0..100).filter(|&i| {
1784                     v.borrow()[i+100] == 1
1785                 }).count();
1786
1787                 assert_eq!(nk, 50);
1788                 assert_eq!(nv, 50);
1789             });
1790         };
1791
1792         DROP_VECTOR.with(|v| {
1793             for i in 0..200 {
1794                 assert_eq!(v.borrow()[i], 0);
1795             }
1796         });
1797     }
1798
1799     #[test]
1800     fn test_empty_pop() {
1801         let mut m: HashMap<int, bool> = HashMap::new();
1802         assert_eq!(m.remove(&0), None);
1803     }
1804
1805     #[test]
1806     fn test_lots_of_insertions() {
1807         let mut m = HashMap::new();
1808
1809         // Try this a few times to make sure we never screw up the hashmap's
1810         // internal state.
1811         for _ in 0..10 {
1812             assert!(m.is_empty());
1813
1814             for i in range_inclusive(1, 1000) {
1815                 assert!(m.insert(i, i).is_none());
1816
1817                 for j in range_inclusive(1, i) {
1818                     let r = m.get(&j);
1819                     assert_eq!(r, Some(&j));
1820                 }
1821
1822                 for j in range_inclusive(i+1, 1000) {
1823                     let r = m.get(&j);
1824                     assert_eq!(r, None);
1825                 }
1826             }
1827
1828             for i in range_inclusive(1001, 2000) {
1829                 assert!(!m.contains_key(&i));
1830             }
1831
1832             // remove forwards
1833             for i in range_inclusive(1, 1000) {
1834                 assert!(m.remove(&i).is_some());
1835
1836                 for j in range_inclusive(1, i) {
1837                     assert!(!m.contains_key(&j));
1838                 }
1839
1840                 for j in range_inclusive(i+1, 1000) {
1841                     assert!(m.contains_key(&j));
1842                 }
1843             }
1844
1845             for i in range_inclusive(1, 1000) {
1846                 assert!(!m.contains_key(&i));
1847             }
1848
1849             for i in range_inclusive(1, 1000) {
1850                 assert!(m.insert(i, i).is_none());
1851             }
1852
1853             // remove backwards
1854             for i in range_step_inclusive(1000, 1, -1) {
1855                 assert!(m.remove(&i).is_some());
1856
1857                 for j in range_inclusive(i, 1000) {
1858                     assert!(!m.contains_key(&j));
1859                 }
1860
1861                 for j in range_inclusive(1, i-1) {
1862                     assert!(m.contains_key(&j));
1863                 }
1864             }
1865         }
1866     }
1867
1868     #[test]
1869     fn test_find_mut() {
1870         let mut m = HashMap::new();
1871         assert!(m.insert(1, 12).is_none());
1872         assert!(m.insert(2, 8).is_none());
1873         assert!(m.insert(5, 14).is_none());
1874         let new = 100;
1875         match m.get_mut(&5) {
1876             None => panic!(), Some(x) => *x = new
1877         }
1878         assert_eq!(m.get(&5), Some(&new));
1879     }
1880
1881     #[test]
1882     fn test_insert_overwrite() {
1883         let mut m = HashMap::new();
1884         assert!(m.insert(1, 2).is_none());
1885         assert_eq!(*m.get(&1).unwrap(), 2);
1886         assert!(!m.insert(1, 3).is_none());
1887         assert_eq!(*m.get(&1).unwrap(), 3);
1888     }
1889
1890     #[test]
1891     fn test_insert_conflicts() {
1892         let mut m = HashMap::with_capacity(4);
1893         assert!(m.insert(1, 2).is_none());
1894         assert!(m.insert(5, 3).is_none());
1895         assert!(m.insert(9, 4).is_none());
1896         assert_eq!(*m.get(&9).unwrap(), 4);
1897         assert_eq!(*m.get(&5).unwrap(), 3);
1898         assert_eq!(*m.get(&1).unwrap(), 2);
1899     }
1900
1901     #[test]
1902     fn test_conflict_remove() {
1903         let mut m = HashMap::with_capacity(4);
1904         assert!(m.insert(1, 2).is_none());
1905         assert_eq!(*m.get(&1).unwrap(), 2);
1906         assert!(m.insert(5, 3).is_none());
1907         assert_eq!(*m.get(&1).unwrap(), 2);
1908         assert_eq!(*m.get(&5).unwrap(), 3);
1909         assert!(m.insert(9, 4).is_none());
1910         assert_eq!(*m.get(&1).unwrap(), 2);
1911         assert_eq!(*m.get(&5).unwrap(), 3);
1912         assert_eq!(*m.get(&9).unwrap(), 4);
1913         assert!(m.remove(&1).is_some());
1914         assert_eq!(*m.get(&9).unwrap(), 4);
1915         assert_eq!(*m.get(&5).unwrap(), 3);
1916     }
1917
1918     #[test]
1919     fn test_is_empty() {
1920         let mut m = HashMap::with_capacity(4);
1921         assert!(m.insert(1, 2).is_none());
1922         assert!(!m.is_empty());
1923         assert!(m.remove(&1).is_some());
1924         assert!(m.is_empty());
1925     }
1926
1927     #[test]
1928     fn test_pop() {
1929         let mut m = HashMap::new();
1930         m.insert(1, 2);
1931         assert_eq!(m.remove(&1), Some(2));
1932         assert_eq!(m.remove(&1), None);
1933     }
1934
1935     #[test]
1936     fn test_iterate() {
1937         let mut m = HashMap::with_capacity(4);
1938         for i in 0..32 {
1939             assert!(m.insert(i, i*2).is_none());
1940         }
1941         assert_eq!(m.len(), 32);
1942
1943         let mut observed: u32 = 0;
1944
1945         for (k, v) in &m {
1946             assert_eq!(*v, *k * 2);
1947             observed |= 1 << *k;
1948         }
1949         assert_eq!(observed, 0xFFFF_FFFF);
1950     }
1951
1952     #[test]
1953     fn test_keys() {
1954         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1955         let map: HashMap<_, _> = vec.into_iter().collect();
1956         let keys: Vec<_> = map.keys().cloned().collect();
1957         assert_eq!(keys.len(), 3);
1958         assert!(keys.contains(&1));
1959         assert!(keys.contains(&2));
1960         assert!(keys.contains(&3));
1961     }
1962
1963     #[test]
1964     fn test_values() {
1965         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1966         let map: HashMap<_, _> = vec.into_iter().collect();
1967         let values: Vec<_> = map.values().cloned().collect();
1968         assert_eq!(values.len(), 3);
1969         assert!(values.contains(&'a'));
1970         assert!(values.contains(&'b'));
1971         assert!(values.contains(&'c'));
1972     }
1973
1974     #[test]
1975     fn test_find() {
1976         let mut m = HashMap::new();
1977         assert!(m.get(&1).is_none());
1978         m.insert(1, 2);
1979         match m.get(&1) {
1980             None => panic!(),
1981             Some(v) => assert_eq!(*v, 2)
1982         }
1983     }
1984
1985     #[test]
1986     fn test_eq() {
1987         let mut m1 = HashMap::new();
1988         m1.insert(1, 2);
1989         m1.insert(2, 3);
1990         m1.insert(3, 4);
1991
1992         let mut m2 = HashMap::new();
1993         m2.insert(1, 2);
1994         m2.insert(2, 3);
1995
1996         assert!(m1 != m2);
1997
1998         m2.insert(3, 4);
1999
2000         assert_eq!(m1, m2);
2001     }
2002
2003     #[test]
2004     fn test_show() {
2005         let mut map = HashMap::new();
2006         let empty: HashMap<i32, i32> = HashMap::new();
2007
2008         map.insert(1, 2);
2009         map.insert(3, 4);
2010
2011         let map_str = format!("{:?}", map);
2012
2013         assert!(map_str == "{1: 2, 3: 4}" ||
2014                 map_str == "{3: 4, 1: 2}");
2015         assert_eq!(format!("{:?}", empty), "{}");
2016     }
2017
2018     #[test]
2019     fn test_expand() {
2020         let mut m = HashMap::new();
2021
2022         assert_eq!(m.len(), 0);
2023         assert!(m.is_empty());
2024
2025         let mut i = 0;
2026         let old_cap = m.table.capacity();
2027         while old_cap == m.table.capacity() {
2028             m.insert(i, i);
2029             i += 1;
2030         }
2031
2032         assert_eq!(m.len(), i);
2033         assert!(!m.is_empty());
2034     }
2035
2036     #[test]
2037     fn test_behavior_resize_policy() {
2038         let mut m = HashMap::new();
2039
2040         assert_eq!(m.len(), 0);
2041         assert_eq!(m.table.capacity(), 0);
2042         assert!(m.is_empty());
2043
2044         m.insert(0, 0);
2045         m.remove(&0);
2046         assert!(m.is_empty());
2047         let initial_cap = m.table.capacity();
2048         m.reserve(initial_cap);
2049         let cap = m.table.capacity();
2050
2051         assert_eq!(cap, initial_cap * 2);
2052
2053         let mut i = 0;
2054         for _ in 0..cap * 3 / 4 {
2055             m.insert(i, i);
2056             i += 1;
2057         }
2058         // three quarters full
2059
2060         assert_eq!(m.len(), i);
2061         assert_eq!(m.table.capacity(), cap);
2062
2063         for _ in 0..cap / 4 {
2064             m.insert(i, i);
2065             i += 1;
2066         }
2067         // half full
2068
2069         let new_cap = m.table.capacity();
2070         assert_eq!(new_cap, cap * 2);
2071
2072         for _ in 0..cap / 2 - 1 {
2073             i -= 1;
2074             m.remove(&i);
2075             assert_eq!(m.table.capacity(), new_cap);
2076         }
2077         // A little more than one quarter full.
2078         m.shrink_to_fit();
2079         assert_eq!(m.table.capacity(), cap);
2080         // again, a little more than half full
2081         for _ in 0..cap / 2 - 1 {
2082             i -= 1;
2083             m.remove(&i);
2084         }
2085         m.shrink_to_fit();
2086
2087         assert_eq!(m.len(), i);
2088         assert!(!m.is_empty());
2089         assert_eq!(m.table.capacity(), initial_cap);
2090     }
2091
2092     #[test]
2093     fn test_reserve_shrink_to_fit() {
2094         let mut m = HashMap::new();
2095         m.insert(0, 0);
2096         m.remove(&0);
2097         assert!(m.capacity() >= m.len());
2098         for i in 0..128 {
2099             m.insert(i, i);
2100         }
2101         m.reserve(256);
2102
2103         let usable_cap = m.capacity();
2104         for i in 128..(128 + 256) {
2105             m.insert(i, i);
2106             assert_eq!(m.capacity(), usable_cap);
2107         }
2108
2109         for i in 100..(128 + 256) {
2110             assert_eq!(m.remove(&i), Some(i));
2111         }
2112         m.shrink_to_fit();
2113
2114         assert_eq!(m.len(), 100);
2115         assert!(!m.is_empty());
2116         assert!(m.capacity() >= m.len());
2117
2118         for i in 0..100 {
2119             assert_eq!(m.remove(&i), Some(i));
2120         }
2121         m.shrink_to_fit();
2122         m.insert(0, 0);
2123
2124         assert_eq!(m.len(), 1);
2125         assert!(m.capacity() >= m.len());
2126         assert_eq!(m.remove(&0), Some(0));
2127     }
2128
2129     #[test]
2130     fn test_from_iter() {
2131         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2132
2133         let map: HashMap<_, _> = xs.iter().cloned().collect();
2134
2135         for &(k, v) in &xs {
2136             assert_eq!(map.get(&k), Some(&v));
2137         }
2138     }
2139
2140     #[test]
2141     fn test_size_hint() {
2142         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2143
2144         let map: HashMap<_, _>  = xs.iter().cloned().collect();
2145
2146         let mut iter = map.iter();
2147
2148         for _ in iter.by_ref().take(3) {}
2149
2150         assert_eq!(iter.size_hint(), (3, Some(3)));
2151     }
2152
2153     #[test]
2154     fn test_iter_len() {
2155         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2156
2157         let map: HashMap<_, _>  = xs.iter().cloned().collect();
2158
2159         let mut iter = map.iter();
2160
2161         for _ in iter.by_ref().take(3) {}
2162
2163         assert_eq!(iter.len(), 3);
2164     }
2165
2166     #[test]
2167     fn test_mut_size_hint() {
2168         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2169
2170         let mut map: HashMap<_, _>  = xs.iter().cloned().collect();
2171
2172         let mut iter = map.iter_mut();
2173
2174         for _ in iter.by_ref().take(3) {}
2175
2176         assert_eq!(iter.size_hint(), (3, Some(3)));
2177     }
2178
2179     #[test]
2180     fn test_iter_mut_len() {
2181         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2182
2183         let mut map: HashMap<_, _>  = xs.iter().cloned().collect();
2184
2185         let mut iter = map.iter_mut();
2186
2187         for _ in iter.by_ref().take(3) {}
2188
2189         assert_eq!(iter.len(), 3);
2190     }
2191
2192     #[test]
2193     fn test_index() {
2194         let mut map = HashMap::new();
2195
2196         map.insert(1, 2);
2197         map.insert(2, 1);
2198         map.insert(3, 4);
2199
2200         assert_eq!(map[2], 1);
2201     }
2202
2203     #[test]
2204     #[should_panic]
2205     fn test_index_nonexistent() {
2206         let mut map = HashMap::new();
2207
2208         map.insert(1, 2);
2209         map.insert(2, 1);
2210         map.insert(3, 4);
2211
2212         map[4];
2213     }
2214
2215     #[test]
2216     fn test_entry(){
2217         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2218
2219         let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2220
2221         // Existing key (insert)
2222         match map.entry(1) {
2223             Vacant(_) => unreachable!(),
2224             Occupied(mut view) => {
2225                 assert_eq!(view.get(), &10);
2226                 assert_eq!(view.insert(100), 10);
2227             }
2228         }
2229         assert_eq!(map.get(&1).unwrap(), &100);
2230         assert_eq!(map.len(), 6);
2231
2232
2233         // Existing key (update)
2234         match map.entry(2) {
2235             Vacant(_) => unreachable!(),
2236             Occupied(mut view) => {
2237                 let v = view.get_mut();
2238                 let new_v = (*v) * 10;
2239                 *v = new_v;
2240             }
2241         }
2242         assert_eq!(map.get(&2).unwrap(), &200);
2243         assert_eq!(map.len(), 6);
2244
2245         // Existing key (take)
2246         match map.entry(3) {
2247             Vacant(_) => unreachable!(),
2248             Occupied(view) => {
2249                 assert_eq!(view.remove(), 30);
2250             }
2251         }
2252         assert_eq!(map.get(&3), None);
2253         assert_eq!(map.len(), 5);
2254
2255
2256         // Inexistent key (insert)
2257         match map.entry(10) {
2258             Occupied(_) => unreachable!(),
2259             Vacant(view) => {
2260                 assert_eq!(*view.insert(1000), 1000);
2261             }
2262         }
2263         assert_eq!(map.get(&10).unwrap(), &1000);
2264         assert_eq!(map.len(), 6);
2265     }
2266
2267     #[test]
2268     fn test_entry_take_doesnt_corrupt() {
2269         #![allow(deprecated)] //rand
2270         // Test for #19292
2271         fn check(m: &HashMap<isize, ()>) {
2272             for k in m.keys() {
2273                 assert!(m.contains_key(k),
2274                         "{} is in keys() but not in the map?", k);
2275             }
2276         }
2277
2278         let mut m = HashMap::new();
2279         let mut rng = weak_rng();
2280
2281         // Populate the map with some items.
2282         for _ in 0..50 {
2283             let x = rng.gen_range(-10, 10);
2284             m.insert(x, ());
2285         }
2286
2287         for i in 0..1000 {
2288             let x = rng.gen_range(-10, 10);
2289             match m.entry(x) {
2290                 Vacant(_) => {},
2291                 Occupied(e) => {
2292                     println!("{}: remove {}", i, x);
2293                     e.remove();
2294                 },
2295             }
2296
2297             check(&m);
2298         }
2299     }
2300 }