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.
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.
11 // ignore-lexer-test FIXME #15883
14 use self::SearchResult::*;
15 use self::VacantEntryState::*;
19 use cmp::{max, Eq, PartialEq};
21 use fmt::{self, Debug};
22 use hash::{Hash, SipHasher};
23 use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map};
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};
42 use super::table::BucketState::{
46 use super::state::HashState;
48 const INITIAL_LOG2_CAP: usize = 5;
49 #[unstable(feature = "std_misc")]
50 pub const INITIAL_CAPACITY: usize = 1 << INITIAL_LOG2_CAP; // 2^5
52 /// The default behavior of HashMap implements a load factor of 90.9%.
53 /// This behavior is characterized by the following condition:
55 /// - if size > 0.909 * capacity: grow the map
57 struct DefaultResizePolicy;
59 impl DefaultResizePolicy {
60 fn new() -> DefaultResizePolicy {
65 fn min_capacity(&self, usable_size: usize) -> usize {
66 // Here, we are rephrasing the logic by specifying the lower limit
69 // - if `cap < size * 1.1`: grow the map
73 /// An inverse of `min_capacity`, approximately.
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
83 // This doesn't have to be checked for overflow since allocation size
84 // in bytes will overflow earlier than multiplication by 10.
90 fn test_resize_policy() {
91 let rp = DefaultResizePolicy;
93 assert!(rp.min_capacity(rp.usable_capacity(n)) <= n);
94 assert!(rp.usable_capacity(rp.min_capacity(n)) <= n);
98 // The main performance trick in this hashmap is called Robin Hood Hashing.
99 // It gains its excellent performance from one essential operation:
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.
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
109 // > Why a load factor of approximately 90%?
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.
121 // > Wait, what? Where did you get 1-α^k from?
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.
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.
137 // ## Future Improvements (FIXME!)
139 // Allow the load factor to be changed dynamically and/or at initialization.
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.
145 // ## Future Optimizations (FIXME!)
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.
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).
161 // Shrinking the table could simply reallocate in place after moving buckets
162 // to the first half.
164 // The growth algorithm (fragment of the Proof of Correctness)
165 // --------------------
167 // The growth algorithm is basically a fast path of the naive reinsertion-
168 // during-resize algorithm. Other paths should never be taken.
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.
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:
194 // [yy_xxx_xxxx_xxx|xx_yyy_yyyy_yyy]
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
202 // Theorem: A linear robin hood reinsertion from the first ideal element
203 // produces identical results to a linear naive reinsertion from the same
206 // FIXME(Gankro, pczarn): review the proof and put it all in a separate README.md
208 /// A hash map implementation which uses linear probing with Robin
209 /// Hood bucket stealing.
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.
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)]`.
220 /// It is a logic error for a key to be modified in such a way that the key's
221 /// hash, as determined by the `Hash` trait, or its equality, as determined by
222 /// the `Eq` trait, changes while it is in the map. This is normally only
223 /// possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
225 /// Relevant papers/articles:
227 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
228 /// 2. Emmanuel Goossaert. ["Robin Hood
229 /// hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
230 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
231 /// deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
236 /// use std::collections::HashMap;
238 /// // type inference lets us omit an explicit type signature (which
239 /// // would be `HashMap<&str, &str>` in this example).
240 /// let mut book_reviews = HashMap::new();
242 /// // review some books.
243 /// book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book.");
244 /// book_reviews.insert("Grimms' Fairy Tales", "Masterpiece.");
245 /// book_reviews.insert("Pride and Prejudice", "Very enjoyable.");
246 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
248 /// // check for a specific one.
249 /// if !book_reviews.contains_key(&("Les Misérables")) {
250 /// println!("We've got {} reviews, but Les Misérables ain't one.",
251 /// book_reviews.len());
254 /// // oops, this review has a lot of spelling mistakes, let's delete it.
255 /// book_reviews.remove(&("The Adventures of Sherlock Holmes"));
257 /// // look up the values associated with some keys.
258 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
259 /// for book in to_find.iter() {
260 /// match book_reviews.get(book) {
261 /// Some(review) => println!("{}: {}", *book, *review),
262 /// None => println!("{} is unreviewed.", *book)
266 /// // iterate over everything.
267 /// for (book, review) in book_reviews.iter() {
268 /// println!("{}: \"{}\"", *book, *review);
272 /// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
273 /// We must also derive `PartialEq`.
276 /// use std::collections::HashMap;
278 /// #[derive(Hash, Eq, PartialEq, Debug)]
285 /// /// Create a new Viking.
286 /// fn new(name: &str, country: &str) -> Viking {
287 /// Viking { name: name.to_string(), country: country.to_string() }
291 /// // Use a HashMap to store the vikings' health points.
292 /// let mut vikings = HashMap::new();
294 /// vikings.insert(Viking::new("Einar", "Norway"), 25);
295 /// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
296 /// vikings.insert(Viking::new("Harald", "Iceland"), 12);
298 /// // Use derived implementation to print the status of the vikings.
299 /// for (viking, health) in vikings.iter() {
300 /// println!("{:?} has {} hp", viking, health);
304 #[stable(feature = "rust1", since = "1.0.0")]
305 pub struct HashMap<K, V, S = RandomState> {
306 // All hashes are keyed on these values, to prevent hash collision attacks.
309 table: RawTable<K, V>,
311 resize_policy: DefaultResizePolicy,
314 /// Search for a pre-hashed key.
315 fn search_hashed<K, V, M, F>(table: M,
318 -> SearchResult<K, V, M> where
319 M: Deref<Target=RawTable<K, V>>,
320 F: FnMut(&K) -> bool,
322 // This is the only function where capacity can be zero. To avoid
323 // undefined behaviour when Bucket::new gets the raw bucket in this
324 // case, immediately return the appropriate search result.
325 if table.capacity() == 0 {
326 return TableRef(table);
329 let size = table.size();
330 let mut probe = Bucket::new(table, hash);
331 let ib = probe.index();
333 while probe.index() != ib + size {
334 let full = match probe.peek() {
335 Empty(b) => return TableRef(b.into_table()), // hit an empty bucket
339 if full.distance() + ib < full.index() {
340 // We can finish the search early if we hit any bucket
341 // with a lower distance to initial bucket than we've probed.
342 return TableRef(full.into_table());
345 // If the hash doesn't match, it can't be this one..
346 if hash == full.hash() {
347 // If the key doesn't match, it can't be this one..
348 if is_match(full.read().0) {
349 return FoundExisting(full);
356 TableRef(probe.into_table())
359 fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
360 let (empty, retkey, retval) = starting_bucket.take();
361 let mut gap = match empty.gap_peek() {
363 None => return (retkey, retval)
366 while gap.full().distance() != 0 {
367 gap = match gap.shift() {
373 // Now we've done all our shifting. Return the value we grabbed earlier.
377 /// Perform robin hood bucket stealing at the given `bucket`. You must
378 /// also pass the position of that bucket's initial bucket so we don't have
379 /// to recalculate it.
381 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
382 fn robin_hood<'a, K: 'a, V: 'a>(mut bucket: FullBucketMut<'a, K, V>,
388 let starting_index = bucket.index();
390 let table = bucket.table(); // FIXME "lifetime too short".
393 // There can be at most `size - dib` buckets to displace, because
394 // in the worst case, there are `size` elements and we already are
395 // `distance` buckets away from the initial one.
396 let idx_end = starting_index + size - bucket.distance();
399 let (old_hash, old_key, old_val) = bucket.replace(hash, k, v);
401 let probe = bucket.next();
402 assert!(probe.index() != idx_end);
404 let full_bucket = match probe.peek() {
407 let b = bucket.put(old_hash, old_key, old_val);
408 // Now that it's stolen, just read the value's pointer
409 // right out of the table!
410 return Bucket::at_index(b.into_table(), starting_index)
416 Full(bucket) => bucket
419 let probe_ib = full_bucket.index() - full_bucket.distance();
421 bucket = full_bucket;
423 // Robin hood! Steal the spot.
435 /// A result that works like Option<FullBucket<..>> but preserves
436 /// the reference that grants us access to the table in any case.
437 enum SearchResult<K, V, M> {
438 // This is an entry that holds the given key:
439 FoundExisting(FullBucket<K, V, M>),
441 // There was no such entry. The reference is given back:
445 impl<K, V, M> SearchResult<K, V, M> {
446 fn into_option(self) -> Option<FullBucket<K, V, M>> {
448 FoundExisting(bucket) => Some(bucket),
454 impl<K, V, S> HashMap<K, V, S>
455 where K: Eq + Hash, S: HashState
457 fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash {
458 table::make_hash(&self.hash_state, x)
461 /// Search for a key, yielding the index if it's found in the hashtable.
462 /// If you already have the hash for the key lying around, use
464 fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> Option<FullBucketImm<'a, K, V>>
465 where K: Borrow<Q>, Q: Eq + Hash
467 let hash = self.make_hash(q);
468 search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
472 fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> Option<FullBucketMut<'a, K, V>>
473 where K: Borrow<Q>, Q: Eq + Hash
475 let hash = self.make_hash(q);
476 search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
480 // The caller should ensure that invariants by Robin Hood Hashing hold.
481 fn insert_hashed_ordered(&mut self, hash: SafeHash, k: K, v: V) {
482 let cap = self.table.capacity();
483 let mut buckets = Bucket::new(&mut self.table, hash);
484 let ib = buckets.index();
486 while buckets.index() != ib + cap {
487 // We don't need to compare hashes for value swap.
488 // Not even DIBs for Robin Hood.
489 buckets = match buckets.peek() {
491 empty.put(hash, k, v);
494 Full(b) => b.into_bucket()
498 panic!("Internal HashMap error: Out of space.");
502 impl<K: Hash + Eq, V> HashMap<K, V, RandomState> {
503 /// Create an empty HashMap.
508 /// use std::collections::HashMap;
509 /// let mut map: HashMap<&str, int> = HashMap::new();
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn new() -> HashMap<K, V, RandomState> {
517 /// Creates an empty hash map with the given initial capacity.
522 /// use std::collections::HashMap;
523 /// let mut map: HashMap<&str, int> = HashMap::with_capacity(10);
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
528 HashMap::with_capacity_and_hash_state(capacity, Default::default())
532 impl<K, V, S> HashMap<K, V, S>
533 where K: Eq + Hash, S: HashState
535 /// Creates an empty hashmap which will use the given hasher to hash keys.
537 /// The creates map has the default initial capacity.
542 /// use std::collections::HashMap;
543 /// use std::collections::hash_map::RandomState;
545 /// let s = RandomState::new();
546 /// let mut map = HashMap::with_hash_state(s);
547 /// map.insert(1, 2);
550 #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
551 pub fn with_hash_state(hash_state: S) -> HashMap<K, V, S> {
553 hash_state: hash_state,
554 resize_policy: DefaultResizePolicy::new(),
555 table: RawTable::new(0),
559 /// Create an empty HashMap with space for at least `capacity`
560 /// elements, using `hasher` to hash the keys.
562 /// Warning: `hasher` is normally randomly generated, and
563 /// is designed to allow HashMaps to be resistant to attacks that
564 /// cause many collisions and very poor performance. Setting it
565 /// manually using this function can expose a DoS attack vector.
570 /// use std::collections::HashMap;
571 /// use std::collections::hash_map::RandomState;
573 /// let s = RandomState::new();
574 /// let mut map = HashMap::with_capacity_and_hash_state(10, s);
575 /// map.insert(1, 2);
578 #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
579 pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
580 -> HashMap<K, V, S> {
581 let resize_policy = DefaultResizePolicy::new();
582 let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
583 let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow");
584 assert!(internal_cap >= capacity, "capacity overflow");
586 hash_state: hash_state,
587 resize_policy: resize_policy,
588 table: RawTable::new(internal_cap),
592 /// Returns the number of elements the map can hold without reallocating.
597 /// use std::collections::HashMap;
598 /// let map: HashMap<int, int> = HashMap::with_capacity(100);
599 /// assert!(map.capacity() >= 100);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn capacity(&self) -> usize {
604 self.resize_policy.usable_capacity(self.table.capacity())
607 /// Reserves capacity for at least `additional` more elements to be inserted
608 /// in the `HashMap`. The collection may reserve more space to avoid
609 /// frequent reallocations.
613 /// Panics if the new allocation size overflows `usize`.
618 /// use std::collections::HashMap;
619 /// let mut map: HashMap<&str, int> = HashMap::new();
622 #[stable(feature = "rust1", since = "1.0.0")]
623 pub fn reserve(&mut self, additional: usize) {
624 let new_size = self.len().checked_add(additional).expect("capacity overflow");
625 let min_cap = self.resize_policy.min_capacity(new_size);
627 // An invalid value shouldn't make us run out of space. This includes
628 // an overflow check.
629 assert!(new_size <= min_cap);
631 if self.table.capacity() < min_cap {
632 let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY);
633 self.resize(new_capacity);
637 /// Resizes the internal vectors to a new capacity. It's your responsibility to:
638 /// 1) Make sure the new capacity is enough for all the elements, accounting
639 /// for the load factor.
640 /// 2) Ensure new_capacity is a power of two or zero.
641 fn resize(&mut self, new_capacity: usize) {
642 assert!(self.table.size() <= new_capacity);
643 assert!(new_capacity.is_power_of_two() || new_capacity == 0);
645 let mut old_table = replace(&mut self.table, RawTable::new(new_capacity));
646 let old_size = old_table.size();
648 if old_table.capacity() == 0 || old_table.size() == 0 {
653 // Specialization of the other branch.
654 let mut bucket = Bucket::first(&mut old_table);
656 // "So a few of the first shall be last: for many be called,
659 // We'll most likely encounter a few buckets at the beginning that
660 // have their initial buckets near the end of the table. They were
661 // placed at the beginning as the probe wrapped around the table
662 // during insertion. We must skip forward to a bucket that won't
663 // get reinserted too early and won't unfairly steal others spot.
664 // This eliminates the need for robin hood.
666 bucket = match bucket.peek() {
668 if full.distance() == 0 {
669 // This bucket occupies its ideal spot.
670 // It indicates the start of another "cluster".
671 bucket = full.into_bucket();
674 // Leaving this bucket in the last cluster for later.
678 // Encountered a hole between clusters.
685 // This is how the buckets might be laid out in memory:
686 // ($ marks an initialized bucket)
688 // |$$$_$$$$$$_$$$$$|
690 // But we've skipped the entire initial cluster of buckets
691 // and will continue iteration in this order:
694 // ^ wrap around once end is reached
697 // ^ exit once table.size == 0
699 bucket = match bucket.peek() {
701 let h = bucket.hash();
702 let (b, k, v) = bucket.take();
703 self.insert_hashed_ordered(h, k, v);
705 let t = b.table(); // FIXME "lifetime too short".
706 if t.size() == 0 { break }
710 Empty(b) => b.into_bucket()
715 assert_eq!(self.table.size(), old_size);
718 /// Shrinks the capacity of the map as much as possible. It will drop
719 /// down as much as possible while maintaining the internal rules
720 /// and possibly leaving some space in accordance with the resize policy.
725 /// use std::collections::HashMap;
727 /// let mut map: HashMap<int, int> = HashMap::with_capacity(100);
728 /// map.insert(1, 2);
729 /// map.insert(3, 4);
730 /// assert!(map.capacity() >= 100);
731 /// map.shrink_to_fit();
732 /// assert!(map.capacity() >= 2);
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn shrink_to_fit(&mut self) {
736 let min_capacity = self.resize_policy.min_capacity(self.len());
737 let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY);
739 // An invalid value shouldn't make us run out of space.
740 debug_assert!(self.len() <= min_capacity);
742 if self.table.capacity() != min_capacity {
743 let old_table = replace(&mut self.table, RawTable::new(min_capacity));
744 let old_size = old_table.size();
746 // Shrink the table. Naive algorithm for resizing:
747 for (h, k, v) in old_table.into_iter() {
748 self.insert_hashed_nocheck(h, k, v);
751 debug_assert_eq!(self.table.size(), old_size);
755 /// Insert a pre-hashed key-value pair, without first checking
756 /// that there's enough room in the buckets. Returns a reference to the
757 /// newly insert value.
759 /// If the key already exists, the hashtable will be returned untouched
760 /// and a reference to the existing element will be returned.
761 fn insert_hashed_nocheck(&mut self, hash: SafeHash, k: K, v: V) -> &mut V {
762 self.insert_or_replace_with(hash, k, v, |_, _, _| ())
765 fn insert_or_replace_with<'a, F>(&'a mut self,
769 mut found_existing: F)
771 F: FnMut(&mut K, &mut V, V),
773 // Worst case, we'll find one empty bucket among `size + 1` buckets.
774 let size = self.table.size();
775 let mut probe = Bucket::new(&mut self.table, hash);
776 let ib = probe.index();
779 let mut bucket = match probe.peek() {
782 return bucket.put(hash, k, v).into_mut_refs().1;
784 Full(bucket) => bucket
788 if bucket.hash() == hash {
790 if k == *bucket.read_mut().0 {
791 let (bucket_k, bucket_v) = bucket.into_mut_refs();
792 debug_assert!(k == *bucket_k);
793 // Key already exists. Get its reference.
794 found_existing(bucket_k, bucket_v, v);
799 let robin_ib = bucket.index() as int - bucket.distance() as int;
801 if (ib as int) < robin_ib {
802 // Found a luckier bucket than me. Better steal his spot.
803 return robin_hood(bucket, robin_ib as usize, hash, k, v);
806 probe = bucket.next();
807 assert!(probe.index() != ib + size + 1);
811 /// An iterator visiting all keys in arbitrary order.
812 /// Iterator element type is `&'a K`.
817 /// use std::collections::HashMap;
819 /// let mut map = HashMap::new();
820 /// map.insert("a", 1);
821 /// map.insert("b", 2);
822 /// map.insert("c", 3);
824 /// for key in map.keys() {
825 /// println!("{}", key);
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
830 fn first<A, B>((a, _): (A, B)) -> A { a }
831 let first: fn((&'a K,&'a V)) -> &'a K = first; // coerce to fn ptr
833 Keys { inner: self.iter().map(first) }
836 /// An iterator visiting all values in arbitrary order.
837 /// Iterator element type is `&'a V`.
842 /// use std::collections::HashMap;
844 /// let mut map = HashMap::new();
845 /// map.insert("a", 1);
846 /// map.insert("b", 2);
847 /// map.insert("c", 3);
849 /// for val in map.values() {
850 /// println!("{}", val);
853 #[stable(feature = "rust1", since = "1.0.0")]
854 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
855 fn second<A, B>((_, b): (A, B)) -> B { b }
856 let second: fn((&'a K,&'a V)) -> &'a V = second; // coerce to fn ptr
858 Values { inner: self.iter().map(second) }
861 /// An iterator visiting all key-value pairs in arbitrary order.
862 /// Iterator element type is `(&'a K, &'a V)`.
867 /// use std::collections::HashMap;
869 /// let mut map = HashMap::new();
870 /// map.insert("a", 1);
871 /// map.insert("b", 2);
872 /// map.insert("c", 3);
874 /// for (key, val) in map.iter() {
875 /// println!("key: {} val: {}", key, val);
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn iter(&self) -> Iter<K, V> {
880 Iter { inner: self.table.iter() }
883 /// An iterator visiting all key-value pairs in arbitrary order,
884 /// with mutable references to the values.
885 /// Iterator element type is `(&'a K, &'a mut V)`.
890 /// use std::collections::HashMap;
892 /// let mut map = HashMap::new();
893 /// map.insert("a", 1);
894 /// map.insert("b", 2);
895 /// map.insert("c", 3);
897 /// // Update all values
898 /// for (_, val) in map.iter_mut() {
902 /// for (key, val) in map.iter() {
903 /// println!("key: {} val: {}", key, val);
906 #[stable(feature = "rust1", since = "1.0.0")]
907 pub fn iter_mut(&mut self) -> IterMut<K, V> {
908 IterMut { inner: self.table.iter_mut() }
911 /// Creates a consuming iterator, that is, one that moves each key-value
912 /// pair out of the map in arbitrary order. The map cannot be used after
918 /// use std::collections::HashMap;
920 /// let mut map = HashMap::new();
921 /// map.insert("a", 1);
922 /// map.insert("b", 2);
923 /// map.insert("c", 3);
925 /// // Not possible with .iter()
926 /// let vec: Vec<(&str, int)> = map.into_iter().collect();
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn into_iter(self) -> IntoIter<K, V> {
930 fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
931 let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two;
934 inner: self.table.into_iter().map(last_two)
938 /// Gets the given key's corresponding entry in the map for in-place manipulation.
939 #[stable(feature = "rust1", since = "1.0.0")]
940 pub fn entry(&mut self, key: K) -> Entry<K, V> {
944 let hash = self.make_hash(&key);
945 search_entry_hashed(&mut self.table, hash, key)
948 /// Returns the number of elements in the map.
953 /// use std::collections::HashMap;
955 /// let mut a = HashMap::new();
956 /// assert_eq!(a.len(), 0);
957 /// a.insert(1, "a");
958 /// assert_eq!(a.len(), 1);
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn len(&self) -> usize { self.table.size() }
963 /// Returns true if the map contains no elements.
968 /// use std::collections::HashMap;
970 /// let mut a = HashMap::new();
971 /// assert!(a.is_empty());
972 /// a.insert(1, "a");
973 /// assert!(!a.is_empty());
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn is_empty(&self) -> bool { self.len() == 0 }
979 /// Clears the map, returning all key-value pairs as an iterator. Keeps the
980 /// allocated memory for reuse.
985 /// use std::collections::HashMap;
987 /// let mut a = HashMap::new();
988 /// a.insert(1, "a");
989 /// a.insert(2, "b");
991 /// for (k, v) in a.drain().take(1) {
992 /// assert!(k == 1 || k == 2);
993 /// assert!(v == "a" || v == "b");
996 /// assert!(a.is_empty());
999 #[unstable(feature = "std_misc",
1000 reason = "matches collection reform specification, waiting for dust to settle")]
1001 pub fn drain(&mut self) -> Drain<K, V> {
1002 fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
1003 let last_two: fn((SafeHash, K, V)) -> (K, V) = last_two; // coerce to fn pointer
1006 inner: self.table.drain().map(last_two),
1010 /// Clears the map, removing all key-value pairs. Keeps the allocated memory
1016 /// use std::collections::HashMap;
1018 /// let mut a = HashMap::new();
1019 /// a.insert(1, "a");
1021 /// assert!(a.is_empty());
1023 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub fn clear(&mut self) {
1029 /// Returns a reference to the value corresponding to the key.
1031 /// The key may be any borrowed form of the map's key type, but
1032 /// `Hash` and `Eq` on the borrowed form *must* match those for
1038 /// use std::collections::HashMap;
1040 /// let mut map = HashMap::new();
1041 /// map.insert(1, "a");
1042 /// assert_eq!(map.get(&1), Some(&"a"));
1043 /// assert_eq!(map.get(&2), None);
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
1047 where K: Borrow<Q>, Q: Hash + Eq
1049 self.search(k).map(|bucket| bucket.into_refs().1)
1052 /// Returns true if the map contains a value for the specified key.
1054 /// The key may be any borrowed form of the map's key type, but
1055 /// `Hash` and `Eq` on the borrowed form *must* match those for
1061 /// use std::collections::HashMap;
1063 /// let mut map = HashMap::new();
1064 /// map.insert(1, "a");
1065 /// assert_eq!(map.contains_key(&1), true);
1066 /// assert_eq!(map.contains_key(&2), false);
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
1070 where K: Borrow<Q>, Q: Hash + Eq
1072 self.search(k).is_some()
1075 /// Returns a mutable reference to the value corresponding to the key.
1077 /// The key may be any borrowed form of the map's key type, but
1078 /// `Hash` and `Eq` on the borrowed form *must* match those for
1084 /// use std::collections::HashMap;
1086 /// let mut map = HashMap::new();
1087 /// map.insert(1, "a");
1088 /// match map.get_mut(&1) {
1089 /// Some(x) => *x = "b",
1092 /// assert_eq!(map[1], "b");
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
1096 where K: Borrow<Q>, Q: Hash + Eq
1098 self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
1101 /// Inserts a key-value pair from the map. If the key already had a value
1102 /// present in the map, that value is returned. Otherwise, `None` is returned.
1107 /// use std::collections::HashMap;
1109 /// let mut map = HashMap::new();
1110 /// assert_eq!(map.insert(37, "a"), None);
1111 /// assert_eq!(map.is_empty(), false);
1113 /// map.insert(37, "b");
1114 /// assert_eq!(map.insert(37, "c"), Some("b"));
1115 /// assert_eq!(map[37], "c");
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 pub fn insert(&mut self, k: K, v: V) -> Option<V> {
1119 let hash = self.make_hash(&k);
1122 let mut retval = None;
1123 self.insert_or_replace_with(hash, k, v, |_, val_ref, val| {
1124 retval = Some(replace(val_ref, val));
1129 /// Removes a key from the map, returning the value at the key if the key
1130 /// was previously in the map.
1132 /// The key may be any borrowed form of the map's key type, but
1133 /// `Hash` and `Eq` on the borrowed form *must* match those for
1139 /// use std::collections::HashMap;
1141 /// let mut map = HashMap::new();
1142 /// map.insert(1, "a");
1143 /// assert_eq!(map.remove(&1), Some("a"));
1144 /// assert_eq!(map.remove(&1), None);
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
1148 where K: Borrow<Q>, Q: Hash + Eq
1150 if self.table.size() == 0 {
1154 self.search_mut(k).map(|bucket| pop_internal(bucket).1)
1158 fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHash, k: K)
1161 // Worst case, we'll find one empty bucket among `size + 1` buckets.
1162 let size = table.size();
1163 let mut probe = Bucket::new(table, hash);
1164 let ib = probe.index();
1167 let bucket = match probe.peek() {
1170 return Vacant(VacantEntry {
1173 elem: NoElem(bucket),
1176 Full(bucket) => bucket
1180 if bucket.hash() == hash {
1182 if k == *bucket.read().0 {
1183 return Occupied(OccupiedEntry{
1189 let robin_ib = bucket.index() as int - bucket.distance() as int;
1191 if (ib as int) < robin_ib {
1192 // Found a luckier bucket than me. Better steal his spot.
1193 return Vacant(VacantEntry {
1196 elem: NeqElem(bucket, robin_ib as usize),
1200 probe = bucket.next();
1201 assert!(probe.index() != ib + size + 1);
1205 impl<K, V, S> PartialEq for HashMap<K, V, S>
1206 where K: Eq + Hash, V: PartialEq, S: HashState
1208 fn eq(&self, other: &HashMap<K, V, S>) -> bool {
1209 if self.len() != other.len() { return false; }
1211 self.iter().all(|(key, value)|
1212 other.get(key).map_or(false, |v| *value == *v)
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl<K, V, S> Eq for HashMap<K, V, S>
1219 where K: Eq + Hash, V: Eq, S: HashState
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl<K, V, S> Debug for HashMap<K, V, S>
1224 where K: Eq + Hash + Debug, V: Debug, S: HashState
1226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1227 try!(write!(f, "{{"));
1229 for (i, (k, v)) in self.iter().enumerate() {
1230 if i != 0 { try!(write!(f, ", ")); }
1231 try!(write!(f, "{:?}: {:?}", *k, *v));
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<K, V, S> Default for HashMap<K, V, S>
1241 S: HashState + Default,
1243 fn default() -> HashMap<K, V, S> {
1244 HashMap::with_hash_state(Default::default())
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl<K, Q: ?Sized, V, S> Index<Q> for HashMap<K, V, S>
1250 where K: Eq + Hash + Borrow<Q>,
1257 fn index<'a>(&'a self, index: &Q) -> &'a V {
1258 self.get(index).expect("no entry found for key")
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<K, V, S, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S>
1264 where K: Eq + Hash + Borrow<Q>,
1269 fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
1270 self.get_mut(index).expect("no entry found for key")
1274 /// HashMap iterator.
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub struct Iter<'a, K: 'a, V: 'a> {
1277 inner: table::Iter<'a, K, V>
1280 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1281 impl<'a, K, V> Clone for Iter<'a, K, V> {
1282 fn clone(&self) -> Iter<'a, K, V> {
1284 inner: self.inner.clone()
1289 /// HashMap mutable values iterator.
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub struct IterMut<'a, K: 'a, V: 'a> {
1292 inner: table::IterMut<'a, K, V>
1295 /// HashMap move iterator.
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 pub struct IntoIter<K, V> {
1298 inner: iter::Map<table::IntoIter<K, V>, fn((SafeHash, K, V)) -> (K, V)>
1301 /// HashMap keys iterator.
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 pub struct Keys<'a, K: 'a, V: 'a> {
1304 inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
1307 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1308 impl<'a, K, V> Clone for Keys<'a, K, V> {
1309 fn clone(&self) -> Keys<'a, K, V> {
1311 inner: self.inner.clone()
1316 /// HashMap values iterator.
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 pub struct Values<'a, K: 'a, V: 'a> {
1319 inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
1322 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1323 impl<'a, K, V> Clone for Values<'a, K, V> {
1324 fn clone(&self) -> Values<'a, K, V> {
1326 inner: self.inner.clone()
1331 /// HashMap drain iterator.
1332 #[unstable(feature = "std_misc",
1333 reason = "matches collection reform specification, waiting for dust to settle")]
1334 pub struct Drain<'a, K: 'a, V: 'a> {
1335 inner: iter::Map<table::Drain<'a, K, V>, fn((SafeHash, K, V)) -> (K, V)>
1338 /// A view into a single occupied location in a HashMap.
1339 #[unstable(feature = "std_misc",
1340 reason = "precise API still being fleshed out")]
1341 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
1342 elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
1345 /// A view into a single empty location in a HashMap.
1346 #[unstable(feature = "std_misc",
1347 reason = "precise API still being fleshed out")]
1348 pub struct VacantEntry<'a, K: 'a, V: 'a> {
1351 elem: VacantEntryState<K, V, &'a mut RawTable<K, V>>,
1354 /// A view into a single location in a map, which may be vacant or occupied.
1355 #[unstable(feature = "std_misc",
1356 reason = "precise API still being fleshed out")]
1357 pub enum Entry<'a, K: 'a, V: 'a> {
1358 /// An occupied Entry.
1359 Occupied(OccupiedEntry<'a, K, V>),
1361 Vacant(VacantEntry<'a, K, V>),
1364 /// Possible states of a VacantEntry.
1365 enum VacantEntryState<K, V, M> {
1366 /// The index is occupied, but the key to insert has precedence,
1367 /// and will kick the current one out on insertion.
1368 NeqElem(FullBucket<K, V, M>, usize),
1369 /// The index is genuinely vacant.
1370 NoElem(EmptyBucket<K, V, M>),
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
1375 where K: Eq + Hash, S: HashState
1377 type Item = (&'a K, &'a V);
1378 type IntoIter = Iter<'a, K, V>;
1380 fn into_iter(self) -> Iter<'a, K, V> {
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
1387 where K: Eq + Hash, S: HashState
1389 type Item = (&'a K, &'a mut V);
1390 type IntoIter = IterMut<'a, K, V>;
1392 fn into_iter(mut self) -> IterMut<'a, K, V> {
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<K, V, S> IntoIterator for HashMap<K, V, S>
1399 where K: Eq + Hash, S: HashState
1402 type IntoIter = IntoIter<K, V>;
1404 fn into_iter(self) -> IntoIter<K, V> {
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1411 type Item = (&'a K, &'a V);
1413 #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1414 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1418 #[inline] fn len(&self) -> usize { self.inner.len() }
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1423 type Item = (&'a K, &'a mut V);
1425 #[inline] fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1426 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1430 #[inline] fn len(&self) -> usize { self.inner.len() }
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<K, V> Iterator for IntoIter<K, V> {
1437 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1438 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1442 #[inline] fn len(&self) -> usize { self.inner.len() }
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1449 #[inline] fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1450 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1454 #[inline] fn len(&self) -> usize { self.inner.len() }
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<'a, K, V> Iterator for Values<'a, K, V> {
1461 #[inline] fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1462 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1466 #[inline] fn len(&self) -> usize { self.inner.len() }
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<'a, K, V> Iterator for Drain<'a, K, V> {
1473 #[inline] fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1474 #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
1478 #[inline] fn len(&self) -> usize { self.inner.len() }
1481 #[unstable(feature = "std_misc",
1482 reason = "matches collection reform v2 specification, waiting for dust to settle")]
1483 impl<'a, K, V> Entry<'a, K, V> {
1484 /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant.
1485 pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
1487 Occupied(entry) => Ok(entry.into_mut()),
1488 Vacant(entry) => Err(entry),
1493 impl<'a, K, V> OccupiedEntry<'a, K, V> {
1494 /// Gets a reference to the value in the entry.
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 pub fn get(&self) -> &V {
1500 /// Gets a mutable reference to the value in the entry.
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 pub fn get_mut(&mut self) -> &mut V {
1503 self.elem.read_mut().1
1506 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1507 /// with a lifetime bound to the map itself
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub fn into_mut(self) -> &'a mut V {
1510 self.elem.into_mut_refs().1
1513 /// Sets the value of the entry, and returns the entry's old value
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 pub fn insert(&mut self, mut value: V) -> V {
1516 let old_value = self.get_mut();
1517 mem::swap(&mut value, old_value);
1521 /// Takes the value out of the entry, and returns it
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 pub fn remove(self) -> V {
1524 pop_internal(self.elem).1
1528 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
1529 /// Sets the value of the entry with the VacantEntry's key,
1530 /// and returns a mutable reference to it
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 pub fn insert(self, value: V) -> &'a mut V {
1534 NeqElem(bucket, ib) => {
1535 robin_hood(bucket, ib, self.hash, self.key, value)
1538 bucket.put(self.hash, self.key, value).into_mut_refs().1
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
1546 where K: Eq + Hash, S: HashState + Default
1548 fn from_iter<T: IntoIterator<Item=(K, V)>>(iterable: T) -> HashMap<K, V, S> {
1549 let iter = iterable.into_iter();
1550 let lower = iter.size_hint().0;
1551 let mut map = HashMap::with_capacity_and_hash_state(lower,
1552 Default::default());
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
1560 where K: Eq + Hash, S: HashState
1562 fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1563 for (k, v) in iter {
1570 /// `RandomState` is the default state for `HashMap` types.
1572 /// A particular instance `RandomState` will create the same instances of
1573 /// `Hasher`, but the hashers created by two different `RandomState`
1574 /// instances are unlikely to produce the same result for the same values.
1576 #[unstable(feature = "std_misc",
1577 reason = "hashing an hash maps may be altered")]
1578 pub struct RandomState {
1583 #[unstable(feature = "std_misc",
1584 reason = "hashing an hash maps may be altered")]
1586 /// Construct a new `RandomState` that is initialized with random keys.
1588 #[allow(deprecated)]
1589 pub fn new() -> RandomState {
1590 let mut r = rand::thread_rng();
1591 RandomState { k0: r.gen(), k1: r.gen() }
1595 #[unstable(feature = "std_misc",
1596 reason = "hashing an hash maps may be altered")]
1597 impl HashState for RandomState {
1598 type Hasher = SipHasher;
1599 fn hasher(&self) -> SipHasher {
1600 SipHasher::new_with_keys(self.k0, self.k1)
1604 #[unstable(feature = "std_misc",
1605 reason = "hashing an hash maps may be altered")]
1606 impl Default for RandomState {
1608 fn default() -> RandomState {
1618 use super::Entry::{Occupied, Vacant};
1619 use iter::{range_inclusive, range_step_inclusive, repeat};
1621 use rand::{weak_rng, Rng};
1624 fn test_create_capacity_zero() {
1625 let mut m = HashMap::with_capacity(0);
1627 assert!(m.insert(1, 1).is_none());
1629 assert!(m.contains_key(&1));
1630 assert!(!m.contains_key(&0));
1635 let mut m = HashMap::new();
1636 assert_eq!(m.len(), 0);
1637 assert!(m.insert(1, 2).is_none());
1638 assert_eq!(m.len(), 1);
1639 assert!(m.insert(2, 4).is_none());
1640 assert_eq!(m.len(), 2);
1641 assert_eq!(*m.get(&1).unwrap(), 2);
1642 assert_eq!(*m.get(&2).unwrap(), 4);
1645 thread_local! { static DROP_VECTOR: RefCell<Vec<int>> = RefCell::new(Vec::new()) }
1647 #[derive(Hash, PartialEq, Eq)]
1653 fn new(k: usize) -> Dropable {
1654 DROP_VECTOR.with(|slot| {
1655 slot.borrow_mut()[k] += 1;
1662 impl Drop for Dropable {
1663 fn drop(&mut self) {
1664 DROP_VECTOR.with(|slot| {
1665 slot.borrow_mut()[self.k] -= 1;
1670 impl Clone for Dropable {
1671 fn clone(&self) -> Dropable {
1672 Dropable::new(self.k)
1678 DROP_VECTOR.with(|slot| {
1679 *slot.borrow_mut() = repeat(0).take(200).collect();
1683 let mut m = HashMap::new();
1685 DROP_VECTOR.with(|v| {
1687 assert_eq!(v.borrow()[i], 0);
1692 let d1 = Dropable::new(i);
1693 let d2 = Dropable::new(i+100);
1697 DROP_VECTOR.with(|v| {
1699 assert_eq!(v.borrow()[i], 1);
1704 let k = Dropable::new(i);
1705 let v = m.remove(&k);
1707 assert!(v.is_some());
1709 DROP_VECTOR.with(|v| {
1710 assert_eq!(v.borrow()[i], 1);
1711 assert_eq!(v.borrow()[i+100], 1);
1715 DROP_VECTOR.with(|v| {
1717 assert_eq!(v.borrow()[i], 0);
1718 assert_eq!(v.borrow()[i+100], 0);
1722 assert_eq!(v.borrow()[i], 1);
1723 assert_eq!(v.borrow()[i+100], 1);
1728 DROP_VECTOR.with(|v| {
1730 assert_eq!(v.borrow()[i], 0);
1736 fn test_move_iter_drops() {
1737 DROP_VECTOR.with(|v| {
1738 *v.borrow_mut() = repeat(0).take(200).collect();
1742 let mut hm = HashMap::new();
1744 DROP_VECTOR.with(|v| {
1746 assert_eq!(v.borrow()[i], 0);
1751 let d1 = Dropable::new(i);
1752 let d2 = Dropable::new(i+100);
1756 DROP_VECTOR.with(|v| {
1758 assert_eq!(v.borrow()[i], 1);
1765 // By the way, ensure that cloning doesn't screw up the dropping.
1769 let mut half = hm.into_iter().take(50);
1771 DROP_VECTOR.with(|v| {
1773 assert_eq!(v.borrow()[i], 1);
1777 for _ in half.by_ref() {}
1779 DROP_VECTOR.with(|v| {
1780 let nk = (0..100).filter(|&i| {
1784 let nv = (0..100).filter(|&i| {
1785 v.borrow()[i+100] == 1
1793 DROP_VECTOR.with(|v| {
1795 assert_eq!(v.borrow()[i], 0);
1801 fn test_empty_pop() {
1802 let mut m: HashMap<int, bool> = HashMap::new();
1803 assert_eq!(m.remove(&0), None);
1807 fn test_lots_of_insertions() {
1808 let mut m = HashMap::new();
1810 // Try this a few times to make sure we never screw up the hashmap's
1813 assert!(m.is_empty());
1815 for i in range_inclusive(1, 1000) {
1816 assert!(m.insert(i, i).is_none());
1818 for j in range_inclusive(1, i) {
1820 assert_eq!(r, Some(&j));
1823 for j in range_inclusive(i+1, 1000) {
1825 assert_eq!(r, None);
1829 for i in range_inclusive(1001, 2000) {
1830 assert!(!m.contains_key(&i));
1834 for i in range_inclusive(1, 1000) {
1835 assert!(m.remove(&i).is_some());
1837 for j in range_inclusive(1, i) {
1838 assert!(!m.contains_key(&j));
1841 for j in range_inclusive(i+1, 1000) {
1842 assert!(m.contains_key(&j));
1846 for i in range_inclusive(1, 1000) {
1847 assert!(!m.contains_key(&i));
1850 for i in range_inclusive(1, 1000) {
1851 assert!(m.insert(i, i).is_none());
1855 for i in range_step_inclusive(1000, 1, -1) {
1856 assert!(m.remove(&i).is_some());
1858 for j in range_inclusive(i, 1000) {
1859 assert!(!m.contains_key(&j));
1862 for j in range_inclusive(1, i-1) {
1863 assert!(m.contains_key(&j));
1870 fn test_find_mut() {
1871 let mut m = HashMap::new();
1872 assert!(m.insert(1, 12).is_none());
1873 assert!(m.insert(2, 8).is_none());
1874 assert!(m.insert(5, 14).is_none());
1876 match m.get_mut(&5) {
1877 None => panic!(), Some(x) => *x = new
1879 assert_eq!(m.get(&5), Some(&new));
1883 fn test_insert_overwrite() {
1884 let mut m = HashMap::new();
1885 assert!(m.insert(1, 2).is_none());
1886 assert_eq!(*m.get(&1).unwrap(), 2);
1887 assert!(!m.insert(1, 3).is_none());
1888 assert_eq!(*m.get(&1).unwrap(), 3);
1892 fn test_insert_conflicts() {
1893 let mut m = HashMap::with_capacity(4);
1894 assert!(m.insert(1, 2).is_none());
1895 assert!(m.insert(5, 3).is_none());
1896 assert!(m.insert(9, 4).is_none());
1897 assert_eq!(*m.get(&9).unwrap(), 4);
1898 assert_eq!(*m.get(&5).unwrap(), 3);
1899 assert_eq!(*m.get(&1).unwrap(), 2);
1903 fn test_conflict_remove() {
1904 let mut m = HashMap::with_capacity(4);
1905 assert!(m.insert(1, 2).is_none());
1906 assert_eq!(*m.get(&1).unwrap(), 2);
1907 assert!(m.insert(5, 3).is_none());
1908 assert_eq!(*m.get(&1).unwrap(), 2);
1909 assert_eq!(*m.get(&5).unwrap(), 3);
1910 assert!(m.insert(9, 4).is_none());
1911 assert_eq!(*m.get(&1).unwrap(), 2);
1912 assert_eq!(*m.get(&5).unwrap(), 3);
1913 assert_eq!(*m.get(&9).unwrap(), 4);
1914 assert!(m.remove(&1).is_some());
1915 assert_eq!(*m.get(&9).unwrap(), 4);
1916 assert_eq!(*m.get(&5).unwrap(), 3);
1920 fn test_is_empty() {
1921 let mut m = HashMap::with_capacity(4);
1922 assert!(m.insert(1, 2).is_none());
1923 assert!(!m.is_empty());
1924 assert!(m.remove(&1).is_some());
1925 assert!(m.is_empty());
1930 let mut m = HashMap::new();
1932 assert_eq!(m.remove(&1), Some(2));
1933 assert_eq!(m.remove(&1), None);
1938 let mut m = HashMap::with_capacity(4);
1940 assert!(m.insert(i, i*2).is_none());
1942 assert_eq!(m.len(), 32);
1944 let mut observed: u32 = 0;
1947 assert_eq!(*v, *k * 2);
1948 observed |= 1 << *k;
1950 assert_eq!(observed, 0xFFFF_FFFF);
1955 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1956 let map: HashMap<_, _> = vec.into_iter().collect();
1957 let keys: Vec<_> = map.keys().cloned().collect();
1958 assert_eq!(keys.len(), 3);
1959 assert!(keys.contains(&1));
1960 assert!(keys.contains(&2));
1961 assert!(keys.contains(&3));
1966 let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
1967 let map: HashMap<_, _> = vec.into_iter().collect();
1968 let values: Vec<_> = map.values().cloned().collect();
1969 assert_eq!(values.len(), 3);
1970 assert!(values.contains(&'a'));
1971 assert!(values.contains(&'b'));
1972 assert!(values.contains(&'c'));
1977 let mut m = HashMap::new();
1978 assert!(m.get(&1).is_none());
1982 Some(v) => assert_eq!(*v, 2)
1988 let mut m1 = HashMap::new();
1993 let mut m2 = HashMap::new();
2006 let mut map = HashMap::new();
2007 let empty: HashMap<i32, i32> = HashMap::new();
2012 let map_str = format!("{:?}", map);
2014 assert!(map_str == "{1: 2, 3: 4}" ||
2015 map_str == "{3: 4, 1: 2}");
2016 assert_eq!(format!("{:?}", empty), "{}");
2021 let mut m = HashMap::new();
2023 assert_eq!(m.len(), 0);
2024 assert!(m.is_empty());
2027 let old_cap = m.table.capacity();
2028 while old_cap == m.table.capacity() {
2033 assert_eq!(m.len(), i);
2034 assert!(!m.is_empty());
2038 fn test_behavior_resize_policy() {
2039 let mut m = HashMap::new();
2041 assert_eq!(m.len(), 0);
2042 assert_eq!(m.table.capacity(), 0);
2043 assert!(m.is_empty());
2047 assert!(m.is_empty());
2048 let initial_cap = m.table.capacity();
2049 m.reserve(initial_cap);
2050 let cap = m.table.capacity();
2052 assert_eq!(cap, initial_cap * 2);
2055 for _ in 0..cap * 3 / 4 {
2059 // three quarters full
2061 assert_eq!(m.len(), i);
2062 assert_eq!(m.table.capacity(), cap);
2064 for _ in 0..cap / 4 {
2070 let new_cap = m.table.capacity();
2071 assert_eq!(new_cap, cap * 2);
2073 for _ in 0..cap / 2 - 1 {
2076 assert_eq!(m.table.capacity(), new_cap);
2078 // A little more than one quarter full.
2080 assert_eq!(m.table.capacity(), cap);
2081 // again, a little more than half full
2082 for _ in 0..cap / 2 - 1 {
2088 assert_eq!(m.len(), i);
2089 assert!(!m.is_empty());
2090 assert_eq!(m.table.capacity(), initial_cap);
2094 fn test_reserve_shrink_to_fit() {
2095 let mut m = HashMap::new();
2098 assert!(m.capacity() >= m.len());
2104 let usable_cap = m.capacity();
2105 for i in 128..(128 + 256) {
2107 assert_eq!(m.capacity(), usable_cap);
2110 for i in 100..(128 + 256) {
2111 assert_eq!(m.remove(&i), Some(i));
2115 assert_eq!(m.len(), 100);
2116 assert!(!m.is_empty());
2117 assert!(m.capacity() >= m.len());
2120 assert_eq!(m.remove(&i), Some(i));
2125 assert_eq!(m.len(), 1);
2126 assert!(m.capacity() >= m.len());
2127 assert_eq!(m.remove(&0), Some(0));
2131 fn test_from_iter() {
2132 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2134 let map: HashMap<_, _> = xs.iter().cloned().collect();
2136 for &(k, v) in &xs {
2137 assert_eq!(map.get(&k), Some(&v));
2142 fn test_size_hint() {
2143 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2145 let map: HashMap<_, _> = xs.iter().cloned().collect();
2147 let mut iter = map.iter();
2149 for _ in iter.by_ref().take(3) {}
2151 assert_eq!(iter.size_hint(), (3, Some(3)));
2155 fn test_iter_len() {
2156 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2158 let map: HashMap<_, _> = xs.iter().cloned().collect();
2160 let mut iter = map.iter();
2162 for _ in iter.by_ref().take(3) {}
2164 assert_eq!(iter.len(), 3);
2168 fn test_mut_size_hint() {
2169 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2171 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2173 let mut iter = map.iter_mut();
2175 for _ in iter.by_ref().take(3) {}
2177 assert_eq!(iter.size_hint(), (3, Some(3)));
2181 fn test_iter_mut_len() {
2182 let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2184 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2186 let mut iter = map.iter_mut();
2188 for _ in iter.by_ref().take(3) {}
2190 assert_eq!(iter.len(), 3);
2195 let mut map = HashMap::new();
2201 assert_eq!(map[2], 1);
2206 fn test_index_nonexistent() {
2207 let mut map = HashMap::new();
2218 let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
2220 let mut map: HashMap<_, _> = xs.iter().cloned().collect();
2222 // Existing key (insert)
2223 match map.entry(1) {
2224 Vacant(_) => unreachable!(),
2225 Occupied(mut view) => {
2226 assert_eq!(view.get(), &10);
2227 assert_eq!(view.insert(100), 10);
2230 assert_eq!(map.get(&1).unwrap(), &100);
2231 assert_eq!(map.len(), 6);
2234 // Existing key (update)
2235 match map.entry(2) {
2236 Vacant(_) => unreachable!(),
2237 Occupied(mut view) => {
2238 let v = view.get_mut();
2239 let new_v = (*v) * 10;
2243 assert_eq!(map.get(&2).unwrap(), &200);
2244 assert_eq!(map.len(), 6);
2246 // Existing key (take)
2247 match map.entry(3) {
2248 Vacant(_) => unreachable!(),
2250 assert_eq!(view.remove(), 30);
2253 assert_eq!(map.get(&3), None);
2254 assert_eq!(map.len(), 5);
2257 // Inexistent key (insert)
2258 match map.entry(10) {
2259 Occupied(_) => unreachable!(),
2261 assert_eq!(*view.insert(1000), 1000);
2264 assert_eq!(map.get(&10).unwrap(), &1000);
2265 assert_eq!(map.len(), 6);
2269 fn test_entry_take_doesnt_corrupt() {
2270 #![allow(deprecated)] //rand
2272 fn check(m: &HashMap<isize, ()>) {
2274 assert!(m.contains_key(k),
2275 "{} is in keys() but not in the map?", k);
2279 let mut m = HashMap::new();
2280 let mut rng = weak_rng();
2282 // Populate the map with some items.
2284 let x = rng.gen_range(-10, 10);
2289 let x = rng.gen_range(-10, 10);
2293 println!("{}: remove {}", i, x);