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