]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hash/map.rs
Merge pull request #20675 from jbcrail/fix-test-comments
[rust.git] / src / libstd / collections / hash / map.rs
1 // Copyright 2014 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::BorrowFrom;
18 use clone::Clone;
19 use cmp::{max, Eq, PartialEq};
20 use default::Default;
21 use fmt::{self, Show};
22 use hash::{Hash, Hasher, RandomSipHasher};
23 use iter::{self, Iterator, 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;
29 use option::Option::{Some, None};
30 use result::Result;
31 use result::Result::{Ok, Err};
32
33 use super::table::{
34     self,
35     Bucket,
36     EmptyBucket,
37     FullBucket,
38     FullBucketImm,
39     FullBucketMut,
40     RawTable,
41     SafeHash
42 };
43 use super::table::BucketState::{
44     Empty,
45     Full,
46 };
47
48 const INITIAL_LOG2_CAP: uint = 5;
49 pub const INITIAL_CAPACITY: uint = 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: uint) -> uint {
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: uint) -> uint {
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 lef-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     use prelude::v1::*;
91     let rp = DefaultResizePolicy;
92     for n in range(0u, 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 doc.rs
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, Show)]
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"), 25u);
290 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24u);
291 /// vikings.insert(Viking::new("Harald", "Iceland"), 12u);
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]
300 pub struct HashMap<K, V, H = RandomSipHasher> {
301     // All hashes are keyed on these values, to prevent hash collision attacks.
302     hasher: H,
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     let size = table.size();
318     let mut probe = Bucket::new(table, hash);
319     let ib = probe.index();
320
321     while probe.index() != ib + size {
322         let full = match probe.peek() {
323             Empty(b) => return TableRef(b.into_table()), // hit an empty bucket
324             Full(b) => b
325         };
326
327         if full.distance() + ib < full.index() {
328             // We can finish the search early if we hit any bucket
329             // with a lower distance to initial bucket than we've probed.
330             return TableRef(full.into_table());
331         }
332
333         // If the hash doesn't match, it can't be this one..
334         if hash == full.hash() {
335             // If the key doesn't match, it can't be this one..
336             if is_match(full.read().0) {
337                 return FoundExisting(full);
338             }
339         }
340
341         probe = full.next();
342     }
343
344     TableRef(probe.into_table())
345 }
346
347 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
348     let (empty, retkey, retval) = starting_bucket.take();
349     let mut gap = match empty.gap_peek() {
350         Some(b) => b,
351         None => return (retkey, retval)
352     };
353
354     while gap.full().distance() != 0 {
355         gap = match gap.shift() {
356             Some(b) => b,
357             None => break
358         };
359     }
360
361     // Now we've done all our shifting. Return the value we grabbed earlier.
362     (retkey, retval)
363 }
364
365 /// Perform robin hood bucket stealing at the given `bucket`. You must
366 /// also pass the position of that bucket's initial bucket so we don't have
367 /// to recalculate it.
368 ///
369 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
370 fn robin_hood<'a, K: 'a, V: 'a>(mut bucket: FullBucketMut<'a, K, V>,
371                         mut ib: uint,
372                         mut hash: SafeHash,
373                         mut k: K,
374                         mut v: V)
375                         -> &'a mut V {
376     let starting_index = bucket.index();
377     let size = {
378         let table = bucket.table(); // FIXME "lifetime too short".
379         table.size()
380     };
381     // There can be at most `size - dib` buckets to displace, because
382     // in the worst case, there are `size` elements and we already are
383     // `distance` buckets away from the initial one.
384     let idx_end = starting_index + size - bucket.distance();
385
386     loop {
387         let (old_hash, old_key, old_val) = bucket.replace(hash, k, v);
388         loop {
389             let probe = bucket.next();
390             assert!(probe.index() != idx_end);
391
392             let full_bucket = match probe.peek() {
393                 Empty(bucket) => {
394                     // Found a hole!
395                     let b = bucket.put(old_hash, old_key, old_val);
396                     // Now that it's stolen, just read the value's pointer
397                     // right out of the table!
398                     return Bucket::at_index(b.into_table(), starting_index)
399                                .peek()
400                                .expect_full()
401                                .into_mut_refs()
402                                .1;
403                 },
404                 Full(bucket) => bucket
405             };
406
407             let probe_ib = full_bucket.index() - full_bucket.distance();
408
409             bucket = full_bucket;
410
411             // Robin hood! Steal the spot.
412             if ib < probe_ib {
413                 ib = probe_ib;
414                 hash = old_hash;
415                 k = old_key;
416                 v = old_val;
417                 break;
418             }
419         }
420     }
421 }
422
423 /// A result that works like Option<FullBucket<..>> but preserves
424 /// the reference that grants us access to the table in any case.
425 enum SearchResult<K, V, M> {
426     // This is an entry that holds the given key:
427     FoundExisting(FullBucket<K, V, M>),
428
429     // There was no such entry. The reference is given back:
430     TableRef(M)
431 }
432
433 impl<K, V, M> SearchResult<K, V, M> {
434     fn into_option(self) -> Option<FullBucket<K, V, M>> {
435         match self {
436             FoundExisting(bucket) => Some(bucket),
437             TableRef(_) => None
438         }
439     }
440 }
441
442 #[old_impl_check]
443 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
444     fn make_hash<X: ?Sized + Hash<S>>(&self, x: &X) -> SafeHash {
445         table::make_hash(&self.hasher, x)
446     }
447
448     /// Search for a key, yielding the index if it's found in the hashtable.
449     /// If you already have the hash for the key lying around, use
450     /// search_hashed.
451     fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> Option<FullBucketImm<'a, K, V>>
452         where Q: BorrowFrom<K> + Eq + Hash<S>
453     {
454         let hash = self.make_hash(q);
455         search_hashed(&self.table, hash, |k| q.eq(BorrowFrom::borrow_from(k)))
456             .into_option()
457     }
458
459     fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> Option<FullBucketMut<'a, K, V>>
460         where Q: BorrowFrom<K> + Eq + Hash<S>
461     {
462         let hash = self.make_hash(q);
463         search_hashed(&mut self.table, hash, |k| q.eq(BorrowFrom::borrow_from(k)))
464             .into_option()
465     }
466
467     // The caller should ensure that invariants by Robin Hood Hashing hold.
468     fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
469         let cap = self.table.capacity();
470         let mut buckets = Bucket::new(&mut self.table, hash);
471         let ib = buckets.index();
472
473         while buckets.index() != ib + cap {
474             // We don't need to compare hashes for value swap.
475             // Not even DIBs for Robin Hood.
476             buckets = match buckets.peek() {
477                 Empty(empty) => {
478                     empty.put(hash, k, v);
479                     return;
480                 }
481                 Full(b) => b.into_bucket()
482             };
483             buckets.next();
484         }
485         panic!("Internal HashMap error: Out of space.");
486     }
487 }
488
489 impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> {
490     /// Create an empty HashMap.
491     ///
492     /// # Example
493     ///
494     /// ```
495     /// use std::collections::HashMap;
496     /// let mut map: HashMap<&str, int> = HashMap::new();
497     /// ```
498     #[inline]
499     #[stable]
500     pub fn new() -> HashMap<K, V, RandomSipHasher> {
501         let hasher = RandomSipHasher::new();
502         HashMap::with_hasher(hasher)
503     }
504
505     /// Creates an empty hash map with the given initial capacity.
506     ///
507     /// # Example
508     ///
509     /// ```
510     /// use std::collections::HashMap;
511     /// let mut map: HashMap<&str, int> = HashMap::with_capacity(10);
512     /// ```
513     #[inline]
514     #[stable]
515     pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomSipHasher> {
516         let hasher = RandomSipHasher::new();
517         HashMap::with_capacity_and_hasher(capacity, hasher)
518     }
519 }
520
521 #[old_impl_check]
522 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
523     /// Creates an empty hashmap which will use the given hasher to hash keys.
524     ///
525     /// The creates map has the default initial capacity.
526     ///
527     /// # Example
528     ///
529     /// ```
530     /// use std::collections::HashMap;
531     /// use std::hash::sip::SipHasher;
532     ///
533     /// let h = SipHasher::new();
534     /// let mut map = HashMap::with_hasher(h);
535     /// map.insert(1i, 2u);
536     /// ```
537     #[inline]
538     #[unstable = "hasher stuff is unclear"]
539     pub fn with_hasher(hasher: H) -> HashMap<K, V, H> {
540         HashMap {
541             hasher:        hasher,
542             resize_policy: DefaultResizePolicy::new(),
543             table:         RawTable::new(0),
544         }
545     }
546
547     /// Create an empty HashMap with space for at least `capacity`
548     /// elements, using `hasher` to hash the keys.
549     ///
550     /// Warning: `hasher` is normally randomly generated, and
551     /// is designed to allow HashMaps to be resistant to attacks that
552     /// cause many collisions and very poor performance. Setting it
553     /// manually using this function can expose a DoS attack vector.
554     ///
555     /// # Example
556     ///
557     /// ```
558     /// use std::collections::HashMap;
559     /// use std::hash::sip::SipHasher;
560     ///
561     /// let h = SipHasher::new();
562     /// let mut map = HashMap::with_capacity_and_hasher(10, h);
563     /// map.insert(1i, 2u);
564     /// ```
565     #[inline]
566     #[unstable = "hasher stuff is unclear"]
567     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashMap<K, V, H> {
568         let resize_policy = DefaultResizePolicy::new();
569         let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
570         let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow");
571         assert!(internal_cap >= capacity, "capacity overflow");
572         HashMap {
573             hasher:        hasher,
574             resize_policy: resize_policy,
575             table:         RawTable::new(internal_cap),
576         }
577     }
578
579     /// Returns the number of elements the map can hold without reallocating.
580     ///
581     /// # Example
582     ///
583     /// ```
584     /// use std::collections::HashMap;
585     /// let map: HashMap<int, int> = HashMap::with_capacity(100);
586     /// assert!(map.capacity() >= 100);
587     /// ```
588     #[inline]
589     #[stable]
590     pub fn capacity(&self) -> uint {
591         self.resize_policy.usable_capacity(self.table.capacity())
592     }
593
594     /// Reserves capacity for at least `additional` more elements to be inserted
595     /// in the `HashMap`. The collection may reserve more space to avoid
596     /// frequent reallocations.
597     ///
598     /// # Panics
599     ///
600     /// Panics if the new allocation size overflows `uint`.
601     ///
602     /// # Example
603     ///
604     /// ```
605     /// use std::collections::HashMap;
606     /// let mut map: HashMap<&str, int> = HashMap::new();
607     /// map.reserve(10);
608     /// ```
609     #[stable]
610     pub fn reserve(&mut self, additional: uint) {
611         let new_size = self.len().checked_add(additional).expect("capacity overflow");
612         let min_cap = self.resize_policy.min_capacity(new_size);
613
614         // An invalid value shouldn't make us run out of space. This includes
615         // an overflow check.
616         assert!(new_size <= min_cap);
617
618         if self.table.capacity() < min_cap {
619             let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
620             self.resize(new_capacity);
621         }
622     }
623
624     /// Resizes the internal vectors to a new capacity. It's your responsibility to:
625     ///   1) Make sure the new capacity is enough for all the elements, accounting
626     ///      for the load factor.
627     ///   2) Ensure new_capacity is a power of two or zero.
628     fn resize(&mut self, new_capacity: uint) {
629         assert!(self.table.size() <= new_capacity);
630         assert!(new_capacity.is_power_of_two() || new_capacity == 0);
631
632         let mut old_table = replace(&mut self.table, RawTable::new(new_capacity));
633         let old_size = old_table.size();
634
635         if old_table.capacity() == 0 || old_table.size() == 0 {
636             return;
637         }
638
639         // Grow the table.
640         // Specialization of the other branch.
641         let mut bucket = Bucket::first(&mut old_table);
642
643         // "So a few of the first shall be last: for many be called,
644         // but few chosen."
645         //
646         // We'll most likely encounter a few buckets at the beginning that
647         // have their initial buckets near the end of the table. They were
648         // placed at the beginning as the probe wrapped around the table
649         // during insertion. We must skip forward to a bucket that won't
650         // get reinserted too early and won't unfairly steal others spot.
651         // This eliminates the need for robin hood.
652         loop {
653             bucket = match bucket.peek() {
654                 Full(full) => {
655                     if full.distance() == 0 {
656                         // This bucket occupies its ideal spot.
657                         // It indicates the start of another "cluster".
658                         bucket = full.into_bucket();
659                         break;
660                     }
661                     // Leaving this bucket in the last cluster for later.
662                     full.into_bucket()
663                 }
664                 Empty(b) => {
665                     // Encountered a hole between clusters.
666                     b.into_bucket()
667                 }
668             };
669             bucket.next();
670         }
671
672         // This is how the buckets might be laid out in memory:
673         // ($ marks an initialized bucket)
674         //  ________________
675         // |$$$_$$$$$$_$$$$$|
676         //
677         // But we've skipped the entire initial cluster of buckets
678         // and will continue iteration in this order:
679         //  ________________
680         //     |$$$$$$_$$$$$
681         //                  ^ wrap around once end is reached
682         //  ________________
683         //  $$$_____________|
684         //    ^ exit once table.size == 0
685         loop {
686             bucket = match bucket.peek() {
687                 Full(bucket) => {
688                     let h = bucket.hash();
689                     let (b, k, v) = bucket.take();
690                     self.insert_hashed_ordered(h, k, v);
691                     {
692                         let t = b.table(); // FIXME "lifetime too short".
693                         if t.size() == 0 { break }
694                     };
695                     b.into_bucket()
696                 }
697                 Empty(b) => b.into_bucket()
698             };
699             bucket.next();
700         }
701
702         assert_eq!(self.table.size(), old_size);
703     }
704
705     /// Shrinks the capacity of the map as much as possible. It will drop
706     /// down as much as possible while maintaining the internal rules
707     /// and possibly leaving some space in accordance with the resize policy.
708     ///
709     /// # Example
710     ///
711     /// ```
712     /// use std::collections::HashMap;
713     ///
714     /// let mut map: HashMap<int, int> = HashMap::with_capacity(100);
715     /// map.insert(1, 2);
716     /// map.insert(3, 4);
717     /// assert!(map.capacity() >= 100);
718     /// map.shrink_to_fit();
719     /// assert!(map.capacity() >= 2);
720     /// ```
721     #[stable]
722     pub fn shrink_to_fit(&mut self) {
723         let min_capacity = self.resize_policy.min_capacity(self.len());
724         let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY);
725
726         // An invalid value shouldn't make us run out of space.
727         debug_assert!(self.len() <= min_capacity);
728
729         if self.table.capacity() != min_capacity {
730             let old_table = replace(&mut self.table, RawTable::new(min_capacity));
731             let old_size = old_table.size();
732
733             // Shrink the table. Naive algorithm for resizing:
734             for (h, k, v) in old_table.into_iter() {
735                 self.insert_hashed_nocheck(h, k, v);
736             }
737
738             debug_assert_eq!(self.table.size(), old_size);
739         }
740     }
741
742     /// Insert a pre-hashed key-value pair, without first checking
743     /// that there's enough room in the buckets. Returns a reference to the
744     /// newly insert value.
745     ///
746     /// If the key already exists, the hashtable will be returned untouched
747     /// and a reference to the existing element will be returned.
748     fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> &mut V {
749         self.insert_or_replace_with(hash, k, v, |_, _, _| ())
750     }
751
752     fn insert_or_replace_with<'a, F>(&'a mut self,
753                                      hash: SafeHash,
754                                      k: K,
755                                      v: V,
756                                      mut found_existing: F)
757                                      -> &'a mut V where
758         F: FnMut(&mut K, &mut V, V),
759     {
760         // Worst case, we'll find one empty bucket among `size + 1` buckets.
761         let size = self.table.size();
762         let mut probe = Bucket::new(&mut self.table, hash);
763         let ib = probe.index();
764
765         loop {
766             let mut bucket = match probe.peek() {
767                 Empty(bucket) => {
768                     // Found a hole!
769                     return bucket.put(hash, k, v).into_mut_refs().1;
770                 }
771                 Full(bucket) => bucket
772             };
773
774             // hash matches?
775             if bucket.hash() == hash {
776                 // key matches?
777                 if k == *bucket.read_mut().0 {
778                     let (bucket_k, bucket_v) = bucket.into_mut_refs();
779                     debug_assert!(k == *bucket_k);
780                     // Key already exists. Get its reference.
781                     found_existing(bucket_k, bucket_v, v);
782                     return bucket_v;
783                 }
784             }
785
786             let robin_ib = bucket.index() as int - bucket.distance() as int;
787
788             if (ib as int) < robin_ib {
789                 // Found a luckier bucket than me. Better steal his spot.
790                 return robin_hood(bucket, robin_ib as uint, hash, k, v);
791             }
792
793             probe = bucket.next();
794             assert!(probe.index() != ib + size + 1);
795         }
796     }
797
798     /// An iterator visiting all keys in arbitrary order.
799     /// Iterator element type is `&'a K`.
800     ///
801     /// # Example
802     ///
803     /// ```
804     /// use std::collections::HashMap;
805     ///
806     /// let mut map = HashMap::new();
807     /// map.insert("a", 1i);
808     /// map.insert("b", 2);
809     /// map.insert("c", 3);
810     ///
811     /// for key in map.keys() {
812     ///     println!("{}", key);
813     /// }
814     /// ```
815     #[stable]
816     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
817         fn first<A, B>((a, _): (A, B)) -> A { a }
818         let first: fn((&'a K,&'a V)) -> &'a K = first; // coerce to fn ptr
819
820         Keys { inner: self.iter().map(first) }
821     }
822
823     /// An iterator visiting all values in arbitrary order.
824     /// Iterator element type is `&'a V`.
825     ///
826     /// # Example
827     ///
828     /// ```
829     /// use std::collections::HashMap;
830     ///
831     /// let mut map = HashMap::new();
832     /// map.insert("a", 1i);
833     /// map.insert("b", 2);
834     /// map.insert("c", 3);
835     ///
836     /// for key in map.values() {
837     ///     println!("{}", key);
838     /// }
839     /// ```
840     #[stable]
841     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
842         fn second<A, B>((_, b): (A, B)) -> B { b }
843         let second: fn((&'a K,&'a V)) -> &'a V = second; // coerce to fn ptr
844
845         Values { inner: self.iter().map(second) }
846     }
847
848     /// An iterator visiting all key-value pairs in arbitrary order.
849     /// Iterator element type is `(&'a K, &'a V)`.
850     ///
851     /// # Example
852     ///
853     /// ```
854     /// use std::collections::HashMap;
855     ///
856     /// let mut map = HashMap::new();
857     /// map.insert("a", 1i);
858     /// map.insert("b", 2);
859     /// map.insert("c", 3);
860     ///
861     /// for (key, val) in map.iter() {
862     ///     println!("key: {} val: {}", key, val);
863     /// }
864     /// ```
865     #[stable]
866     pub fn iter(&self) -> Iter<K, V> {
867         Iter { inner: self.table.iter() }
868     }
869
870     /// An iterator visiting all key-value pairs in arbitrary order,
871     /// with mutable references to the values.
872     /// Iterator element type is `(&'a K, &'a mut V)`.
873     ///
874     /// # Example
875     ///
876     /// ```
877     /// use std::collections::HashMap;
878     ///
879     /// let mut map = HashMap::new();
880     /// map.insert("a", 1i);
881     /// map.insert("b", 2);
882     /// map.insert("c", 3);
883     ///
884     /// // Update all values
885     /// for (_, val) in map.iter_mut() {
886     ///     *val *= 2;
887     /// }
888     ///
889     /// for (key, val) in map.iter() {
890     ///     println!("key: {} val: {}", key, val);
891     /// }
892     /// ```
893     #[stable]
894     pub fn iter_mut(&mut self) -> IterMut<K, V> {
895         IterMut { inner: self.table.iter_mut() }
896     }
897
898     /// Creates a consuming iterator, that is, one that moves each key-value
899     /// pair out of the map in arbitrary order. The map cannot be used after
900     /// calling this.
901     ///
902     /// # Example
903     ///
904     /// ```
905     /// use std::collections::HashMap;
906     ///
907     /// let mut map = HashMap::new();
908     /// map.insert("a", 1i);
909     /// map.insert("b", 2);
910     /// map.insert("c", 3);
911     ///
912     /// // Not possible with .iter()
913     /// let vec: Vec<(&str, int)> = map.into_iter().collect();
914     /// ```
915     #[stable]
916     pub fn into_iter(self) -> IntoIter<K, V> {
917         fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
918         let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two;
919
920         IntoIter {
921             inner: self.table.into_iter().map(last_two)
922         }
923     }
924
925     /// Gets the given key's corresponding entry in the map for in-place manipulation.
926     #[unstable = "precise API still being fleshed out"]
927     pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V>
928     {
929         // Gotta resize now.
930         self.reserve(1);
931
932         let hash = self.make_hash(&key);
933         search_entry_hashed(&mut self.table, hash, key)
934     }
935
936     /// Return the number of elements in the map.
937     ///
938     /// # Example
939     ///
940     /// ```
941     /// use std::collections::HashMap;
942     ///
943     /// let mut a = HashMap::new();
944     /// assert_eq!(a.len(), 0);
945     /// a.insert(1u, "a");
946     /// assert_eq!(a.len(), 1);
947     /// ```
948     #[stable]
949     pub fn len(&self) -> uint { self.table.size() }
950
951     /// Return true if the map contains no elements.
952     ///
953     /// # Example
954     ///
955     /// ```
956     /// use std::collections::HashMap;
957     ///
958     /// let mut a = HashMap::new();
959     /// assert!(a.is_empty());
960     /// a.insert(1u, "a");
961     /// assert!(!a.is_empty());
962     /// ```
963     #[inline]
964     #[stable]
965     pub fn is_empty(&self) -> bool { self.len() == 0 }
966
967     /// Clears the map, returning all key-value pairs as an iterator. Keeps the
968     /// allocated memory for reuse.
969     ///
970     /// # Example
971     ///
972     /// ```
973     /// use std::collections::HashMap;
974     ///
975     /// let mut a = HashMap::new();
976     /// a.insert(1u, "a");
977     /// a.insert(2u, "b");
978     ///
979     /// for (k, v) in a.drain().take(1) {
980     ///     assert!(k == 1 || k == 2);
981     ///     assert!(v == "a" || v == "b");
982     /// }
983     ///
984     /// assert!(a.is_empty());
985     /// ```
986     #[inline]
987     #[unstable = "matches collection reform specification, waiting for dust to settle"]
988     pub fn drain(&mut self) -> Drain<K, V> {
989         fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
990         let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two; // coerce to fn pointer
991
992         Drain {
993             inner: self.table.drain().map(last_two),
994         }
995     }
996
997     /// Clears the map, removing all key-value pairs. Keeps the allocated memory
998     /// for reuse.
999     ///
1000     /// # Example
1001     ///
1002     /// ```
1003     /// use std::collections::HashMap;
1004     ///
1005     /// let mut a = HashMap::new();
1006     /// a.insert(1u, "a");
1007     /// a.clear();
1008     /// assert!(a.is_empty());
1009     /// ```
1010     #[stable]
1011     #[inline]
1012     pub fn clear(&mut self) {
1013         self.drain();
1014     }
1015
1016     /// Returns a reference to the value corresponding to the key.
1017     ///
1018     /// The key may be any borrowed form of the map's key type, but
1019     /// `Hash` and `Eq` on the borrowed form *must* match those for
1020     /// the key type.
1021     ///
1022     /// # Example
1023     ///
1024     /// ```
1025     /// use std::collections::HashMap;
1026     ///
1027     /// let mut map = HashMap::new();
1028     /// map.insert(1u, "a");
1029     /// assert_eq!(map.get(&1), Some(&"a"));
1030     /// assert_eq!(map.get(&2), None);
1031     /// ```
1032     #[stable]
1033     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1034         where Q: Hash<S> + Eq + BorrowFrom<K>
1035     {
1036         self.search(k).map(|bucket| bucket.into_refs().1)
1037     }
1038
1039     /// Returns true if the map contains a value for the specified key.
1040     ///
1041     /// The key may be any borrowed form of the map's key type, but
1042     /// `Hash` and `Eq` on the borrowed form *must* match those for
1043     /// the key type.
1044     ///
1045     /// # Example
1046     ///
1047     /// ```
1048     /// use std::collections::HashMap;
1049     ///
1050     /// let mut map = HashMap::new();
1051     /// map.insert(1u, "a");
1052     /// assert_eq!(map.contains_key(&1), true);
1053     /// assert_eq!(map.contains_key(&2), false);
1054     /// ```
1055     #[stable]
1056     pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1057         where Q: Hash<S> + Eq + BorrowFrom<K>
1058     {
1059         self.search(k).is_some()
1060     }
1061
1062     /// Returns a mutable reference to the value corresponding to the key.
1063     ///
1064     /// The key may be any borrowed form of the map's key type, but
1065     /// `Hash` and `Eq` on the borrowed form *must* match those for
1066     /// the key type.
1067     ///
1068     /// # Example
1069     ///
1070     /// ```
1071     /// use std::collections::HashMap;
1072     ///
1073     /// let mut map = HashMap::new();
1074     /// map.insert(1u, "a");
1075     /// match map.get_mut(&1) {
1076     ///     Some(x) => *x = "b",
1077     ///     None => (),
1078     /// }
1079     /// assert_eq!(map[1], "b");
1080     /// ```
1081     #[stable]
1082     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1083         where Q: Hash<S> + Eq + BorrowFrom<K>
1084     {
1085         self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1086     }
1087
1088     /// Inserts a key-value pair from the map. If the key already had a value
1089     /// present in the map, that value is returned. Otherwise, `None` is returned.
1090     ///
1091     /// # Example
1092     ///
1093     /// ```
1094     /// use std::collections::HashMap;
1095     ///
1096     /// let mut map = HashMap::new();
1097     /// assert_eq!(map.insert(37u, "a"), None);
1098     /// assert_eq!(map.is_empty(), false);
1099     ///
1100     /// map.insert(37, "b");
1101     /// assert_eq!(map.insert(37, "c"), Some("b"));
1102     /// assert_eq!(map[37], "c");
1103     /// ```
1104     #[stable]
1105     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1106         let hash = self.make_hash(&k);
1107         self.reserve(1);
1108
1109         let mut retval = None;
1110         self.insert_or_replace_with(hash, k, v, |_, val_ref, val| {
1111             retval = Some(replace(val_ref, val));
1112         });
1113         retval
1114     }
1115
1116     /// Removes a key from the map, returning the value at the key if the key
1117     /// was previously in the map.
1118     ///
1119     /// The key may be any borrowed form of the map's key type, but
1120     /// `Hash` and `Eq` on the borrowed form *must* match those for
1121     /// the key type.
1122     ///
1123     /// # Example
1124     ///
1125     /// ```
1126     /// use std::collections::HashMap;
1127     ///
1128     /// let mut map = HashMap::new();
1129     /// map.insert(1u, "a");
1130     /// assert_eq!(map.remove(&1), Some("a"));
1131     /// assert_eq!(map.remove(&1), None);
1132     /// ```
1133     #[stable]
1134     pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1135         where Q: Hash<S> + Eq + BorrowFrom<K>
1136     {
1137         if self.table.size() == 0 {
1138             return None
1139         }
1140
1141         self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1142     }
1143 }
1144
1145 fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHash, k: K)
1146         -> Entry<'a, K, V>
1147 {
1148     // Worst case, we'll find one empty bucket among `size + 1` buckets.
1149     let size = table.size();
1150     let mut probe = Bucket::new(table, hash);
1151     let ib = probe.index();
1152
1153     loop {
1154         let bucket = match probe.peek() {
1155             Empty(bucket) => {
1156                 // Found a hole!
1157                 return Vacant(VacantEntry {
1158                     hash: hash,
1159                     key: k,
1160                     elem: NoElem(bucket),
1161                 });
1162             },
1163             Full(bucket) => bucket
1164         };
1165
1166         // hash matches?
1167         if bucket.hash() == hash {
1168             // key matches?
1169             if k == *bucket.read().0 {
1170                 return Occupied(OccupiedEntry{
1171                     elem: bucket,
1172                 });
1173             }
1174         }
1175
1176         let robin_ib = bucket.index() as int - bucket.distance() as int;
1177
1178         if (ib as int) < robin_ib {
1179             // Found a luckier bucket than me. Better steal his spot.
1180             return Vacant(VacantEntry {
1181                 hash: hash,
1182                 key: k,
1183                 elem: NeqElem(bucket, robin_ib as uint),
1184             });
1185         }
1186
1187         probe = bucket.next();
1188         assert!(probe.index() != ib + size + 1);
1189     }
1190 }
1191
1192 #[stable]
1193 #[old_impl_check]
1194 impl<K: Eq + Hash<S>, V: PartialEq, S, H: Hasher<S>> PartialEq for HashMap<K, V, H> {
1195     fn eq(&self, other: &HashMap<K, V, H>) -> bool {
1196         if self.len() != other.len() { return false; }
1197
1198         self.iter().all(|(key, value)|
1199             other.get(key).map_or(false, |v| *value == *v)
1200         )
1201     }
1202 }
1203
1204 #[stable]
1205 #[old_impl_check]
1206 impl<K: Eq + Hash<S>, V: Eq, S, H: Hasher<S>> Eq for HashMap<K, V, H> {}
1207
1208 #[stable]
1209 #[old_impl_check]
1210 impl<K: Eq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> {
1211     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1212         try!(write!(f, "HashMap {{"));
1213
1214         for (i, (k, v)) in self.iter().enumerate() {
1215             if i != 0 { try!(write!(f, ", ")); }
1216             try!(write!(f, "{:?}: {:?}", *k, *v));
1217         }
1218
1219         write!(f, "}}")
1220     }
1221 }
1222
1223 #[stable]
1224 #[old_impl_check]
1225 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H> {
1226     #[stable]
1227     fn default() -> HashMap<K, V, H> {
1228         HashMap::with_hasher(Default::default())
1229     }
1230 }
1231
1232 #[stable]
1233 #[old_impl_check]
1234 impl<K: Hash<S> + Eq, Q: ?Sized, V, S, H: Hasher<S>> Index<Q> for HashMap<K, V, H>
1235     where Q: BorrowFrom<K> + Hash<S> + Eq
1236 {
1237     type Output = V;
1238
1239     #[inline]
1240     fn index<'a>(&'a self, index: &Q) -> &'a V {
1241         self.get(index).expect("no entry found for key")
1242     }
1243 }
1244
1245 #[stable]
1246 #[old_impl_check]
1247 impl<K: Hash<S> + Eq, Q: ?Sized, V, S, H: Hasher<S>> IndexMut<Q> for HashMap<K, V, H>
1248     where Q: BorrowFrom<K> + Hash<S> + Eq
1249 {
1250     type Output = V;
1251
1252     #[inline]
1253     fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
1254         self.get_mut(index).expect("no entry found for key")
1255     }
1256 }
1257
1258 /// HashMap iterator
1259 #[stable]
1260 pub struct Iter<'a, K: 'a, V: 'a> {
1261     inner: table::Iter<'a, K, V>
1262 }
1263
1264 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1265 impl<'a, K, V> Clone for Iter<'a, K, V> {
1266     fn clone(&self) -> Iter<'a, K, V> {
1267         Iter {
1268             inner: self.inner.clone()
1269         }
1270     }
1271 }
1272
1273 /// HashMap mutable values iterator
1274 #[stable]
1275 pub struct IterMut<'a, K: 'a, V: 'a> {
1276     inner: table::IterMut<'a, K, V>
1277 }
1278
1279 /// HashMap move iterator
1280 #[stable]
1281 pub struct IntoIter<K, V> {
1282     inner: iter::Map<
1283         (SafeHash, K, V),
1284         (K, V),
1285         table::IntoIter<K, V>,
1286         fn((SafeHash, K, V)) -> (K, V),
1287     >
1288 }
1289
1290 /// HashMap keys iterator
1291 #[stable]
1292 pub struct Keys<'a, K: 'a, V: 'a> {
1293     inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
1294 }
1295
1296 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1297 impl<'a, K, V> Clone for Keys<'a, K, V> {
1298     fn clone(&self) -> Keys<'a, K, V> {
1299         Keys {
1300             inner: self.inner.clone()
1301         }
1302     }
1303 }
1304
1305 /// HashMap values iterator
1306 #[stable]
1307 pub struct Values<'a, K: 'a, V: 'a> {
1308     inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
1309 }
1310
1311 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1312 impl<'a, K, V> Clone for Values<'a, K, V> {
1313     fn clone(&self) -> Values<'a, K, V> {
1314         Values {
1315             inner: self.inner.clone()
1316         }
1317     }
1318 }
1319
1320 /// HashMap drain iterator
1321 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1322 pub struct Drain<'a, K: 'a, V: 'a> {
1323     inner: iter::Map<
1324         (SafeHash, K, V),
1325         (K, V),
1326         table::Drain<'a, K, V>,
1327         fn((SafeHash, K, V)) -> (K, V),
1328     >
1329 }
1330
1331 /// A view into a single occupied location in a HashMap
1332 #[unstable = "precise API still being fleshed out"]
1333 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1334     elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1335 }
1336
1337 /// A view into a single empty location in a HashMap
1338 #[unstable = "precise API still being fleshed out"]
1339 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1340     hash: SafeHash,
1341     key: K,
1342     elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1343 }
1344
1345 /// A view into a single location in a map, which may be vacant or occupied
1346 #[unstable = "precise API still being fleshed out"]
1347 pub enum Entry<'a, K: 'a, V: 'a> {
1348     /// An occupied Entry
1349     Occupied(OccupiedEntry<'a, K, V>),
1350     /// A vacant Entry
1351     Vacant(VacantEntry<'a, K, V>),
1352 }
1353
1354 /// Possible states of a VacantEntry
1355 enum VacantEntryState<K, V, M> {
1356     /// The index is occupied, but the key to insert has precedence,
1357     /// and will kick the current one out on insertion
1358     NeqElem(FullBucket<K, V, M>, uint),
1359     /// The index is genuinely vacant
1360     NoElem(EmptyBucket<K, V, M>),
1361 }
1362
1363 #[stable]
1364 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1365     type Item = (&'a K, &'a V);
1366
1367     #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1368     #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1369 }
1370
1371 #[stable]
1372 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1373     type Item = (&'a K, &'a mut V);
1374
1375     #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1376     #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1377 }
1378
1379 #[stable]
1380 impl<K, V> Iterator for IntoIter<K, V> {
1381     type Item = (K, V);
1382
1383     #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1384     #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1385 }
1386
1387 #[stable]
1388 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1389     type Item = &'a K;
1390
1391     #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1392     #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1393 }
1394
1395 #[stable]
1396 impl<'a, K, V> Iterator for Values<'a, K, V> {
1397     type Item = &'a V;
1398
1399     #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1400     #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1401 }
1402
1403 #[stable]
1404 impl<'a, K: 'a, V: 'a> Iterator for Drain<'a, K, V> {
1405     type Item = (K, V);
1406
1407     #[inline]
1408     fn next(&mut self) -> Option<(K, V)> {
1409         self.inner.next()
1410     }
1411     #[inline]
1412     fn size_hint(&self) -> (uint, Option<uint>) {
1413         self.inner.size_hint()
1414     }
1415 }
1416
1417 #[unstable = "matches collection reform v2 specification, waiting for dust to settle"]
1418 impl<'a, K, V> Entry<'a, K, V> {
1419     /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
1420     pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
1421         match self {
1422             Occupied(entry) => Ok(entry.into_mut()),
1423             Vacant(entry) => Err(entry),
1424         }
1425     }
1426 }
1427
1428 #[unstable = "matches collection reform v2 specification, waiting for dust to settle"]
1429 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1430     /// Gets a reference to the value in the entry
1431     pub fn get(&self) -> &V {
1432         self.elem.read().1
1433     }
1434
1435     /// Gets a mutable reference to the value in the entry
1436     pub fn get_mut(&mut self) -> &mut V {
1437         self.elem.read_mut().1
1438     }
1439
1440     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1441     /// with a lifetime bound to the map itself
1442     pub fn into_mut(self) -> &'a mut V {
1443         self.elem.into_mut_refs().1
1444     }
1445
1446     /// Sets the value of the entry, and returns the entry's old value
1447     pub fn insert(&mut self, mut value: V) -> V {
1448         let old_value = self.get_mut();
1449         mem::swap(&mut value, old_value);
1450         value
1451     }
1452
1453     /// Takes the value out of the entry, and returns it
1454     pub fn remove(self) -> V {
1455         pop_internal(self.elem).1
1456     }
1457 }
1458
1459 #[unstable = "matches collection reform v2 specification, waiting for dust to settle"]
1460 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1461     /// Sets the value of the entry with the VacantEntry's key,
1462     /// and returns a mutable reference to it
1463     pub fn insert(self, value: V) -> &'a mut V {
1464         match self.elem {
1465             NeqElem(bucket, ib) => {
1466                 robin_hood(bucket, ib, self.hash, self.key, value)
1467             }
1468             NoElem(bucket) => {
1469                 bucket.put(self.hash, self.key, value).into_mut_refs().1
1470             }
1471         }
1472     }
1473 }
1474
1475 #[stable]
1476 #[old_impl_check]
1477 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> FromIterator<(K, V)> for HashMap<K, V, H> {
1478     fn from_iter<T: Iterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, H> {
1479         let lower = iter.size_hint().0;
1480         let mut map = HashMap::with_capacity_and_hasher(lower, Default::default());
1481         map.extend(iter);
1482         map
1483     }
1484 }
1485
1486 #[stable]
1487 #[old_impl_check]
1488 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Extend<(K, V)> for HashMap<K, V, H> {
1489     fn extend<T: Iterator<Item=(K, V)>>(&mut self, mut iter: T) {
1490         for (k, v) in iter {
1491             self.insert(k, v);
1492         }
1493     }
1494 }
1495
1496 #[cfg(test)]
1497 mod test_map {
1498     use prelude::v1::*;
1499
1500     use super::HashMap;
1501     use super::Entry::{Occupied, Vacant};
1502     use iter::{range_inclusive, range_step_inclusive, repeat};
1503     use cell::RefCell;
1504     use rand::{weak_rng, Rng};
1505
1506     #[test]
1507     fn test_create_capacity_zero() {
1508         let mut m = HashMap::with_capacity(0);
1509
1510         assert!(m.insert(1i, 1i).is_none());
1511
1512         assert!(m.contains_key(&1));
1513         assert!(!m.contains_key(&0));
1514     }
1515
1516     #[test]
1517     fn test_insert() {
1518         let mut m = HashMap::new();
1519         assert_eq!(m.len(), 0);
1520         assert!(m.insert(1i, 2i).is_none());
1521         assert_eq!(m.len(), 1);
1522         assert!(m.insert(2i, 4i).is_none());
1523         assert_eq!(m.len(), 2);
1524         assert_eq!(*m.get(&1).unwrap(), 2);
1525         assert_eq!(*m.get(&2).unwrap(), 4);
1526     }
1527
1528     thread_local! { static DROP_VECTOR: RefCell<Vec<int>> = RefCell::new(Vec::new()) }
1529
1530     #[derive(Hash, PartialEq, Eq)]
1531     struct Dropable {
1532         k: uint
1533     }
1534
1535     impl Dropable {
1536         fn new(k: uint) -> Dropable {
1537             DROP_VECTOR.with(|slot| {
1538                 slot.borrow_mut()[k] += 1;
1539             });
1540
1541             Dropable { k: k }
1542         }
1543     }
1544
1545     impl Drop for Dropable {
1546         fn drop(&mut self) {
1547             DROP_VECTOR.with(|slot| {
1548                 slot.borrow_mut()[self.k] -= 1;
1549             });
1550         }
1551     }
1552
1553     impl Clone for Dropable {
1554         fn clone(&self) -> Dropable {
1555             Dropable::new(self.k)
1556         }
1557     }
1558
1559     #[test]
1560     fn test_drops() {
1561         DROP_VECTOR.with(|slot| {
1562             *slot.borrow_mut() = repeat(0i).take(200).collect();
1563         });
1564
1565         {
1566             let mut m = HashMap::new();
1567
1568             DROP_VECTOR.with(|v| {
1569                 for i in range(0u, 200) {
1570                     assert_eq!(v.borrow()[i], 0);
1571                 }
1572             });
1573
1574             for i in range(0u, 100) {
1575                 let d1 = Dropable::new(i);
1576                 let d2 = Dropable::new(i+100);
1577                 m.insert(d1, d2);
1578             }
1579
1580             DROP_VECTOR.with(|v| {
1581                 for i in range(0u, 200) {
1582                     assert_eq!(v.borrow()[i], 1);
1583                 }
1584             });
1585
1586             for i in range(0u, 50) {
1587                 let k = Dropable::new(i);
1588                 let v = m.remove(&k);
1589
1590                 assert!(v.is_some());
1591
1592                 DROP_VECTOR.with(|v| {
1593                     assert_eq!(v.borrow()[i], 1);
1594                     assert_eq!(v.borrow()[i+100], 1);
1595                 });
1596             }
1597
1598             DROP_VECTOR.with(|v| {
1599                 for i in range(0u, 50) {
1600                     assert_eq!(v.borrow()[i], 0);
1601                     assert_eq!(v.borrow()[i+100], 0);
1602                 }
1603
1604                 for i in range(50u, 100) {
1605                     assert_eq!(v.borrow()[i], 1);
1606                     assert_eq!(v.borrow()[i+100], 1);
1607                 }
1608             });
1609         }
1610
1611         DROP_VECTOR.with(|v| {
1612             for i in range(0u, 200) {
1613                 assert_eq!(v.borrow()[i], 0);
1614             }
1615         });
1616     }
1617
1618     #[test]
1619     fn test_move_iter_drops() {
1620         DROP_VECTOR.with(|v| {
1621             *v.borrow_mut() = repeat(0).take(200).collect();
1622         });
1623
1624         let hm = {
1625             let mut hm = HashMap::new();
1626
1627             DROP_VECTOR.with(|v| {
1628                 for i in range(0u, 200) {
1629                     assert_eq!(v.borrow()[i], 0);
1630                 }
1631             });
1632
1633             for i in range(0u, 100) {
1634                 let d1 = Dropable::new(i);
1635                 let d2 = Dropable::new(i+100);
1636                 hm.insert(d1, d2);
1637             }
1638
1639             DROP_VECTOR.with(|v| {
1640                 for i in range(0u, 200) {
1641                     assert_eq!(v.borrow()[i], 1);
1642                 }
1643             });
1644
1645             hm
1646         };
1647
1648         // By the way, ensure that cloning doesn't screw up the dropping.
1649         drop(hm.clone());
1650
1651         {
1652             let mut half = hm.into_iter().take(50);
1653
1654             DROP_VECTOR.with(|v| {
1655                 for i in range(0u, 200) {
1656                     assert_eq!(v.borrow()[i], 1);
1657                 }
1658             });
1659
1660             for _ in half {}
1661
1662             DROP_VECTOR.with(|v| {
1663                 let nk = range(0u, 100).filter(|&i| {
1664                     v.borrow()[i] == 1
1665                 }).count();
1666
1667                 let nv = range(0u, 100).filter(|&i| {
1668                     v.borrow()[i+100] == 1
1669                 }).count();
1670
1671                 assert_eq!(nk, 50);
1672                 assert_eq!(nv, 50);
1673             });
1674         };
1675
1676         DROP_VECTOR.with(|v| {
1677             for i in range(0u, 200) {
1678                 assert_eq!(v.borrow()[i], 0);
1679             }
1680         });
1681     }
1682
1683     #[test]
1684     fn test_empty_pop() {
1685         let mut m: HashMap<int, bool> = HashMap::new();
1686         assert_eq!(m.remove(&0), None);
1687     }
1688
1689     #[test]
1690     fn test_lots_of_insertions() {
1691         let mut m = HashMap::new();
1692
1693         // Try this a few times to make sure we never screw up the hashmap's
1694         // internal state.
1695         for _ in range(0i, 10) {
1696             assert!(m.is_empty());
1697
1698             for i in range_inclusive(1i, 1000) {
1699                 assert!(m.insert(i, i).is_none());
1700
1701                 for j in range_inclusive(1, i) {
1702                     let r = m.get(&j);
1703                     assert_eq!(r, Some(&j));
1704                 }
1705
1706                 for j in range_inclusive(i+1, 1000) {
1707                     let r = m.get(&j);
1708                     assert_eq!(r, None);
1709                 }
1710             }
1711
1712             for i in range_inclusive(1001i, 2000) {
1713                 assert!(!m.contains_key(&i));
1714             }
1715
1716             // remove forwards
1717             for i in range_inclusive(1i, 1000) {
1718                 assert!(m.remove(&i).is_some());
1719
1720                 for j in range_inclusive(1, i) {
1721                     assert!(!m.contains_key(&j));
1722                 }
1723
1724                 for j in range_inclusive(i+1, 1000) {
1725                     assert!(m.contains_key(&j));
1726                 }
1727             }
1728
1729             for i in range_inclusive(1i, 1000) {
1730                 assert!(!m.contains_key(&i));
1731             }
1732
1733             for i in range_inclusive(1i, 1000) {
1734                 assert!(m.insert(i, i).is_none());
1735             }
1736
1737             // remove backwards
1738             for i in range_step_inclusive(1000i, 1, -1) {
1739                 assert!(m.remove(&i).is_some());
1740
1741                 for j in range_inclusive(i, 1000) {
1742                     assert!(!m.contains_key(&j));
1743                 }
1744
1745                 for j in range_inclusive(1, i-1) {
1746                     assert!(m.contains_key(&j));
1747                 }
1748             }
1749         }
1750     }
1751
1752     #[test]
1753     fn test_find_mut() {
1754         let mut m = HashMap::new();
1755         assert!(m.insert(1i, 12i).is_none());
1756         assert!(m.insert(2i, 8i).is_none());
1757         assert!(m.insert(5i, 14i).is_none());
1758         let new = 100;
1759         match m.get_mut(&5) {
1760             None => panic!(), Some(x) => *x = new
1761         }
1762         assert_eq!(m.get(&5), Some(&new));
1763     }
1764
1765     #[test]
1766     fn test_insert_overwrite() {
1767         let mut m = HashMap::new();
1768         assert!(m.insert(1i, 2i).is_none());
1769         assert_eq!(*m.get(&1).unwrap(), 2);
1770         assert!(!m.insert(1i, 3i).is_none());
1771         assert_eq!(*m.get(&1).unwrap(), 3);
1772     }
1773
1774     #[test]
1775     fn test_insert_conflicts() {
1776         let mut m = HashMap::with_capacity(4);
1777         assert!(m.insert(1i, 2i).is_none());
1778         assert!(m.insert(5i, 3i).is_none());
1779         assert!(m.insert(9i, 4i).is_none());
1780         assert_eq!(*m.get(&9).unwrap(), 4);
1781         assert_eq!(*m.get(&5).unwrap(), 3);
1782         assert_eq!(*m.get(&1).unwrap(), 2);
1783     }
1784
1785     #[test]
1786     fn test_conflict_remove() {
1787         let mut m = HashMap::with_capacity(4);
1788         assert!(m.insert(1i, 2i).is_none());
1789         assert_eq!(*m.get(&1).unwrap(), 2);
1790         assert!(m.insert(5, 3).is_none());
1791         assert_eq!(*m.get(&1).unwrap(), 2);
1792         assert_eq!(*m.get(&5).unwrap(), 3);
1793         assert!(m.insert(9, 4).is_none());
1794         assert_eq!(*m.get(&1).unwrap(), 2);
1795         assert_eq!(*m.get(&5).unwrap(), 3);
1796         assert_eq!(*m.get(&9).unwrap(), 4);
1797         assert!(m.remove(&1).is_some());
1798         assert_eq!(*m.get(&9).unwrap(), 4);
1799         assert_eq!(*m.get(&5).unwrap(), 3);
1800     }
1801
1802     #[test]
1803     fn test_is_empty() {
1804         let mut m = HashMap::with_capacity(4);
1805         assert!(m.insert(1i, 2i).is_none());
1806         assert!(!m.is_empty());
1807         assert!(m.remove(&1).is_some());
1808         assert!(m.is_empty());
1809     }
1810
1811     #[test]
1812     fn test_pop() {
1813         let mut m = HashMap::new();
1814         m.insert(1i, 2i);
1815         assert_eq!(m.remove(&1), Some(2));
1816         assert_eq!(m.remove(&1), None);
1817     }
1818
1819     #[test]
1820     fn test_iterate() {
1821         let mut m = HashMap::with_capacity(4);
1822         for i in range(0u, 32) {
1823             assert!(m.insert(i, i*2).is_none());
1824         }
1825         assert_eq!(m.len(), 32);
1826
1827         let mut observed: u32 = 0;
1828
1829         for (k, v) in m.iter() {
1830             assert_eq!(*v, *k * 2);
1831             observed |= 1 << *k;
1832         }
1833         assert_eq!(observed, 0xFFFF_FFFF);
1834     }
1835
1836     #[test]
1837     fn test_keys() {
1838         let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
1839         let map = vec.into_iter().collect::<HashMap<int, char>>();
1840         let keys = map.keys().map(|&k| k).collect::<Vec<int>>();
1841         assert_eq!(keys.len(), 3);
1842         assert!(keys.contains(&1));
1843         assert!(keys.contains(&2));
1844         assert!(keys.contains(&3));
1845     }
1846
1847     #[test]
1848     fn test_values() {
1849         let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
1850         let map = vec.into_iter().collect::<HashMap<int, char>>();
1851         let values = map.values().map(|&v| v).collect::<Vec<char>>();
1852         assert_eq!(values.len(), 3);
1853         assert!(values.contains(&'a'));
1854         assert!(values.contains(&'b'));
1855         assert!(values.contains(&'c'));
1856     }
1857
1858     #[test]
1859     fn test_find() {
1860         let mut m = HashMap::new();
1861         assert!(m.get(&1i).is_none());
1862         m.insert(1i, 2i);
1863         match m.get(&1) {
1864             None => panic!(),
1865             Some(v) => assert_eq!(*v, 2)
1866         }
1867     }
1868
1869     #[test]
1870     fn test_eq() {
1871         let mut m1 = HashMap::new();
1872         m1.insert(1i, 2i);
1873         m1.insert(2i, 3i);
1874         m1.insert(3i, 4i);
1875
1876         let mut m2 = HashMap::new();
1877         m2.insert(1i, 2i);
1878         m2.insert(2i, 3i);
1879
1880         assert!(m1 != m2);
1881
1882         m2.insert(3i, 4i);
1883
1884         assert_eq!(m1, m2);
1885     }
1886
1887     #[test]
1888     fn test_show() {
1889         let mut map: HashMap<int, int> = HashMap::new();
1890         let empty: HashMap<int, int> = HashMap::new();
1891
1892         map.insert(1i, 2i);
1893         map.insert(3i, 4i);
1894
1895         let map_str = format!("{:?}", map);
1896
1897         assert!(map_str == "HashMap {1i: 2i, 3i: 4i}" ||
1898                 map_str == "HashMap {3i: 4i, 1i: 2i}");
1899         assert_eq!(format!("{:?}", empty), "HashMap {}");
1900     }
1901
1902     #[test]
1903     fn test_expand() {
1904         let mut m = HashMap::new();
1905
1906         assert_eq!(m.len(), 0);
1907         assert!(m.is_empty());
1908
1909         let mut i = 0u;
1910         let old_cap = m.table.capacity();
1911         while old_cap == m.table.capacity() {
1912             m.insert(i, i);
1913             i += 1;
1914         }
1915
1916         assert_eq!(m.len(), i);
1917         assert!(!m.is_empty());
1918     }
1919
1920     #[test]
1921     fn test_behavior_resize_policy() {
1922         let mut m = HashMap::new();
1923
1924         assert_eq!(m.len(), 0);
1925         assert_eq!(m.table.capacity(), 0);
1926         assert!(m.is_empty());
1927
1928         m.insert(0, 0);
1929         m.remove(&0);
1930         assert!(m.is_empty());
1931         let initial_cap = m.table.capacity();
1932         m.reserve(initial_cap);
1933         let cap = m.table.capacity();
1934
1935         assert_eq!(cap, initial_cap * 2);
1936
1937         let mut i = 0u;
1938         for _ in range(0, cap * 3 / 4) {
1939             m.insert(i, i);
1940             i += 1;
1941         }
1942         // three quarters full
1943
1944         assert_eq!(m.len(), i);
1945         assert_eq!(m.table.capacity(), cap);
1946
1947         for _ in range(0, cap / 4) {
1948             m.insert(i, i);
1949             i += 1;
1950         }
1951         // half full
1952
1953         let new_cap = m.table.capacity();
1954         assert_eq!(new_cap, cap * 2);
1955
1956         for _ in range(0, cap / 2 - 1) {
1957             i -= 1;
1958             m.remove(&i);
1959             assert_eq!(m.table.capacity(), new_cap);
1960         }
1961         // A little more than one quarter full.
1962         m.shrink_to_fit();
1963         assert_eq!(m.table.capacity(), cap);
1964         // again, a little more than half full
1965         for _ in range(0, cap / 2 - 1) {
1966             i -= 1;
1967             m.remove(&i);
1968         }
1969         m.shrink_to_fit();
1970
1971         assert_eq!(m.len(), i);
1972         assert!(!m.is_empty());
1973         assert_eq!(m.table.capacity(), initial_cap);
1974     }
1975
1976     #[test]
1977     fn test_reserve_shrink_to_fit() {
1978         let mut m = HashMap::new();
1979         m.insert(0u, 0u);
1980         m.remove(&0);
1981         assert!(m.capacity() >= m.len());
1982         for i in range(0, 128) {
1983             m.insert(i, i);
1984         }
1985         m.reserve(256);
1986
1987         let usable_cap = m.capacity();
1988         for i in range(128, 128+256) {
1989             m.insert(i, i);
1990             assert_eq!(m.capacity(), usable_cap);
1991         }
1992
1993         for i in range(100, 128+256) {
1994             assert_eq!(m.remove(&i), Some(i));
1995         }
1996         m.shrink_to_fit();
1997
1998         assert_eq!(m.len(), 100);
1999         assert!(!m.is_empty());
2000         assert!(m.capacity() >= m.len());
2001
2002         for i in range(0, 100) {
2003             assert_eq!(m.remove(&i), Some(i));
2004         }
2005         m.shrink_to_fit();
2006         m.insert(0, 0);
2007
2008         assert_eq!(m.len(), 1);
2009         assert!(m.capacity() >= m.len());
2010         assert_eq!(m.remove(&0), Some(0));
2011     }
2012
2013     #[test]
2014     fn test_find_equiv() {
2015         let mut m = HashMap::new();
2016
2017         let (foo, bar, baz) = (1i,2i,3i);
2018         m.insert("foo".to_string(), foo);
2019         m.insert("bar".to_string(), bar);
2020         m.insert("baz".to_string(), baz);
2021
2022
2023         assert_eq!(m.get("foo"), Some(&foo));
2024         assert_eq!(m.get("bar"), Some(&bar));
2025         assert_eq!(m.get("baz"), Some(&baz));
2026
2027         assert_eq!(m.get("qux"), None);
2028     }
2029
2030     #[test]
2031     fn test_from_iter() {
2032         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2033
2034         let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2035
2036         for &(k, v) in xs.iter() {
2037             assert_eq!(map.get(&k), Some(&v));
2038         }
2039     }
2040
2041     #[test]
2042     fn test_size_hint() {
2043         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2044
2045         let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2046
2047         let mut iter = map.iter();
2048
2049         for _ in iter.by_ref().take(3) {}
2050
2051         assert_eq!(iter.size_hint(), (3, Some(3)));
2052     }
2053
2054     #[test]
2055     fn test_mut_size_hint() {
2056         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2057
2058         let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2059
2060         let mut iter = map.iter_mut();
2061
2062         for _ in iter.by_ref().take(3) {}
2063
2064         assert_eq!(iter.size_hint(), (3, Some(3)));
2065     }
2066
2067     #[test]
2068     fn test_index() {
2069         let mut map: HashMap<int, int> = HashMap::new();
2070
2071         map.insert(1, 2);
2072         map.insert(2, 1);
2073         map.insert(3, 4);
2074
2075         assert_eq!(map[2], 1);
2076     }
2077
2078     #[test]
2079     #[should_fail]
2080     fn test_index_nonexistent() {
2081         let mut map: HashMap<int, int> = HashMap::new();
2082
2083         map.insert(1, 2);
2084         map.insert(2, 1);
2085         map.insert(3, 4);
2086
2087         map[4];
2088     }
2089
2090     #[test]
2091     fn test_entry(){
2092         let xs = [(1i, 10i), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2093
2094         let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2095
2096         // Existing key (insert)
2097         match map.entry(1) {
2098             Vacant(_) => unreachable!(),
2099             Occupied(mut view) => {
2100                 assert_eq!(view.get(), &10);
2101                 assert_eq!(view.insert(100), 10);
2102             }
2103         }
2104         assert_eq!(map.get(&1).unwrap(), &100);
2105         assert_eq!(map.len(), 6);
2106
2107
2108         // Existing key (update)
2109         match map.entry(2) {
2110             Vacant(_) => unreachable!(),
2111             Occupied(mut view) => {
2112                 let v = view.get_mut();
2113                 let new_v = (*v) * 10;
2114                 *v = new_v;
2115             }
2116         }
2117         assert_eq!(map.get(&2).unwrap(), &200);
2118         assert_eq!(map.len(), 6);
2119
2120         // Existing key (take)
2121         match map.entry(3) {
2122             Vacant(_) => unreachable!(),
2123             Occupied(view) => {
2124                 assert_eq!(view.remove(), 30);
2125             }
2126         }
2127         assert_eq!(map.get(&3), None);
2128         assert_eq!(map.len(), 5);
2129
2130
2131         // Inexistent key (insert)
2132         match map.entry(10) {
2133             Occupied(_) => unreachable!(),
2134             Vacant(view) => {
2135                 assert_eq!(*view.insert(1000), 1000);
2136             }
2137         }
2138         assert_eq!(map.get(&10).unwrap(), &1000);
2139         assert_eq!(map.len(), 6);
2140     }
2141
2142     #[test]
2143     fn test_entry_take_doesnt_corrupt() {
2144         // Test for #19292
2145         fn check(m: &HashMap<int, ()>) {
2146             for k in m.keys() {
2147                 assert!(m.contains_key(k),
2148                         "{} is in keys() but not in the map?", k);
2149             }
2150         }
2151
2152         let mut m = HashMap::new();
2153         let mut rng = weak_rng();
2154
2155         // Populate the map with some items.
2156         for _ in range(0u, 50) {
2157             let x = rng.gen_range(-10, 10);
2158             m.insert(x, ());
2159         }
2160
2161         for i in range(0u, 1000) {
2162             let x = rng.gen_range(-10, 10);
2163             match m.entry(x) {
2164                 Vacant(_) => {},
2165                 Occupied(e) => {
2166                     println!("{}: remove {}", i, x);
2167                     e.remove();
2168                 },
2169             }
2170
2171             check(&m);
2172         }
2173     }
2174 }