ordermap/
lib.rs

1
2#![deny(unsafe_code)]
3#![doc(html_root_url = "https://docs.rs/ordermap/0.3/")]
4
5//! [`OrderMap`] is a hash table where the iteration order of the key-value
6//! pairs is independent of the hash values of the keys.
7//!
8//! [`OrderMap`]: struct.OrderMap.html
9
10#[macro_use]
11mod macros;
12#[cfg(feature = "serde-1")]
13mod serde;
14mod util;
15mod equivalent;
16mod mutable_keys;
17
18pub mod set;
19
20use std::hash::Hash;
21use std::hash::BuildHasher;
22use std::hash::Hasher;
23use std::iter::FromIterator;
24use std::collections::hash_map::RandomState;
25use std::ops::RangeFull;
26
27use std::cmp::{max, Ordering};
28use std::fmt;
29use std::mem::{replace};
30use std::marker::PhantomData;
31
32use util::{third, ptrdistance, enumerate};
33pub use equivalent::Equivalent;
34pub use mutable_keys::MutableKeys;
35pub use set::OrderSet;
36
37fn hash_elem_using<B: BuildHasher, K: ?Sized + Hash>(build: &B, k: &K) -> HashValue {
38    let mut h = build.build_hasher();
39    k.hash(&mut h);
40    HashValue(h.finish() as usize)
41}
42
43/// Hash value newtype. Not larger than usize, since anything larger
44/// isn't used for selecting position anyway.
45#[derive(Copy, Debug)]
46struct HashValue(usize);
47
48impl HashValue {
49    #[inline(always)]
50    fn get(self) -> usize { self.0 }
51}
52
53impl Clone for HashValue {
54    #[inline]
55    fn clone(&self) -> Self { *self }
56}
57impl PartialEq for HashValue {
58    #[inline]
59    fn eq(&self, rhs: &Self) -> bool {
60        self.0 == rhs.0
61    }
62}
63
64/// A possibly truncated hash value.
65///
66#[derive(Debug)]
67struct ShortHash<Sz>(usize, PhantomData<Sz>);
68
69impl<Sz> ShortHash<Sz> {
70    /// Pretend this is a full HashValue, which
71    /// is completely ok w.r.t determining bucket index
72    ///
73    /// - Sz = u32: 32-bit hash is enough to select bucket index
74    /// - Sz = u64: hash is not truncated
75    fn into_hash(self) -> HashValue {
76        HashValue(self.0)
77    }
78}
79
80impl<Sz> Copy for ShortHash<Sz> { }
81impl<Sz> Clone for ShortHash<Sz> {
82    #[inline]
83    fn clone(&self) -> Self { *self }
84}
85
86impl<Sz> PartialEq for ShortHash<Sz> {
87    #[inline]
88    fn eq(&self, rhs: &Self) -> bool {
89        self.0 == rhs.0
90    }
91}
92
93// Compare ShortHash == HashValue by truncating appropriately
94// if applicable before the comparison
95impl<Sz> PartialEq<HashValue> for ShortHash<Sz> where Sz: Size {
96    #[inline]
97    fn eq(&self, rhs: &HashValue) -> bool {
98        if Sz::is_64_bit() {
99            self.0 == rhs.0
100        } else {
101            lo32(self.0 as u64) == lo32(rhs.0 as u64)
102        }
103    }
104}
105impl<Sz> From<ShortHash<Sz>> for HashValue {
106    fn from(x: ShortHash<Sz>) -> Self { HashValue(x.0) }
107}
108
109/// `Pos` is stored in the `indices` array and it points to the index of a
110/// `Bucket` in self.entries.
111///
112/// Pos can be interpreted either as a 64-bit index, or as a 32-bit index and
113/// a 32-bit hash.
114///
115/// Storing the truncated hash next to the index saves loading the hash from the
116/// entry, increasing the cache efficiency.
117///
118/// Note that the lower 32 bits of the hash is enough to compute desired
119/// position and probe distance in a hash map with less than 2**32 buckets.
120///
121/// The OrderMap will simply query its **current raw capacity** to see what its
122/// current size class is, and dispatch to the 32-bit or 64-bit lookup code as
123/// appropriate. Only the growth code needs some extra logic to handle the
124/// transition from one class to another
125#[derive(Copy)]
126struct Pos {
127    index: u64,
128}
129
130impl Clone for Pos {
131    #[inline(always)]
132    fn clone(&self) -> Self { *self }
133}
134
135impl fmt::Debug for Pos {
136    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137        match self.pos() {
138            Some(i) => write!(f, "Pos({} / {:x})", i, self.index),
139            None => write!(f, "Pos(None)"),
140        }
141    }
142}
143
144impl Pos {
145    #[inline]
146    fn none() -> Self { Pos { index: !0 } }
147
148    #[inline]
149    fn is_none(&self) -> bool { self.index == !0 }
150
151    /// Return the index part of the Pos value inside `Some(_)` if the position
152    /// is not none, otherwise return `None`.
153    #[inline]
154    fn pos(&self) -> Option<usize> {
155        if self.index == !0 { None } else { Some(lo32(self.index as u64)) }
156    }
157
158    /// Set the index part of the Pos value to `i`
159    #[inline]
160    fn set_pos<Sz>(&mut self, i: usize)
161        where Sz: Size,
162    {
163        debug_assert!(!self.is_none());
164        if Sz::is_64_bit() {
165            self.index = i as u64;
166        } else {
167            self.index = i as u64 | ((self.index >> 32) << 32)
168        }
169    }
170
171    #[inline]
172    fn with_hash<Sz>(i: usize, hash: HashValue) -> Self
173        where Sz: Size
174    {
175        if Sz::is_64_bit() {
176            Pos {
177                index: i as u64,
178            }
179        } else {
180            Pos {
181                index: i as u64 | ((hash.0 as u64) << 32)
182            }
183        }
184    }
185
186    /// “Resolve” the Pos into a combination of its index value and
187    /// a proxy value to the hash (whether it contains the hash or not
188    /// depends on the size class of the hash map).
189    #[inline]
190    fn resolve<Sz>(&self) -> Option<(usize, ShortHashProxy<Sz>)>
191        where Sz: Size
192    {
193        if Sz::is_64_bit() {
194            if !self.is_none() {
195                Some((self.index as usize, ShortHashProxy::new(0)))
196            } else {
197                None
198            }
199        } else {
200            if !self.is_none() {
201                let (i, hash) = split_lo_hi(self.index);
202                Some((i as usize, ShortHashProxy::new(hash as usize)))
203            } else {
204                None
205            }
206        }
207    }
208
209    /// Like resolve, but the Pos **must** be non-none. Return its index.
210    #[inline]
211    fn resolve_existing_index<Sz>(&self) -> usize 
212        where Sz: Size
213    {
214        debug_assert!(!self.is_none(), "datastructure inconsistent: none where valid Pos expected");
215        if Sz::is_64_bit() {
216            self.index as usize
217        } else {
218            let (i, _) = split_lo_hi(self.index);
219            i as usize
220        }
221    }
222
223}
224
225#[inline]
226fn lo32(x: u64) -> usize { (x & 0xFFFF_FFFF) as usize }
227
228// split into low, hi parts
229#[inline]
230fn split_lo_hi(x: u64) -> (u32, u32) { (x as u32, (x >> 32) as u32) }
231
232// Possibly contains the truncated hash value for an entry, depending on
233// the size class.
234struct ShortHashProxy<Sz>(usize, PhantomData<Sz>);
235
236impl<Sz> ShortHashProxy<Sz>
237    where Sz: Size
238{
239    fn new(x: usize) -> Self {
240        ShortHashProxy(x, PhantomData)
241    }
242
243    /// Get the hash from either `self` or from a lookup into `entries`,
244    /// depending on `Sz`.
245    fn get_short_hash<K, V>(&self, entries: &[Bucket<K, V>], index: usize) -> ShortHash<Sz> {
246        if Sz::is_64_bit() {
247            ShortHash(entries[index].hash.0, PhantomData)
248        } else {
249            ShortHash(self.0, PhantomData)
250        }
251    }
252}
253
254/// A hash table where the iteration order of the key-value pairs is independent
255/// of the hash values of the keys.
256///
257/// The interface is closely compatible with the standard `HashMap`, but also
258/// has additional features.
259///
260/// # Order
261///
262/// The key-value pairs have a consistent order that is determined by
263/// the sequence of insertion and removal calls on the map. The order does
264/// not depend on the keys or the hash function at all.
265///
266/// All iterators traverse the map in *the order*.
267///
268/// # Indices
269///
270/// The key-value pairs are indexed in a compact range without holes in the
271/// range `0..self.len()`. For example, the method `.get_full` looks up the
272/// index for a key, and the method `.get_index` looks up the key-value pair by
273/// index.
274///
275/// # Examples
276///
277/// ```
278/// use ordermap::OrderMap;
279///
280/// // count the frequency of each letter in a sentence.
281/// let mut letters = OrderMap::new();
282/// for ch in "a short treatise on fungi".chars() {
283///     *letters.entry(ch).or_insert(0) += 1;
284/// }
285/// 
286/// assert_eq!(letters[&'s'], 2);
287/// assert_eq!(letters[&'t'], 3);
288/// assert_eq!(letters[&'u'], 1);
289/// assert_eq!(letters.get(&'y'), None);
290/// ```
291#[derive(Clone)]
292pub struct OrderMap<K, V, S = RandomState> {
293    mask: usize,
294    /// indices are the buckets. indices.len() == raw capacity
295    indices: Box<[Pos]>,
296    /// entries is a dense vec of entries in their order. entries.len() == len
297    entries: Vec<Bucket<K, V>>,
298    hash_builder: S,
299}
300
301#[derive(Copy, Clone, Debug)]
302struct Bucket<K, V> {
303    hash: HashValue,
304    key: K,
305    value: V,
306}
307
308#[inline(always)]
309fn desired_pos(mask: usize, hash: HashValue) -> usize {
310    hash.0 & mask
311}
312
313/// The number of steps that `current` is forward of the desired position for hash
314#[inline(always)]
315fn probe_distance(mask: usize, hash: HashValue, current: usize) -> usize {
316    current.wrapping_sub(desired_pos(mask, hash)) & mask
317}
318
319enum Inserted<V> {
320    Done,
321    Swapped { prev_value: V },
322    RobinHood {
323        probe: usize,
324        old_pos: Pos,
325    }
326}
327
328impl<K, V, S> fmt::Debug for OrderMap<K, V, S>
329    where K: fmt::Debug + Hash + Eq,
330          V: fmt::Debug,
331          S: BuildHasher,
332{
333    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
334        try!(f.debug_map().entries(self.iter()).finish());
335        if cfg!(not(feature = "test_debug")) {
336            return Ok(());
337        }
338        try!(writeln!(f, ""));
339        for (i, index) in enumerate(&*self.indices) {
340            try!(write!(f, "{}: {:?}", i, index));
341            if let Some(pos) = index.pos() {
342                let hash = self.entries[pos].hash;
343                let key = &self.entries[pos].key;
344                let desire = desired_pos(self.mask, hash);
345                try!(write!(f, ", desired={}, probe_distance={}, key={:?}",
346                              desire,
347                              probe_distance(self.mask, hash, i),
348                              key));
349            }
350            try!(writeln!(f, ""));
351        }
352        try!(writeln!(f, "cap={}, raw_cap={}, entries.cap={}",
353                      self.capacity(),
354                      self.raw_capacity(),
355                      self.entries.capacity()));
356        Ok(())
357    }
358}
359
360#[inline]
361fn usable_capacity(cap: usize) -> usize {
362    cap - cap / 4
363}
364
365#[inline]
366fn to_raw_capacity(n: usize) -> usize {
367    n + n / 3
368}
369
370// this could not be captured in an efficient iterator
371macro_rules! probe_loop {
372    ($probe_var: ident < $len: expr, $body: expr) => {
373        loop {
374            if $probe_var < $len {
375                $body
376                $probe_var += 1;
377            } else {
378                $probe_var = 0;
379            }
380        }
381    }
382}
383
384impl<K, V> OrderMap<K, V> {
385    /// Create a new map. (Does not allocate.)
386    pub fn new() -> Self {
387        Self::with_capacity(0)
388    }
389
390    /// Create a new map with capacity for `n` key-value pairs. (Does not
391    /// allocate if `n` is zero.)
392    ///
393    /// Computes in **O(n)** time.
394    pub fn with_capacity(n: usize) -> Self {
395        Self::with_capacity_and_hasher(n, <_>::default())
396    }
397}
398
399impl<K, V, S> OrderMap<K, V, S>
400{
401    /// Create a new map with capacity for `n` key-value pairs. (Does not
402    /// allocate if `n` is zero.)
403    ///
404    /// Computes in **O(n)** time.
405    pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self
406        where S: BuildHasher
407    {
408        if n == 0 {
409            OrderMap {
410                mask: 0,
411                indices: Box::new([]),
412                entries: Vec::new(),
413                hash_builder: hash_builder,
414            }
415        } else {
416            let raw = to_raw_capacity(n);
417            let raw_cap = max(raw.next_power_of_two(), 8);
418            OrderMap {
419                mask: raw_cap.wrapping_sub(1),
420                indices: vec![Pos::none(); raw_cap].into_boxed_slice(),
421                entries: Vec::with_capacity(usable_capacity(raw_cap)),
422                hash_builder: hash_builder,
423            }
424        }
425    }
426
427    /// Return the number of key-value pairs in the map.
428    ///
429    /// Computes in **O(1)** time.
430    pub fn len(&self) -> usize { self.entries.len() }
431
432    /// Returns true if the map contains no elements.
433    ///
434    /// Computes in **O(1)** time.
435    pub fn is_empty(&self) -> bool { self.len() == 0 }
436
437    /// Create a new map with `hash_builder`
438    pub fn with_hasher(hash_builder: S) -> Self
439        where S: BuildHasher
440    {
441        Self::with_capacity_and_hasher(0, hash_builder)
442    }
443
444    /// Return a reference to the map's `BuildHasher`.
445    pub fn hasher(&self) -> &S
446        where S: BuildHasher
447    {
448        &self.hash_builder
449    }
450
451    // Return whether we need 32 or 64 bits to specify a bucket or entry index
452    #[cfg(not(feature = "test_low_transition_point"))]
453    fn size_class_is_64bit(&self) -> bool {
454        usize::max_value() > u32::max_value() as usize &&
455            self.raw_capacity() >= u32::max_value() as usize
456    }
457
458    // for testing
459    #[cfg(feature = "test_low_transition_point")]
460    fn size_class_is_64bit(&self) -> bool {
461        self.raw_capacity() >= 64
462    }
463
464    #[inline(always)]
465    fn raw_capacity(&self) -> usize {
466        self.indices.len()
467    }
468
469    /// Computes in **O(1)** time.
470    pub fn capacity(&self) -> usize {
471        usable_capacity(self.raw_capacity())
472    }
473}
474
475/// Trait for the "size class". Either u32 or u64 depending on the index
476/// size needed to address an entry's indes in self.entries.
477trait Size {
478    fn is_64_bit() -> bool;
479    fn is_same_size<T: Size>() -> bool {
480        Self::is_64_bit() == T::is_64_bit()
481    }
482}
483
484impl Size for u32 {
485    #[inline]
486    fn is_64_bit() -> bool { false }
487}
488
489impl Size for u64 {
490    #[inline]
491    fn is_64_bit() -> bool { true }
492}
493
494/// Call self.method(args) with `::<u32>` or `::<u64>` depending on `self`
495/// size class.
496///
497/// The u32 or u64 is *prepended* to the type parameter list!
498macro_rules! dispatch_32_vs_64 {
499    ($self_:ident . $method:ident::<$($t:ty),*>($($arg:expr),*)) => {
500        if $self_.size_class_is_64bit() {
501            $self_.$method::<u64, $($t),*>($($arg),*)
502        } else {
503            $self_.$method::<u32, $($t),*>($($arg),*)
504        }
505    };
506    ($self_:ident . $method:ident ($($arg:expr),*)) => {
507        if $self_.size_class_is_64bit() {
508            $self_.$method::<u64>($($arg),*)
509        } else {
510            $self_.$method::<u32>($($arg),*)
511        }
512    };
513}
514
515/// Entry for an existing key-value pair or a vacant location to
516/// insert one.
517///
518/// FIXME: Remove dependence on the `S` parameter
519/// (to match HashMap).
520pub enum Entry<'a, K: 'a, V: 'a, S: 'a = RandomState> {
521    /// Existing slot with equivalent key.
522    Occupied(OccupiedEntry<'a, K, V, S>),
523    /// Vacant slot (no equivalent key in the map).
524    Vacant(VacantEntry<'a, K, V, S>),
525}
526
527impl<'a, K, V, S> Entry<'a, K, V, S> {
528    /// Computes in **O(1)** time (amortized average).
529    pub fn or_insert(self, default: V) -> &'a mut V {
530        match self {
531            Entry::Occupied(entry) => entry.into_mut(),
532            Entry::Vacant(entry) => entry.insert(default),
533        }
534    }
535
536    /// Computes in **O(1)** time (amortized average).
537    pub fn or_insert_with<F>(self, call: F) -> &'a mut V
538        where F: FnOnce() -> V,
539    {
540        match self {
541            Entry::Occupied(entry) => entry.into_mut(),
542            Entry::Vacant(entry) => entry.insert(call()),
543        }
544    }
545
546    pub fn key(&self) -> &K {
547        match *self {
548            Entry::Occupied(ref entry) => entry.key(),
549            Entry::Vacant(ref entry) => entry.key(),
550        }
551    }
552
553    /// Return the index where the key-value pair exists or will be inserted.
554    pub fn index(&self) -> usize {
555        match *self {
556            Entry::Occupied(ref entry) => entry.index(),
557            Entry::Vacant(ref entry) => entry.index(),
558        }
559    }
560}
561
562pub struct OccupiedEntry<'a, K: 'a, V: 'a, S: 'a = RandomState> {
563    map: &'a mut OrderMap<K, V, S>,
564    key: K,
565    probe: usize,
566    index: usize,
567}
568
569impl<'a, K, V, S> OccupiedEntry<'a, K, V, S> {
570    pub fn key(&self) -> &K { &self.key }
571    pub fn get(&self) -> &V {
572        &self.map.entries[self.index].value
573    }
574    pub fn get_mut(&mut self) -> &mut V {
575        &mut self.map.entries[self.index].value
576    }
577
578    /// Return the index of the key-value pair
579    pub fn index(&self) -> usize {
580        self.index
581    }
582    pub fn into_mut(self) -> &'a mut V {
583        &mut self.map.entries[self.index].value
584    }
585
586    pub fn insert(self, value: V) -> V {
587        replace(&mut self.into_mut(), value)
588    }
589
590    pub fn remove(self) -> V {
591        self.remove_entry().1
592    }
593
594    /// Remove and return the key, value pair stored in the map for this entry
595    pub fn remove_entry(self) -> (K, V) {
596        self.map.remove_found(self.probe, self.index)
597    }
598}
599
600
601pub struct VacantEntry<'a, K: 'a, V: 'a, S: 'a = RandomState> {
602    map: &'a mut OrderMap<K, V, S>,
603    key: K,
604    hash: HashValue,
605    probe: usize,
606}
607
608impl<'a, K, V, S> VacantEntry<'a, K, V, S> {
609    pub fn key(&self) -> &K { &self.key }
610    pub fn into_key(self) -> K { self.key }
611    /// Return the index where the key-value pair will be inserted.
612    pub fn index(&self) -> usize { self.map.len() }
613    pub fn insert(self, value: V) -> &'a mut V {
614        if self.map.size_class_is_64bit() {
615            self.insert_impl::<u64>(value)
616        } else {
617            self.insert_impl::<u32>(value)
618        }
619    }
620
621    fn insert_impl<Sz>(self, value: V) -> &'a mut V
622        where Sz: Size
623    {
624        let index = self.map.entries.len();
625        self.map.entries.push(Bucket { hash: self.hash, key: self.key, value: value });
626        let old_pos = Pos::with_hash::<Sz>(index, self.hash);
627        self.map.insert_phase_2::<Sz>(self.probe, old_pos);
628        &mut {self.map}.entries[index].value
629    }
630}
631
632impl<K, V, S> OrderMap<K, V, S>
633    where K: Hash + Eq,
634          S: BuildHasher,
635{
636    // Warning, this is a code duplication zone Entry is not yet finished
637    fn entry_phase_1<Sz>(&mut self, key: K) -> Entry<K, V, S>
638        where Sz: Size
639    {
640        let hash = hash_elem_using(&self.hash_builder, &key);
641        let mut probe = desired_pos(self.mask, hash);
642        let mut dist = 0;
643        debug_assert!(self.len() < self.raw_capacity());
644        probe_loop!(probe < self.indices.len(), {
645            if let Some((i, hash_proxy)) = self.indices[probe].resolve::<Sz>() {
646                let entry_hash = hash_proxy.get_short_hash(&self.entries, i);
647                // if existing element probed less than us, swap
648                let their_dist = probe_distance(self.mask, entry_hash.into_hash(), probe);
649                if their_dist < dist {
650                    // robin hood: steal the spot if it's better for us
651                    return Entry::Vacant(VacantEntry {
652                        map: self,
653                        hash: hash,
654                        key: key,
655                        probe: probe,
656                    });
657                } else if entry_hash == hash && self.entries[i].key == key {
658                    return Entry::Occupied(OccupiedEntry {
659                        map: self,
660                        key: key,
661                        probe: probe,
662                        index: i,
663                    });
664                }
665            } else {
666                // empty bucket, insert here
667                return Entry::Vacant(VacantEntry {
668                    map: self,
669                    hash: hash,
670                    key: key,
671                    probe: probe,
672                });
673            }
674            dist += 1;
675        });
676    }
677
678    /// Remove all key-value pairs in the map, while preserving its capacity.
679    ///
680    /// Computes in **O(n)** time.
681    pub fn clear(&mut self) {
682        self.entries.clear();
683        self.clear_indices();
684    }
685
686    // clear self.indices to the same state as "no elements"
687    fn clear_indices(&mut self) {
688        for pos in self.indices.iter_mut() {
689            *pos = Pos::none();
690        }
691    }
692
693    /// Reserve capacity for `additional` more key-value pairs.
694    ///
695    /// FIXME Not implemented fully yet.
696    pub fn reserve(&mut self, additional: usize) {
697        if additional > 0 {
698            self.reserve_one();
699        }
700    }
701
702    // First phase: Look for the preferred location for key.
703    //
704    // We will know if `key` is already in the map, before we need to insert it.
705    // When we insert they key, it might be that we need to continue displacing
706    // entries (robin hood hashing), in which case Inserted::RobinHood is returned
707    fn insert_phase_1<Sz>(&mut self, key: K, value: V) -> Inserted<V>
708        where Sz: Size
709    {
710        let hash = hash_elem_using(&self.hash_builder, &key);
711        let mut probe = desired_pos(self.mask, hash);
712        let mut dist = 0;
713        let insert_kind;
714        debug_assert!(self.len() < self.raw_capacity());
715        probe_loop!(probe < self.indices.len(), {
716            let pos = &mut self.indices[probe];
717            if let Some((i, hash_proxy)) = pos.resolve::<Sz>() {
718                let entry_hash = hash_proxy.get_short_hash(&self.entries, i);
719                // if existing element probed less than us, swap
720                let their_dist = probe_distance(self.mask, entry_hash.into_hash(), probe);
721                if their_dist < dist {
722                    // robin hood: steal the spot if it's better for us
723                    let index = self.entries.len();
724                    insert_kind = Inserted::RobinHood {
725                        probe: probe,
726                        old_pos: Pos::with_hash::<Sz>(index, hash),
727                    };
728                    break;
729                } else if entry_hash == hash && self.entries[i].key == key {
730                    return Inserted::Swapped {
731                        prev_value: replace(&mut self.entries[i].value, value),
732                    };
733                }
734            } else {
735                // empty bucket, insert here
736                let index = self.entries.len();
737                *pos = Pos::with_hash::<Sz>(index, hash);
738                insert_kind = Inserted::Done;
739                break;
740            }
741            dist += 1;
742        });
743        self.entries.push(Bucket { hash: hash, key: key, value: value });
744        insert_kind
745    }
746
747    fn first_allocation(&mut self) {
748        debug_assert_eq!(self.len(), 0);
749        let raw_cap = 8usize;
750        self.mask = raw_cap.wrapping_sub(1);
751        self.indices = vec![Pos::none(); raw_cap].into_boxed_slice();
752        self.entries = Vec::with_capacity(usable_capacity(raw_cap));
753    }
754
755    #[inline(never)]
756    // `Sz` is *current* Size class, before grow
757    fn double_capacity<Sz>(&mut self)
758        where Sz: Size
759    {
760        debug_assert!(self.raw_capacity() == 0 || self.len() > 0);
761        if self.raw_capacity() == 0 {
762            return self.first_allocation();
763        }
764
765        // find first ideally placed element -- start of cluster
766        let mut first_ideal = 0;
767        for (i, index) in enumerate(&*self.indices) {
768            if let Some(pos) = index.pos() {
769                if 0 == probe_distance(self.mask, self.entries[pos].hash, i) {
770                    first_ideal = i;
771                    break;
772                }
773            }
774        }
775
776        // visit the entries in an order where we can simply reinsert them
777        // into self.indices without any bucket stealing.
778        let new_raw_cap = self.indices.len() * 2;
779        let old_indices = replace(&mut self.indices, vec![Pos::none(); new_raw_cap].into_boxed_slice());
780        self.mask = new_raw_cap.wrapping_sub(1);
781
782        // `Sz` is the old size class, and either u32 or u64 is the new
783        for &pos in &old_indices[first_ideal..] {
784            dispatch_32_vs_64!(self.reinsert_entry_in_order::<Sz>(pos));
785        }
786
787        for &pos in &old_indices[..first_ideal] {
788            dispatch_32_vs_64!(self.reinsert_entry_in_order::<Sz>(pos));
789        }
790        let more = self.capacity() - self.len();
791        self.entries.reserve_exact(more);
792    }
793
794    // write to self.indices
795    // read from self.entries at `pos`
796    //
797    // reinserting rewrites all `Pos` entries anyway. This handles transitioning
798    // from u32 to u64 size class if needed by using the two type parameters.
799    fn reinsert_entry_in_order<SzNew, SzOld>(&mut self, pos: Pos)
800        where SzNew: Size,
801              SzOld: Size,
802    {
803        if let Some((i, hash_proxy)) = pos.resolve::<SzOld>() {
804            // only if the size class is conserved can we use the short hash
805            let entry_hash = if SzOld::is_same_size::<SzNew>() {
806                hash_proxy.get_short_hash(&self.entries, i).into_hash()
807            } else {
808                self.entries[i].hash
809            };
810            // find first empty bucket and insert there
811            let mut probe = desired_pos(self.mask, entry_hash);
812            probe_loop!(probe < self.indices.len(), {
813                if let Some(_) = self.indices[probe].resolve::<SzNew>() {
814                    /* nothing */
815                } else {
816                    // empty bucket, insert here
817                    self.indices[probe] = Pos::with_hash::<SzNew>(i, entry_hash);
818                    return;
819                }
820            });
821        }
822    }
823
824    fn reserve_one(&mut self) {
825        if self.len() == self.capacity() {
826            dispatch_32_vs_64!(self.double_capacity());
827        }
828    }
829
830    /// Insert a key-value pair in the map.
831    ///
832    /// If an equivalent key already exists in the map: the key remains and
833    /// retains in its place in the order, its corresponding value is updated
834    /// with `value` and the older value is returned inside `Some(_)`.
835    ///
836    /// If no equivalent key existed in the map: the new key-value pair is
837    /// inserted, last in order, and `None` is returned.
838    ///
839    /// Computes in **O(1)** time (amortized average).
840    ///
841    /// See also [`entry`](#method.entry) if you you want to insert *or* modify
842    /// or if you need to get the `index` of the corresponding key-value pair.
843    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
844        self.reserve_one();
845        if self.size_class_is_64bit() {
846            match self.insert_phase_1::<u64>(key, value) {
847                Inserted::Swapped { prev_value } => Some(prev_value),
848                Inserted::Done => None,
849                Inserted::RobinHood { probe, old_pos } => {
850                    self.insert_phase_2::<u64>(probe, old_pos);
851                    None
852                }
853            }
854        } else {
855            match self.insert_phase_1::<u32>(key, value) {
856                Inserted::Swapped { prev_value } => Some(prev_value),
857                Inserted::Done => None,
858                Inserted::RobinHood { probe, old_pos } => {
859                    self.insert_phase_2::<u32>(probe, old_pos);
860                    None
861                }
862            }
863        }
864    }
865
866    /// Get the given key’s corresponding entry in the map for insertion and/or
867    /// in-place manipulation.
868    ///
869    /// Computes in **O(1)** time (amortized average).
870    pub fn entry(&mut self, key: K) -> Entry<K, V, S> {
871        self.reserve_one();
872        dispatch_32_vs_64!(self.entry_phase_1(key))
873    }
874
875
876    /// Return an iterator over the key-value pairs of the map, in their order
877    pub fn iter(&self) -> Iter<K, V> {
878        Iter {
879            iter: self.entries.iter()
880        }
881    }
882
883    /// Return an iterator over the key-value pairs of the map, in their order
884    pub fn iter_mut(&mut self) -> IterMut<K, V> {
885        IterMut {
886            iter: self.entries.iter_mut()
887        }
888    }
889
890    /// Return an iterator over the keys of the map, in their order
891    pub fn keys(&self) -> Keys<K, V> {
892        Keys {
893            iter: self.entries.iter()
894        }
895    }
896
897    /// Return an iterator over the values of the map, in their order
898    pub fn values(&self) -> Values<K, V> {
899        Values {
900            iter: self.entries.iter()
901        }
902    }
903
904    /// Return an iterator over mutable references to the the values of the map,
905    /// in their order
906    pub fn values_mut(&mut self) -> ValuesMut<K, V> {
907        ValuesMut {
908            iter: self.entries.iter_mut()
909        }
910    }
911
912    /// Return `true` if and equivalent to `key` exists in the map.
913    ///
914    /// Computes in **O(1)** time (average).
915    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
916        where Q: Hash + Equivalent<K>,
917    {
918        self.find(key).is_some()
919    }
920
921    /// Return a reference to the value stored for `key`, if it is present,
922    /// else `None`.
923    ///
924    /// Computes in **O(1)** time (average).
925    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
926        where Q: Hash + Equivalent<K>,
927    {
928        self.get_full(key).map(third)
929    }
930
931    /// Return item index, key and value
932    pub fn get_full<Q: ?Sized>(&self, key: &Q) -> Option<(usize, &K, &V)>
933        where Q: Hash + Equivalent<K>,
934    {
935        if let Some((_, found)) = self.find(key) {
936            let entry = &self.entries[found];
937            Some((found, &entry.key, &entry.value))
938        } else {
939            None
940        }
941    }
942
943    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
944        where Q: Hash + Equivalent<K>,
945    {
946        self.get_full_mut(key).map(third)
947    }
948
949    pub fn get_full_mut<Q: ?Sized>(&mut self, key: &Q)
950        -> Option<(usize, &K, &mut V)>
951        where Q: Hash + Equivalent<K>,
952    {
953        self.get_full_mut2(key).map(|(i, k, v)| (i, &*k, v))
954    }
955
956    /// Return probe (indices) and position (entries)
957    fn find<Q: ?Sized>(&self, key: &Q) -> Option<(usize, usize)>
958        where Q: Hash + Equivalent<K>,
959    {
960        if self.len() == 0 { return None; }
961        let h = hash_elem_using(&self.hash_builder, key);
962        self.find_using(h, move |entry| { Q::equivalent(key, &entry.key) })
963    }
964
965    /// NOTE: Same as .swap_remove
966    ///
967    /// Computes in **O(1)** time (average).
968    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
969        where Q: Hash + Equivalent<K>,
970    {
971        self.swap_remove(key)
972    }
973
974    /// Remove the key-value pair equivalent to `key` and return
975    /// its value.
976    ///
977    /// Like `Vec::swap_remove`, the pair is removed by swapping it with the
978    /// last element of the map and popping it off. **This perturbs
979    /// the postion of what used to be the last element!**
980    ///
981    /// Return `None` if `key` is not in map.
982    ///
983    /// Computes in **O(1)** time (average).
984    pub fn swap_remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
985        where Q: Hash + Equivalent<K>,
986    {
987        self.swap_remove_full(key).map(third)
988    }
989
990    /// Remove the key-value pair equivalent to `key` and return it and
991    /// the index it had.
992    ///
993    /// Like `Vec::swap_remove`, the pair is removed by swapping it with the
994    /// last element of the map and popping it off. **This perturbs
995    /// the postion of what used to be the last element!**
996    ///
997    /// Return `None` if `key` is not in map.
998    pub fn swap_remove_full<Q: ?Sized>(&mut self, key: &Q) -> Option<(usize, K, V)>
999        where Q: Hash + Equivalent<K>,
1000    {
1001        let (probe, found) = match self.find(key) {
1002            None => return None,
1003            Some(t) => t,
1004        };
1005        let (k, v) = self.remove_found(probe, found);
1006        Some((found, k, v))
1007    }
1008
1009    /// Remove the last key-value pair
1010    ///
1011    /// Computes in **O(1)** time (average).
1012    pub fn pop(&mut self) -> Option<(K, V)> {
1013        self.pop_impl()
1014    }
1015
1016    /// Scan through each key-value pair in the map and keep those where the
1017    /// closure `keep` returns `true`.
1018    ///
1019    /// The elements are visited in order, and remaining elements keep their
1020    /// order.
1021    ///
1022    /// Computes in **O(n)** time (average).
1023    pub fn retain<F>(&mut self, mut keep: F)
1024        where F: FnMut(&K, &mut V) -> bool,
1025    {
1026        self.retain_mut(move |k, v| keep(k, v));
1027    }
1028
1029    fn retain_mut<F>(&mut self, keep: F)
1030        where F: FnMut(&mut K, &mut V) -> bool,
1031    {
1032        dispatch_32_vs_64!(self.retain_in_order_impl::<F>(keep));
1033    }
1034
1035    fn retain_in_order_impl<Sz, F>(&mut self, mut keep: F)
1036        where F: FnMut(&mut K, &mut V) -> bool,
1037              Sz: Size,
1038    {
1039        // Like Vec::retain in self.entries; for each removed key-value pair,
1040        // we clear its corresponding spot in self.indices, and run the
1041        // usual backward shift in self.indices.
1042        let len = self.entries.len();
1043        let mut n_deleted = 0;
1044        for i in 0..len {
1045            let will_keep;
1046            let hash;
1047            {
1048                let ent = &mut self.entries[i];
1049                hash = ent.hash;
1050                will_keep = keep(&mut ent.key, &mut ent.value);
1051            };
1052            let probe = find_existing_entry_at::<Sz>(&self.indices, hash, self.mask, i);
1053            if !will_keep {
1054                n_deleted += 1;
1055                self.indices[probe] = Pos::none();
1056                self.backward_shift_after_removal::<Sz>(probe);
1057            } else if n_deleted > 0 {
1058                self.indices[probe].set_pos::<Sz>(i - n_deleted);
1059                self.entries.swap(i - n_deleted, i);
1060            }
1061        }
1062        self.entries.truncate(len - n_deleted);
1063    }
1064
1065    /// Sort the map’s key-value pairs by the default ordering of the keys.
1066    ///
1067    /// See `sort_by` for details.
1068    pub fn sort_keys(&mut self)
1069        where K: Ord,
1070    {
1071        self.sort_by(|k1, _, k2, _| Ord::cmp(k1, k2))
1072    }
1073
1074    /// Sort the map’s key-value pairs in place using the comparison
1075    /// function `compare`.
1076    ///
1077    /// The comparison function receives two key and value pairs to compare (you
1078    /// can sort by keys or values or their combination as needed).
1079    ///
1080    /// Computes in **O(n log n + c)** time and **O(n)** space where *n* is
1081    /// the length of the map and *c* the capacity. The sort is stable.
1082    pub fn sort_by<F>(&mut self, mut compare: F)
1083        where F: FnMut(&K, &V, &K, &V) -> Ordering,
1084    {
1085        // here we temporarily use the hash field in a bucket to store the old
1086        // index instead.
1087        //
1088        // Save the old hash values in `side_index`.
1089        // Then we can sort `self.entries` in place.
1090        let mut side_index = Vec::from_iter(enumerate(&mut self.entries).map(|(i, elt)| {
1091            replace(&mut elt.hash, HashValue(i)).get()
1092        }));
1093
1094        self.entries.sort_by(move |ei, ej| compare(&ei.key, &ei.value, &ej.key, &ej.value));
1095
1096        // Here we write back the hash values from side_index and fill
1097        // in side_index with a mapping from the old to the new index instead.
1098        for (i, ent) in enumerate(&mut self.entries) {
1099            let old_index = ent.hash.get();
1100            ent.hash = HashValue(replace(&mut side_index[old_index], i));
1101        }
1102
1103        // Apply new index to self.indices
1104        dispatch_32_vs_64!(self.apply_new_index(&side_index));
1105    }
1106
1107    fn apply_new_index<Sz>(&mut self, new_index: &[usize])
1108        where Sz: Size
1109    {
1110        for pos in self.indices.iter_mut() {
1111            if let Some((i, _)) = pos.resolve::<Sz>() {
1112                pos.set_pos::<Sz>(new_index[i]);
1113            }
1114        }
1115    }
1116
1117    /// Sort the key-value pairs of the map and return a by value iterator of
1118    /// the key-value pairs with the result.
1119    ///
1120    /// The sort is stable.
1121    pub fn sorted_by<F>(mut self, mut cmp: F) -> IntoIter<K, V>
1122        where F: FnMut(&K, &V, &K, &V) -> Ordering
1123    {
1124        self.entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
1125        self.into_iter()
1126    }
1127
1128    /// Clears the `OrderMap`, returning all key-value pairs as a drain iterator.
1129    /// Keeps the allocated memory for reuse.
1130    pub fn drain(&mut self, range: RangeFull) -> Drain<K, V> {
1131        self.clear_indices();
1132
1133        Drain {
1134            iter: self.entries.drain(range),
1135        }
1136    }
1137}
1138
1139impl<K, V, S> OrderMap<K, V, S> {
1140    /// Get a key-value pair by index
1141    ///
1142    /// Valid indices are *0 <= index < self.len()*
1143    ///
1144    /// Computes in **O(1)** time.
1145    pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
1146        self.entries.get(index).map(|ent| (&ent.key, &ent.value))
1147    }
1148
1149    /// Get a key-value pair by index
1150    ///
1151    /// Valid indices are *0 <= index < self.len()*
1152    ///
1153    /// Computes in **O(1)** time.
1154    pub fn get_index_mut(&mut self, index: usize) -> Option<(&mut K, &mut V)> {
1155        self.entries.get_mut(index).map(|ent| (&mut ent.key, &mut ent.value))
1156    }
1157
1158    /// Remove the key-value pair by index
1159    ///
1160    /// Valid indices are *0 <= index < self.len()*
1161    ///
1162    /// Computes in **O(1)** time (average).
1163    pub fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> {
1164        let (probe, found) = match self.entries.get(index)
1165            .map(|e| self.find_existing_entry(e))
1166        {
1167            None => return None,
1168            Some(t) => t,
1169        };
1170        Some(self.remove_found(probe, found))
1171    }
1172}
1173
1174// Methods that don't use any properties (Hash / Eq) of K.
1175//
1176// It's cleaner to separate them out, then the compiler checks that we are not
1177// using Hash + Eq at all in these methods.
1178//
1179// However, we should probably not let this show in the public API or docs.
1180impl<K, V, S> OrderMap<K, V, S> {
1181    fn pop_impl(&mut self) -> Option<(K, V)> {
1182        let (probe, found) = match self.entries.last()
1183            .map(|e| self.find_existing_entry(e))
1184        {
1185            None => return None,
1186            Some(t) => t,
1187        };
1188        debug_assert_eq!(found, self.entries.len() - 1);
1189        Some(self.remove_found(probe, found))
1190    }
1191
1192    /// phase 2 is post-insert where we forward-shift `Pos` in the indices.
1193    fn insert_phase_2<Sz>(&mut self, mut probe: usize, mut old_pos: Pos)
1194        where Sz: Size
1195    {
1196        probe_loop!(probe < self.indices.len(), {
1197            let pos = &mut self.indices[probe];
1198            if pos.is_none() {
1199                *pos = old_pos;
1200                break;
1201            } else {
1202                old_pos = replace(pos, old_pos);
1203            }
1204        });
1205    }
1206
1207
1208    /// Return probe (indices) and position (entries)
1209    fn find_using<F>(&self, hash: HashValue, key_eq: F) -> Option<(usize, usize)>
1210        where F: Fn(&Bucket<K, V>) -> bool,
1211    {
1212        dispatch_32_vs_64!(self.find_using_impl::<_>(hash, key_eq))
1213    }
1214
1215    fn find_using_impl<Sz, F>(&self, hash: HashValue, key_eq: F) -> Option<(usize, usize)>
1216        where F: Fn(&Bucket<K, V>) -> bool,
1217              Sz: Size,
1218    {
1219        debug_assert!(self.len() > 0);
1220        let mut probe = desired_pos(self.mask, hash);
1221        let mut dist = 0;
1222        probe_loop!(probe < self.indices.len(), {
1223            if let Some((i, hash_proxy)) = self.indices[probe].resolve::<Sz>() {
1224                let entry_hash = hash_proxy.get_short_hash(&self.entries, i);
1225                if dist > probe_distance(self.mask, entry_hash.into_hash(), probe) {
1226                    // give up when probe distance is too long
1227                    return None;
1228                } else if entry_hash == hash && key_eq(&self.entries[i]) {
1229                    return Some((probe, i));
1230                }
1231            } else {
1232                return None;
1233            }
1234            dist += 1;
1235        });
1236    }
1237
1238    /// Find `entry` which is already placed inside self.entries;
1239    /// return its probe and entry index.
1240    fn find_existing_entry(&self, entry: &Bucket<K, V>) -> (usize, usize)
1241    {
1242        debug_assert!(self.len() > 0);
1243        dispatch_32_vs_64!(self.find_existing_entry_impl(entry))
1244    }
1245
1246    fn find_existing_entry_impl<Sz>(&self, entry: &Bucket<K, V>) -> (usize, usize)
1247        where Sz: Size,
1248    {
1249        let hash = entry.hash;
1250        let actual_pos = ptrdistance(&self.entries[0], entry);
1251        let probe = find_existing_entry_at::<Sz>(&self.indices, hash, self.mask, actual_pos);
1252        (probe, actual_pos)
1253    }
1254
1255    fn remove_found(&mut self, probe: usize, found: usize) -> (K, V) {
1256        dispatch_32_vs_64!(self.remove_found_impl(probe, found))
1257    }
1258
1259    fn remove_found_impl<Sz>(&mut self, probe: usize, found: usize) -> (K, V)
1260        where Sz: Size
1261    {
1262        // index `probe` and entry `found` is to be removed
1263        // use swap_remove, but then we need to update the index that points
1264        // to the other entry that has to move
1265        self.indices[probe] = Pos::none();
1266        let entry = self.entries.swap_remove(found);
1267
1268        // correct index that points to the entry that had to swap places
1269        if let Some(entry) = self.entries.get(found) {
1270            // was not last element
1271            // examine new element in `found` and find it in indices
1272            let mut probe = desired_pos(self.mask, entry.hash);
1273            probe_loop!(probe < self.indices.len(), {
1274                if let Some((i, _)) = self.indices[probe].resolve::<Sz>() {
1275                    if i >= self.entries.len() {
1276                        // found it
1277                        self.indices[probe] = Pos::with_hash::<Sz>(found, entry.hash);
1278                        break;
1279                    }
1280                }
1281            });
1282        }
1283
1284        self.backward_shift_after_removal::<Sz>(probe);
1285
1286        (entry.key, entry.value)
1287    }
1288
1289    fn backward_shift_after_removal<Sz>(&mut self, probe_at_remove: usize)
1290        where Sz: Size
1291    {
1292        // backward shift deletion in self.indices
1293        // after probe, shift all non-ideally placed indices backward
1294        let mut last_probe = probe_at_remove;
1295        let mut probe = probe_at_remove + 1;
1296        probe_loop!(probe < self.indices.len(), {
1297            if let Some((i, hash_proxy)) = self.indices[probe].resolve::<Sz>() {
1298                let entry_hash = hash_proxy.get_short_hash(&self.entries, i);
1299                if probe_distance(self.mask, entry_hash.into_hash(), probe) > 0 {
1300                    self.indices[last_probe] = self.indices[probe];
1301                    self.indices[probe] = Pos::none();
1302                } else {
1303                    break;
1304                }
1305            } else {
1306                break;
1307            }
1308            last_probe = probe;
1309        });
1310    }
1311
1312}
1313
1314/// Find, in the indices, an entry that already exists at a known position
1315/// inside self.entries in the OrderMap.
1316///
1317/// This is effectively reverse lookup, from the entries into the hash buckets.
1318///
1319/// Return the probe index (into self.indices)
1320///
1321/// + indices: The self.indices of the map,
1322/// + hash: The full hash value from the bucket
1323/// + mask: self.mask.
1324/// + entry_index: The index of the entry in self.entries
1325fn find_existing_entry_at<Sz>(indices: &[Pos], hash: HashValue,
1326                              mask: usize, entry_index: usize) -> usize
1327    where Sz: Size,
1328{
1329    let mut probe = desired_pos(mask, hash);
1330    probe_loop!(probe < indices.len(), {
1331        // the entry *must* be present; if we hit a Pos::none this was not true
1332        // and there is a debug assertion in resolve_existing_index for that.
1333        let i = indices[probe].resolve_existing_index::<Sz>();
1334        if i == entry_index { return probe; }
1335    });
1336}
1337
1338use std::slice::Iter as SliceIter;
1339use std::slice::IterMut as SliceIterMut;
1340use std::vec::IntoIter as VecIntoIter;
1341
1342pub struct Keys<'a, K: 'a, V: 'a> {
1343    iter: SliceIter<'a, Bucket<K, V>>,
1344}
1345
1346impl<'a, K, V> Iterator for Keys<'a, K, V> {
1347    type Item = &'a K;
1348
1349    iterator_methods!(|entry| &entry.key);
1350}
1351
1352impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1353    fn next_back(&mut self) -> Option<&'a K> {
1354        self.iter.next_back().map(|ent| &ent.key)
1355    }
1356}
1357
1358impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1359    fn len(&self) -> usize {
1360        self.iter.len()
1361    }
1362}
1363
1364pub struct Values<'a, K: 'a, V: 'a> {
1365    iter: SliceIter<'a, Bucket<K, V>>,
1366}
1367
1368impl<'a, K, V> Iterator for Values<'a, K, V> {
1369    type Item = &'a V;
1370
1371    iterator_methods!(|ent| &ent.value);
1372}
1373
1374impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1375    fn next_back(&mut self) -> Option<Self::Item> {
1376        self.iter.next_back().map(|ent| &ent.value)
1377    }
1378}
1379
1380impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1381    fn len(&self) -> usize {
1382        self.iter.len()
1383    }
1384}
1385
1386pub struct ValuesMut<'a, K: 'a, V: 'a> {
1387    iter: SliceIterMut<'a, Bucket<K, V>>,
1388}
1389
1390impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1391    type Item = &'a mut V;
1392
1393    iterator_methods!(|ent| &mut ent.value);
1394}
1395
1396impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1397    fn next_back(&mut self) -> Option<Self::Item> {
1398        self.iter.next_back().map(|ent| &mut ent.value)
1399    }
1400}
1401
1402impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1403    fn len(&self) -> usize {
1404        self.iter.len()
1405    }
1406}
1407
1408pub struct Iter<'a, K: 'a, V: 'a> {
1409    iter: SliceIter<'a, Bucket<K, V>>,
1410}
1411
1412impl<'a, K, V> Iterator for Iter<'a, K, V> {
1413    type Item = (&'a K, &'a V);
1414
1415    iterator_methods!(|e| (&e.key, &e.value));
1416}
1417
1418impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1419    fn next_back(&mut self) -> Option<Self::Item> {
1420        self.iter.next_back().map(|e| (&e.key, &e.value))
1421    }
1422}
1423
1424impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1425    fn len(&self) -> usize {
1426        self.iter.len()
1427    }
1428}
1429
1430pub struct IterMut<'a, K: 'a, V: 'a> {
1431    iter: SliceIterMut<'a, Bucket<K, V>>,
1432}
1433
1434impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1435    type Item = (&'a K, &'a mut V);
1436
1437    iterator_methods!(|e| (&e.key, &mut e.value));
1438}
1439
1440impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1441    fn next_back(&mut self) -> Option<Self::Item> {
1442        self.iter.next_back().map(|e| (&e.key, &mut e.value))
1443    }
1444}
1445
1446impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1447    fn len(&self) -> usize {
1448        self.iter.len()
1449    }
1450}
1451
1452pub struct IntoIter<K, V> {
1453    iter: VecIntoIter<Bucket<K, V>>,
1454}
1455
1456impl<K, V> Iterator for IntoIter<K, V> {
1457    type Item = (K, V);
1458
1459    iterator_methods!(|entry| (entry.key, entry.value));
1460}
1461
1462impl<'a, K, V> DoubleEndedIterator for IntoIter<K, V> {
1463    fn next_back(&mut self) -> Option<Self::Item> {
1464        self.iter.next_back().map(|entry| (entry.key, entry.value))
1465    }
1466}
1467
1468impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1469    fn len(&self) -> usize {
1470        self.iter.len()
1471    }
1472}
1473
1474pub struct Drain<'a, K, V> where K: 'a, V: 'a {
1475    iter: ::std::vec::Drain<'a, Bucket<K, V>>
1476}
1477
1478impl<'a, K, V> Iterator for Drain<'a, K, V> {
1479    type Item = (K, V);
1480
1481    iterator_methods!(|bucket| (bucket.key, bucket.value));
1482}
1483
1484impl<'a, K, V> DoubleEndedIterator for Drain<'a, K, V> {
1485    double_ended_iterator_methods!(|bucket| (bucket.key, bucket.value));
1486}
1487
1488
1489impl<'a, K, V, S> IntoIterator for &'a OrderMap<K, V, S>
1490    where K: Hash + Eq,
1491          S: BuildHasher,
1492{
1493    type Item = (&'a K, &'a V);
1494    type IntoIter = Iter<'a, K, V>;
1495    fn into_iter(self) -> Self::IntoIter {
1496        self.iter()
1497    }
1498}
1499
1500impl<'a, K, V, S> IntoIterator for &'a mut OrderMap<K, V, S>
1501    where K: Hash + Eq,
1502          S: BuildHasher,
1503{
1504    type Item = (&'a K, &'a mut V);
1505    type IntoIter = IterMut<'a, K, V>;
1506    fn into_iter(self) -> Self::IntoIter {
1507        self.iter_mut()
1508    }
1509}
1510
1511impl<K, V, S> IntoIterator for OrderMap<K, V, S>
1512    where K: Hash + Eq,
1513          S: BuildHasher,
1514{
1515    type Item = (K, V);
1516    type IntoIter = IntoIter<K, V>;
1517    fn into_iter(self) -> Self::IntoIter {
1518        IntoIter {
1519            iter: self.entries.into_iter(),
1520        }
1521    }
1522}
1523
1524use std::ops::{Index, IndexMut};
1525
1526impl<'a, K, V, Q: ?Sized, S> Index<&'a Q> for OrderMap<K, V, S>
1527    where Q: Hash + Equivalent<K>,
1528          K: Hash + Eq,
1529          S: BuildHasher,
1530{
1531    type Output = V;
1532
1533    /// ***Panics*** if `key` is not present in the map.
1534    fn index(&self, key: &'a Q) -> &V {
1535        if let Some(v) = self.get(key) {
1536            v
1537        } else {
1538            panic!("OrderMap: key not found")
1539        }
1540    }
1541}
1542
1543/// Mutable indexing allows changing / updating values of key-value
1544/// pairs that are already present.
1545///
1546/// You can **not** insert new pairs with index syntax, use `.insert()`.
1547impl<'a, K, V, Q: ?Sized, S> IndexMut<&'a Q> for OrderMap<K, V, S>
1548    where Q: Hash + Equivalent<K>,
1549          K: Hash + Eq,
1550          S: BuildHasher,
1551{
1552    /// ***Panics*** if `key` is not present in the map.
1553    fn index_mut(&mut self, key: &'a Q) -> &mut V {
1554        if let Some(v) = self.get_mut(key) {
1555            v
1556        } else {
1557            panic!("OrderMap: key not found")
1558        }
1559    }
1560}
1561
1562impl<K, V, S> FromIterator<(K, V)> for OrderMap<K, V, S>
1563    where K: Hash + Eq,
1564          S: BuildHasher + Default,
1565{
1566    /// Create an `OrderMap` from the sequence of key-value pairs in the
1567    /// iterable.
1568    ///
1569    /// `from_iter` uses the same logic as `extend`. See
1570    /// [`extend`](#method.extend) for more details.
1571    fn from_iter<I: IntoIterator<Item=(K, V)>>(iterable: I) -> Self {
1572        let iter = iterable.into_iter();
1573        let (low, _) = iter.size_hint();
1574        let mut map = Self::with_capacity_and_hasher(low, <_>::default());
1575        map.extend(iter);
1576        map
1577    }
1578}
1579
1580impl<K, V, S> Extend<(K, V)> for OrderMap<K, V, S>
1581    where K: Hash + Eq,
1582          S: BuildHasher,
1583{
1584    /// Extend the map with all key-value pairs in the iterable.
1585    ///
1586    /// This is equivalent to calling [`insert`](#method.insert) for each of
1587    /// them in order, which means that for keys that already existed
1588    /// in the map, their value is updated but it keeps the existing order.
1589    ///
1590    /// New keys are inserted inserted in the order in the sequence. If
1591    /// equivalents of a key occur more than once, the last corresponding value
1592    /// prevails.
1593    fn extend<I: IntoIterator<Item=(K, V)>>(&mut self, iterable: I) {
1594        for (k, v) in iterable { self.insert(k, v); }
1595    }
1596}
1597
1598impl<'a, K, V, S> Extend<(&'a K, &'a V)> for OrderMap<K, V, S>
1599    where K: Hash + Eq + Copy,
1600          V: Copy,
1601          S: BuildHasher,
1602{
1603    /// Extend the map with all key-value pairs in the iterable.
1604    ///
1605    /// See the first extend method for more details.
1606    fn extend<I: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iterable: I) {
1607        self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)));
1608    }
1609}
1610
1611impl<K, V, S> Default for OrderMap<K, V, S>
1612    where S: BuildHasher + Default,
1613{
1614    /// Return an empty `OrderMap`
1615    fn default() -> Self {
1616        Self::with_capacity_and_hasher(0, S::default())
1617    }
1618}
1619
1620impl<K, V1, S1, V2, S2> PartialEq<OrderMap<K, V2, S2>> for OrderMap<K, V1, S1>
1621    where K: Hash + Eq,
1622          V1: PartialEq<V2>,
1623          S1: BuildHasher,
1624          S2: BuildHasher
1625{
1626    fn eq(&self, other: &OrderMap<K, V2, S2>) -> bool {
1627        if self.len() != other.len() {
1628            return false;
1629        }
1630
1631        self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
1632    }
1633}
1634
1635impl<K, V, S> Eq for OrderMap<K, V, S>
1636    where K: Eq + Hash,
1637          V: Eq,
1638          S: BuildHasher
1639{
1640}
1641
1642#[cfg(test)]
1643mod tests {
1644    use super::*;
1645    use util::enumerate;
1646
1647    #[test]
1648    fn it_works() {
1649        let mut map = OrderMap::new();
1650        assert_eq!(map.is_empty(), true);
1651        map.insert(1, ());
1652        map.insert(1, ());
1653        assert_eq!(map.len(), 1);
1654        assert!(map.get(&1).is_some());
1655        assert_eq!(map.is_empty(), false);
1656    }
1657
1658    #[test]
1659    fn new() {
1660        let map = OrderMap::<String, String>::new();
1661        println!("{:?}", map);
1662        assert_eq!(map.capacity(), 0);
1663        assert_eq!(map.len(), 0);
1664        assert_eq!(map.is_empty(), true);
1665    }
1666
1667    #[test]
1668    fn insert() {
1669        let insert = [0, 4, 2, 12, 8, 7, 11, 5];
1670        let not_present = [1, 3, 6, 9, 10];
1671        let mut map = OrderMap::with_capacity(insert.len());
1672
1673        for (i, &elt) in enumerate(&insert) {
1674            assert_eq!(map.len(), i);
1675            map.insert(elt, elt);
1676            assert_eq!(map.len(), i + 1);
1677            assert_eq!(map.get(&elt), Some(&elt));
1678            assert_eq!(map[&elt], elt);
1679        }
1680        println!("{:?}", map);
1681
1682        for &elt in &not_present {
1683            assert!(map.get(&elt).is_none());
1684        }
1685    }
1686
1687    #[test]
1688    fn insert_2() {
1689        let mut map = OrderMap::with_capacity(16);
1690
1691        let mut keys = vec![];
1692        keys.extend(0..16);
1693        keys.extend(128..267);
1694
1695        for &i in &keys {
1696            let old_map = map.clone();
1697            map.insert(i, ());
1698            for key in old_map.keys() {
1699                if !map.get(key).is_some() {
1700                    println!("old_map: {:?}", old_map);
1701                    println!("map: {:?}", map);
1702                    panic!("did not find {} in map", key);
1703                }
1704            }
1705        }
1706
1707        for &i in &keys {
1708            assert!(map.get(&i).is_some(), "did not find {}", i);
1709        }
1710    }
1711
1712    #[test]
1713    fn insert_order() {
1714        let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1715        let mut map = OrderMap::new();
1716
1717        for &elt in &insert {
1718            map.insert(elt, ());
1719        }
1720
1721        assert_eq!(map.keys().count(), map.len());
1722        assert_eq!(map.keys().count(), insert.len());
1723        for (a, b) in insert.iter().zip(map.keys()) {
1724            assert_eq!(a, b);
1725        }
1726        for (i, k) in (0..insert.len()).zip(map.keys()) {
1727            assert_eq!(map.get_index(i).unwrap().0, k);
1728        }
1729    }
1730
1731    #[test]
1732    fn grow() {
1733        let insert = [0, 4, 2, 12, 8, 7, 11];
1734        let not_present = [1, 3, 6, 9, 10];
1735        let mut map = OrderMap::with_capacity(insert.len());
1736
1737
1738        for (i, &elt) in enumerate(&insert) {
1739            assert_eq!(map.len(), i);
1740            map.insert(elt, elt);
1741            assert_eq!(map.len(), i + 1);
1742            assert_eq!(map.get(&elt), Some(&elt));
1743            assert_eq!(map[&elt], elt);
1744        }
1745
1746        println!("{:?}", map);
1747        for &elt in &insert {
1748            map.insert(elt * 10, elt);
1749        }
1750        for &elt in &insert {
1751            map.insert(elt * 100, elt);
1752        }
1753        for (i, &elt) in insert.iter().cycle().enumerate().take(100) {
1754            map.insert(elt * 100 + i as i32, elt);
1755        }
1756        println!("{:?}", map);
1757        for &elt in &not_present {
1758            assert!(map.get(&elt).is_none());
1759        }
1760    }
1761
1762    #[test]
1763    fn remove() {
1764        let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1765        let mut map = OrderMap::new();
1766
1767        for &elt in &insert {
1768            map.insert(elt, elt);
1769        }
1770
1771        assert_eq!(map.keys().count(), map.len());
1772        assert_eq!(map.keys().count(), insert.len());
1773        for (a, b) in insert.iter().zip(map.keys()) {
1774            assert_eq!(a, b);
1775        }
1776
1777        let remove_fail = [99, 77];
1778        let remove = [4, 12, 8, 7];
1779
1780        for &key in &remove_fail {
1781            assert!(map.swap_remove_full(&key).is_none());
1782        }
1783        println!("{:?}", map);
1784        for &key in &remove {
1785        //println!("{:?}", map);
1786            let index = map.get_full(&key).unwrap().0;
1787            assert_eq!(map.swap_remove_full(&key), Some((index, key, key)));
1788        }
1789        println!("{:?}", map);
1790
1791        for key in &insert {
1792            assert_eq!(map.get(key).is_some(), !remove.contains(key));
1793        }
1794        assert_eq!(map.len(), insert.len() - remove.len());
1795        assert_eq!(map.keys().count(), insert.len() - remove.len());
1796    }
1797
1798    #[test]
1799    fn remove_to_empty() {
1800        let mut map = ordermap! { 0 => 0, 4 => 4, 5 => 5 };
1801        map.swap_remove(&5).unwrap();
1802        map.swap_remove(&4).unwrap();
1803        map.swap_remove(&0).unwrap();
1804        assert!(map.is_empty());
1805    }
1806
1807    #[test]
1808    fn swap_remove_index() {
1809        let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
1810        let mut map = OrderMap::new();
1811
1812        for &elt in &insert {
1813            map.insert(elt, elt * 2);
1814        }
1815
1816        let mut vector = insert.to_vec();
1817        let remove_sequence = &[3, 3, 10, 4, 5, 4, 3, 0, 1];
1818
1819        // check that the same swap remove sequence on vec and map
1820        // have the same result.
1821        for &rm in remove_sequence {
1822            let out_vec = vector.swap_remove(rm);
1823            let (out_map, _) = map.swap_remove_index(rm).unwrap();
1824            assert_eq!(out_vec, out_map);
1825        }
1826        assert_eq!(vector.len(), map.len());
1827        for (a, b) in vector.iter().zip(map.keys()) {
1828            assert_eq!(a, b);
1829        }
1830    }
1831
1832    #[test]
1833    fn partial_eq_and_eq() {
1834        let mut map_a = OrderMap::new();
1835        map_a.insert(1, "1");
1836        map_a.insert(2, "2");
1837        let mut map_b = map_a.clone();
1838        assert_eq!(map_a, map_b);
1839        map_b.remove(&1);
1840        assert_ne!(map_a, map_b);
1841
1842        let map_c: OrderMap<_, String> = map_b.into_iter().map(|(k, v)| (k, v.to_owned())).collect();
1843        assert_ne!(map_a, map_c);
1844        assert_ne!(map_c, map_a);
1845    }
1846
1847    #[test]
1848    fn extend() {
1849        let mut map = OrderMap::new();
1850        map.extend(vec![(&1, &2), (&3, &4)]);
1851        map.extend(vec![(5, 6)]);
1852        assert_eq!(map.into_iter().collect::<Vec<_>>(), vec![(1, 2), (3, 4), (5, 6)]);
1853    }
1854
1855    #[test]
1856    fn entry() {
1857        let mut map = OrderMap::new();
1858        
1859        map.insert(1, "1");
1860        map.insert(2, "2");
1861        {
1862            let e = map.entry(3);
1863            assert_eq!(e.index(), 2);
1864            let e = e.or_insert("3");
1865            assert_eq!(e, &"3");
1866        }
1867        
1868        let e = map.entry(2);
1869        assert_eq!(e.index(), 1);
1870        assert_eq!(e.key(), &2);
1871        match e {
1872            Entry::Occupied(ref e) => assert_eq!(e.get(), &"2"),
1873            Entry::Vacant(_) => panic!()
1874        }
1875        assert_eq!(e.or_insert("4"), &"2");
1876    }
1877}