]> git.lizzy.rs Git - rust.git/blob - src/libstd/collections/hashmap.rs
Add a ton of ignore-lexer-test
[rust.git] / src / libstd / collections / hashmap.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 //! Unordered containers, implemented as hash-tables (`HashSet` and `HashMap` types)
14
15 use clone::Clone;
16 use cmp::{max, Eq, Equiv, PartialEq};
17 use collections::{Collection, Mutable, Set, MutableSet, Map, MutableMap};
18 use default::Default;
19 use fmt::Show;
20 use fmt;
21 use hash::{Hash, Hasher, RandomSipHasher};
22 use iter::{Iterator, FilterMap, Chain, Repeat, Zip, Extendable};
23 use iter::{range, range_inclusive, FromIterator};
24 use iter;
25 use mem::replace;
26 use num;
27 use option::{Some, None, Option};
28 use result::{Ok, Err};
29
30 mod table {
31     use clone::Clone;
32     use cmp;
33     use hash::{Hash, Hasher};
34     use iter::range_step_inclusive;
35     use iter::{Iterator, range};
36     use kinds::marker;
37     use mem::{min_align_of, size_of};
38     use mem::{overwrite, transmute};
39     use num::{CheckedMul, is_power_of_two};
40     use ops::Drop;
41     use option::{Some, None, Option};
42     use ptr::RawPtr;
43     use ptr::set_memory;
44     use ptr;
45     use rt::heap::{allocate, deallocate};
46
47     static EMPTY_BUCKET: u64 = 0u64;
48
49     /// The raw hashtable, providing safe-ish access to the unzipped and highly
50     /// optimized arrays of hashes, keys, and values.
51     ///
52     /// This design uses less memory and is a lot faster than the naive
53     /// `Vec<Option<u64, K, V>>`, because we don't pay for the overhead of an
54     /// option on every element, and we get a generally more cache-aware design.
55     ///
56     /// Key invariants of this structure:
57     ///
58     ///   - if hashes[i] == EMPTY_BUCKET, then keys[i] and vals[i] have
59     ///     'undefined' contents. Don't read from them. This invariant is
60     ///     enforced outside this module with the `EmptyIndex`, `FullIndex`,
61     ///     and `SafeHash` types.
62     ///
63     ///   - An `EmptyIndex` is only constructed for a bucket at an index with
64     ///     a hash of EMPTY_BUCKET.
65     ///
66     ///   - A `FullIndex` is only constructed for a bucket at an index with a
67     ///     non-EMPTY_BUCKET hash.
68     ///
69     ///   - A `SafeHash` is only constructed for non-`EMPTY_BUCKET` hash. We get
70     ///     around hashes of zero by changing them to 0x8000_0000_0000_0000,
71     ///     which will likely map to the same bucket, while not being confused
72     ///     with "empty".
73     ///
74     ///   - All three "arrays represented by pointers" are the same length:
75     ///     `capacity`. This is set at creation and never changes. The arrays
76     ///     are unzipped to save space (we don't have to pay for the padding
77     ///     between odd sized elements, such as in a map from u64 to u8), and
78     ///     be more cache aware (scanning through 8 hashes brings in 2 cache
79     ///     lines, since they're all right beside each other).
80     ///
81     /// You can kind of think of this module/data structure as a safe wrapper
82     /// around just the "table" part of the hashtable. It enforces some
83     /// invariants at the type level and employs some performance trickery,
84     /// but in general is just a tricked out `Vec<Option<u64, K, V>>`.
85     ///
86     /// FIXME(cgaebel):
87     ///
88     /// Feb 11, 2014: This hashtable was just implemented, and, hard as I tried,
89     /// isn't yet totally safe. There's a "known exploit" that you can create
90     /// multiple FullIndexes for a bucket, `take` one, and then still `take`
91     /// the other causing undefined behavior. Currently, there's no story
92     /// for how to protect against this statically. Therefore, there are asserts
93     /// on `take`, `get`, `get_mut`, and `put` which check the bucket state.
94     /// With time, and when we're confident this works correctly, they should
95     /// be removed. Also, the bounds check in `peek` is especially painful,
96     /// as that's called in the innermost loops of the hashtable and has the
97     /// potential to be a major performance drain. Remove this too.
98     ///
99     /// Or, better than remove, only enable these checks for debug builds.
100     /// There's currently no "debug-only" asserts in rust, so if you're reading
101     /// this and going "what? of course there are debug-only asserts!", then
102     /// please make this use them!
103     #[unsafe_no_drop_flag]
104     pub struct RawTable<K, V> {
105         capacity: uint,
106         size:     uint,
107         hashes:   *mut u64,
108         keys:     *mut K,
109         vals:     *mut V,
110     }
111
112     /// Represents an index into a `RawTable` with no key or value in it.
113     pub struct EmptyIndex {
114         idx:    int,
115         nocopy: marker::NoCopy,
116     }
117
118     /// Represents an index into a `RawTable` with a key, value, and hash
119     /// in it.
120     pub struct FullIndex {
121         idx:    int,
122         hash:   SafeHash,
123         nocopy: marker::NoCopy,
124     }
125
126     impl FullIndex {
127         /// Since we get the hash for free whenever we check the bucket state,
128         /// this function is provided for fast access, letting us avoid
129         /// redundant trips back to the hashtable.
130         #[inline(always)]
131         pub fn hash(&self) -> SafeHash { self.hash }
132
133         /// Same comment as with `hash`.
134         #[inline(always)]
135         pub fn raw_index(&self) -> uint { self.idx as uint }
136     }
137
138     /// Represents the state of a bucket: it can either have a key/value
139     /// pair (be full) or not (be empty). You cannot `take` empty buckets,
140     /// and you cannot `put` into full buckets.
141     pub enum BucketState {
142         Empty(EmptyIndex),
143         Full(FullIndex),
144     }
145
146     /// A hash that is not zero, since we use a hash of zero to represent empty
147     /// buckets.
148     #[deriving(PartialEq)]
149     pub struct SafeHash {
150         hash: u64,
151     }
152
153     impl SafeHash {
154         /// Peek at the hash value, which is guaranteed to be non-zero.
155         #[inline(always)]
156         pub fn inspect(&self) -> u64 { self.hash }
157     }
158
159     /// We need to remove hashes of 0. That's reserved for empty buckets.
160     /// This function wraps up `hash_keyed` to be the only way outside this
161     /// module to generate a SafeHash.
162     pub fn make_hash<T: Hash<S>, S, H: Hasher<S>>(hasher: &H, t: &T) -> SafeHash {
163         match hasher.hash(t) {
164             // This constant is exceedingly likely to hash to the same
165             // bucket, but it won't be counted as empty!
166             EMPTY_BUCKET => SafeHash { hash: 0x8000_0000_0000_0000 },
167             h            => SafeHash { hash: h },
168         }
169     }
170
171     fn round_up_to_next(unrounded: uint, target_alignment: uint) -> uint {
172         assert!(is_power_of_two(target_alignment));
173         (unrounded + target_alignment - 1) & !(target_alignment - 1)
174     }
175
176     #[test]
177     fn test_rounding() {
178         assert_eq!(round_up_to_next(0, 4), 0);
179         assert_eq!(round_up_to_next(1, 4), 4);
180         assert_eq!(round_up_to_next(2, 4), 4);
181         assert_eq!(round_up_to_next(3, 4), 4);
182         assert_eq!(round_up_to_next(4, 4), 4);
183         assert_eq!(round_up_to_next(5, 4), 8);
184     }
185
186     // Returns a tuple of (minimum required malloc alignment, hash_offset,
187     // key_offset, val_offset, array_size), from the start of a mallocated array.
188     fn calculate_offsets(
189         hash_size: uint, hash_align: uint,
190         keys_size: uint, keys_align: uint,
191         vals_size: uint, vals_align: uint) -> (uint, uint, uint, uint, uint) {
192
193         let hash_offset   = 0;
194         let end_of_hashes = hash_offset + hash_size;
195
196         let keys_offset   = round_up_to_next(end_of_hashes, keys_align);
197         let end_of_keys   = keys_offset + keys_size;
198
199         let vals_offset   = round_up_to_next(end_of_keys, vals_align);
200         let end_of_vals   = vals_offset + vals_size;
201
202         let min_align = cmp::max(hash_align, cmp::max(keys_align, vals_align));
203
204         (min_align, hash_offset, keys_offset, vals_offset, end_of_vals)
205     }
206
207     #[test]
208     fn test_offset_calculation() {
209         assert_eq!(calculate_offsets(128, 8, 15, 1, 4, 4 ), (8, 0, 128, 144, 148));
210         assert_eq!(calculate_offsets(3,   1, 2,  1, 1, 1 ), (1, 0, 3,   5,   6));
211         assert_eq!(calculate_offsets(6,   2, 12, 4, 24, 8), (8, 0, 8,   24,  48));
212     }
213
214     impl<K, V> RawTable<K, V> {
215
216         /// Does not initialize the buckets. The caller should ensure they,
217         /// at the very least, set every hash to EMPTY_BUCKET.
218         unsafe fn new_uninitialized(capacity: uint) -> RawTable<K, V> {
219             let hashes_size = capacity.checked_mul(&size_of::<u64>())
220                                       .expect("capacity overflow");
221             let keys_size = capacity.checked_mul(&size_of::< K >())
222                                     .expect("capacity overflow");
223             let vals_size = capacity.checked_mul(&size_of::< V >())
224                                     .expect("capacity overflow");
225
226             // Allocating hashmaps is a little tricky. We need to allocate three
227             // arrays, but since we know their sizes and alignments up front,
228             // we just allocate a single array, and then have the subarrays
229             // point into it.
230             //
231             // This is great in theory, but in practice getting the alignment
232             // right is a little subtle. Therefore, calculating offsets has been
233             // factored out into a different function.
234             let (malloc_alignment, hash_offset, keys_offset, vals_offset, size) =
235                 calculate_offsets(
236                     hashes_size, min_align_of::<u64>(),
237                     keys_size,   min_align_of::< K >(),
238                     vals_size,   min_align_of::< V >());
239
240             let buffer = allocate(size, malloc_alignment);
241
242             let hashes = buffer.offset(hash_offset as int) as *mut u64;
243             let keys   = buffer.offset(keys_offset as int) as *mut K;
244             let vals   = buffer.offset(vals_offset as int) as *mut V;
245
246             RawTable {
247                 capacity: capacity,
248                 size:     0,
249                 hashes:   hashes,
250                 keys:     keys,
251                 vals:     vals,
252             }
253         }
254
255         /// Creates a new raw table from a given capacity. All buckets are
256         /// initially empty.
257         #[allow(experimental)]
258         pub fn new(capacity: uint) -> RawTable<K, V> {
259             unsafe {
260                 let ret = RawTable::new_uninitialized(capacity);
261                 set_memory(ret.hashes, 0u8, capacity);
262                 ret
263             }
264         }
265
266         /// Reads a bucket at a given index, returning an enum indicating whether
267         /// there's anything there or not. You need to match on this enum to get
268         /// the appropriate types to pass on to most of the other functions in
269         /// this module.
270         pub fn peek(&self, index: uint) -> BucketState {
271             debug_assert!(index < self.capacity);
272
273             let idx  = index as int;
274             let hash = unsafe { *self.hashes.offset(idx) };
275
276             let nocopy = marker::NoCopy;
277
278             match hash {
279                 EMPTY_BUCKET =>
280                     Empty(EmptyIndex {
281                         idx:    idx,
282                         nocopy: nocopy
283                     }),
284                 full_hash =>
285                     Full(FullIndex {
286                         idx:    idx,
287                         hash:   SafeHash { hash: full_hash },
288                         nocopy: nocopy,
289                     })
290             }
291         }
292
293         /// Gets references to the key and value at a given index.
294         pub fn read<'a>(&'a self, index: &FullIndex) -> (&'a K, &'a V) {
295             let idx = index.idx;
296
297             unsafe {
298                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
299                 (&*self.keys.offset(idx), &*self.vals.offset(idx))
300             }
301         }
302
303         /// Gets references to the key and value at a given index, with the
304         /// value's reference being mutable.
305         pub fn read_mut<'a>(&'a mut self, index: &FullIndex) -> (&'a K, &'a mut V) {
306             let idx = index.idx;
307
308             unsafe {
309                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
310                 (&*self.keys.offset(idx), &mut *self.vals.offset(idx))
311             }
312         }
313
314         /// Read everything, mutably.
315         pub fn read_all_mut<'a>(&'a mut self, index: &FullIndex)
316             -> (&'a mut SafeHash, &'a mut K, &'a mut V) {
317             let idx = index.idx;
318
319             unsafe {
320                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
321                 (transmute(self.hashes.offset(idx)),
322                  &mut *self.keys.offset(idx), &mut *self.vals.offset(idx))
323             }
324         }
325
326         /// Puts a key and value pair, along with the key's hash, into a given
327         /// index in the hashtable. Note how the `EmptyIndex` is 'moved' into this
328         /// function, because that slot will no longer be empty when we return!
329         /// A FullIndex is returned for later use, pointing to the newly-filled
330         /// slot in the hashtable.
331         ///
332         /// Use `make_hash` to construct a `SafeHash` to pass to this function.
333         pub fn put(&mut self, index: EmptyIndex, hash: SafeHash, k: K, v: V) -> FullIndex {
334             let idx = index.idx;
335
336             unsafe {
337                 debug_assert_eq!(*self.hashes.offset(idx), EMPTY_BUCKET);
338                 *self.hashes.offset(idx) = hash.inspect();
339                 overwrite(&mut *self.keys.offset(idx), k);
340                 overwrite(&mut *self.vals.offset(idx), v);
341             }
342
343             self.size += 1;
344
345             FullIndex { idx: idx, hash: hash, nocopy: marker::NoCopy }
346         }
347
348         /// Removes a key and value from the hashtable.
349         ///
350         /// This works similarly to `put`, building an `EmptyIndex` out of the
351         /// taken FullIndex.
352         pub fn take(&mut self, index: FullIndex) -> (EmptyIndex, K, V) {
353             let idx  = index.idx;
354
355             unsafe {
356                 debug_assert!(*self.hashes.offset(idx) != EMPTY_BUCKET);
357
358                 *self.hashes.offset(idx) = EMPTY_BUCKET;
359
360                 // Drop the mutable constraint.
361                 let keys = self.keys as *const K;
362                 let vals = self.vals as *const V;
363
364                 let k = ptr::read(keys.offset(idx));
365                 let v = ptr::read(vals.offset(idx));
366
367                 self.size -= 1;
368
369                 (EmptyIndex { idx: idx, nocopy: marker::NoCopy }, k, v)
370             }
371         }
372
373         /// The hashtable's capacity, similar to a vector's.
374         pub fn capacity(&self) -> uint {
375             self.capacity
376         }
377
378         /// The number of elements ever `put` in the hashtable, minus the number
379         /// of elements ever `take`n.
380         pub fn size(&self) -> uint {
381             self.size
382         }
383
384         pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
385             Entries { table: self, idx: 0, elems_seen: 0 }
386         }
387
388         pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
389             MutEntries { table: self, idx: 0, elems_seen: 0 }
390         }
391
392         pub fn move_iter(self) -> MoveEntries<K, V> {
393             MoveEntries { table: self, idx: 0 }
394         }
395     }
396
397     // `read_all_mut` casts a `*u64` to a `*SafeHash`. Since we statically
398     // ensure that a `FullIndex` points to an index with a non-zero hash,
399     // and a `SafeHash` is just a `u64` with a different name, this is
400     // safe.
401     //
402     // This test ensures that a `SafeHash` really IS the same size as a
403     // `u64`. If you need to change the size of `SafeHash` (and
404     // consequently made this test fail), `read_all_mut` needs to be
405     // modified to no longer assume this.
406     #[test]
407     fn can_alias_safehash_as_u64() {
408         assert_eq!(size_of::<SafeHash>(), size_of::<u64>())
409     }
410
411     /// Iterator over shared references to entries in a table.
412     pub struct Entries<'a, K, V> {
413         table: &'a RawTable<K, V>,
414         idx: uint,
415         elems_seen: uint,
416     }
417
418     /// Iterator over mutable references to entries in a table.
419     pub struct MutEntries<'a, K, V> {
420         table: &'a mut RawTable<K, V>,
421         idx: uint,
422         elems_seen: uint,
423     }
424
425     /// Iterator over the entries in a table, consuming the table.
426     pub struct MoveEntries<K, V> {
427         table: RawTable<K, V>,
428         idx: uint
429     }
430
431     impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> {
432         fn next(&mut self) -> Option<(&'a K, &'a V)> {
433             while self.idx < self.table.capacity() {
434                 let i = self.idx;
435                 self.idx += 1;
436
437                 match self.table.peek(i) {
438                     Empty(_)  => {},
439                     Full(idx) => {
440                         self.elems_seen += 1;
441                         return Some(self.table.read(&idx));
442                     }
443                 }
444             }
445
446             None
447         }
448
449         fn size_hint(&self) -> (uint, Option<uint>) {
450             let size = self.table.size() - self.elems_seen;
451             (size, Some(size))
452         }
453     }
454
455     impl<'a, K, V> Iterator<(&'a K, &'a mut V)> for MutEntries<'a, K, V> {
456         fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
457             while self.idx < self.table.capacity() {
458                 let i = self.idx;
459                 self.idx += 1;
460
461                 match self.table.peek(i) {
462                     Empty(_)  => {},
463                     // the transmute here fixes:
464                     // error: lifetime of `self` is too short to guarantee its contents
465                     //        can be safely reborrowed
466                     Full(idx) => unsafe {
467                         self.elems_seen += 1;
468                         return Some(transmute(self.table.read_mut(&idx)));
469                     }
470                 }
471             }
472
473             None
474         }
475
476         fn size_hint(&self) -> (uint, Option<uint>) {
477             let size = self.table.size() - self.elems_seen;
478             (size, Some(size))
479         }
480     }
481
482     impl<K, V> Iterator<(SafeHash, K, V)> for MoveEntries<K, V> {
483         fn next(&mut self) -> Option<(SafeHash, K, V)> {
484             while self.idx < self.table.capacity() {
485                 let i = self.idx;
486                 self.idx += 1;
487
488                 match self.table.peek(i) {
489                     Empty(_) => {},
490                     Full(idx) => {
491                         let h = idx.hash();
492                         let (_, k, v) = self.table.take(idx);
493                         return Some((h, k, v));
494                     }
495                 }
496             }
497
498             None
499         }
500
501         fn size_hint(&self) -> (uint, Option<uint>) {
502             let size = self.table.size();
503             (size, Some(size))
504         }
505     }
506
507     impl<K: Clone, V: Clone> Clone for RawTable<K, V> {
508         fn clone(&self) -> RawTable<K, V> {
509             unsafe {
510                 let mut new_ht = RawTable::new_uninitialized(self.capacity());
511
512                 for i in range(0, self.capacity()) {
513                     match self.peek(i) {
514                         Empty(_)  => {
515                             *new_ht.hashes.offset(i as int) = EMPTY_BUCKET;
516                         },
517                         Full(idx) => {
518                             let hash = idx.hash().inspect();
519                             let (k, v) = self.read(&idx);
520                             *new_ht.hashes.offset(i as int) = hash;
521                             overwrite(&mut *new_ht.keys.offset(i as int), (*k).clone());
522                             overwrite(&mut *new_ht.vals.offset(i as int), (*v).clone());
523                         }
524                     }
525                 }
526
527                 new_ht.size = self.size();
528
529                 new_ht
530             }
531         }
532     }
533
534     #[unsafe_destructor]
535     impl<K, V> Drop for RawTable<K, V> {
536         fn drop(&mut self) {
537             // This is in reverse because we're likely to have partially taken
538             // some elements out with `.move_iter()` from the front.
539             for i in range_step_inclusive(self.capacity as int - 1, 0, -1) {
540                 // Check if the size is 0, so we don't do a useless scan when
541                 // dropping empty tables such as on resize.
542                 if self.size == 0 { break }
543
544                 match self.peek(i as uint) {
545                     Empty(_)  => {},
546                     Full(idx) => { self.take(idx); }
547                 }
548             }
549
550             assert_eq!(self.size, 0);
551
552             if self.hashes.is_not_null() {
553                 let hashes_size = self.capacity * size_of::<u64>();
554                 let keys_size = self.capacity * size_of::<K>();
555                 let vals_size = self.capacity * size_of::<V>();
556                 let (align, _, _, _, size) = calculate_offsets(hashes_size, min_align_of::<u64>(),
557                                                                keys_size, min_align_of::<K>(),
558                                                                vals_size, min_align_of::<V>());
559
560                 unsafe {
561                     deallocate(self.hashes as *mut u8, size, align);
562                     // Remember how everything was allocated out of one buffer
563                     // during initialization? We only need one call to free here.
564                 }
565
566                 self.hashes = RawPtr::null();
567             }
568         }
569     }
570 }
571
572 static INITIAL_LOG2_CAP: uint = 5;
573 static INITIAL_CAPACITY: uint = 1 << INITIAL_LOG2_CAP; // 2^5
574
575 /// The default behavior of HashMap implements a load factor of 90.9%.
576 /// This behavior is characterized by the following conditions:
577 ///
578 /// - if `size * 1.1 < cap < size * 4` then shouldn't resize
579 /// - if `cap < minimum_capacity * 2` then shouldn't shrink
580 #[deriving(Clone)]
581 struct DefaultResizePolicy {
582     /// Doubled minimal capacity. The capacity must never drop below
583     /// the minimum capacity. (The check happens before the capacity
584     /// is potentially halved.)
585     minimum_capacity2: uint
586 }
587
588 impl DefaultResizePolicy {
589     fn new(new_capacity: uint) -> DefaultResizePolicy {
590         DefaultResizePolicy {
591             minimum_capacity2: new_capacity << 1
592         }
593     }
594
595     #[inline]
596     fn capacity_range(&self, new_size: uint) -> (uint, uint) {
597         ((new_size * 11) / 10, max(new_size << 3, self.minimum_capacity2))
598     }
599
600     #[inline]
601     fn reserve(&mut self, new_capacity: uint) {
602         self.minimum_capacity2 = new_capacity << 1;
603     }
604 }
605
606 // The main performance trick in this hashmap is called Robin Hood Hashing.
607 // It gains its excellent performance from one key invariant:
608 //
609 //    If an insertion collides with an existing element, and that elements
610 //    "probe distance" (how far away the element is from its ideal location)
611 //    is higher than how far we've already probed, swap the elements.
612 //
613 // This massively lowers variance in probe distance, and allows us to get very
614 // high load factors with good performance. The 90% load factor I use is rather
615 // conservative.
616 //
617 // > Why a load factor of approximately 90%?
618 //
619 // In general, all the distances to initial buckets will converge on the mean.
620 // At a load factor of Î±, the odds of finding the target bucket after k
621 // probes is approximately 1-α^k. If we set this equal to 50% (since we converge
622 // on the mean) and set k=8 (64-byte cache line / 8-byte hash), Î±=0.92. I round
623 // this down to make the math easier on the CPU and avoid its FPU.
624 // Since on average we start the probing in the middle of a cache line, this
625 // strategy pulls in two cache lines of hashes on every lookup. I think that's
626 // pretty good, but if you want to trade off some space, it could go down to one
627 // cache line on average with an Î± of 0.84.
628 //
629 // > Wait, what? Where did you get 1-α^k from?
630 //
631 // On the first probe, your odds of a collision with an existing element is Î±.
632 // The odds of doing this twice in a row is approximately Î±^2. For three times,
633 // Î±^3, etc. Therefore, the odds of colliding k times is Î±^k. The odds of NOT
634 // colliding after k tries is 1-α^k.
635 //
636 // Future Improvements (FIXME!)
637 // ============================
638 //
639 // Allow the load factor to be changed dynamically and/or at initialization.
640 //
641 // Also, would it be possible for us to reuse storage when growing the
642 // underlying table? This is exactly the use case for 'realloc', and may
643 // be worth exploring.
644 //
645 // Future Optimizations (FIXME!)
646 // =============================
647 //
648 // The paper cited below mentions an implementation which keeps track of the
649 // distance-to-initial-bucket histogram. I'm suspicious of this approach because
650 // it requires maintaining an internal map. If this map were replaced with a
651 // hashmap, it would be faster, but now our data structure is self-referential
652 // and blows up. Also, this allows very good first guesses, but array accesses
653 // are no longer linear and in one direction, as we have now. There is also
654 // memory and cache pressure that this map would entail that would be very
655 // difficult to properly see in a microbenchmark.
656 //
657 // Another possible design choice that I made without any real reason is
658 // parameterizing the raw table over keys and values. Technically, all we need
659 // is the size and alignment of keys and values, and the code should be just as
660 // efficient (well, we might need one for power-of-two size and one for not...).
661 // This has the potential to reduce code bloat in rust executables, without
662 // really losing anything except 4 words (key size, key alignment, val size,
663 // val alignment) which can be passed in to every call of a `RawTable` function.
664 // This would definitely be an avenue worth exploring if people start complaining
665 // about the size of rust executables.
666 //
667 // There's also an "optimization" that has been omitted regarding how the
668 // hashtable allocates. The vector type has set the expectation that a hashtable
669 // which never has an element inserted should not allocate. I'm suspicious of
670 // implementing this for hashtables, because supporting it has no performance
671 // benefit over using an `Option<HashMap<K, V>>`, and is significantly more
672 // complicated.
673
674 /// A hash map implementation which uses linear probing with Robin
675 /// Hood bucket stealing.
676 ///
677 /// The hashes are all keyed by the task-local random number generator
678 /// on creation by default, this means the ordering of the keys is
679 /// randomized, but makes the tables more resistant to
680 /// denial-of-service attacks (Hash DoS). This behaviour can be
681 /// overridden with one of the constructors.
682 ///
683 /// It is required that the keys implement the `Eq` and `Hash` traits, although
684 /// this can frequently be achieved by using `#[deriving(Eq, Hash)]`.
685 ///
686 /// Relevant papers/articles:
687 ///
688 /// 1. Pedro Celis. ["Robin Hood Hashing"](https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf)
689 /// 2. Emmanuel Goossaert. ["Robin Hood
690 ///    hashing"](http://codecapsule.com/2013/11/11/robin-hood-hashing/)
691 /// 3. Emmanuel Goossaert. ["Robin Hood hashing: backward shift
692 ///    deletion"](http://codecapsule.com/2013/11/17/robin-hood-hashing-backward-shift-deletion/)
693 ///
694 /// # Example
695 ///
696 /// ```rust
697 /// use std::collections::HashMap;
698 ///
699 /// // type inference lets us omit an explicit type signature (which
700 /// // would be `HashMap<&str, &str>` in this example).
701 /// let mut book_reviews = HashMap::new();
702 ///
703 /// // review some books.
704 /// book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.");
705 /// book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.");
706 /// book_reviews.insert("Pride and Prejudice",               "Very enjoyable.");
707 /// book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");
708 ///
709 /// // check for a specific one.
710 /// if !book_reviews.contains_key(&("Les Misérables")) {
711 ///     println!("We've got {} reviews, but Les Misérables ain't one.",
712 ///              book_reviews.len());
713 /// }
714 ///
715 /// // oops, this review has a lot of spelling mistakes, let's delete it.
716 /// book_reviews.remove(&("The Adventures of Sherlock Holmes"));
717 ///
718 /// // look up the values associated with some keys.
719 /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
720 /// for book in to_find.iter() {
721 ///     match book_reviews.find(book) {
722 ///         Some(review) => println!("{}: {}", *book, *review),
723 ///         None => println!("{} is unreviewed.", *book)
724 ///     }
725 /// }
726 ///
727 /// // iterate over everything.
728 /// for (book, review) in book_reviews.iter() {
729 ///     println!("{}: \"{}\"", *book, *review);
730 /// }
731 /// ```
732 #[deriving(Clone)]
733 pub struct HashMap<K, V, H = RandomSipHasher> {
734     // All hashes are keyed on these values, to prevent hash collision attacks.
735     hasher: H,
736
737     table: table::RawTable<K, V>,
738
739     // We keep this at the end since it might as well have tail padding.
740     resize_policy: DefaultResizePolicy,
741 }
742
743 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
744     // Probe the `idx`th bucket for a given hash, returning the index of the
745     // target bucket.
746     //
747     // This exploits the power-of-two size of the hashtable. As long as this
748     // is always true, we can use a bitmask of cap-1 to do modular arithmetic.
749     //
750     // Prefer using this with increasing values of `idx` rather than repeatedly
751     // calling `probe_next`. This reduces data-dependencies between loops, which
752     // can help the optimizer, and certainly won't hurt it. `probe_next` is
753     // simply for convenience, and is no more efficient than `probe`.
754     fn probe(&self, hash: &table::SafeHash, idx: uint) -> uint {
755         let hash_mask = self.table.capacity() - 1;
756
757         // So I heard a rumor that unsigned overflow is safe in rust..
758         ((hash.inspect() as uint) + idx) & hash_mask
759     }
760
761     // Generate the next probe in a sequence. Prefer using 'probe' by itself,
762     // but this can sometimes be useful.
763     fn probe_next(&self, probe: uint) -> uint {
764         let hash_mask = self.table.capacity() - 1;
765         (probe + 1) & hash_mask
766     }
767
768     fn make_hash<X: Hash<S>>(&self, x: &X) -> table::SafeHash {
769         table::make_hash(&self.hasher, x)
770     }
771
772     /// Get the distance of the bucket at the given index that it lies
773     /// from its 'ideal' location.
774     ///
775     /// In the cited blog posts above, this is called the "distance to
776     /// initial bucket", or DIB.
777     fn bucket_distance(&self, index_of_elem: &table::FullIndex) -> uint {
778         // where the hash of the element that happens to reside at
779         // `index_of_elem` tried to place itself first.
780         let first_probe_index = self.probe(&index_of_elem.hash(), 0);
781
782         let raw_index = index_of_elem.raw_index();
783
784         if first_probe_index <= raw_index {
785              // probe just went forward
786             raw_index - first_probe_index
787         } else {
788             // probe wrapped around the hashtable
789             raw_index + (self.table.capacity() - first_probe_index)
790         }
791     }
792
793     /// Search for a pre-hashed key.
794     fn search_hashed_generic(&self, hash: &table::SafeHash, is_match: |&K| -> bool)
795         -> Option<table::FullIndex> {
796         for num_probes in range(0u, self.table.size()) {
797             let probe = self.probe(hash, num_probes);
798
799             let idx = match self.table.peek(probe) {
800                 table::Empty(_)  => return None, // hit an empty bucket
801                 table::Full(idx) => idx
802             };
803
804             // We can finish the search early if we hit any bucket
805             // with a lower distance to initial bucket than we've probed.
806             if self.bucket_distance(&idx) < num_probes { return None }
807
808             // If the hash doesn't match, it can't be this one..
809             if *hash != idx.hash() { continue }
810
811             let (k, _) = self.table.read(&idx);
812
813             // If the key doesn't match, it can't be this one..
814             if !is_match(k) { continue }
815
816             return Some(idx);
817         }
818
819         return None
820     }
821
822     fn search_hashed(&self, hash: &table::SafeHash, k: &K) -> Option<table::FullIndex> {
823         self.search_hashed_generic(hash, |k_| *k == *k_)
824     }
825
826     fn search_equiv<Q: Hash<S> + Equiv<K>>(&self, q: &Q) -> Option<table::FullIndex> {
827         self.search_hashed_generic(&self.make_hash(q), |k| q.equiv(k))
828     }
829
830     /// Search for a key, yielding the index if it's found in the hashtable.
831     /// If you already have the hash for the key lying around, use
832     /// search_hashed.
833     fn search(&self, k: &K) -> Option<table::FullIndex> {
834         self.search_hashed(&self.make_hash(k), k)
835     }
836
837     fn pop_internal(&mut self, starting_index: table::FullIndex) -> Option<V> {
838         let starting_probe = starting_index.raw_index();
839
840         let ending_probe = {
841             let mut probe = self.probe_next(starting_probe);
842             for _ in range(0u, self.table.size()) {
843                 match self.table.peek(probe) {
844                     table::Empty(_) => {}, // empty bucket. this is the end of our shifting.
845                     table::Full(idx) => {
846                         // Bucket that isn't us, which has a non-zero probe distance.
847                         // This isn't the ending index, so keep searching.
848                         if self.bucket_distance(&idx) != 0 {
849                             probe = self.probe_next(probe);
850                             continue;
851                         }
852
853                         // if we do have a bucket_distance of zero, we're at the end
854                         // of what we need to shift.
855                     }
856                 }
857                 break;
858             }
859
860             probe
861         };
862
863         let (_, _, retval) = self.table.take(starting_index);
864
865         let mut      probe = starting_probe;
866         let mut next_probe = self.probe_next(probe);
867
868         // backwards-shift all the elements after our newly-deleted one.
869         while next_probe != ending_probe {
870             match self.table.peek(next_probe) {
871                 table::Empty(_) => {
872                     // nothing to shift in. just empty it out.
873                     match self.table.peek(probe) {
874                         table::Empty(_) => {},
875                         table::Full(idx) => { self.table.take(idx); }
876                     }
877                 },
878                 table::Full(next_idx) => {
879                     // something to shift. move it over!
880                     let next_hash = next_idx.hash();
881                     let (_, next_key, next_val) = self.table.take(next_idx);
882                     match self.table.peek(probe) {
883                         table::Empty(idx) => {
884                             self.table.put(idx, next_hash, next_key, next_val);
885                         },
886                         table::Full(idx) => {
887                             let (emptyidx, _, _) = self.table.take(idx);
888                             self.table.put(emptyidx, next_hash, next_key, next_val);
889                         }
890                     }
891                 }
892             }
893
894             probe = next_probe;
895             next_probe = self.probe_next(next_probe);
896         }
897
898         // Done the backwards shift, but there's still an element left!
899         // Empty it out.
900         match self.table.peek(probe) {
901             table::Empty(_) => {},
902             table::Full(idx) => { self.table.take(idx); }
903         }
904
905         // Now we're done all our shifting. Return the value we grabbed
906         // earlier.
907         return Some(retval);
908     }
909
910     /// Like `pop`, but can operate on any type that is equivalent to a key.
911     #[experimental]
912     pub fn pop_equiv<Q:Hash<S> + Equiv<K>>(&mut self, k: &Q) -> Option<V> {
913         if self.table.size() == 0 {
914             return None
915         }
916
917         let potential_new_size = self.table.size() - 1;
918         self.make_some_room(potential_new_size);
919
920         let starting_index = match self.search_equiv(k) {
921             Some(idx) => idx,
922             None      => return None,
923         };
924
925         self.pop_internal(starting_index)
926     }
927 }
928
929 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Collection for HashMap<K, V, H> {
930     /// Return the number of elements in the map
931     fn len(&self) -> uint { self.table.size() }
932 }
933
934 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Mutable for HashMap<K, V, H> {
935     /// Clear the map, removing all key-value pairs. Keeps the allocated memory
936     /// for reuse.
937     fn clear(&mut self) {
938         // Prevent reallocations from happening from now on. Makes it possible
939         // for the map to be reused but has a downside: reserves permanently.
940         self.resize_policy.reserve(self.table.size());
941
942         for i in range(0, self.table.capacity()) {
943             match self.table.peek(i) {
944                 table::Empty(_)  => {},
945                 table::Full(idx) => { self.table.take(idx); }
946             }
947         }
948     }
949 }
950
951 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Map<K, V> for HashMap<K, V, H> {
952     fn find<'a>(&'a self, k: &K) -> Option<&'a V> {
953         self.search(k).map(|idx| {
954             let (_, v) = self.table.read(&idx);
955             v
956         })
957     }
958
959     fn contains_key(&self, k: &K) -> bool {
960         self.search(k).is_some()
961     }
962 }
963
964 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> MutableMap<K, V> for HashMap<K, V, H> {
965     fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> {
966         match self.search(k) {
967             None => None,
968             Some(idx) => {
969                 let (_, v) = self.table.read_mut(&idx);
970                 Some(v)
971             }
972         }
973     }
974
975     fn swap(&mut self, k: K, v: V) -> Option<V> {
976         let hash = self.make_hash(&k);
977         let potential_new_size = self.table.size() + 1;
978         self.make_some_room(potential_new_size);
979
980         for dib in range_inclusive(0u, self.table.size()) {
981             let probe = self.probe(&hash, dib);
982
983             let idx = match self.table.peek(probe) {
984                 table::Empty(idx) => {
985                     // Found a hole!
986                     self.table.put(idx, hash, k, v);
987                     return None;
988                 },
989                 table::Full(idx) => idx
990             };
991
992             if idx.hash() == hash {
993                 let (bucket_k, bucket_v) = self.table.read_mut(&idx);
994                 if k == *bucket_k {
995                     // Found an existing value.
996                     return Some(replace(bucket_v, v));
997                 }
998             }
999
1000             let probe_dib = self.bucket_distance(&idx);
1001
1002             if probe_dib < dib {
1003                 // Found a luckier bucket. This implies that the key does not
1004                 // already exist in the hashtable. Just do a robin hood
1005                 // insertion, then.
1006                 self.robin_hood(idx, probe_dib, hash, k, v);
1007                 return None;
1008             }
1009         }
1010
1011         // We really shouldn't be here.
1012         fail!("Internal HashMap error: Out of space.");
1013     }
1014
1015     fn pop(&mut self, k: &K) -> Option<V> {
1016         if self.table.size() == 0 {
1017             return None
1018         }
1019
1020         let potential_new_size = self.table.size() - 1;
1021         self.make_some_room(potential_new_size);
1022
1023         let starting_index = match self.search(k) {
1024             Some(idx) => idx,
1025             None      => return None,
1026         };
1027
1028         self.pop_internal(starting_index)
1029     }
1030
1031 }
1032
1033 impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> {
1034     /// Create an empty HashMap.
1035     #[inline]
1036     pub fn new() -> HashMap<K, V, RandomSipHasher> {
1037         HashMap::with_capacity(INITIAL_CAPACITY)
1038     }
1039
1040     /// Creates an empty hash map with the given initial capacity.
1041     #[inline]
1042     pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomSipHasher> {
1043         let hasher = RandomSipHasher::new();
1044         HashMap::with_capacity_and_hasher(capacity, hasher)
1045     }
1046 }
1047
1048 impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
1049     /// Creates an empty hashmap which will use the given hasher to hash keys.
1050     ///
1051     /// The creates map has the default initial capacity.
1052     #[inline]
1053     pub fn with_hasher(hasher: H) -> HashMap<K, V, H> {
1054         HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
1055     }
1056
1057     /// Create an empty HashMap with space for at least `capacity`
1058     /// elements, using `hasher` to hash the keys.
1059     ///
1060     /// Warning: `hasher` is normally randomly generated, and
1061     /// is designed to allow HashMaps to be resistant to attacks that
1062     /// cause many collisions and very poor performance. Setting it
1063     /// manually using this function can expose a DoS attack vector.
1064     #[inline]
1065     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashMap<K, V, H> {
1066         let cap = num::next_power_of_two(max(INITIAL_CAPACITY, capacity));
1067         HashMap {
1068             hasher:        hasher,
1069             resize_policy: DefaultResizePolicy::new(cap),
1070             table:         table::RawTable::new(cap),
1071         }
1072     }
1073
1074     /// The hashtable will never try to shrink below this size. You can use
1075     /// this function to reduce reallocations if your hashtable frequently
1076     /// grows and shrinks by large amounts.
1077     ///
1078     /// This function has no effect on the operational semantics of the
1079     /// hashtable, only on performance.
1080     pub fn reserve(&mut self, new_minimum_capacity: uint) {
1081         let cap = num::next_power_of_two(
1082             max(INITIAL_CAPACITY, new_minimum_capacity));
1083
1084         self.resize_policy.reserve(cap);
1085
1086         if self.table.capacity() < cap {
1087             self.resize(cap);
1088         }
1089     }
1090
1091     /// Resizes the internal vectors to a new capacity. It's your responsibility to:
1092     ///   1) Make sure the new capacity is enough for all the elements, accounting
1093     ///      for the load factor.
1094     ///   2) Ensure new_capacity is a power of two.
1095     fn resize(&mut self, new_capacity: uint) {
1096         assert!(self.table.size() <= new_capacity);
1097         assert!(num::is_power_of_two(new_capacity));
1098
1099         let old_table = replace(&mut self.table, table::RawTable::new(new_capacity));
1100         let old_size  = old_table.size();
1101
1102         for (h, k, v) in old_table.move_iter() {
1103             self.insert_hashed_nocheck(h, k, v);
1104         }
1105
1106         assert_eq!(self.table.size(), old_size);
1107     }
1108
1109     /// Performs any necessary resize operations, such that there's space for
1110     /// new_size elements.
1111     fn make_some_room(&mut self, new_size: uint) {
1112         let (grow_at, shrink_at) = self.resize_policy.capacity_range(new_size);
1113         let cap = self.table.capacity();
1114
1115         // An invalid value shouldn't make us run out of space.
1116         debug_assert!(grow_at >= new_size);
1117
1118         if cap <= grow_at {
1119             let new_capacity = cap << 1;
1120             self.resize(new_capacity);
1121         } else if shrink_at <= cap {
1122             let new_capacity = cap >> 1;
1123             self.resize(new_capacity);
1124         }
1125     }
1126
1127     /// Perform robin hood bucket stealing at the given 'index'. You must
1128     /// also pass that probe's "distance to initial bucket" so we don't have
1129     /// to recalculate it, as well as the total number of probes already done
1130     /// so we have some sort of upper bound on the number of probes to do.
1131     ///
1132     /// 'hash', 'k', and 'v' are the elements to robin hood into the hashtable.
1133     fn robin_hood(&mut self, mut index: table::FullIndex, mut dib_param: uint,
1134                   mut hash: table::SafeHash, mut k: K, mut v: V) {
1135         'outer: loop {
1136             let (old_hash, old_key, old_val) = {
1137                 let (old_hash_ref, old_key_ref, old_val_ref) =
1138                         self.table.read_all_mut(&index);
1139
1140                 let old_hash = replace(old_hash_ref, hash);
1141                 let old_key  = replace(old_key_ref,  k);
1142                 let old_val  = replace(old_val_ref,  v);
1143
1144                 (old_hash, old_key, old_val)
1145             };
1146
1147             let mut probe = self.probe_next(index.raw_index());
1148
1149             for dib in range(dib_param + 1, self.table.size()) {
1150                 let full_index = match self.table.peek(probe) {
1151                     table::Empty(idx) => {
1152                         // Finally. A hole!
1153                         self.table.put(idx, old_hash, old_key, old_val);
1154                         return;
1155                     },
1156                     table::Full(idx) => idx
1157                 };
1158
1159                 let probe_dib = self.bucket_distance(&full_index);
1160
1161                 // Robin hood! Steal the spot.
1162                 if probe_dib < dib {
1163                     index = full_index;
1164                     dib_param = probe_dib;
1165                     hash = old_hash;
1166                     k = old_key;
1167                     v = old_val;
1168                     continue 'outer;
1169                 }
1170
1171                 probe = self.probe_next(probe);
1172             }
1173
1174             fail!("HashMap fatal error: 100% load factor?");
1175         }
1176     }
1177
1178     /// Insert a pre-hashed key-value pair, without first checking
1179     /// that there's enough room in the buckets. Returns a reference to the
1180     /// newly insert value.
1181     ///
1182     /// If the key already exists, the hashtable will be returned untouched
1183     /// and a reference to the existing element will be returned.
1184     fn insert_hashed_nocheck<'a>(
1185         &'a mut self, hash: table::SafeHash, k: K, v: V) -> &'a mut V {
1186
1187         for dib in range_inclusive(0u, self.table.size()) {
1188             let probe = self.probe(&hash, dib);
1189
1190             let idx = match self.table.peek(probe) {
1191                 table::Empty(idx) => {
1192                     // Found a hole!
1193                     let fullidx  = self.table.put(idx, hash, k, v);
1194                     let (_, val) = self.table.read_mut(&fullidx);
1195                     return val;
1196                 },
1197                 table::Full(idx) => idx
1198             };
1199
1200             if idx.hash() == hash {
1201                 let (bucket_k, bucket_v) = self.table.read_mut(&idx);
1202                 // FIXME #12147 the conditional return confuses
1203                 // borrowck if we return bucket_v directly
1204                 let bv: *mut V = bucket_v;
1205                 if k == *bucket_k {
1206                     // Key already exists. Get its reference.
1207                     return unsafe {&mut *bv};
1208                 }
1209             }
1210
1211             let probe_dib = self.bucket_distance(&idx);
1212
1213             if  probe_dib < dib {
1214                 // Found a luckier bucket than me. Better steal his spot.
1215                 self.robin_hood(idx, probe_dib, hash, k, v);
1216
1217                 // Now that it's stolen, just read the value's pointer
1218                 // right out of the table!
1219                 match self.table.peek(probe) {
1220                     table::Empty(_)  => fail!("Just stole a spot, but now that spot's empty."),
1221                     table::Full(idx) => {
1222                         let (_, v) = self.table.read_mut(&idx);
1223                         return v;
1224                     }
1225                 }
1226             }
1227         }
1228
1229         // We really shouldn't be here.
1230         fail!("Internal HashMap error: Out of space.");
1231     }
1232
1233     /// Inserts an element which has already been hashed, returning a reference
1234     /// to that element inside the hashtable. This is more efficient that using
1235     /// `insert`, since the key will not be rehashed.
1236     fn insert_hashed<'a>(&'a mut self, hash: table::SafeHash, k: K, v: V) -> &'a mut V {
1237         let potential_new_size = self.table.size() + 1;
1238         self.make_some_room(potential_new_size);
1239         self.insert_hashed_nocheck(hash, k, v)
1240     }
1241
1242     /// Return the value corresponding to the key in the map, or insert
1243     /// and return the value if it doesn't exist.
1244     pub fn find_or_insert<'a>(&'a mut self, k: K, v: V) -> &'a mut V {
1245         self.find_with_or_insert_with(k, v, |_k, _v, _a| (), |_k, a| a)
1246     }
1247
1248     /// Return the value corresponding to the key in the map, or create,
1249     /// insert, and return a new value if it doesn't exist.
1250     pub fn find_or_insert_with<'a>(&'a mut self, k: K, f: |&K| -> V)
1251                                -> &'a mut V {
1252         self.find_with_or_insert_with(k, (), |_k, _v, _a| (), |k, _a| f(k))
1253     }
1254
1255     /// Insert a key-value pair into the map if the key is not already present.
1256     /// Otherwise, modify the existing value for the key.
1257     /// Returns the new or modified value for the key.
1258     pub fn insert_or_update_with<'a>(
1259                                  &'a mut self,
1260                                  k: K,
1261                                  v: V,
1262                                  f: |&K, &mut V|)
1263                                  -> &'a mut V {
1264         self.find_with_or_insert_with(k, v, |k, v, _a| f(k, v), |_k, a| a)
1265     }
1266
1267     /// Modify and return the value corresponding to the key in the map, or
1268     /// insert and return a new value if it doesn't exist.
1269     ///
1270     /// This method allows for all insertion behaviours of a hashmap;
1271     /// see methods like `insert`, `find_or_insert` and
1272     /// `insert_or_update_with` for less general and more friendly
1273     /// variations of this.
1274     ///
1275     /// # Example
1276     ///
1277     /// ```rust
1278     /// use std::collections::HashMap;
1279     ///
1280     /// // map some strings to vectors of strings
1281     /// let mut map = HashMap::new();
1282     /// map.insert("a key", vec!["value"]);
1283     /// map.insert("z key", vec!["value"]);
1284     ///
1285     /// let new = vec!["a key", "b key", "z key"];
1286     ///
1287     /// for k in new.move_iter() {
1288     ///     map.find_with_or_insert_with(
1289     ///         k, "new value",
1290     ///         // if the key does exist either prepend or append this
1291     ///         // new value based on the first letter of the key.
1292     ///         |key, already, new| {
1293     ///             if key.as_slice().starts_with("z") {
1294     ///                 already.unshift(new);
1295     ///             } else {
1296     ///                 already.push(new);
1297     ///             }
1298     ///         },
1299     ///         // if the key doesn't exist in the map yet, add it in
1300     ///         // the obvious way.
1301     ///         |_k, v| vec![v]);
1302     /// }
1303     ///
1304     /// assert_eq!(map.len(), 3);
1305     /// assert_eq!(map.get(&"a key"), &vec!["value", "new value"]);
1306     /// assert_eq!(map.get(&"b key"), &vec!["new value"]);
1307     /// assert_eq!(map.get(&"z key"), &vec!["new value", "value"]);
1308     /// ```
1309     pub fn find_with_or_insert_with<'a, A>(&'a mut self,
1310                                            k: K,
1311                                            a: A,
1312                                            found: |&K, &mut V, A|,
1313                                            not_found: |&K, A| -> V)
1314                                           -> &'a mut V {
1315         let hash = self.make_hash(&k);
1316         match self.search_hashed(&hash, &k) {
1317             None => {
1318                 let v = not_found(&k, a);
1319                 self.insert_hashed(hash, k, v)
1320             },
1321             Some(idx) => {
1322                 let (_, v_ref) = self.table.read_mut(&idx);
1323                 found(&k, v_ref, a);
1324                 v_ref
1325             }
1326         }
1327     }
1328
1329     /// Retrieves a value for the given key, failing if the key is not present.
1330     pub fn get<'a>(&'a self, k: &K) -> &'a V {
1331         match self.find(k) {
1332             Some(v) => v,
1333             None => fail!("no entry found for key")
1334         }
1335     }
1336
1337     /// Retrieves a (mutable) value for the given key, failing if the key is not present.
1338     pub fn get_mut<'a>(&'a mut self, k: &K) -> &'a mut V {
1339         match self.find_mut(k) {
1340             Some(v) => v,
1341             None => fail!("no entry found for key")
1342         }
1343     }
1344
1345     /// Return true if the map contains a value for the specified key,
1346     /// using equivalence.
1347     pub fn contains_key_equiv<Q: Hash<S> + Equiv<K>>(&self, key: &Q) -> bool {
1348         self.search_equiv(key).is_some()
1349     }
1350
1351     /// Return the value corresponding to the key in the map, using
1352     /// equivalence.
1353     pub fn find_equiv<'a, Q: Hash<S> + Equiv<K>>(&'a self, k: &Q) -> Option<&'a V> {
1354         match self.search_equiv(k) {
1355             None      => None,
1356             Some(idx) => {
1357                 let (_, v_ref) = self.table.read(&idx);
1358                 Some(v_ref)
1359             }
1360         }
1361     }
1362
1363     /// An iterator visiting all keys in arbitrary order.
1364     /// Iterator element type is &'a K.
1365     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1366         self.iter().map(|(k, _v)| k)
1367     }
1368
1369     /// An iterator visiting all values in arbitrary order.
1370     /// Iterator element type is &'a V.
1371     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1372         self.iter().map(|(_k, v)| v)
1373     }
1374
1375     /// An iterator visiting all key-value pairs in arbitrary order.
1376     /// Iterator element type is (&'a K, &'a V).
1377     pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
1378         self.table.iter()
1379     }
1380
1381     /// An iterator visiting all key-value pairs in arbitrary order,
1382     /// with mutable references to the values.
1383     /// Iterator element type is (&'a K, &'a mut V).
1384     pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
1385         self.table.mut_iter()
1386     }
1387
1388     /// Creates a consuming iterator, that is, one that moves each key-value
1389     /// pair out of the map in arbitrary order. The map cannot be used after
1390     /// calling this.
1391     pub fn move_iter(self) -> MoveEntries<K, V> {
1392         self.table.move_iter().map(|(_, k, v)| (k, v))
1393     }
1394 }
1395
1396 impl<K: Eq + Hash<S>, V: Clone, S, H: Hasher<S>> HashMap<K, V, H> {
1397     /// Like `find`, but returns a copy of the value.
1398     pub fn find_copy(&self, k: &K) -> Option<V> {
1399         self.find(k).map(|v| (*v).clone())
1400     }
1401
1402     /// Like `get`, but returns a copy of the value.
1403     pub fn get_copy(&self, k: &K) -> V {
1404         (*self.get(k)).clone()
1405     }
1406 }
1407
1408 impl<K: Eq + Hash<S>, V: PartialEq, S, H: Hasher<S>> PartialEq for HashMap<K, V, H> {
1409     fn eq(&self, other: &HashMap<K, V, H>) -> bool {
1410         if self.len() != other.len() { return false; }
1411
1412         self.iter()
1413           .all(|(key, value)| {
1414             match other.find(key) {
1415                 None    => false,
1416                 Some(v) => *value == *v
1417             }
1418         })
1419     }
1420 }
1421
1422 impl<K: Eq + Hash<S>, V: Eq, S, H: Hasher<S>> Eq for HashMap<K, V, H> {}
1423
1424 impl<K: Eq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> {
1425     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1426         try!(write!(f, "{{"));
1427
1428         for (i, (k, v)) in self.iter().enumerate() {
1429             if i != 0 { try!(write!(f, ", ")); }
1430             try!(write!(f, "{}: {}", *k, *v));
1431         }
1432
1433         write!(f, "}}")
1434     }
1435 }
1436
1437 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H> {
1438     fn default() -> HashMap<K, V, H> {
1439         HashMap::with_hasher(Default::default())
1440     }
1441 }
1442
1443 /// HashMap iterator
1444 pub type Entries<'a, K, V> = table::Entries<'a, K, V>;
1445
1446 /// HashMap mutable values iterator
1447 pub type MutEntries<'a, K, V> = table::MutEntries<'a, K, V>;
1448
1449 /// HashMap move iterator
1450 pub type MoveEntries<K, V> =
1451     iter::Map<'static, (table::SafeHash, K, V), (K, V), table::MoveEntries<K, V>>;
1452
1453 /// HashMap keys iterator
1454 pub type Keys<'a, K, V> =
1455     iter::Map<'static, (&'a K, &'a V), &'a K, Entries<'a, K, V>>;
1456
1457 /// HashMap values iterator
1458 pub type Values<'a, K, V> =
1459     iter::Map<'static, (&'a K, &'a V), &'a V, Entries<'a, K, V>>;
1460
1461 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> FromIterator<(K, V)> for HashMap<K, V, H> {
1462     fn from_iter<T: Iterator<(K, V)>>(iter: T) -> HashMap<K, V, H> {
1463         let (lower, _) = iter.size_hint();
1464         let mut map = HashMap::with_capacity_and_hasher(lower, Default::default());
1465         map.extend(iter);
1466         map
1467     }
1468 }
1469
1470 impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Extendable<(K, V)> for HashMap<K, V, H> {
1471     fn extend<T: Iterator<(K, V)>>(&mut self, mut iter: T) {
1472         for (k, v) in iter {
1473             self.insert(k, v);
1474         }
1475     }
1476 }
1477
1478 /// HashSet iterator
1479 pub type SetItems<'a, K> =
1480     iter::Map<'static, (&'a K, &'a ()), &'a K, Entries<'a, K, ()>>;
1481
1482 /// HashSet move iterator
1483 pub type SetMoveItems<K> =
1484     iter::Map<'static, (K, ()), K, MoveEntries<K, ()>>;
1485
1486 /// An implementation of a hash set using the underlying representation of a
1487 /// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
1488 /// requires that the elements implement the `Eq` and `Hash` traits.
1489 #[deriving(Clone)]
1490 pub struct HashSet<T, H = RandomSipHasher> {
1491     map: HashMap<T, (), H>
1492 }
1493
1494 impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> {
1495     fn eq(&self, other: &HashSet<T, H>) -> bool {
1496         if self.len() != other.len() { return false; }
1497
1498         self.iter().all(|key| other.contains(key))
1499     }
1500 }
1501
1502 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {}
1503
1504 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Collection for HashSet<T, H> {
1505     fn len(&self) -> uint { self.map.len() }
1506 }
1507
1508 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Mutable for HashSet<T, H> {
1509     fn clear(&mut self) { self.map.clear() }
1510 }
1511
1512 impl<T: Eq + Hash<S>, S, H: Hasher<S>> Set<T> for HashSet<T, H> {
1513     fn contains(&self, value: &T) -> bool { self.map.contains_key(value) }
1514
1515     fn is_disjoint(&self, other: &HashSet<T, H>) -> bool {
1516         self.iter().all(|v| !other.contains(v))
1517     }
1518
1519     fn is_subset(&self, other: &HashSet<T, H>) -> bool {
1520         self.iter().all(|v| other.contains(v))
1521     }
1522 }
1523
1524 impl<T: Eq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> {
1525     fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) }
1526
1527     fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
1528 }
1529
1530 impl<T: Hash + Eq> HashSet<T, RandomSipHasher> {
1531     /// Create an empty HashSet
1532     #[inline]
1533     pub fn new() -> HashSet<T, RandomSipHasher> {
1534         HashSet::with_capacity(INITIAL_CAPACITY)
1535     }
1536
1537     /// Create an empty HashSet with space for at least `n` elements in
1538     /// the hash table.
1539     #[inline]
1540     pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> {
1541         HashSet { map: HashMap::with_capacity(capacity) }
1542     }
1543 }
1544
1545 impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
1546     /// Creates a new empty hash set which will use the given hasher to hash
1547     /// keys.
1548     ///
1549     /// The hash set is also created with the default initial capacity.
1550     #[inline]
1551     pub fn with_hasher(hasher: H) -> HashSet<T, H> {
1552         HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
1553     }
1554
1555     /// Create an empty HashSet with space for at least `capacity`
1556     /// elements in the hash table, using `hasher` to hash the keys.
1557     ///
1558     /// Warning: `hasher` is normally randomly generated, and
1559     /// is designed to allow `HashSet`s to be resistant to attacks that
1560     /// cause many collisions and very poor performance. Setting it
1561     /// manually using this function can expose a DoS attack vector.
1562     #[inline]
1563     pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> {
1564         HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) }
1565     }
1566
1567     /// Reserve space for at least `n` elements in the hash table.
1568     pub fn reserve(&mut self, n: uint) {
1569         self.map.reserve(n)
1570     }
1571
1572     /// Returns true if the hash set contains a value equivalent to the
1573     /// given query value.
1574     pub fn contains_equiv<Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
1575       self.map.contains_key_equiv(value)
1576     }
1577
1578     /// An iterator visiting all elements in arbitrary order.
1579     /// Iterator element type is &'a T.
1580     pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
1581         self.map.keys()
1582     }
1583
1584     /// Creates a consuming iterator, that is, one that moves each value out
1585     /// of the set in arbitrary order. The set cannot be used after calling
1586     /// this.
1587     pub fn move_iter(self) -> SetMoveItems<T> {
1588         self.map.move_iter().map(|(k, _)| k)
1589     }
1590
1591     /// Visit the values representing the difference
1592     pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> SetAlgebraItems<'a, T, H> {
1593         Repeat::new(other).zip(self.iter())
1594             .filter_map(|(other, elt)| {
1595                 if !other.contains(elt) { Some(elt) } else { None }
1596             })
1597     }
1598
1599     /// Visit the values representing the symmetric difference
1600     pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>)
1601         -> Chain<SetAlgebraItems<'a, T, H>, SetAlgebraItems<'a, T, H>> {
1602         self.difference(other).chain(other.difference(self))
1603     }
1604
1605     /// Visit the values representing the intersection
1606     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>)
1607         -> SetAlgebraItems<'a, T, H> {
1608         Repeat::new(other).zip(self.iter())
1609             .filter_map(|(other, elt)| {
1610                 if other.contains(elt) { Some(elt) } else { None }
1611             })
1612     }
1613
1614     /// Visit the values representing the union
1615     pub fn union<'a>(&'a self, other: &'a HashSet<T, H>)
1616         -> Chain<SetItems<'a, T>, SetAlgebraItems<'a, T, H>> {
1617         self.iter().chain(other.difference(self))
1618     }
1619 }
1620
1621 impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
1622     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1623         try!(write!(f, "{{"));
1624
1625         for (i, x) in self.iter().enumerate() {
1626             if i != 0 { try!(write!(f, ", ")); }
1627             try!(write!(f, "{}", *x));
1628         }
1629
1630         write!(f, "}}")
1631     }
1632 }
1633
1634 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
1635     fn from_iter<I: Iterator<T>>(iter: I) -> HashSet<T, H> {
1636         let (lower, _) = iter.size_hint();
1637         let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
1638         set.extend(iter);
1639         set
1640     }
1641 }
1642
1643 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H> {
1644     fn extend<I: Iterator<T>>(&mut self, mut iter: I) {
1645         for k in iter {
1646             self.insert(k);
1647         }
1648     }
1649 }
1650
1651 impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> {
1652     fn default() -> HashSet<T, H> {
1653         HashSet::with_hasher(Default::default())
1654     }
1655 }
1656
1657 // `Repeat` is used to feed the filter closure an explicit capture
1658 // of a reference to the other set
1659 /// Set operations iterator
1660 pub type SetAlgebraItems<'a, T, H> =
1661     FilterMap<'static, (&'a HashSet<T, H>, &'a T), &'a T,
1662               Zip<Repeat<&'a HashSet<T, H>>, SetItems<'a, T>>>;
1663
1664 #[cfg(test)]
1665 mod test_map {
1666     use prelude::*;
1667
1668     use super::HashMap;
1669     use cmp::Equiv;
1670     use hash;
1671     use iter::{Iterator,range_inclusive,range_step_inclusive};
1672     use cell::RefCell;
1673
1674     struct KindaIntLike(int);
1675
1676     impl Equiv<int> for KindaIntLike {
1677         fn equiv(&self, other: &int) -> bool {
1678             let KindaIntLike(this) = *self;
1679             this == *other
1680         }
1681     }
1682     impl<S: hash::Writer> hash::Hash<S> for KindaIntLike {
1683         fn hash(&self, state: &mut S) {
1684             let KindaIntLike(this) = *self;
1685             this.hash(state)
1686         }
1687     }
1688
1689     #[test]
1690     fn test_create_capacity_zero() {
1691         let mut m = HashMap::with_capacity(0);
1692
1693         assert!(m.insert(1i, 1i));
1694
1695         assert!(m.contains_key(&1));
1696         assert!(!m.contains_key(&0));
1697     }
1698
1699     #[test]
1700     fn test_insert() {
1701         let mut m = HashMap::new();
1702         assert_eq!(m.len(), 0);
1703         assert!(m.insert(1i, 2i));
1704         assert_eq!(m.len(), 1);
1705         assert!(m.insert(2i, 4i));
1706         assert_eq!(m.len(), 2);
1707         assert_eq!(*m.find(&1).unwrap(), 2);
1708         assert_eq!(*m.find(&2).unwrap(), 4);
1709     }
1710
1711     local_data_key!(drop_vector: RefCell<Vec<int>>)
1712
1713     #[deriving(Hash, PartialEq, Eq)]
1714     struct Dropable {
1715         k: uint
1716     }
1717
1718
1719     impl Dropable {
1720         fn new(k: uint) -> Dropable {
1721             let v = drop_vector.get().unwrap();
1722             v.borrow_mut().as_mut_slice()[k] += 1;
1723
1724             Dropable { k: k }
1725         }
1726     }
1727
1728     impl Drop for Dropable {
1729         fn drop(&mut self) {
1730             let v = drop_vector.get().unwrap();
1731             v.borrow_mut().as_mut_slice()[self.k] -= 1;
1732         }
1733     }
1734
1735     #[test]
1736     fn test_drops() {
1737         drop_vector.replace(Some(RefCell::new(Vec::from_elem(200, 0i))));
1738
1739         {
1740             let mut m = HashMap::new();
1741
1742             let v = drop_vector.get().unwrap();
1743             for i in range(0u, 200) {
1744                 assert_eq!(v.borrow().as_slice()[i], 0);
1745             }
1746             drop(v);
1747
1748             for i in range(0u, 100) {
1749                 let d1 = Dropable::new(i);
1750                 let d2 = Dropable::new(i+100);
1751                 m.insert(d1, d2);
1752             }
1753
1754             let v = drop_vector.get().unwrap();
1755             for i in range(0u, 200) {
1756                 assert_eq!(v.borrow().as_slice()[i], 1);
1757             }
1758             drop(v);
1759
1760             for i in range(0u, 50) {
1761                 let k = Dropable::new(i);
1762                 let v = m.pop(&k);
1763
1764                 assert!(v.is_some());
1765
1766                 let v = drop_vector.get().unwrap();
1767                 assert_eq!(v.borrow().as_slice()[i], 1);
1768                 assert_eq!(v.borrow().as_slice()[i+100], 1);
1769             }
1770
1771             let v = drop_vector.get().unwrap();
1772             for i in range(0u, 50) {
1773                 assert_eq!(v.borrow().as_slice()[i], 0);
1774                 assert_eq!(v.borrow().as_slice()[i+100], 0);
1775             }
1776
1777             for i in range(50u, 100) {
1778                 assert_eq!(v.borrow().as_slice()[i], 1);
1779                 assert_eq!(v.borrow().as_slice()[i+100], 1);
1780             }
1781         }
1782
1783         let v = drop_vector.get().unwrap();
1784         for i in range(0u, 200) {
1785             assert_eq!(v.borrow().as_slice()[i], 0);
1786         }
1787     }
1788
1789     #[test]
1790     fn test_empty_pop() {
1791         let mut m: HashMap<int, bool> = HashMap::new();
1792         assert_eq!(m.pop(&0), None);
1793     }
1794
1795     #[test]
1796     fn test_lots_of_insertions() {
1797         let mut m = HashMap::new();
1798
1799         // Try this a few times to make sure we never screw up the hashmap's
1800         // internal state.
1801         for _ in range(0i, 10) {
1802             assert!(m.is_empty());
1803
1804             for i in range_inclusive(1i, 1000) {
1805                 assert!(m.insert(i, i));
1806
1807                 for j in range_inclusive(1, i) {
1808                     let r = m.find(&j);
1809                     assert_eq!(r, Some(&j));
1810                 }
1811
1812                 for j in range_inclusive(i+1, 1000) {
1813                     let r = m.find(&j);
1814                     assert_eq!(r, None);
1815                 }
1816             }
1817
1818             for i in range_inclusive(1001i, 2000) {
1819                 assert!(!m.contains_key(&i));
1820             }
1821
1822             // remove forwards
1823             for i in range_inclusive(1i, 1000) {
1824                 assert!(m.remove(&i));
1825
1826                 for j in range_inclusive(1, i) {
1827                     assert!(!m.contains_key(&j));
1828                 }
1829
1830                 for j in range_inclusive(i+1, 1000) {
1831                     assert!(m.contains_key(&j));
1832                 }
1833             }
1834
1835             for i in range_inclusive(1i, 1000) {
1836                 assert!(!m.contains_key(&i));
1837             }
1838
1839             for i in range_inclusive(1i, 1000) {
1840                 assert!(m.insert(i, i));
1841             }
1842
1843             // remove backwards
1844             for i in range_step_inclusive(1000i, 1, -1) {
1845                 assert!(m.remove(&i));
1846
1847                 for j in range_inclusive(i, 1000) {
1848                     assert!(!m.contains_key(&j));
1849                 }
1850
1851                 for j in range_inclusive(1, i-1) {
1852                     assert!(m.contains_key(&j));
1853                 }
1854             }
1855         }
1856     }
1857
1858     #[test]
1859     fn test_find_mut() {
1860         let mut m = HashMap::new();
1861         assert!(m.insert(1i, 12i));
1862         assert!(m.insert(2i, 8i));
1863         assert!(m.insert(5i, 14i));
1864         let new = 100;
1865         match m.find_mut(&5) {
1866             None => fail!(), Some(x) => *x = new
1867         }
1868         assert_eq!(m.find(&5), Some(&new));
1869     }
1870
1871     #[test]
1872     fn test_insert_overwrite() {
1873         let mut m = HashMap::new();
1874         assert!(m.insert(1i, 2i));
1875         assert_eq!(*m.find(&1).unwrap(), 2);
1876         assert!(!m.insert(1i, 3i));
1877         assert_eq!(*m.find(&1).unwrap(), 3);
1878     }
1879
1880     #[test]
1881     fn test_insert_conflicts() {
1882         let mut m = HashMap::with_capacity(4);
1883         assert!(m.insert(1i, 2i));
1884         assert!(m.insert(5i, 3i));
1885         assert!(m.insert(9i, 4i));
1886         assert_eq!(*m.find(&9).unwrap(), 4);
1887         assert_eq!(*m.find(&5).unwrap(), 3);
1888         assert_eq!(*m.find(&1).unwrap(), 2);
1889     }
1890
1891     #[test]
1892     fn test_conflict_remove() {
1893         let mut m = HashMap::with_capacity(4);
1894         assert!(m.insert(1i, 2i));
1895         assert_eq!(*m.find(&1).unwrap(), 2);
1896         assert!(m.insert(5, 3));
1897         assert_eq!(*m.find(&1).unwrap(), 2);
1898         assert_eq!(*m.find(&5).unwrap(), 3);
1899         assert!(m.insert(9, 4));
1900         assert_eq!(*m.find(&1).unwrap(), 2);
1901         assert_eq!(*m.find(&5).unwrap(), 3);
1902         assert_eq!(*m.find(&9).unwrap(), 4);
1903         assert!(m.remove(&1));
1904         assert_eq!(*m.find(&9).unwrap(), 4);
1905         assert_eq!(*m.find(&5).unwrap(), 3);
1906     }
1907
1908     #[test]
1909     fn test_is_empty() {
1910         let mut m = HashMap::with_capacity(4);
1911         assert!(m.insert(1i, 2i));
1912         assert!(!m.is_empty());
1913         assert!(m.remove(&1));
1914         assert!(m.is_empty());
1915     }
1916
1917     #[test]
1918     fn test_pop() {
1919         let mut m = HashMap::new();
1920         m.insert(1i, 2i);
1921         assert_eq!(m.pop(&1), Some(2));
1922         assert_eq!(m.pop(&1), None);
1923     }
1924
1925     #[test]
1926     #[allow(experimental)]
1927     fn test_pop_equiv() {
1928         let mut m = HashMap::new();
1929         m.insert(1i, 2i);
1930         assert_eq!(m.pop_equiv(&KindaIntLike(1)), Some(2));
1931         assert_eq!(m.pop_equiv(&KindaIntLike(1)), None);
1932     }
1933
1934     #[test]
1935     fn test_swap() {
1936         let mut m = HashMap::new();
1937         assert_eq!(m.swap(1i, 2i), None);
1938         assert_eq!(m.swap(1i, 3i), Some(2));
1939         assert_eq!(m.swap(1i, 4i), Some(3));
1940     }
1941
1942     #[test]
1943     fn test_move_iter() {
1944         let hm = {
1945             let mut hm = HashMap::new();
1946
1947             hm.insert('a', 1i);
1948             hm.insert('b', 2i);
1949
1950             hm
1951         };
1952
1953         let v = hm.move_iter().collect::<Vec<(char, int)>>();
1954         assert!([('a', 1), ('b', 2)] == v.as_slice() || [('b', 2), ('a', 1)] == v.as_slice());
1955     }
1956
1957     #[test]
1958     fn test_iterate() {
1959         let mut m = HashMap::with_capacity(4);
1960         for i in range(0u, 32) {
1961             assert!(m.insert(i, i*2));
1962         }
1963         assert_eq!(m.len(), 32);
1964
1965         let mut observed: u32 = 0;
1966
1967         for (k, v) in m.iter() {
1968             assert_eq!(*v, *k * 2);
1969             observed |= 1 << *k;
1970         }
1971         assert_eq!(observed, 0xFFFF_FFFF);
1972     }
1973
1974     #[test]
1975     fn test_keys() {
1976         let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
1977         let map = vec.move_iter().collect::<HashMap<int, char>>();
1978         let keys = map.keys().map(|&k| k).collect::<Vec<int>>();
1979         assert_eq!(keys.len(), 3);
1980         assert!(keys.contains(&1));
1981         assert!(keys.contains(&2));
1982         assert!(keys.contains(&3));
1983     }
1984
1985     #[test]
1986     fn test_values() {
1987         let vec = vec![(1i, 'a'), (2i, 'b'), (3i, 'c')];
1988         let map = vec.move_iter().collect::<HashMap<int, char>>();
1989         let values = map.values().map(|&v| v).collect::<Vec<char>>();
1990         assert_eq!(values.len(), 3);
1991         assert!(values.contains(&'a'));
1992         assert!(values.contains(&'b'));
1993         assert!(values.contains(&'c'));
1994     }
1995
1996     #[test]
1997     fn test_find() {
1998         let mut m = HashMap::new();
1999         assert!(m.find(&1i).is_none());
2000         m.insert(1i, 2i);
2001         match m.find(&1) {
2002             None => fail!(),
2003             Some(v) => assert_eq!(*v, 2)
2004         }
2005     }
2006
2007     #[test]
2008     fn test_eq() {
2009         let mut m1 = HashMap::new();
2010         m1.insert(1i, 2i);
2011         m1.insert(2i, 3i);
2012         m1.insert(3i, 4i);
2013
2014         let mut m2 = HashMap::new();
2015         m2.insert(1i, 2i);
2016         m2.insert(2i, 3i);
2017
2018         assert!(m1 != m2);
2019
2020         m2.insert(3i, 4i);
2021
2022         assert_eq!(m1, m2);
2023     }
2024
2025     #[test]
2026     fn test_show() {
2027         let mut map: HashMap<int, int> = HashMap::new();
2028         let empty: HashMap<int, int> = HashMap::new();
2029
2030         map.insert(1i, 2i);
2031         map.insert(3i, 4i);
2032
2033         let map_str = format!("{}", map);
2034
2035         assert!(map_str == "{1: 2, 3: 4}".to_string() || map_str == "{3: 4, 1: 2}".to_string());
2036         assert_eq!(format!("{}", empty), "{}".to_string());
2037     }
2038
2039     #[test]
2040     fn test_expand() {
2041         let mut m = HashMap::new();
2042
2043         assert_eq!(m.len(), 0);
2044         assert!(m.is_empty());
2045
2046         let mut i = 0u;
2047         let old_cap = m.table.capacity();
2048         while old_cap == m.table.capacity() {
2049             m.insert(i, i);
2050             i += 1;
2051         }
2052
2053         assert_eq!(m.len(), i);
2054         assert!(!m.is_empty());
2055     }
2056
2057     #[test]
2058     fn test_resize_policy() {
2059         let mut m = HashMap::new();
2060
2061         assert_eq!(m.len(), 0);
2062         assert!(m.is_empty());
2063
2064         let initial_cap = m.table.capacity();
2065         m.reserve(initial_cap * 2);
2066         let cap = m.table.capacity();
2067
2068         assert_eq!(cap, initial_cap * 2);
2069
2070         let mut i = 0u;
2071         for _ in range(0, cap * 3 / 4) {
2072             m.insert(i, i);
2073             i += 1;
2074         }
2075
2076         assert_eq!(m.len(), i);
2077         assert_eq!(m.table.capacity(), cap);
2078
2079         for _ in range(0, cap / 4) {
2080             m.insert(i, i);
2081             i += 1;
2082         }
2083
2084         let new_cap = m.table.capacity();
2085         assert_eq!(new_cap, cap * 2);
2086
2087         for _ in range(0, cap / 2) {
2088             i -= 1;
2089             m.remove(&i);
2090             assert_eq!(m.table.capacity(), new_cap);
2091         }
2092
2093         for _ in range(0, cap / 2 - 1) {
2094             i -= 1;
2095             m.remove(&i);
2096         }
2097
2098         assert_eq!(m.table.capacity(), cap);
2099         assert_eq!(m.len(), i);
2100         assert!(!m.is_empty());
2101     }
2102
2103     #[test]
2104     fn test_find_equiv() {
2105         let mut m = HashMap::new();
2106
2107         let (foo, bar, baz) = (1i,2i,3i);
2108         m.insert("foo".to_string(), foo);
2109         m.insert("bar".to_string(), bar);
2110         m.insert("baz".to_string(), baz);
2111
2112
2113         assert_eq!(m.find_equiv(&("foo")), Some(&foo));
2114         assert_eq!(m.find_equiv(&("bar")), Some(&bar));
2115         assert_eq!(m.find_equiv(&("baz")), Some(&baz));
2116
2117         assert_eq!(m.find_equiv(&("qux")), None);
2118     }
2119
2120     #[test]
2121     fn test_from_iter() {
2122         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2123
2124         let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2125
2126         for &(k, v) in xs.iter() {
2127             assert_eq!(map.find(&k), Some(&v));
2128         }
2129     }
2130
2131     #[test]
2132     fn test_size_hint() {
2133         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2134
2135         let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2136
2137         let mut iter = map.iter();
2138
2139         for _ in iter.by_ref().take(3) {}
2140
2141         assert_eq!(iter.size_hint(), (3, Some(3)));
2142     }
2143
2144     #[test]
2145     fn test_mut_size_hint() {
2146         let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
2147
2148         let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
2149
2150         let mut iter = map.mut_iter();
2151
2152         for _ in iter.by_ref().take(3) {}
2153
2154         assert_eq!(iter.size_hint(), (3, Some(3)));
2155     }
2156 }
2157
2158 #[cfg(test)]
2159 mod test_set {
2160     use prelude::*;
2161
2162     use super::HashSet;
2163     use slice::ImmutableEqVector;
2164     use collections::Collection;
2165
2166     #[test]
2167     fn test_disjoint() {
2168         let mut xs = HashSet::new();
2169         let mut ys = HashSet::new();
2170         assert!(xs.is_disjoint(&ys));
2171         assert!(ys.is_disjoint(&xs));
2172         assert!(xs.insert(5i));
2173         assert!(ys.insert(11i));
2174         assert!(xs.is_disjoint(&ys));
2175         assert!(ys.is_disjoint(&xs));
2176         assert!(xs.insert(7));
2177         assert!(xs.insert(19));
2178         assert!(xs.insert(4));
2179         assert!(ys.insert(2));
2180         assert!(ys.insert(-11));
2181         assert!(xs.is_disjoint(&ys));
2182         assert!(ys.is_disjoint(&xs));
2183         assert!(ys.insert(7));
2184         assert!(!xs.is_disjoint(&ys));
2185         assert!(!ys.is_disjoint(&xs));
2186     }
2187
2188     #[test]
2189     fn test_subset_and_superset() {
2190         let mut a = HashSet::new();
2191         assert!(a.insert(0i));
2192         assert!(a.insert(5));
2193         assert!(a.insert(11));
2194         assert!(a.insert(7));
2195
2196         let mut b = HashSet::new();
2197         assert!(b.insert(0i));
2198         assert!(b.insert(7));
2199         assert!(b.insert(19));
2200         assert!(b.insert(250));
2201         assert!(b.insert(11));
2202         assert!(b.insert(200));
2203
2204         assert!(!a.is_subset(&b));
2205         assert!(!a.is_superset(&b));
2206         assert!(!b.is_subset(&a));
2207         assert!(!b.is_superset(&a));
2208
2209         assert!(b.insert(5));
2210
2211         assert!(a.is_subset(&b));
2212         assert!(!a.is_superset(&b));
2213         assert!(!b.is_subset(&a));
2214         assert!(b.is_superset(&a));
2215     }
2216
2217     #[test]
2218     fn test_iterate() {
2219         let mut a = HashSet::new();
2220         for i in range(0u, 32) {
2221             assert!(a.insert(i));
2222         }
2223         let mut observed: u32 = 0;
2224         for k in a.iter() {
2225             observed |= 1 << *k;
2226         }
2227         assert_eq!(observed, 0xFFFF_FFFF);
2228     }
2229
2230     #[test]
2231     fn test_intersection() {
2232         let mut a = HashSet::new();
2233         let mut b = HashSet::new();
2234
2235         assert!(a.insert(11i));
2236         assert!(a.insert(1));
2237         assert!(a.insert(3));
2238         assert!(a.insert(77));
2239         assert!(a.insert(103));
2240         assert!(a.insert(5));
2241         assert!(a.insert(-5));
2242
2243         assert!(b.insert(2i));
2244         assert!(b.insert(11));
2245         assert!(b.insert(77));
2246         assert!(b.insert(-9));
2247         assert!(b.insert(-42));
2248         assert!(b.insert(5));
2249         assert!(b.insert(3));
2250
2251         let mut i = 0;
2252         let expected = [3, 5, 11, 77];
2253         for x in a.intersection(&b) {
2254             assert!(expected.contains(x));
2255             i += 1
2256         }
2257         assert_eq!(i, expected.len());
2258     }
2259
2260     #[test]
2261     fn test_difference() {
2262         let mut a = HashSet::new();
2263         let mut b = HashSet::new();
2264
2265         assert!(a.insert(1i));
2266         assert!(a.insert(3));
2267         assert!(a.insert(5));
2268         assert!(a.insert(9));
2269         assert!(a.insert(11));
2270
2271         assert!(b.insert(3i));
2272         assert!(b.insert(9));
2273
2274         let mut i = 0;
2275         let expected = [1, 5, 11];
2276         for x in a.difference(&b) {
2277             assert!(expected.contains(x));
2278             i += 1
2279         }
2280         assert_eq!(i, expected.len());
2281     }
2282
2283     #[test]
2284     fn test_symmetric_difference() {
2285         let mut a = HashSet::new();
2286         let mut b = HashSet::new();
2287
2288         assert!(a.insert(1i));
2289         assert!(a.insert(3));
2290         assert!(a.insert(5));
2291         assert!(a.insert(9));
2292         assert!(a.insert(11));
2293
2294         assert!(b.insert(-2i));
2295         assert!(b.insert(3));
2296         assert!(b.insert(9));
2297         assert!(b.insert(14));
2298         assert!(b.insert(22));
2299
2300         let mut i = 0;
2301         let expected = [-2, 1, 5, 11, 14, 22];
2302         for x in a.symmetric_difference(&b) {
2303             assert!(expected.contains(x));
2304             i += 1
2305         }
2306         assert_eq!(i, expected.len());
2307     }
2308
2309     #[test]
2310     fn test_union() {
2311         let mut a = HashSet::new();
2312         let mut b = HashSet::new();
2313
2314         assert!(a.insert(1i));
2315         assert!(a.insert(3));
2316         assert!(a.insert(5));
2317         assert!(a.insert(9));
2318         assert!(a.insert(11));
2319         assert!(a.insert(16));
2320         assert!(a.insert(19));
2321         assert!(a.insert(24));
2322
2323         assert!(b.insert(-2i));
2324         assert!(b.insert(1));
2325         assert!(b.insert(5));
2326         assert!(b.insert(9));
2327         assert!(b.insert(13));
2328         assert!(b.insert(19));
2329
2330         let mut i = 0;
2331         let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19, 24];
2332         for x in a.union(&b) {
2333             assert!(expected.contains(x));
2334             i += 1
2335         }
2336         assert_eq!(i, expected.len());
2337     }
2338
2339     #[test]
2340     fn test_from_iter() {
2341         let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
2342
2343         let set: HashSet<int> = xs.iter().map(|&x| x).collect();
2344
2345         for x in xs.iter() {
2346             assert!(set.contains(x));
2347         }
2348     }
2349
2350     #[test]
2351     fn test_move_iter() {
2352         let hs = {
2353             let mut hs = HashSet::new();
2354
2355             hs.insert('a');
2356             hs.insert('b');
2357
2358             hs
2359         };
2360
2361         let v = hs.move_iter().collect::<Vec<char>>();
2362         assert!(['a', 'b'] == v.as_slice() || ['b', 'a'] == v.as_slice());
2363     }
2364
2365     #[test]
2366     fn test_eq() {
2367         // These constants once happened to expose a bug in insert().
2368         // I'm keeping them around to prevent a regression.
2369         let mut s1 = HashSet::new();
2370
2371         s1.insert(1i);
2372         s1.insert(2);
2373         s1.insert(3);
2374
2375         let mut s2 = HashSet::new();
2376
2377         s2.insert(1i);
2378         s2.insert(2);
2379
2380         assert!(s1 != s2);
2381
2382         s2.insert(3);
2383
2384         assert_eq!(s1, s2);
2385     }
2386
2387     #[test]
2388     fn test_show() {
2389         let mut set: HashSet<int> = HashSet::new();
2390         let empty: HashSet<int> = HashSet::new();
2391
2392         set.insert(1i);
2393         set.insert(2);
2394
2395         let set_str = format!("{}", set);
2396
2397         assert!(set_str == "{1, 2}".to_string() || set_str == "{2, 1}".to_string());
2398         assert_eq!(format!("{}", empty), "{}".to_string());
2399     }
2400 }
2401
2402 #[cfg(test)]
2403 mod bench {
2404     extern crate test;
2405     use prelude::*;
2406
2407     use self::test::Bencher;
2408     use iter::{range_inclusive};
2409
2410     #[bench]
2411     fn new_drop(b : &mut Bencher) {
2412         use super::HashMap;
2413
2414         b.iter(|| {
2415             let m : HashMap<int, int> = HashMap::new();
2416             assert_eq!(m.len(), 0);
2417         })
2418     }
2419
2420     #[bench]
2421     fn new_insert_drop(b : &mut Bencher) {
2422         use super::HashMap;
2423
2424         b.iter(|| {
2425             let mut m = HashMap::new();
2426             m.insert(0i, 0i);
2427             assert_eq!(m.len(), 1);
2428         })
2429     }
2430
2431     #[bench]
2432     fn insert(b: &mut Bencher) {
2433         use super::HashMap;
2434
2435         let mut m = HashMap::new();
2436
2437         for i in range_inclusive(1i, 1000) {
2438             m.insert(i, i);
2439         }
2440
2441         let mut k = 1001;
2442
2443         b.iter(|| {
2444             m.insert(k, k);
2445             k += 1;
2446         });
2447     }
2448
2449     #[bench]
2450     fn find_existing(b: &mut Bencher) {
2451         use super::HashMap;
2452
2453         let mut m = HashMap::new();
2454
2455         for i in range_inclusive(1i, 1000) {
2456             m.insert(i, i);
2457         }
2458
2459         b.iter(|| {
2460             for i in range_inclusive(1i, 1000) {
2461                 m.contains_key(&i);
2462             }
2463         });
2464     }
2465
2466     #[bench]
2467     fn find_nonexisting(b: &mut Bencher) {
2468         use super::HashMap;
2469
2470         let mut m = HashMap::new();
2471
2472         for i in range_inclusive(1i, 1000) {
2473             m.insert(i, i);
2474         }
2475
2476         b.iter(|| {
2477             for i in range_inclusive(1001i, 2000) {
2478                 m.contains_key(&i);
2479             }
2480         });
2481     }
2482
2483     #[bench]
2484     fn hashmap_as_queue(b: &mut Bencher) {
2485         use super::HashMap;
2486
2487         let mut m = HashMap::new();
2488
2489         for i in range_inclusive(1i, 1000) {
2490             m.insert(i, i);
2491         }
2492
2493         let mut k = 1i;
2494
2495         b.iter(|| {
2496             m.pop(&k);
2497             m.insert(k + 1000, k + 1000);
2498             k += 1;
2499         });
2500     }
2501
2502     #[bench]
2503     fn find_pop_insert(b: &mut Bencher) {
2504         use super::HashMap;
2505
2506         let mut m = HashMap::new();
2507
2508         for i in range_inclusive(1i, 1000) {
2509             m.insert(i, i);
2510         }
2511
2512         let mut k = 1i;
2513
2514         b.iter(|| {
2515             m.find(&(k + 400));
2516             m.find(&(k + 2000));
2517             m.pop(&k);
2518             m.insert(k + 1000, k + 1000);
2519             k += 1;
2520         })
2521     }
2522 }