Skip to main content

trie/
map.rs

1// Copyright 2013-2026 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//! An ordered map based on a trie.
12
13pub use self::Entry::*;
14use self::TrieNode::*;
15
16use std::cmp::Ordering;
17use std::fmt::{self, Debug};
18use std::hash::{Hash, Hasher};
19use std::iter;
20use std::marker::PhantomData;
21use std::mem;
22use std::ops;
23use std::ptr;
24use std::slice;
25
26#[cfg(target_pointer_width = "32")]
27pub const USIZE_BITS: usize = 32;
28
29#[cfg(target_pointer_width = "64")]
30pub const USIZE_BITS: usize = 64;
31
32// FIXME(conventions): implement bounded iterators
33// FIXME(conventions): implement into_iter
34// FIXME(conventions): replace each_reverse by making iter DoubleEnded
35
36// FIXME: #5244: need to manually update the InternalNode constructor
37const SHIFT: usize = 4;
38const SIZE: usize = 1 << SHIFT;
39const MASK: usize = SIZE - 1;
40// The number of chunks that the key is divided into. Also the maximum depth of the map.
41const MAX_DEPTH: usize = USIZE_BITS / SHIFT;
42
43/// A map implemented as a radix trie.
44///
45/// Keys are split into sequences of 4 bits, which are used to place elements in
46/// 16-entry arrays which are nested to form a tree structure. Inserted elements are placed
47/// as close to the top of the tree as possible. The most significant bits of the key are used to
48/// assign the key to a node/bucket in the first layer. If there are no other elements keyed by
49/// the same 4 bits in the first layer, a leaf node will be created in the first layer.
50/// When keys coincide, the next 4 bits are used to assign the node to a bucket in the next layer,
51/// with this process continuing until an empty spot is found or there are no more bits left in the
52/// key. As a result, the maximum depth using 32-bit `usize` keys is 8. The worst collisions occur
53/// for very small numbers. For example, 1 and 2 are identical in all but their least significant
54/// 4 bits. If both numbers are used as keys, a chain of maximum length will be created to
55/// differentiate them.
56///
57/// # Examples
58///
59/// ```
60/// let mut map = trie::Map::new();
61/// map.insert(27, "Olaf");
62/// map.insert(1, "Edgar");
63/// map.insert(13, "Ruth");
64/// map.insert(1, "Martin");
65///
66/// assert_eq!(map.len(), 3);
67/// assert_eq!(map.get(&1), Some(&"Martin"));
68///
69/// if !map.contains_key(&90) {
70///     println!("Nobody is keyed 90");
71/// }
72///
73/// // Update a key
74/// match map.get_mut(&1) {
75///     Some(value) => *value = "Olga",
76///     None => (),
77/// }
78///
79/// map.remove(&13);
80/// assert_eq!(map.len(), 2);
81///
82/// // Print the key value pairs, ordered by key.
83/// for (key, value) in map.iter() {
84///     // Prints `1: Olga` then `27: Olaf`
85///     println!("{}: {}", key, value);
86/// }
87///
88/// map.clear();
89/// assert!(map.is_empty());
90/// ```
91#[derive(Clone)]
92pub struct Map<T> {
93    root: InternalNode<T>,
94    length: usize,
95}
96
97// An internal node holds SIZE child nodes, which may themselves contain more internal nodes.
98//
99// Throughout this implementation, "idx" is used to refer to a section of key that is used
100// to access a node. The layer of the tree directly below the root corresponds to idx 0.
101struct InternalNode<T> {
102    // The number of direct children which are external (i.e. that store a value).
103    count: usize,
104    children: [TrieNode<T>; SIZE],
105}
106
107// Each child of an InternalNode may be internal, in which case nesting continues,
108// external (containing a value), or empty
109#[derive(Clone)]
110enum TrieNode<T> {
111    Internal(Box<InternalNode<T>>),
112    External(usize, T),
113    Nothing,
114}
115
116impl<T: PartialEq> PartialEq for Map<T> {
117    fn eq(&self, other: &Map<T>) -> bool {
118        self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b)
119    }
120}
121
122impl<T: Eq> Eq for Map<T> {}
123
124impl<T: PartialOrd> PartialOrd for Map<T> {
125    #[inline]
126    fn partial_cmp(&self, other: &Map<T>) -> Option<Ordering> {
127        self.iter().partial_cmp(other.iter())
128    }
129}
130
131impl<T: Ord> Ord for Map<T> {
132    #[inline]
133    fn cmp(&self, other: &Map<T>) -> Ordering {
134        self.iter().cmp(other.iter())
135    }
136}
137
138impl<T: Debug> Debug for Map<T> {
139    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140        f.debug_map().entries(self.iter()).finish()
141    }
142}
143
144impl<T> Default for Map<T> {
145    #[inline]
146    fn default() -> Map<T> {
147        Map::new()
148    }
149}
150
151impl<T> Map<T> {
152    /// Creates an empty map.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// let mut map: trie::Map<&str> = trie::Map::new();
158    /// ```
159    #[inline]
160    pub fn new() -> Map<T> {
161        Map {
162            root: InternalNode::new(),
163            length: 0,
164        }
165    }
166
167    /// Visits all key-value pairs in reverse order. Aborts traversal when `f` returns `false`.
168    /// Returns `true` if `f` returns `true` for all elements.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// let map: trie::Map<&str> = [(1, "a"), (2, "b"), (3, "c")].iter().cloned().collect();
174    ///
175    /// let mut vec = vec![];
176    /// assert_eq!(true, map.each_reverse(|&key, &value| { vec.push((key, value)); true }));
177    /// assert_eq!(vec, [(3, "c"), (2, "b"), (1, "a")]);
178    ///
179    /// // Stop when we reach 2
180    /// let mut vec = vec![];
181    /// assert_eq!(false, map.each_reverse(|&key, &value| { vec.push(value); key != 2 }));
182    /// assert_eq!(vec, ["c", "b"]);
183    /// ```
184    #[inline]
185    pub fn each_reverse<'a, F>(&'a self, mut f: F) -> bool
186    where
187        F: FnMut(&usize, &'a T) -> bool,
188    {
189        self.root.each_reverse(&mut f)
190    }
191
192    /// Gets an iterator visiting all keys in ascending order by the keys.
193    /// The iterator's element type is `usize`.
194    pub fn keys(&self) -> Keys<'_, T> {
195        Keys(self.iter())
196    }
197
198    /// Gets an iterator visiting all values in ascending order by the keys.
199    /// The iterator's element type is `&'r T`.
200    pub fn values(&self) -> Values<'_, T> {
201        Values(self.iter())
202    }
203
204    /// Gets an iterator over the key-value pairs in the map, ordered by keys.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// let map: trie::Map<&str> = [(3, "c"), (1, "a"), (2, "b")].iter().cloned().collect();
210    ///
211    /// for (key, value) in map.iter() {
212    ///     println!("{}: {}", key, value);
213    /// }
214    /// ```
215    pub fn iter(&self) -> Iter<'_, T> {
216        let mut iter = unsafe { Iter::new() };
217        iter.stack[0] = self.root.children.iter();
218        iter.length = 1;
219        iter.remaining = self.length;
220
221        iter
222    }
223
224    /// Gets an iterator over the key-value pairs in the map, with the
225    /// ability to mutate the values.
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// let mut map: trie::Map<i32> = [(1, 2), (2, 4), (3, 6)].iter().cloned().collect();
231    ///
232    /// for (key, value) in map.iter_mut() {
233    ///     *value = -(key as i32);
234    /// }
235    ///
236    /// assert_eq!(map.get(&1), Some(&-1));
237    /// assert_eq!(map.get(&2), Some(&-2));
238    /// assert_eq!(map.get(&3), Some(&-3));
239    /// ```
240    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
241        let mut iter = unsafe { IterMut::new() };
242        iter.stack[0] = self.root.children.iter_mut();
243        iter.length = 1;
244        iter.remaining = self.length;
245
246        iter
247    }
248
249    /// Return the number of elements in the map.
250    ///
251    /// # Examples
252    ///
253    /// ```
254    /// let mut a = trie::Map::new();
255    /// assert_eq!(a.len(), 0);
256    /// a.insert(1, "a");
257    /// assert_eq!(a.len(), 1);
258    /// ```
259    #[inline]
260    pub fn len(&self) -> usize {
261        self.length
262    }
263
264    /// Return true if the map contains no elements.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// let mut a = trie::Map::new();
270    /// assert!(a.is_empty());
271    /// a.insert(1, "a");
272    /// assert!(!a.is_empty());
273    /// ```
274    #[inline]
275    pub fn is_empty(&self) -> bool {
276        self.len() == 0
277    }
278
279    /// Clears the map, removing all values.
280    ///
281    /// # Examples
282    ///
283    /// ```
284    /// let mut a = trie::Map::new();
285    /// a.insert(1, "a");
286    /// a.clear();
287    /// assert!(a.is_empty());
288    /// ```
289    #[inline]
290    pub fn clear(&mut self) {
291        self.root = InternalNode::new();
292        self.length = 0;
293    }
294
295    /// Returns a reference to the value corresponding to the key.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// let mut map = trie::Map::new();
301    /// map.insert(1, "a");
302    /// assert_eq!(map.get(&1), Some(&"a"));
303    /// assert_eq!(map.get(&2), None);
304    /// ```
305    #[inline]
306    pub fn get(&self, key: &usize) -> Option<&T> {
307        let mut node = &self.root;
308        let mut idx = 0;
309        loop {
310            match node.children[chunk(*key, idx)] {
311                Internal(ref x) => node = &**x,
312                External(stored, ref value) => {
313                    if stored == *key {
314                        return Some(value);
315                    } else {
316                        return None;
317                    }
318                }
319                Nothing => return None,
320            }
321            idx += 1;
322        }
323    }
324
325    /// Returns true if the map contains a value for the specified key.
326    ///
327    /// # Examples
328    ///
329    /// ```
330    /// let mut map = trie::Map::new();
331    /// map.insert(1, "a");
332    /// assert_eq!(map.contains_key(&1), true);
333    /// assert_eq!(map.contains_key(&2), false);
334    /// ```
335    #[inline]
336    pub fn contains_key(&self, key: &usize) -> bool {
337        self.get(key).is_some()
338    }
339
340    /// Returns a mutable reference to the value corresponding to the key.
341    ///
342    /// # Examples
343    ///
344    /// ```
345    /// let mut map = trie::Map::new();
346    /// map.insert(1, "a");
347    /// match map.get_mut(&1) {
348    ///     Some(x) => *x = "b",
349    ///     None => (),
350    /// }
351    /// assert_eq!(map[&1], "b");
352    /// ```
353    #[inline]
354    pub fn get_mut(&mut self, key: &usize) -> Option<&mut T> {
355        find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1)
356    }
357
358    /// Inserts a key-value pair from the map. If the key already had a value
359    /// present in the map, that value is returned. Otherwise, `None` is returned.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// let mut map = trie::Map::new();
365    /// assert_eq!(map.insert(37, "a"), None);
366    /// assert_eq!(map.is_empty(), false);
367    ///
368    /// map.insert(37, "b");
369    /// assert_eq!(map.insert(37, "c"), Some("b"));
370    /// assert_eq!(map[&37], "c");
371    /// ```
372    pub fn insert(&mut self, key: usize, value: T) -> Option<T> {
373        let (_, old_val) = insert(
374            &mut self.root.count,
375            &mut self.root.children[chunk(key, 0)],
376            key,
377            value,
378            1,
379        );
380        if old_val.is_none() {
381            self.length += 1
382        }
383        old_val
384    }
385
386    /// Removes a key from the map, returning the value at the key if the key
387    /// was previously in the map.
388    ///
389    /// # Examples
390    ///
391    /// ```
392    /// let mut map = trie::Map::new();
393    /// map.insert(1, "a");
394    /// assert_eq!(map.remove(&1), Some("a"));
395    /// assert_eq!(map.remove(&1), None);
396    /// ```
397    pub fn remove(&mut self, key: &usize) -> Option<T> {
398        let ret = remove(
399            &mut self.root.count,
400            &mut self.root.children[chunk(*key, 0)],
401            *key,
402            1,
403        );
404        if ret.is_some() {
405            self.length -= 1
406        }
407        ret
408    }
409}
410
411macro_rules! bound {
412    (
413        $iterator_name:ident,
414        // the current treemap
415        self = $this:expr,
416        // the key to look for
417        key = $key:expr,
418        // are we looking at the upper bound?
419        is_upper = $upper:expr,
420
421        // method name for iterating.
422        iter = $iter:ident,
423
424        // this is just an optional mut, but there's no 0-or-1 repeats yet.
425        mutability = ($($mut_:tt)*),
426        const = ($($const_:tt)*)
427    ) => {
428        {
429            // We need an unsafe pointer here because we are borrowing
430            // mutable references to the internals of each of these
431            // mutable nodes, while still using the outer node.
432            //
433            // However, we're allowed to flaunt rustc like this because we
434            // never actually modify the "shape" of the nodes. The only
435            // place that mutation is can actually occur is of the actual
436            // values of the map (as the return value of the
437            // iterator), i.e. we can never cause a deallocation of any
438            // InternalNodes so the raw pointer is always valid.
439            let this = $this;
440            let mut node = & $($mut_)* this.root as *$($mut_)* $($const_)* InternalNode<T>;
441
442            let key = $key;
443
444            let mut it = unsafe {$iterator_name::new()};
445            // everything else is zero'd, as we want.
446            it.remaining = this.length;
447
448            // this addr is necessary for the `Internal` pattern.
449            loop {
450                let children = unsafe { & $($mut_)* (*node).children };
451                // it.length is the current depth in the iterator and the
452                // current depth through the `usize` key we've traversed.
453                let child_id = chunk(key, it.length);
454                let (slice_idx, ret) = match & $($mut_)* children[child_id] {
455                    & $($mut_)* Internal(ref $($mut_)* n) => {
456                        node = (& $($mut_)* **n) as *$($mut_)* $($const_)* _;
457                        (child_id + 1, false)
458                    }
459                    & $($mut_)* External(stored, _) => {
460                        (if stored < key || ($upper && stored == key) {
461                            child_id + 1
462                        } else {
463                            child_id
464                        }, true)
465                    }
466                    & $($mut_)* Nothing => {
467                        (child_id + 1, true)
468                    }
469                };
470                // push to the stack.
471                it.stack[it.length] = children[slice_idx..].$iter();
472                it.length += 1;
473                if ret { break }
474            }
475
476            it
477        }
478    }
479}
480
481impl<T> Map<T> {
482    // If `upper` is true then returns upper_bound else returns lower_bound.
483    #[inline]
484    fn bound(&self, key: usize, upper: bool) -> Range<'_, T> {
485        Range(bound!(Iter, self = self,
486               key = key, is_upper = upper,
487               iter = iter,
488               mutability = (), const = (const)))
489    }
490
491    /// Gets an iterator pointing to the first key-value pair whose key is not less than `key`.
492    /// If all keys in the map are less than `key` an empty iterator is returned.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// let map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();
498    ///
499    /// assert_eq!(map.lower_bound(4).next(), Some((4, &"b")));
500    /// assert_eq!(map.lower_bound(5).next(), Some((6, &"c")));
501    /// assert_eq!(map.lower_bound(10).next(), None);
502    /// ```
503    pub fn lower_bound(&self, key: usize) -> Range<'_, T> {
504        self.bound(key, false)
505    }
506
507    /// Gets an iterator pointing to the first key-value pair whose key is greater than `key`.
508    /// If all keys in the map are not greater than `key` an empty iterator is returned.
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// let map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();
514    ///
515    /// assert_eq!(map.upper_bound(4).next(), Some((6, &"c")));
516    /// assert_eq!(map.upper_bound(5).next(), Some((6, &"c")));
517    /// assert_eq!(map.upper_bound(10).next(), None);
518    /// ```
519    pub fn upper_bound(&self, key: usize) -> Range<'_, T> {
520        self.bound(key, true)
521    }
522    // If `upper` is true then returns upper_bound else returns lower_bound.
523    #[inline]
524    fn bound_mut(&mut self, key: usize, upper: bool) -> RangeMut<'_, T> {
525        RangeMut(bound!(IterMut, self = self,
526               key = key, is_upper = upper,
527               iter = iter_mut,
528               mutability = (mut), const = ()))
529    }
530
531    /// Gets an iterator pointing to the first key-value pair whose key is not less than `key`.
532    /// If all keys in the map are less than `key` an empty iterator is returned.
533    ///
534    /// # Examples
535    ///
536    /// ```
537    /// let mut map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();
538    ///
539    /// assert_eq!(map.lower_bound_mut(4).next(), Some((4, &mut "b")));
540    /// assert_eq!(map.lower_bound_mut(5).next(), Some((6, &mut "c")));
541    /// assert_eq!(map.lower_bound_mut(10).next(), None);
542    ///
543    /// for (key, value) in map.lower_bound_mut(4) {
544    ///     *value = "changed";
545    /// }
546    ///
547    /// assert_eq!(map.get(&2), Some(&"a"));
548    /// assert_eq!(map.get(&4), Some(&"changed"));
549    /// assert_eq!(map.get(&6), Some(&"changed"));
550    /// ```
551    pub fn lower_bound_mut(&mut self, key: usize) -> RangeMut<'_, T> {
552        self.bound_mut(key, false)
553    }
554
555    /// Gets an iterator pointing to the first key-value pair whose key is greater than `key`.
556    /// If all keys in the map are not greater than `key` an empty iterator is returned.
557    ///
558    /// # Examples
559    ///
560    /// ```
561    /// let mut map: trie::Map<&str> = [(2, "a"), (4, "b"), (6, "c")].iter().cloned().collect();
562    ///
563    /// assert_eq!(map.upper_bound_mut(4).next(), Some((6, &mut "c")));
564    /// assert_eq!(map.upper_bound_mut(5).next(), Some((6, &mut "c")));
565    /// assert_eq!(map.upper_bound_mut(10).next(), None);
566    ///
567    /// for (key, value) in map.upper_bound_mut(4) {
568    ///     *value = "changed";
569    /// }
570    ///
571    /// assert_eq!(map.get(&2), Some(&"a"));
572    /// assert_eq!(map.get(&4), Some(&"b"));
573    /// assert_eq!(map.get(&6), Some(&"changed"));
574    /// ```
575    pub fn upper_bound_mut(&mut self, key: usize) -> RangeMut<'_, T> {
576        self.bound_mut(key, true)
577    }
578}
579
580impl<T> iter::FromIterator<(usize, T)> for Map<T> {
581    fn from_iter<I: IntoIterator<Item = (usize, T)>>(iter: I) -> Map<T> {
582        let mut map = Map::new();
583        map.extend(iter);
584        map
585    }
586}
587
588impl<T> Extend<(usize, T)> for Map<T> {
589    fn extend<I: IntoIterator<Item = (usize, T)>>(&mut self, iter: I) {
590        for (k, v) in iter {
591            self.insert(k, v);
592        }
593    }
594}
595
596impl<T: Hash> Hash for Map<T> {
597    fn hash<H: Hasher>(&self, state: &mut H) {
598        for elt in self.iter() {
599            elt.hash(state);
600        }
601    }
602}
603
604impl<'a, T> ops::Index<&'a usize> for Map<T> {
605    type Output = T;
606    #[inline]
607    fn index(&self, i: &'a usize) -> &T {
608        self.get(i).expect("key not present")
609    }
610}
611
612impl<'a, T> ops::IndexMut<&'a usize> for Map<T> {
613    #[inline]
614    fn index_mut(&mut self, i: &'a usize) -> &mut T {
615        self.get_mut(i).expect("key not present")
616    }
617}
618
619impl<T: Clone> Clone for InternalNode<T> {
620    #[inline]
621    fn clone(&self) -> InternalNode<T> {
622        let ch = &self.children;
623        InternalNode {
624            count: self.count,
625            children: [
626                ch[0].clone(),
627                ch[1].clone(),
628                ch[2].clone(),
629                ch[3].clone(),
630                ch[4].clone(),
631                ch[5].clone(),
632                ch[6].clone(),
633                ch[7].clone(),
634                ch[8].clone(),
635                ch[9].clone(),
636                ch[10].clone(),
637                ch[11].clone(),
638                ch[12].clone(),
639                ch[13].clone(),
640                ch[14].clone(),
641                ch[15].clone(),
642            ],
643        }
644    }
645}
646
647impl<T> InternalNode<T> {
648    #[inline]
649    fn new() -> InternalNode<T> {
650        // FIXME: #5244: [Nothing, ..SIZE] should be possible without implicit
651        // copyability
652        InternalNode {
653            count: 0,
654            children: [
655                Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing,
656                Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing,
657            ],
658        }
659    }
660}
661
662impl<T> InternalNode<T> {
663    fn each_reverse<'a, F>(&'a self, f: &mut F) -> bool
664    where
665        F: FnMut(&usize, &'a T) -> bool,
666    {
667        for elt in self.children.iter().rev() {
668            match *elt {
669                Internal(ref x) => {
670                    if !x.each_reverse(f) {
671                        return false;
672                    }
673                }
674                External(k, ref v) => {
675                    if !f(&k, v) {
676                        return false;
677                    }
678                }
679                Nothing => (),
680            }
681        }
682        true
683    }
684}
685
686// if this was done via a trait, the key could be generic
687#[inline]
688fn chunk(n: usize, idx: usize) -> usize {
689    let sh = USIZE_BITS - (SHIFT * (idx + 1));
690    (n >> sh) & MASK
691}
692
693fn find_mut<T>(child: &mut TrieNode<T>, key: usize, idx: usize) -> Option<&mut T> {
694    match *child {
695        External(stored, ref mut value) if stored == key => Some(value),
696        External(..) => None,
697        Internal(ref mut x) => find_mut(&mut x.children[chunk(key, idx)], key, idx + 1),
698        Nothing => None,
699    }
700}
701
702/// Inserts a new node for the given key and value, at or below `start_node`.
703///
704/// The index (`idx`) is the index of the next node, such that the start node
705/// was accessed via parent.children[chunk(key, idx - 1)].
706///
707/// The count is the external node counter for the start node's parent,
708/// which will be incremented only if `start_node` is transformed into a *new* external node.
709///
710/// Returns a mutable reference to the inserted value and an optional previous value.
711fn insert<'a, T>(
712    count: &mut usize,
713    start_node: &'a mut TrieNode<T>,
714    key: usize,
715    value: T,
716    idx: usize,
717) -> (&'a mut T, Option<T>) {
718    // We branch twice to avoid having to do the `replace` when we
719    // don't need to; this is much faster, especially for keys that
720    // have long shared prefixes.
721
722    let mut hack = false;
723    match *start_node {
724        Nothing => {
725            *count += 1;
726            *start_node = External(key, value);
727            match *start_node {
728                External(_, ref mut value_ref) => return (value_ref, None),
729                _ => unreachable!(),
730            }
731        }
732        Internal(ref mut x) => {
733            let x = &mut **x;
734            return insert(
735                &mut x.count,
736                &mut x.children[chunk(key, idx)],
737                key,
738                value,
739                idx + 1,
740            );
741        }
742        External(stored_key, _) if stored_key == key => {
743            hack = true;
744        }
745        _ => {}
746    }
747
748    if !hack {
749        // Conflict, an external node with differing keys.
750        // We replace the old node by an internal one, then re-insert the two values beneath it.
751        match mem::replace(start_node, Internal(Box::new(InternalNode::new()))) {
752            External(stored_key, stored_value) => {
753                match *start_node {
754                    Internal(ref mut new_node) => {
755                        let new_node = &mut **new_node;
756                        // Re-insert the old value.
757                        insert(
758                            &mut new_node.count,
759                            &mut new_node.children[chunk(stored_key, idx)],
760                            stored_key,
761                            stored_value,
762                            idx + 1,
763                        );
764
765                        // Insert the new value, and return a reference to it directly.
766                        return insert(
767                            &mut new_node.count,
768                            &mut new_node.children[chunk(key, idx)],
769                            key,
770                            value,
771                            idx + 1,
772                        );
773                    }
774                    // Value that was just copied disappeared.
775                    _ => unreachable!(),
776                }
777            }
778            // Logic error in previous match.
779            _ => unreachable!(),
780        }
781    }
782
783    if let External(_, ref mut stored_value) = *start_node {
784        // Swap in the new value and return the old.
785        let old_value = mem::replace(stored_value, value);
786        return (stored_value, Some(old_value));
787    }
788
789    unreachable!();
790}
791
792fn remove<T>(count: &mut usize, child: &mut TrieNode<T>, key: usize, idx: usize) -> Option<T> {
793    let (ret, this) = match *child {
794        External(stored, _) if stored == key => match mem::replace(child, Nothing) {
795            External(_, value) => (Some(value), true),
796            _ => unreachable!(),
797        },
798        External(..) => (None, false),
799        Internal(ref mut x) => {
800            let x = &mut **x;
801            let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)], key, idx + 1);
802            (ret, x.count == 0)
803        }
804        Nothing => (None, false),
805    };
806
807    if this {
808        *child = Nothing;
809        *count -= 1;
810    }
811    ret
812}
813
814/// A view into a single entry in a map, which may be vacant or occupied.
815pub enum Entry<'a, T: 'a> {
816    /// An occupied entry.
817    Occupied(OccupiedEntry<'a, T>),
818    /// A vacant entry.
819    Vacant(VacantEntry<'a, T>),
820}
821
822impl<'a, T> Entry<'a, T> {
823    /// Ensures a value is in the entry by inserting the default if empty, and returns
824    /// a mutable reference to the value in the entry.
825    pub fn or_insert(self, default: T) -> &'a mut T {
826        match self {
827            Occupied(entry) => entry.into_mut(),
828            Vacant(entry) => entry.insert(default),
829        }
830    }
831
832    /// Ensures a value is in the entry by inserting the result of the default function if empty,
833    /// and returns a mutable reference to the value in the entry.
834    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> &'a mut T {
835        match self {
836            Occupied(entry) => entry.into_mut(),
837            Vacant(entry) => entry.insert(default()),
838        }
839    }
840}
841
842/// A view into an occupied entry in a map.
843pub struct OccupiedEntry<'a, T: 'a> {
844    search_stack: SearchStack<'a, T>,
845}
846
847/// A view into a vacant entry in a map.
848pub struct VacantEntry<'a, T: 'a> {
849    search_stack: SearchStack<'a, T>,
850}
851
852/// A list of nodes encoding a path from the root of a map to a node.
853///
854/// Invariants:
855/// * The last node is either `External` or `Nothing`.
856/// * Pointers at indexes less than `length` can be safely dereferenced.
857///
858/// we can only use raw pointers, because of stacked borrows.
859/// Source:
860/// https://rust-unofficial.github.io/too-many-lists/fifth-stacked-borrows.html#managing-stacked-borrows
861struct SearchStack<'a, T: 'a> {
862    map: *mut Map<T>,
863    length: usize,
864    key: usize,
865    items: [*mut TrieNode<T>; MAX_DEPTH],
866    phantom: PhantomData<&'a mut Map<T>>,
867}
868
869impl<'a, T> SearchStack<'a, T> {
870    /// Creates a new search-stack with empty entries.
871    fn new(map: &'a mut Map<T>, key: usize) -> SearchStack<'a, T> {
872        SearchStack {
873            map,
874            length: 0,
875            key,
876            items: [ptr::null_mut(); MAX_DEPTH],
877            phantom: PhantomData,
878        }
879    }
880
881    fn push(&mut self, node: *mut TrieNode<T>) {
882        self.length += 1;
883        self.items[self.length - 1] = node;
884    }
885
886    fn peek(&self) -> *mut TrieNode<T> {
887        self.items[self.length - 1]
888    }
889
890    fn peek_ref(&self) -> &'a mut TrieNode<T> {
891        let item = self.items[self.length - 1];
892        unsafe { &mut *item }
893    }
894
895    fn pop_ref(&mut self) -> &'a mut TrieNode<T> {
896        self.length -= 1;
897        unsafe { &mut *self.items[self.length] }
898    }
899
900    fn is_empty(&self) -> bool {
901        self.length == 0
902    }
903
904    fn get_ref(&self, idx: usize) -> &'a mut TrieNode<T> {
905        assert!(idx < self.length);
906        unsafe { &mut *self.items[idx] }
907    }
908}
909
910// Implementation of SearchStack creation logic.
911// Once a SearchStack has been created the Entry methods are relatively straight-forward.
912impl<T> Map<T> {
913    /// Gets the given key's corresponding entry in the map for in-place manipulation.
914    #[inline]
915    pub fn entry(&mut self, key: usize) -> Entry<'_, T> {
916        // Create an empty search stack.
917        let mut search_stack = SearchStack::new(self, key);
918
919        // Unconditionally add the corresponding node from the first layer.
920        let first_node =
921            unsafe { (&mut (*search_stack.map).root.children[chunk(key, 0)]) as *mut _ };
922        search_stack.push(first_node);
923
924        // While no appropriate slot is found, keep descending down the Trie,
925        // adding nodes to the search stack.
926        let search_successful: bool;
927        loop {
928            match unsafe { next_child(search_stack.peek(), key, search_stack.length) } {
929                (Some(child), _) => search_stack.push(child),
930                (None, success) => {
931                    search_successful = success;
932                    break;
933                }
934            }
935        }
936
937        if search_successful {
938            Occupied(OccupiedEntry { search_stack })
939        } else {
940            Vacant(VacantEntry { search_stack })
941        }
942    }
943}
944
945/// Get a mutable pointer to the next child of a node, given a key and an idx.
946///
947/// The idx is the index of the next child, such that `node` was accessed via
948/// parent.children[chunk(key, idx - 1)].
949///
950/// Returns a tuple with an optional mutable pointer to the next child, and
951/// a boolean flag to indicate whether the external key node was found.
952///
953/// This function is safe only if `node` points to a valid `TrieNode`.
954#[inline]
955unsafe fn next_child<T>(
956    node: *mut TrieNode<T>,
957    key: usize,
958    idx: usize,
959) -> (Option<*mut TrieNode<T>>, bool) {
960    match unsafe { &mut *node } {
961        // If the node is internal, tell the caller to descend further.
962        &mut Internal(ref mut node_internal) => (
963            Some(&mut node_internal.children[chunk(key, idx)] as *mut _),
964            false,
965        ),
966        // If the node is external or empty, the search is complete.
967        // If the key doesn't match, node expansion will be done upon
968        // insertion. If it does match, we've found our node.
969        External(stored_key, _) if *stored_key == key => (None, true),
970        External(..) | Nothing => (None, false),
971    }
972}
973
974// NB: All these methods assume a correctly constructed occupied entry (matching the given key).
975impl<'a, T> OccupiedEntry<'a, T> {
976    /// Gets a reference to the value in the entry.
977    #[inline]
978    pub fn get(&self) -> &T {
979        match *self.search_stack.peek_ref() {
980            External(_, ref value) => value,
981            // Invalid SearchStack, non-external last node.
982            _ => unreachable!(),
983        }
984    }
985
986    /// Gets a mutable reference to the value in the entry.
987    #[inline]
988    pub fn get_mut(&mut self) -> &mut T {
989        match *self.search_stack.peek_ref() {
990            External(_, ref mut value) => value,
991            // Invalid SearchStack, non-external last node.
992            _ => unreachable!(),
993        }
994    }
995
996    /// Converts the OccupiedEntry into a mutable reference to the value in the entry,
997    /// with a lifetime bound to the map itself.
998    #[inline]
999    pub fn into_mut(self) -> &'a mut T {
1000        match *self.search_stack.peek_ref() {
1001            External(_, ref mut value) => value,
1002            // Invalid SearchStack, non-external last node.
1003            _ => unreachable!(),
1004        }
1005    }
1006
1007    /// Sets the value of the entry, and returns the entry's old value.
1008    #[inline]
1009    pub fn insert(&mut self, value: T) -> T {
1010        match *self.search_stack.peek_ref() {
1011            External(_, ref mut stored_value) => mem::replace(stored_value, value),
1012            // Invalid SearchStack, non-external last node.
1013            _ => unreachable!(),
1014        }
1015    }
1016
1017    /// Takes the value out of the entry, and returns it.
1018    #[inline]
1019    pub fn remove(self) -> T {
1020        // This function removes the external leaf-node, then unwinds the search-stack
1021        // deleting now-childless ancestors.
1022        let mut search_stack = self.search_stack;
1023
1024        // Extract the value from the leaf-node of interest.
1025        let leaf_node = mem::replace(search_stack.pop_ref(), Nothing);
1026
1027        let value = match leaf_node {
1028            External(_, value) => value,
1029            // Invalid SearchStack, non-external last node.
1030            _ => unreachable!(),
1031        };
1032
1033        // Iterate backwards through the search stack, deleting nodes if they are childless.
1034        // We compare each ancestor's parent count to 1 because each ancestor reached has just
1035        // had one of its children deleted.
1036        while !search_stack.is_empty() {
1037            let ancestor = search_stack.pop_ref();
1038            match *ancestor {
1039                Internal(ref mut internal) => {
1040                    // If stopping deletion, update the child count and break.
1041                    if internal.count != 1 {
1042                        internal.count -= 1;
1043                        break;
1044                    }
1045                }
1046                // Invalid SearchStack, non-internal ancestor node.
1047                _ => unreachable!(),
1048            }
1049            *ancestor = Nothing;
1050        }
1051
1052        // Decrement the length of the entire map, for the removed node.
1053        unsafe {
1054            (*search_stack.map).length -= 1;
1055        }
1056
1057        value
1058    }
1059}
1060
1061impl<'a, T> VacantEntry<'a, T> {
1062    /// Set the vacant entry to the given value.
1063    pub fn insert(self, value: T) -> &'a mut T {
1064        let search_stack = self.search_stack;
1065        let old_length = search_stack.length;
1066        let key = search_stack.key;
1067
1068        // Update the map's length for the new element.
1069        unsafe {
1070            (*search_stack.map).length += 1;
1071        }
1072
1073        // If there's only 1 node in the search stack, insert a new node below it at idx 1.
1074        if old_length == 1 {
1075            unsafe {
1076                // Note: Small hack to appease the borrow checker. Can't mutably borrow root.count
1077                let mut temp = (*search_stack.map).root.count;
1078                let (value_ref, _) = insert(&mut temp, search_stack.get_ref(0), key, value, 1);
1079                (*search_stack.map).root.count = temp;
1080                value_ref
1081            }
1082        }
1083        // Otherwise, find the predecessor of the last stack node, and insert as normal.
1084        else {
1085            match *search_stack.get_ref(old_length - 2) {
1086                Internal(ref mut parent) => {
1087                    let parent = &mut **parent;
1088                    let (value_ref, _) = insert(
1089                        &mut parent.count,
1090                        &mut parent.children[chunk(key, old_length - 1)],
1091                        key,
1092                        value,
1093                        old_length,
1094                    );
1095                    value_ref
1096                }
1097                // Invalid SearchStack, non-internal ancestor node.
1098                _ => unreachable!(),
1099            }
1100        }
1101    }
1102}
1103
1104/// A forward iterator over a map.
1105pub struct Iter<'a, T: 'a> {
1106    stack: [slice::Iter<'a, TrieNode<T>>; MAX_DEPTH],
1107    length: usize,
1108    remaining: usize,
1109}
1110
1111impl<'a, T> Clone for Iter<'a, T> {
1112    #[cfg(target_pointer_width = "32")]
1113    fn clone(&self) -> Iter<'a, T> {
1114        Iter {
1115            stack: [
1116                self.stack[0].clone(),
1117                self.stack[1].clone(),
1118                self.stack[2].clone(),
1119                self.stack[3].clone(),
1120                self.stack[4].clone(),
1121                self.stack[5].clone(),
1122                self.stack[6].clone(),
1123                self.stack[7].clone(),
1124            ],
1125            ..*self
1126        }
1127    }
1128
1129    #[cfg(target_pointer_width = "64")]
1130    fn clone(&self) -> Iter<'a, T> {
1131        Iter {
1132            stack: [
1133                self.stack[0].clone(),
1134                self.stack[1].clone(),
1135                self.stack[2].clone(),
1136                self.stack[3].clone(),
1137                self.stack[4].clone(),
1138                self.stack[5].clone(),
1139                self.stack[6].clone(),
1140                self.stack[7].clone(),
1141                self.stack[8].clone(),
1142                self.stack[9].clone(),
1143                self.stack[10].clone(),
1144                self.stack[11].clone(),
1145                self.stack[12].clone(),
1146                self.stack[13].clone(),
1147                self.stack[14].clone(),
1148                self.stack[15].clone(),
1149            ],
1150            ..*self
1151        }
1152    }
1153}
1154
1155/// A forward iterator over the key-value pairs of a map, with the
1156/// values being mutable.
1157pub struct IterMut<'a, T: 'a> {
1158    stack: [slice::IterMut<'a, TrieNode<T>>; MAX_DEPTH],
1159    length: usize,
1160    remaining: usize,
1161}
1162
1163/// A forward iterator over the keys of a map.
1164pub struct Keys<'a, T: 'a>(Iter<'a, T>);
1165
1166impl<'a, T> Clone for Keys<'a, T> {
1167    fn clone(&self) -> Keys<'a, T> {
1168        Keys(self.0.clone())
1169    }
1170}
1171
1172impl<'a, T> Iterator for Keys<'a, T> {
1173    type Item = usize;
1174    fn next(&mut self) -> Option<usize> {
1175        self.0.next().map(|e| e.0)
1176    }
1177    fn size_hint(&self) -> (usize, Option<usize>) {
1178        self.0.size_hint()
1179    }
1180}
1181
1182impl<'a, T> ExactSizeIterator for Keys<'a, T> {}
1183
1184/// A forward iterator over the values of a map.
1185pub struct Values<'a, T: 'a>(Iter<'a, T>);
1186
1187impl<'a, T> Clone for Values<'a, T> {
1188    fn clone(&self) -> Values<'a, T> {
1189        Values(self.0.clone())
1190    }
1191}
1192
1193impl<'a, T> Iterator for Values<'a, T> {
1194    type Item = &'a T;
1195    fn next(&mut self) -> Option<&'a T> {
1196        self.0.next().map(|e| e.1)
1197    }
1198    fn size_hint(&self) -> (usize, Option<usize>) {
1199        self.0.size_hint()
1200    }
1201}
1202
1203impl<'a, T> ExactSizeIterator for Values<'a, T> {}
1204
1205macro_rules! iterator_impl {
1206    ($name:ident,
1207     iter = $iter:ident,
1208     mutability = $($mut_:tt)*) => {
1209        impl<'a, T> $name<'a, T> {
1210            // Create new zero'd iterator. We have a thin gilding of safety by
1211            // using init rather than uninit, so that the worst that can happen
1212            // from failing to initialise correctly after calling these is a
1213            // segfault.
1214            #[cfg(target_pointer_width="32")]
1215            unsafe fn new() -> $name<'a, T> {
1216                $name {
1217                    remaining: 0,
1218                    length: 0,
1219                    // ick :( ... at least the compiler will tell us if we screwed up.
1220                    stack: [IntoIterator::into_iter((& $($mut_)*[])),
1221                            IntoIterator::into_iter((& $($mut_)*[])),
1222                            IntoIterator::into_iter((& $($mut_)*[])),
1223                            IntoIterator::into_iter((& $($mut_)*[])),
1224
1225                            IntoIterator::into_iter((& $($mut_)*[])),
1226                            IntoIterator::into_iter((& $($mut_)*[])),
1227                            IntoIterator::into_iter((& $($mut_)*[])),
1228                            IntoIterator::into_iter((& $($mut_)*[])),
1229                            ]
1230                }
1231            }
1232
1233            #[cfg(target_pointer_width="64")]
1234            unsafe fn new() -> $name<'a, T> {
1235                $name {
1236                    remaining: 0,
1237                    length: 0,
1238                    stack: [IntoIterator::into_iter(& $($mut_)*[]),
1239                            IntoIterator::into_iter(& $($mut_)*[]),
1240                            IntoIterator::into_iter(& $($mut_)*[]),
1241                            IntoIterator::into_iter(& $($mut_)*[]),
1242
1243                            IntoIterator::into_iter(& $($mut_)*[]),
1244                            IntoIterator::into_iter(& $($mut_)*[]),
1245                            IntoIterator::into_iter(& $($mut_)*[]),
1246                            IntoIterator::into_iter(& $($mut_)*[]),
1247
1248                            IntoIterator::into_iter(& $($mut_)*[]),
1249                            IntoIterator::into_iter(& $($mut_)*[]),
1250                            IntoIterator::into_iter(& $($mut_)*[]),
1251                            IntoIterator::into_iter(& $($mut_)*[]),
1252
1253                            IntoIterator::into_iter(& $($mut_)*[]),
1254                            IntoIterator::into_iter(& $($mut_)*[]),
1255                            IntoIterator::into_iter(& $($mut_)*[]),
1256                            IntoIterator::into_iter(& $($mut_)*[]),
1257                            ]
1258                }
1259            }
1260        }
1261
1262        impl<'a, T> Iterator for $name<'a, T> {
1263                type Item = (usize, &'a $($mut_)* T);
1264                // you might wonder why we're not even trying to act within the
1265                // rules, and are just manipulating raw pointers like there's no
1266                // such thing as invalid pointers and memory unsafety. The
1267                // reason is performance, without doing this we can get the
1268                // (now replaced) bench_iter_large microbenchmark down to about
1269                // 30000 ns/iter (using .unsafe_get to index self.stack directly, 38000
1270                // ns/iter with [] checked indexing), but this smashes that down
1271                // to 13500 ns/iter.
1272                //
1273                // Fortunately, it's still safe...
1274                //
1275                // We have an invariant that every Internal node
1276                // corresponds to one push to self.stack, and one pop,
1277                // nested appropriately. self.stack has enough storage
1278                // to store the maximum depth of Internal nodes in the
1279                // trie (8 on 32-bit platforms, 16 on 64-bit).
1280                fn next(&mut self) -> Option<(usize, &'a $($mut_)* T)> {
1281                    let start_ptr = self.stack.as_mut_ptr();
1282
1283                    unsafe {
1284                        // write_ptr is the next place to write to the stack.
1285                        // invariant: start_ptr <= write_ptr < end of the
1286                        // vector.
1287                        let mut write_ptr = start_ptr.offset(self.length as isize);
1288                        while write_ptr != start_ptr {
1289                            // indexing back one is safe, since write_ptr >
1290                            // start_ptr now.
1291                            match (*write_ptr.offset(-1)).next() {
1292                                // exhausted this iterator (i.e. finished this
1293                                // Internal node), so pop from the stack.
1294                                //
1295                                // don't bother clearing the memory, because the
1296                                // next time we use it we'll've written to it
1297                                // first.
1298                                None => write_ptr = write_ptr.offset(-1),
1299                                Some(child) => {
1300                                    match *child {
1301                                        Internal(ref $($mut_)* node) => {
1302                                            // going down a level, so push
1303                                            // to the stack (this is the
1304                                            // write referenced above)
1305                                            *write_ptr = node.children.$iter();
1306                                            write_ptr = write_ptr.offset(1);
1307                                        }
1308                                        External(key, ref $($mut_)* value) => {
1309                                            self.remaining -= 1;
1310                                            // store the new length of the
1311                                            // stack, based on our current
1312                                            // position.
1313                                            self.length = (write_ptr as usize
1314                                                            - start_ptr as usize) /
1315                                                mem::size_of::<slice::Iter<'_, TrieNode<T>>>();
1316
1317                                            return Some((key, value));
1318                                        }
1319                                        Nothing => {}
1320                                    }
1321                                }
1322                            }
1323                        }
1324                    }
1325                    return None;
1326                }
1327
1328                #[inline]
1329                fn size_hint(&self) -> (usize, Option<usize>) {
1330                    (self.remaining, Some(self.remaining))
1331                }
1332            }
1333
1334        impl<'a, T> ExactSizeIterator for $name<'a, T> {
1335            fn len(&self) -> usize { self.remaining }
1336        }
1337    }
1338}
1339
1340iterator_impl! { Iter, iter = iter, mutability = }
1341iterator_impl! { IterMut, iter = iter_mut, mutability = mut }
1342
1343/// A bounded forward iterator over a map.
1344pub struct Range<'a, T: 'a>(Iter<'a, T>);
1345
1346impl<'a, T> Clone for Range<'a, T> {
1347    fn clone(&self) -> Range<'a, T> {
1348        Range(self.0.clone())
1349    }
1350}
1351
1352impl<'a, T> Iterator for Range<'a, T> {
1353    type Item = (usize, &'a T);
1354    fn next(&mut self) -> Option<(usize, &'a T)> {
1355        self.0.next()
1356    }
1357    fn size_hint(&self) -> (usize, Option<usize>) {
1358        (0, Some(self.0.remaining))
1359    }
1360}
1361
1362/// A bounded forward iterator over the key-value pairs of a map, with the
1363/// values being mutable.
1364pub struct RangeMut<'a, T: 'a>(IterMut<'a, T>);
1365
1366impl<'a, T> Iterator for RangeMut<'a, T> {
1367    type Item = (usize, &'a mut T);
1368    fn next(&mut self) -> Option<(usize, &'a mut T)> {
1369        self.0.next()
1370    }
1371    fn size_hint(&self) -> (usize, Option<usize>) {
1372        (0, Some(self.0.remaining))
1373    }
1374}
1375
1376impl<'a, T> IntoIterator for &'a Map<T> {
1377    type Item = (usize, &'a T);
1378    type IntoIter = Iter<'a, T>;
1379    fn into_iter(self) -> Iter<'a, T> {
1380        self.iter()
1381    }
1382}
1383
1384impl<'a, T> IntoIterator for &'a mut Map<T> {
1385    type Item = (usize, &'a mut T);
1386    type IntoIter = IterMut<'a, T>;
1387    fn into_iter(self) -> IterMut<'a, T> {
1388        self.iter_mut()
1389    }
1390}
1391
1392#[cfg(test)]
1393mod test {
1394    use std::collections::hash_map::DefaultHasher;
1395    use std::hash::{Hash, Hasher};
1396    use std::hint::black_box;
1397
1398    use super::Entry::*;
1399    use super::TrieNode::*;
1400    use super::{InternalNode, Map};
1401
1402    fn check_integrity<T>(trie: &InternalNode<T>) {
1403        assert!(trie.count != 0);
1404
1405        let mut sum = 0;
1406
1407        for x in trie.children.iter() {
1408            match *x {
1409                Nothing => (),
1410                Internal(ref y) => {
1411                    check_integrity(&**y);
1412                    sum += 1
1413                }
1414                External(_, _) => sum += 1,
1415            }
1416        }
1417
1418        assert_eq!(sum, trie.count);
1419    }
1420
1421    #[test]
1422    fn test_find_mut() {
1423        let mut m = Map::new();
1424        assert!(m.insert(1, 12).is_none());
1425        assert!(m.insert(2, 8).is_none());
1426        assert!(m.insert(5, 14).is_none());
1427        let new = 100;
1428        match m.get_mut(&5) {
1429            None => panic!(),
1430            Some(x) => *x = new,
1431        }
1432        assert_eq!(m.get(&5), Some(&new));
1433    }
1434
1435    #[test]
1436    fn test_find_mut_missing() {
1437        let mut m = Map::new();
1438        assert!(m.get_mut(&0).is_none());
1439        assert!(m.insert(1, 12).is_none());
1440        assert!(m.get_mut(&0).is_none());
1441        assert!(m.insert(2, 8).is_none());
1442        assert!(m.get_mut(&0).is_none());
1443    }
1444
1445    #[test]
1446    fn test_step() {
1447        let mut trie = Map::new();
1448        let n = 300;
1449
1450        for x in (1..n).step_by(2) {
1451            assert!(trie.insert(x, x + 1).is_none());
1452            assert!(trie.contains_key(&x));
1453            check_integrity(&trie.root);
1454        }
1455
1456        for x in (0..n).step_by(2) {
1457            assert!(!trie.contains_key(&x));
1458            assert!(trie.insert(x, x + 1).is_none());
1459            check_integrity(&trie.root);
1460        }
1461
1462        for x in 0..n {
1463            assert!(trie.contains_key(&x));
1464            assert!(trie.insert(x, x + 1).is_some());
1465            check_integrity(&trie.root);
1466        }
1467
1468        for x in (1..n).step_by(2) {
1469            assert!(trie.remove(&x).is_some());
1470            assert!(!trie.contains_key(&x));
1471            check_integrity(&trie.root);
1472        }
1473
1474        for x in (0..n).step_by(2) {
1475            assert!(trie.contains_key(&x));
1476            assert!(trie.insert(x, x + 1).is_some());
1477            check_integrity(&trie.root);
1478        }
1479    }
1480
1481    #[test]
1482    fn test_each_reverse() {
1483        let mut m = Map::new();
1484
1485        assert!(m.insert(3, 6).is_none());
1486        assert!(m.insert(0, 0).is_none());
1487        assert!(m.insert(4, 8).is_none());
1488        assert!(m.insert(2, 4).is_none());
1489        assert!(m.insert(1, 2).is_none());
1490
1491        let mut n = 5;
1492        let mut vec: Vec<&i32> = vec![];
1493        m.each_reverse(|k, v| {
1494            n -= 1;
1495            assert_eq!(*k, n);
1496            vec.push(v);
1497            true
1498        });
1499        assert_eq!(vec, [&8, &6, &4, &2, &0]);
1500    }
1501
1502    #[test]
1503    fn test_each_reverse_break() {
1504        let mut m = Map::new();
1505
1506        for x in (usize::MAX - 10000..usize::MAX).rev() {
1507            m.insert(x, x / 2);
1508        }
1509
1510        let mut n = usize::MAX - 1;
1511        m.each_reverse(|k, v| {
1512            if n == usize::MAX - 5000 {
1513                false
1514            } else {
1515                assert!(n > usize::MAX - 5000);
1516
1517                assert_eq!(*k, n);
1518                assert_eq!(*v, n / 2);
1519                n -= 1;
1520                true
1521            }
1522        });
1523    }
1524
1525    #[test]
1526    fn test_insert() {
1527        let mut m = Map::new();
1528        assert_eq!(m.insert(1, 2), None);
1529        assert_eq!(m.insert(1, 3), Some(2));
1530        assert_eq!(m.insert(1, 4), Some(3));
1531    }
1532
1533    #[test]
1534    fn test_remove() {
1535        let mut m = Map::new();
1536        m.insert(1, 2);
1537        assert_eq!(m.remove(&1), Some(2));
1538        assert_eq!(m.remove(&1), None);
1539    }
1540
1541    #[test]
1542    fn test_from_iter() {
1543        let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
1544
1545        let map: Map<i32> = xs.iter().cloned().collect();
1546
1547        for &(k, v) in xs.iter() {
1548            assert_eq!(map.get(&k), Some(&v));
1549        }
1550    }
1551
1552    #[test]
1553    fn test_keys() {
1554        let vec = [(1, 'a'), (2, 'b'), (3, 'c')];
1555        let map: Map<_> = vec.iter().cloned().collect();
1556        let keys: Vec<_> = map.keys().collect();
1557        assert_eq!(keys.len(), 3);
1558        assert!(keys.contains(&1));
1559        assert!(keys.contains(&2));
1560        assert!(keys.contains(&3));
1561    }
1562
1563    #[test]
1564    fn test_values() {
1565        let vec = [(1, 'a'), (2, 'b'), (3, 'c')];
1566        let map: Map<_> = vec.iter().cloned().collect();
1567        let values: Vec<_> = map.values().cloned().collect();
1568        assert_eq!(values.len(), 3);
1569        assert!(values.contains(&'a'));
1570        assert!(values.contains(&'b'));
1571        assert!(values.contains(&'c'));
1572    }
1573
1574    #[test]
1575    fn test_iteration() {
1576        let empty_map: Map<usize> = Map::new();
1577        assert_eq!(empty_map.iter().next(), None);
1578
1579        let first = usize::MAX - 10000;
1580        let last = usize::MAX;
1581
1582        let mut map = Map::new();
1583        for x in (first..last).rev() {
1584            map.insert(x, x / 2);
1585        }
1586
1587        let mut i = 0;
1588        for (k, &v) in map.iter() {
1589            assert_eq!(k, first + i);
1590            assert_eq!(v, k / 2);
1591            i += 1;
1592        }
1593        assert_eq!(i, last - first);
1594    }
1595
1596    #[test]
1597    fn test_mut_iter() {
1598        let mut empty_map: Map<usize> = Map::new();
1599        assert!(empty_map.iter_mut().next().is_none());
1600
1601        let first = usize::MAX - 10000;
1602        let last = usize::MAX;
1603
1604        let mut map = Map::new();
1605        for x in (first..last).rev() {
1606            map.insert(x, x / 2);
1607        }
1608
1609        let mut i = 0;
1610        for (k, v) in map.iter_mut() {
1611            assert_eq!(k, first + i);
1612            *v -= k / 2;
1613            i += 1;
1614        }
1615        assert_eq!(i, last - first);
1616
1617        assert!(map.iter().all(|(_, &v)| v == 0));
1618    }
1619
1620    #[test]
1621    fn test_bound() {
1622        let empty_map: Map<usize> = Map::new();
1623        assert_eq!(empty_map.lower_bound(0).next(), None);
1624        assert_eq!(empty_map.upper_bound(0).next(), None);
1625
1626        let last = 999;
1627        let step = 3;
1628        let value = 42;
1629
1630        let mut map: Map<usize> = Map::new();
1631        for x in (0..last).step_by(step) {
1632            assert!(x % step == 0);
1633            map.insert(x, value);
1634        }
1635
1636        for i in 0..last - step {
1637            let mut lb = map.lower_bound(i);
1638            let mut ub = map.upper_bound(i);
1639            let next_key = i - i % step + step;
1640            let next_pair = (next_key, &value);
1641            if i % step == 0 {
1642                assert_eq!(lb.next(), Some((i, &value)));
1643            } else {
1644                assert_eq!(lb.next(), Some(next_pair));
1645            }
1646            assert_eq!(ub.next(), Some(next_pair));
1647        }
1648
1649        let mut lb = map.lower_bound(last - step);
1650        assert_eq!(lb.next(), Some((last - step, &value)));
1651        let mut ub = map.upper_bound(last - step);
1652        assert_eq!(ub.next(), None);
1653
1654        for i in last - step + 1..last {
1655            let mut lb = map.lower_bound(i);
1656            assert_eq!(lb.next(), None);
1657            let mut ub = map.upper_bound(i);
1658            assert_eq!(ub.next(), None);
1659        }
1660    }
1661
1662    #[test]
1663    fn test_mut_bound() {
1664        let empty_map: Map<usize> = Map::new();
1665        assert_eq!(empty_map.lower_bound(0).next(), None);
1666        assert_eq!(empty_map.upper_bound(0).next(), None);
1667
1668        let mut m_lower = Map::new();
1669        let mut m_upper = Map::new();
1670        for i in 0..100 {
1671            m_lower.insert(2 * i, 4 * i);
1672            m_upper.insert(2 * i, 4 * i);
1673        }
1674
1675        for i in 0..199 {
1676            let mut lb_it = m_lower.lower_bound_mut(i);
1677            let (k, v) = lb_it.next().unwrap();
1678            let lb = i + i % 2;
1679            assert_eq!(lb, k);
1680            *v -= k;
1681        }
1682
1683        for i in 0..198 {
1684            let mut ub_it = m_upper.upper_bound_mut(i);
1685            let (k, v) = ub_it.next().unwrap();
1686            let ub = i + 2 - i % 2;
1687            assert_eq!(ub, k);
1688            *v -= k;
1689        }
1690
1691        assert!(m_lower.lower_bound_mut(199).next().is_none());
1692        assert!(m_upper.upper_bound_mut(198).next().is_none());
1693
1694        assert!(m_lower.iter().all(|(_, &x)| x == 0));
1695        assert!(m_upper.iter().all(|(_, &x)| x == 0));
1696    }
1697
1698    #[test]
1699    fn test_clone() {
1700        let mut a = Map::new();
1701
1702        a.insert(1, 'a');
1703        a.insert(2, 'b');
1704        a.insert(3, 'c');
1705
1706        assert!(a.clone() == a);
1707    }
1708
1709    #[test]
1710    fn test_eq() {
1711        let mut a = Map::new();
1712        let mut b = Map::new();
1713
1714        assert!(a == b);
1715        assert!(a.insert(0, 5).is_none());
1716        assert!(a != b);
1717        assert!(b.insert(0, 4).is_none());
1718        assert!(a != b);
1719        assert!(a.insert(5, 19).is_none());
1720        assert!(a != b);
1721        assert!(b.insert(0, 5).is_some());
1722        assert!(a != b);
1723        assert!(b.insert(5, 19).is_none());
1724        assert!(a == b);
1725    }
1726
1727    #[test]
1728    fn test_lt() {
1729        let mut a = Map::new();
1730        let mut b = Map::new();
1731
1732        assert!((a >= b) && (b >= a));
1733        assert!(b.insert(2, 5).is_none());
1734        assert!(a < b);
1735        assert!(a.insert(2, 7).is_none());
1736        assert!((a >= b) && b < a);
1737        assert!(b.insert(1, 0).is_none());
1738        assert!(b < a);
1739        assert!(a.insert(0, 6).is_none());
1740        assert!(a < b);
1741        assert!(a.insert(6, 2).is_none());
1742        assert!(a < b && (b >= a));
1743    }
1744
1745    #[test]
1746    fn test_ord() {
1747        let mut a = Map::new();
1748        let mut b = Map::new();
1749
1750        assert!(a == b);
1751        assert!(a.insert(1, 1).is_none());
1752        assert!(a > b && a >= b);
1753        assert!(b < a && b <= a);
1754        assert!(b.insert(2, 2).is_none());
1755        assert!(b > a && b >= a);
1756        assert!(a < b && a <= b);
1757    }
1758
1759    #[test]
1760    fn test_hash() {
1761        fn hash<T: Hash>(t: &T) -> u64 {
1762            let mut s = DefaultHasher::new();
1763            t.hash(&mut s);
1764            s.finish()
1765        }
1766
1767        let mut x = Map::new();
1768        let mut y = Map::new();
1769
1770        assert!(hash(&x) == hash(&y));
1771        x.insert(1, 'a');
1772        x.insert(2, 'b');
1773        x.insert(3, 'c');
1774
1775        y.insert(3, 'c');
1776        y.insert(2, 'b');
1777        y.insert(1, 'a');
1778
1779        assert!(hash(&x) == hash(&y));
1780    }
1781
1782    #[test]
1783    fn test_debug() {
1784        let mut map = Map::new();
1785        let empty: Map<char> = Map::new();
1786
1787        map.insert(1, 'a');
1788        map.insert(2, 'b');
1789
1790        assert_eq!(format!("{:?}", map), "{1: 'a', 2: 'b'}");
1791        assert_eq!(format!("{:?}", empty), "{}");
1792    }
1793
1794    #[test]
1795    fn test_index() {
1796        let mut map = Map::new();
1797
1798        map.insert(1, 2);
1799        map.insert(2, 1);
1800        map.insert(3, 4);
1801
1802        assert_eq!(map[&2], 1);
1803    }
1804
1805    #[test]
1806    #[should_panic]
1807    fn test_index_nonexistent() {
1808        let mut map = Map::new();
1809
1810        map.insert(1, 2);
1811        map.insert(2, 1);
1812        map.insert(3, 4);
1813
1814        black_box(map[&4]);
1815    }
1816
1817    // Number of items to insert into the map during entry tests.
1818    // The tests rely on it being even.
1819    const SQUARES_UPPER_LIM: usize = 128;
1820
1821    /// Make a map storing i^2 for i in [0, 128)
1822    fn squares_map() -> Map<usize> {
1823        let mut map = Map::new();
1824        for i in 0..SQUARES_UPPER_LIM {
1825            map.insert(i, i * i);
1826        }
1827        map
1828    }
1829
1830    #[test]
1831    fn test_entry_get() {
1832        let mut map = squares_map();
1833
1834        for i in 0..SQUARES_UPPER_LIM {
1835            match map.entry(i) {
1836                Occupied(slot) => assert_eq!(slot.get(), &(i * i)),
1837                Vacant(_) => panic!("Key not found."),
1838            }
1839        }
1840        check_integrity(&map.root);
1841    }
1842
1843    #[test]
1844    fn test_entry_get_mut() {
1845        let mut map = squares_map();
1846
1847        // Change the entries to cubes.
1848        for i in 0..SQUARES_UPPER_LIM {
1849            match map.entry(i) {
1850                Occupied(mut e) => {
1851                    *e.get_mut() = i * i * i;
1852                }
1853                Vacant(_) => panic!("Key not found."),
1854            }
1855            assert_eq!(map.get(&i).unwrap(), &(i * i * i));
1856        }
1857
1858        check_integrity(&map.root);
1859    }
1860
1861    #[test]
1862    fn test_entry_into_mut() {
1863        let mut map = Map::new();
1864        map.insert(3, 6);
1865
1866        let value_ref = match map.entry(3) {
1867            Occupied(e) => e.into_mut(),
1868            Vacant(_) => panic!("Entry not found."),
1869        };
1870
1871        assert_eq!(*value_ref, 6);
1872    }
1873
1874    #[test]
1875    fn test_entry_take() {
1876        let mut map = squares_map();
1877        assert_eq!(map.len(), SQUARES_UPPER_LIM);
1878
1879        // Remove every odd key, checking that the correct value is returned.
1880        for i in (1..SQUARES_UPPER_LIM).step_by(2) {
1881            match map.entry(i) {
1882                Occupied(e) => assert_eq!(e.remove(), i * i),
1883                Vacant(_) => panic!("Key not found."),
1884            }
1885        }
1886
1887        check_integrity(&map.root);
1888
1889        // Check that the values for even keys remain unmodified.
1890        for i in (0..SQUARES_UPPER_LIM).step_by(2) {
1891            assert_eq!(map.get(&i).unwrap(), &(i * i));
1892        }
1893
1894        assert_eq!(map.len(), SQUARES_UPPER_LIM / 2);
1895    }
1896
1897    #[test]
1898    fn test_occupied_entry_set() {
1899        let mut map = squares_map();
1900
1901        // Change all the entries to cubes.
1902        for i in 0..SQUARES_UPPER_LIM {
1903            match map.entry(i) {
1904                Occupied(mut e) => assert_eq!(e.insert(i * i * i), i * i),
1905                Vacant(_) => panic!("Key not found."),
1906            }
1907            assert_eq!(map.get(&i).unwrap(), &(i * i * i));
1908        }
1909        check_integrity(&map.root);
1910    }
1911
1912    #[test]
1913    fn test_vacant_entry_set() {
1914        let mut map = Map::new();
1915
1916        for i in 0..SQUARES_UPPER_LIM {
1917            match map.entry(i) {
1918                Vacant(e) => {
1919                    // Insert i^2.
1920                    let inserted_val = e.insert(i * i);
1921                    assert_eq!(*inserted_val, i * i);
1922
1923                    // Update it to i^3 using the returned mutable reference.
1924                    *inserted_val = i * i * i;
1925                }
1926                _ => panic!("Non-existent key found."),
1927            }
1928            assert_eq!(map.get(&i).unwrap(), &(i * i * i));
1929        }
1930
1931        check_integrity(&map.root);
1932        assert_eq!(map.len(), SQUARES_UPPER_LIM);
1933    }
1934
1935    #[test]
1936    fn test_single_key() {
1937        let mut map = Map::new();
1938        map.insert(1, 2);
1939
1940        if let Occupied(e) = map.entry(1) {
1941            e.remove();
1942        }
1943    }
1944}