]> git.lizzy.rs Git - rust.git/blob - src/libcollections/btree/map.rs
Rollup merge of #22005 - nagisa:obsolete-ctx, r=alexcrichton
[rust.git] / src / libcollections / btree / map.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // This implementation is largely based on the high-level description and analysis of B-Trees
12 // found in *Open Data Structures* (ODS). Although our implementation does not use any of
13 // the source found in ODS, if one wishes to review the high-level design of this structure, it
14 // can be freely downloaded at http://opendatastructures.org/. Its contents are as of this
15 // writing (August 2014) freely licensed under the following Creative Commons Attribution
16 // License: [CC BY 2.5 CA](http://creativecommons.org/licenses/by/2.5/ca/).
17
18 use self::Entry::*;
19
20 use core::prelude::*;
21
22 use core::borrow::BorrowFrom;
23 use core::cmp::Ordering;
24 use core::default::Default;
25 use core::fmt::Debug;
26 use core::hash::{Hash, Hasher};
27 use core::iter::{Map, FromIterator, IntoIterator};
28 use core::ops::{Index, IndexMut};
29 use core::{iter, fmt, mem};
30 use Bound::{self, Included, Excluded, Unbounded};
31
32 use ring_buf::RingBuf;
33
34 use self::Continuation::{Continue, Finished};
35 use self::StackOp::*;
36 use super::node::ForceResult::{Leaf, Internal};
37 use super::node::TraversalItem::{self, Elem, Edge};
38 use super::node::{Traversal, MutTraversal, MoveTraversal};
39 use super::node::{self, Node, Found, GoDown};
40
41 /// A map based on a B-Tree.
42 ///
43 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
44 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
45 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
46 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
47 /// is done is *very* inefficient for modern computer architectures. In particular, every element
48 /// is stored in its own individually heap-allocated node. This means that every single insertion
49 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
50 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
51 /// the BST strategy.
52 ///
53 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
54 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
55 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
56 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
57 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
58 /// the node using binary search. As a compromise, one could also perform a linear search
59 /// that initially only checks every i<sup>th</sup> element for some choice of i.
60 ///
61 /// Currently, our implementation simply performs naive linear search. This provides excellent
62 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
63 /// would like to further explore choosing the optimal search strategy based on the choice of B,
64 /// and possibly other factors. Using linear search, searching for a random element is expected
65 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
66 /// however, performance is excellent.
67 #[derive(Clone)]
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub struct BTreeMap<K, V> {
70     root: Node<K, V>,
71     length: usize,
72     depth: usize,
73     b: usize,
74 }
75
76 /// An abstract base over-which all other BTree iterators are built.
77 struct AbsIter<T> {
78     traversals: RingBuf<T>,
79     size: usize,
80 }
81
82 /// An iterator over a BTreeMap's entries.
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct Iter<'a, K: 'a, V: 'a> {
85     inner: AbsIter<Traversal<'a, K, V>>
86 }
87
88 /// A mutable iterator over a BTreeMap's entries.
89 #[stable(feature = "rust1", since = "1.0.0")]
90 pub struct IterMut<'a, K: 'a, V: 'a> {
91     inner: AbsIter<MutTraversal<'a, K, V>>
92 }
93
94 /// An owning iterator over a BTreeMap's entries.
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct IntoIter<K, V> {
97     inner: AbsIter<MoveTraversal<K, V>>
98 }
99
100 /// An iterator over a BTreeMap's keys.
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub struct Keys<'a, K: 'a, V: 'a> {
103     inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
104 }
105
106 /// An iterator over a BTreeMap's values.
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub struct Values<'a, K: 'a, V: 'a> {
109     inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
110 }
111
112 /// An iterator over a sub-range of BTreeMap's entries.
113 pub struct Range<'a, K: 'a, V: 'a> {
114     inner: AbsIter<Traversal<'a, K, V>>
115 }
116
117 /// A mutable iterator over a sub-range of BTreeMap's entries.
118 pub struct RangeMut<'a, K: 'a, V: 'a> {
119     inner: AbsIter<MutTraversal<'a, K, V>>
120 }
121
122 /// A view into a single entry in a map, which may either be vacant or occupied.
123 #[unstable(feature = "collections",
124            reason = "precise API still under development")]
125 pub enum Entry<'a, K:'a, V:'a> {
126     /// A vacant Entry
127     Vacant(VacantEntry<'a, K, V>),
128     /// An occupied Entry
129     Occupied(OccupiedEntry<'a, K, V>),
130 }
131
132 /// A vacant Entry.
133 #[unstable(feature = "collections",
134            reason = "precise API still under development")]
135 pub struct VacantEntry<'a, K:'a, V:'a> {
136     key: K,
137     stack: stack::SearchStack<'a, K, V, node::handle::Edge, node::handle::Leaf>,
138 }
139
140 /// An occupied Entry.
141 #[unstable(feature = "collections",
142            reason = "precise API still under development")]
143 pub struct OccupiedEntry<'a, K:'a, V:'a> {
144     stack: stack::SearchStack<'a, K, V, node::handle::KV, node::handle::LeafOrInternal>,
145 }
146
147 impl<K: Ord, V> BTreeMap<K, V> {
148     /// Makes a new empty BTreeMap with a reasonable choice for B.
149     #[stable(feature = "rust1", since = "1.0.0")]
150     pub fn new() -> BTreeMap<K, V> {
151         //FIXME(Gankro): Tune this as a function of size_of<K/V>?
152         BTreeMap::with_b(6)
153     }
154
155     /// Makes a new empty BTreeMap with the given B.
156     ///
157     /// B cannot be less than 2.
158     pub fn with_b(b: usize) -> BTreeMap<K, V> {
159         assert!(b > 1, "B must be greater than 1");
160         BTreeMap {
161             length: 0,
162             depth: 1,
163             root: Node::make_leaf_root(b),
164             b: b,
165         }
166     }
167
168     /// Clears the map, removing all values.
169     ///
170     /// # Examples
171     ///
172     /// ```
173     /// use std::collections::BTreeMap;
174     ///
175     /// let mut a = BTreeMap::new();
176     /// a.insert(1, "a");
177     /// a.clear();
178     /// assert!(a.is_empty());
179     /// ```
180     #[stable(feature = "rust1", since = "1.0.0")]
181     pub fn clear(&mut self) {
182         let b = self.b;
183         // avoid recursive destructors by manually traversing the tree
184         for _ in mem::replace(self, BTreeMap::with_b(b)) {};
185     }
186
187     // Searching in a B-Tree is pretty straightforward.
188     //
189     // Start at the root. Try to find the key in the current node. If we find it, return it.
190     // If it's not in there, follow the edge *before* the smallest key larger than
191     // the search key. If no such key exists (they're *all* smaller), then just take the last
192     // edge in the node. If we're in a leaf and we don't find our key, then it's not
193     // in the tree.
194
195     /// Returns a reference to the value corresponding to the key.
196     ///
197     /// The key may be any borrowed form of the map's key type, but the ordering
198     /// on the borrowed form *must* match the ordering on the key type.
199     ///
200     /// # Examples
201     ///
202     /// ```
203     /// use std::collections::BTreeMap;
204     ///
205     /// let mut map = BTreeMap::new();
206     /// map.insert(1, "a");
207     /// assert_eq!(map.get(&1), Some(&"a"));
208     /// assert_eq!(map.get(&2), None);
209     /// ```
210     #[stable(feature = "rust1", since = "1.0.0")]
211     pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where Q: BorrowFrom<K> + Ord {
212         let mut cur_node = &self.root;
213         loop {
214             match Node::search(cur_node, key) {
215                 Found(handle) => return Some(handle.into_kv().1),
216                 GoDown(handle) => match handle.force() {
217                     Leaf(_) => return None,
218                     Internal(internal_handle) => {
219                         cur_node = internal_handle.into_edge();
220                         continue;
221                     }
222                 }
223             }
224         }
225     }
226
227     /// Returns true if the map contains a value for the specified key.
228     ///
229     /// The key may be any borrowed form of the map's key type, but the ordering
230     /// on the borrowed form *must* match the ordering on the key type.
231     ///
232     /// # Examples
233     ///
234     /// ```
235     /// use std::collections::BTreeMap;
236     ///
237     /// let mut map = BTreeMap::new();
238     /// map.insert(1, "a");
239     /// assert_eq!(map.contains_key(&1), true);
240     /// assert_eq!(map.contains_key(&2), false);
241     /// ```
242     #[stable(feature = "rust1", since = "1.0.0")]
243     pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where Q: BorrowFrom<K> + Ord {
244         self.get(key).is_some()
245     }
246
247     /// Returns a mutable reference to the value corresponding to the key.
248     ///
249     /// The key may be any borrowed form of the map's key type, but the ordering
250     /// on the borrowed form *must* match the ordering on the key type.
251     ///
252     /// # Examples
253     ///
254     /// ```
255     /// use std::collections::BTreeMap;
256     ///
257     /// let mut map = BTreeMap::new();
258     /// map.insert(1, "a");
259     /// match map.get_mut(&1) {
260     ///     Some(x) => *x = "b",
261     ///     None => (),
262     /// }
263     /// assert_eq!(map[1], "b");
264     /// ```
265     // See `get` for implementation notes, this is basically a copy-paste with mut's added
266     #[stable(feature = "rust1", since = "1.0.0")]
267     pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: BorrowFrom<K> + Ord {
268         // temp_node is a Borrowck hack for having a mutable value outlive a loop iteration
269         let mut temp_node = &mut self.root;
270         loop {
271             let cur_node = temp_node;
272             match Node::search(cur_node, key) {
273                 Found(handle) => return Some(handle.into_kv_mut().1),
274                 GoDown(handle) => match handle.force() {
275                     Leaf(_) => return None,
276                     Internal(internal_handle) => {
277                         temp_node = internal_handle.into_edge_mut();
278                         continue;
279                     }
280                 }
281             }
282         }
283     }
284
285     // Insertion in a B-Tree is a bit complicated.
286     //
287     // First we do the same kind of search described in `find`. But we need to maintain a stack of
288     // all the nodes/edges in our search path. If we find a match for the key we're trying to
289     // insert, just swap the vals and return the old ones. However, when we bottom out in a leaf,
290     // we attempt to insert our key-value pair at the same location we would want to follow another
291     // edge.
292     //
293     // If the node has room, then this is done in the obvious way by shifting elements. However,
294     // if the node itself is full, we split node into two, and give its median key-value
295     // pair to its parent to insert the new node with. Of course, the parent may also be
296     // full, and insertion can propagate until we reach the root. If we reach the root, and
297     // it is *also* full, then we split the root and place the two nodes under a newly made root.
298     //
299     // Note that we subtly deviate from Open Data Structures in our implementation of split.
300     // ODS describes inserting into the node *regardless* of its capacity, and then
301     // splitting *afterwards* if it happens to be overfull. However, this is inefficient.
302     // Instead, we split beforehand, and then insert the key-value pair into the appropriate
303     // result node. This has two consequences:
304     //
305     // 1) While ODS produces a left node of size B-1, and a right node of size B,
306     // we may potentially reverse this. However, this shouldn't effect the analysis.
307     //
308     // 2) While ODS may potentially return the pair we *just* inserted after
309     // the split, we will never do this. Again, this shouldn't effect the analysis.
310
311     /// Inserts a key-value pair from the map. If the key already had a value
312     /// present in the map, that value is returned. Otherwise, `None` is returned.
313     ///
314     /// # Examples
315     ///
316     /// ```
317     /// use std::collections::BTreeMap;
318     ///
319     /// let mut map = BTreeMap::new();
320     /// assert_eq!(map.insert(37, "a"), None);
321     /// assert_eq!(map.is_empty(), false);
322     ///
323     /// map.insert(37, "b");
324     /// assert_eq!(map.insert(37, "c"), Some("b"));
325     /// assert_eq!(map[37], "c");
326     /// ```
327     #[stable(feature = "rust1", since = "1.0.0")]
328     pub fn insert(&mut self, mut key: K, mut value: V) -> Option<V> {
329         // This is a stack of rawptrs to nodes paired with indices, respectively
330         // representing the nodes and edges of our search path. We have to store rawptrs
331         // because as far as Rust is concerned, we can mutate aliased data with such a
332         // stack. It is of course correct, but what it doesn't know is that we will only
333         // be popping and using these ptrs one at a time in child-to-parent order. The alternative
334         // to doing this is to take the Nodes from their parents. This actually makes
335         // borrowck *really* happy and everything is pretty smooth. However, this creates
336         // *tons* of pointless writes, and requires us to always walk all the way back to
337         // the root after an insertion, even if we only needed to change a leaf. Therefore,
338         // we accept this potential unsafety and complexity in the name of performance.
339         //
340         // Regardless, the actual dangerous logic is completely abstracted away from BTreeMap
341         // by the stack module. All it can do is immutably read nodes, and ask the search stack
342         // to proceed down some edge by index. This makes the search logic we'll be reusing in a
343         // few different methods much neater, and of course drastically improves safety.
344         let mut stack = stack::PartialSearchStack::new(self);
345
346         loop {
347             let result = stack.with(move |pusher, node| {
348                 // Same basic logic as found in `find`, but with PartialSearchStack mediating the
349                 // actual nodes for us
350                 return match Node::search(node, &key) {
351                     Found(mut handle) => {
352                         // Perfect match, swap the values and return the old one
353                         mem::swap(handle.val_mut(), &mut value);
354                         Finished(Some(value))
355                     },
356                     GoDown(handle) => {
357                         // We need to keep searching, try to get the search stack
358                         // to go down further
359                         match handle.force() {
360                             Leaf(leaf_handle) => {
361                                 // We've reached a leaf, perform the insertion here
362                                 pusher.seal(leaf_handle).insert(key, value);
363                                 Finished(None)
364                             }
365                             Internal(internal_handle) => {
366                                 // We've found the subtree to insert this key/value pair in,
367                                 // keep searching
368                                 Continue((pusher.push(internal_handle), key, value))
369                             }
370                         }
371                     }
372                 }
373             });
374             match result {
375                 Finished(ret) => { return ret; },
376                 Continue((new_stack, renewed_key, renewed_val)) => {
377                     stack = new_stack;
378                     key = renewed_key;
379                     value = renewed_val;
380                 }
381             }
382         }
383     }
384
385     // Deletion is the most complicated operation for a B-Tree.
386     //
387     // First we do the same kind of search described in
388     // `find`. But we need to maintain a stack of all the nodes/edges in our search path.
389     // If we don't find the key, then we just return `None` and do nothing. If we do find the
390     // key, we perform two operations: remove the item, and then possibly handle underflow.
391     //
392     // # removing the item
393     //      If the node is a leaf, we just remove the item, and shift
394     //      any items after it back to fill the hole.
395     //
396     //      If the node is an internal node, we *swap* the item with the smallest item in
397     //      in its right subtree (which must reside in a leaf), and then revert to the leaf
398     //      case
399     //
400     // # handling underflow
401     //      After removing an item, there may be too few items in the node. We want nodes
402     //      to be mostly full for efficiency, although we make an exception for the root, which
403     //      may have as few as one item. If this is the case, we may first try to steal
404     //      an item from our left or right neighbour.
405     //
406     //      To steal from the left (right) neighbour,
407     //      we take the largest (smallest) item and child from it. We then swap the taken item
408     //      with the item in their mutual parent that separates them, and then insert the
409     //      parent's item and the taken child into the first (last) index of the underflowed node.
410     //
411     //      However, stealing has the possibility of underflowing our neighbour. If this is the
412     //      case, we instead *merge* with our neighbour. This of course reduces the number of
413     //      children in the parent. Therefore, we also steal the item that separates the now
414     //      merged nodes, and insert it into the merged node.
415     //
416     //      Merging may cause the parent to underflow. If this is the case, then we must repeat
417     //      the underflow handling process on the parent. If merging merges the last two children
418     //      of the root, then we replace the root with the merged node.
419
420     /// Removes a key from the map, returning the value at the key if the key
421     /// was previously in the map.
422     ///
423     /// The key may be any borrowed form of the map's key type, but the ordering
424     /// on the borrowed form *must* match the ordering on the key type.
425     ///
426     /// # Examples
427     ///
428     /// ```
429     /// use std::collections::BTreeMap;
430     ///
431     /// let mut map = BTreeMap::new();
432     /// map.insert(1, "a");
433     /// assert_eq!(map.remove(&1), Some("a"));
434     /// assert_eq!(map.remove(&1), None);
435     /// ```
436     #[stable(feature = "rust1", since = "1.0.0")]
437     pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> where Q: BorrowFrom<K> + Ord {
438         // See `swap` for a more thorough description of the stuff going on in here
439         let mut stack = stack::PartialSearchStack::new(self);
440         loop {
441             let result = stack.with(move |pusher, node| {
442                 return match Node::search(node, key) {
443                     Found(handle) => {
444                         // Perfect match. Terminate the stack here, and remove the entry
445                         Finished(Some(pusher.seal(handle).remove()))
446                     },
447                     GoDown(handle) => {
448                         // We need to keep searching, try to go down the next edge
449                         match handle.force() {
450                             // We're at a leaf; the key isn't in here
451                             Leaf(_) => Finished(None),
452                             Internal(internal_handle) => Continue(pusher.push(internal_handle))
453                         }
454                     }
455                 }
456             });
457             match result {
458                 Finished(ret) => return ret,
459                 Continue(new_stack) => stack = new_stack
460             }
461         }
462     }
463 }
464
465 impl<K, V> IntoIterator for BTreeMap<K, V> {
466     type Iter = IntoIter<K, V>;
467
468     fn into_iter(self) -> IntoIter<K, V> {
469         self.into_iter()
470     }
471 }
472
473 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
474     type Iter = Iter<'a, K, V>;
475
476     fn into_iter(self) -> Iter<'a, K, V> {
477         self.iter()
478     }
479 }
480
481 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
482     type Iter = IterMut<'a, K, V>;
483
484     fn into_iter(mut self) -> IterMut<'a, K, V> {
485         self.iter_mut()
486     }
487 }
488
489 /// A helper enum useful for deciding whether to continue a loop since we can't
490 /// return from a closure
491 enum Continuation<A, B> {
492     Continue(A),
493     Finished(B)
494 }
495
496 /// The stack module provides a safe interface for constructing and manipulating a stack of ptrs
497 /// to nodes. By using this module much better safety guarantees can be made, and more search
498 /// boilerplate gets cut out.
499 mod stack {
500     use core::prelude::*;
501     use core::marker;
502     use core::mem;
503     use core::ops::{Deref, DerefMut};
504     use super::BTreeMap;
505     use super::super::node::{self, Node, Fit, Split, Internal, Leaf};
506     use super::super::node::handle;
507     use vec::Vec;
508
509     /// A generic mutable reference, identical to `&mut` except for the fact that its lifetime
510     /// parameter is invariant. This means that wherever an `IdRef` is expected, only an `IdRef`
511     /// with the exact requested lifetime can be used. This is in contrast to normal references,
512     /// where `&'static` can be used in any function expecting any lifetime reference.
513     pub struct IdRef<'id, T: 'id> {
514         inner: &'id mut T,
515         marker: marker::InvariantLifetime<'id>
516     }
517
518     impl<'id, T> Deref for IdRef<'id, T> {
519         type Target = T;
520
521         fn deref(&self) -> &T {
522             &*self.inner
523         }
524     }
525
526     impl<'id, T> DerefMut for IdRef<'id, T> {
527         fn deref_mut(&mut self) -> &mut T {
528             &mut *self.inner
529         }
530     }
531
532     type StackItem<K, V> = node::Handle<*mut Node<K, V>, handle::Edge, handle::Internal>;
533     type Stack<K, V> = Vec<StackItem<K, V>>;
534
535     /// A `PartialSearchStack` handles the construction of a search stack.
536     pub struct PartialSearchStack<'a, K:'a, V:'a> {
537         map: &'a mut BTreeMap<K, V>,
538         stack: Stack<K, V>,
539         next: *mut Node<K, V>,
540     }
541
542     /// A `SearchStack` represents a full path to an element or an edge of interest. It provides
543     /// methods depending on the type of what the path points to for removing an element, inserting
544     /// a new element, and manipulating to element at the top of the stack.
545     pub struct SearchStack<'a, K:'a, V:'a, Type, NodeType> {
546         map: &'a mut BTreeMap<K, V>,
547         stack: Stack<K, V>,
548         top: node::Handle<*mut Node<K, V>, Type, NodeType>,
549     }
550
551     /// A `PartialSearchStack` that doesn't hold a a reference to the next node, and is just
552     /// just waiting for a `Handle` to that next node to be pushed. See `PartialSearchStack::with`
553     /// for more details.
554     pub struct Pusher<'id, 'a, K:'a, V:'a> {
555         map: &'a mut BTreeMap<K, V>,
556         stack: Stack<K, V>,
557         marker: marker::InvariantLifetime<'id>
558     }
559
560     impl<'a, K, V> PartialSearchStack<'a, K, V> {
561         /// Creates a new PartialSearchStack from a BTreeMap by initializing the stack with the
562         /// root of the tree.
563         pub fn new(map: &'a mut BTreeMap<K, V>) -> PartialSearchStack<'a, K, V> {
564             let depth = map.depth;
565
566             PartialSearchStack {
567                 next: &mut map.root as *mut _,
568                 map: map,
569                 stack: Vec::with_capacity(depth),
570             }
571         }
572
573         /// Breaks up the stack into a `Pusher` and the next `Node`, allowing the given closure
574         /// to interact with, search, and finally push the `Node` onto the stack. The passed in
575         /// closure must be polymorphic on the `'id` lifetime parameter, as this statically
576         /// ensures that only `Handle`s from the correct `Node` can be pushed.
577         ///
578         /// The reason this works is that the `Pusher` has an `'id` parameter, and will only accept
579         /// handles with the same `'id`. The closure could only get references with that lifetime
580         /// through its arguments or through some other `IdRef` that it has lying around. However,
581         /// no other `IdRef` could possibly work - because the `'id` is held in an invariant
582         /// parameter, it would need to have precisely the correct lifetime, which would mean that
583         /// at least one of the calls to `with` wouldn't be properly polymorphic, wanting a
584         /// specific lifetime instead of the one that `with` chooses to give it.
585         ///
586         /// See also Haskell's `ST` monad, which uses a similar trick.
587         pub fn with<T, F: for<'id> FnOnce(Pusher<'id, 'a, K, V>,
588                                           IdRef<'id, Node<K, V>>) -> T>(self, closure: F) -> T {
589             let pusher = Pusher {
590                 map: self.map,
591                 stack: self.stack,
592                 marker: marker::InvariantLifetime
593             };
594             let node = IdRef {
595                 inner: unsafe { &mut *self.next },
596                 marker: marker::InvariantLifetime
597             };
598
599             closure(pusher, node)
600         }
601     }
602
603     impl<'id, 'a, K, V> Pusher<'id, 'a, K, V> {
604         /// Pushes the requested child of the stack's current top on top of the stack. If the child
605         /// exists, then a new PartialSearchStack is yielded. Otherwise, a VacantSearchStack is
606         /// yielded.
607         pub fn push(mut self, mut edge: node::Handle<IdRef<'id, Node<K, V>>,
608                                                      handle::Edge,
609                                                      handle::Internal>)
610                     -> PartialSearchStack<'a, K, V> {
611             self.stack.push(edge.as_raw());
612             PartialSearchStack {
613                 map: self.map,
614                 stack: self.stack,
615                 next: edge.edge_mut() as *mut _,
616             }
617         }
618
619         /// Converts the PartialSearchStack into a SearchStack.
620         pub fn seal<Type, NodeType>
621                    (self, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>)
622                     -> SearchStack<'a, K, V, Type, NodeType> {
623             SearchStack {
624                 map: self.map,
625                 stack: self.stack,
626                 top: handle.as_raw(),
627             }
628         }
629     }
630
631     impl<'a, K, V, NodeType> SearchStack<'a, K, V, handle::KV, NodeType> {
632         /// Gets a reference to the value the stack points to.
633         pub fn peek(&self) -> &V {
634             unsafe { self.top.from_raw().into_kv().1 }
635         }
636
637         /// Gets a mutable reference to the value the stack points to.
638         pub fn peek_mut(&mut self) -> &mut V {
639             unsafe { self.top.from_raw_mut().into_kv_mut().1 }
640         }
641
642         /// Converts the stack into a mutable reference to the value it points to, with a lifetime
643         /// tied to the original tree.
644         pub fn into_top(mut self) -> &'a mut V {
645             unsafe {
646                 mem::copy_mut_lifetime(
647                     self.map,
648                     self.top.from_raw_mut().val_mut()
649                 )
650             }
651         }
652     }
653
654     impl<'a, K, V> SearchStack<'a, K, V, handle::KV, handle::Leaf> {
655         /// Removes the key and value in the top element of the stack, then handles underflows as
656         /// described in BTree's pop function.
657         fn remove_leaf(mut self) -> V {
658             self.map.length -= 1;
659
660             // Remove the key-value pair from the leaf that this search stack points to.
661             // Then, note if the leaf is underfull, and promptly forget the leaf and its ptr
662             // to avoid ownership issues.
663             let (value, mut underflow) = unsafe {
664                 let (_, value) = self.top.from_raw_mut().remove_as_leaf();
665                 let underflow = self.top.from_raw().node().is_underfull();
666                 (value, underflow)
667             };
668
669             loop {
670                 match self.stack.pop() {
671                     None => {
672                         // We've reached the root, so no matter what, we're done. We manually
673                         // access the root via the tree itself to avoid creating any dangling
674                         // pointers.
675                         if self.map.root.len() == 0 && !self.map.root.is_leaf() {
676                             // We've emptied out the root, so make its only child the new root.
677                             // If it's a leaf, we just let it become empty.
678                             self.map.depth -= 1;
679                             self.map.root.hoist_lone_child();
680                         }
681                         return value;
682                     }
683                     Some(mut handle) => {
684                         if underflow {
685                             // Underflow! Handle it!
686                             unsafe {
687                                 handle.from_raw_mut().handle_underflow();
688                                 underflow = handle.from_raw().node().is_underfull();
689                             }
690                         } else {
691                             // All done!
692                             return value;
693                         }
694                     }
695                 }
696             }
697         }
698     }
699
700     impl<'a, K, V> SearchStack<'a, K, V, handle::KV, handle::LeafOrInternal> {
701         /// Removes the key and value in the top element of the stack, then handles underflows as
702         /// described in BTree's pop function.
703         pub fn remove(self) -> V {
704             // Ensure that the search stack goes to a leaf. This is necessary to perform deletion
705             // in a BTree. Note that this may put the tree in an inconsistent state (further
706             // described in into_leaf's comments), but this is immediately fixed by the
707             // removing the value we want to remove
708             self.into_leaf().remove_leaf()
709         }
710
711         /// Subroutine for removal. Takes a search stack for a key that might terminate at an
712         /// internal node, and mutates the tree and search stack to *make* it a search stack
713         /// for that same key that *does* terminates at a leaf. If the mutation occurs, then this
714         /// leaves the tree in an inconsistent state that must be repaired by the caller by
715         /// removing the entry in question. Specifically the key-value pair and its successor will
716         /// become swapped.
717         fn into_leaf(mut self) -> SearchStack<'a, K, V, handle::KV, handle::Leaf> {
718             unsafe {
719                 let mut top_raw = self.top;
720                 let mut top = top_raw.from_raw_mut();
721
722                 let key_ptr = top.key_mut() as *mut _;
723                 let val_ptr = top.val_mut() as *mut _;
724
725                 // Try to go into the right subtree of the found key to find its successor
726                 match top.force() {
727                     Leaf(mut leaf_handle) => {
728                         // We're a proper leaf stack, nothing to do
729                         return SearchStack {
730                             map: self.map,
731                             stack: self.stack,
732                             top: leaf_handle.as_raw()
733                         }
734                     }
735                     Internal(mut internal_handle) => {
736                         let mut right_handle = internal_handle.right_edge();
737
738                         //We're not a proper leaf stack, let's get to work.
739                         self.stack.push(right_handle.as_raw());
740
741                         let mut temp_node = right_handle.edge_mut();
742                         loop {
743                             // Walk into the smallest subtree of this node
744                             let node = temp_node;
745
746                             match node.kv_handle(0).force() {
747                                 Leaf(mut handle) => {
748                                     // This node is a leaf, do the swap and return
749                                     mem::swap(handle.key_mut(), &mut *key_ptr);
750                                     mem::swap(handle.val_mut(), &mut *val_ptr);
751                                     return SearchStack {
752                                         map: self.map,
753                                         stack: self.stack,
754                                         top: handle.as_raw()
755                                     }
756                                 },
757                                 Internal(kv_handle) => {
758                                     // This node is internal, go deeper
759                                     let mut handle = kv_handle.into_left_edge();
760                                     self.stack.push(handle.as_raw());
761                                     temp_node = handle.into_edge_mut();
762                                 }
763                             }
764                         }
765                     }
766                 }
767             }
768         }
769     }
770
771     impl<'a, K, V> SearchStack<'a, K, V, handle::Edge, handle::Leaf> {
772         /// Inserts the key and value into the top element in the stack, and if that node has to
773         /// split recursively inserts the split contents into the next element stack until
774         /// splits stop.
775         ///
776         /// Assumes that the stack represents a search path from the root to a leaf.
777         ///
778         /// An &mut V is returned to the inserted value, for callers that want a reference to this.
779         pub fn insert(mut self, key: K, val: V) -> &'a mut V {
780             unsafe {
781                 self.map.length += 1;
782
783                 // Insert the key and value into the leaf at the top of the stack
784                 let (mut insertion, inserted_ptr) = self.top.from_raw_mut()
785                                                         .insert_as_leaf(key, val);
786
787                 loop {
788                     match insertion {
789                         Fit => {
790                             // The last insertion went off without a hitch, no splits! We can stop
791                             // inserting now.
792                             return &mut *inserted_ptr;
793                         }
794                         Split(key, val, right) => match self.stack.pop() {
795                             // The last insertion triggered a split, so get the next element on the
796                             // stack to recursively insert the split node into.
797                             None => {
798                                 // The stack was empty; we've split the root, and need to make a
799                                 // a new one. This is done in-place because we can't move the
800                                 // root out of a reference to the tree.
801                                 Node::make_internal_root(&mut self.map.root, self.map.b,
802                                                          key, val, right);
803
804                                 self.map.depth += 1;
805                                 return &mut *inserted_ptr;
806                             }
807                             Some(mut handle) => {
808                                 // The stack wasn't empty, do the insertion and recurse
809                                 insertion = handle.from_raw_mut()
810                                                   .insert_as_internal(key, val, right);
811                                 continue;
812                             }
813                         }
814                     }
815                 }
816             }
817         }
818     }
819 }
820
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
823     fn from_iter<T: Iterator<Item=(K, V)>>(iter: T) -> BTreeMap<K, V> {
824         let mut map = BTreeMap::new();
825         map.extend(iter);
826         map
827     }
828 }
829
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
832     #[inline]
833     fn extend<T: Iterator<Item=(K, V)>>(&mut self, iter: T) {
834         for (k, v) in iter {
835             self.insert(k, v);
836         }
837     }
838 }
839
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<S: Hasher, K: Hash<S>, V: Hash<S>> Hash<S> for BTreeMap<K, V> {
842     fn hash(&self, state: &mut S) {
843         for elt in self {
844             elt.hash(state);
845         }
846     }
847 }
848
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<K: Ord, V> Default for BTreeMap<K, V> {
851     #[stable(feature = "rust1", since = "1.0.0")]
852     fn default() -> BTreeMap<K, V> {
853         BTreeMap::new()
854     }
855 }
856
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
859     fn eq(&self, other: &BTreeMap<K, V>) -> bool {
860         self.len() == other.len() &&
861             self.iter().zip(other.iter()).all(|(a, b)| a == b)
862     }
863 }
864
865 #[stable(feature = "rust1", since = "1.0.0")]
866 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
867
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
870     #[inline]
871     fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
872         iter::order::partial_cmp(self.iter(), other.iter())
873     }
874 }
875
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
878     #[inline]
879     fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
880         iter::order::cmp(self.iter(), other.iter())
881     }
882 }
883
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
886     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
887         try!(write!(f, "BTreeMap {{"));
888
889         for (i, (k, v)) in self.iter().enumerate() {
890             if i != 0 { try!(write!(f, ", ")); }
891             try!(write!(f, "{:?}: {:?}", *k, *v));
892         }
893
894         write!(f, "}}")
895     }
896 }
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<K: Ord, Q: ?Sized, V> Index<Q> for BTreeMap<K, V>
900     where Q: BorrowFrom<K> + Ord
901 {
902     type Output = V;
903
904     fn index(&self, key: &Q) -> &V {
905         self.get(key).expect("no entry found for key")
906     }
907 }
908
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<K: Ord, Q: ?Sized, V> IndexMut<Q> for BTreeMap<K, V>
911     where Q: BorrowFrom<K> + Ord
912 {
913     type Output = V;
914
915     fn index_mut(&mut self, key: &Q) -> &mut V {
916         self.get_mut(key).expect("no entry found for key")
917     }
918 }
919
920 /// Genericises over how to get the correct type of iterator from the correct type
921 /// of Node ownership.
922 trait Traverse<N> {
923     fn traverse(node: N) -> Self;
924 }
925
926 impl<'a, K, V> Traverse<&'a Node<K, V>> for Traversal<'a, K, V> {
927     fn traverse(node: &'a Node<K, V>) -> Traversal<'a, K, V> {
928         node.iter()
929     }
930 }
931
932 impl<'a, K, V> Traverse<&'a mut Node<K, V>> for MutTraversal<'a, K, V> {
933     fn traverse(node: &'a mut Node<K, V>) -> MutTraversal<'a, K, V> {
934         node.iter_mut()
935     }
936 }
937
938 impl<K, V> Traverse<Node<K, V>> for MoveTraversal<K, V> {
939     fn traverse(node: Node<K, V>) -> MoveTraversal<K, V> {
940         node.into_iter()
941     }
942 }
943
944 /// Represents an operation to perform inside the following iterator methods.
945 /// This is necessary to use in `next` because we want to modify `self.traversals` inside
946 /// a match that borrows it. Similarly in `next_back`. Instead, we use this enum to note
947 /// what we want to do, and do it after the match.
948 enum StackOp<T> {
949     Push(T),
950     Pop,
951 }
952 impl<K, V, E, T> Iterator for AbsIter<T> where
953     T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>,
954 {
955     type Item = (K, V);
956
957     // Our iterator represents a queue of all ancestors of elements we have
958     // yet to yield, from smallest to largest.  Note that the design of these
959     // iterators permits an *arbitrary* initial pair of min and max, making
960     // these arbitrary sub-range iterators.
961     fn next(&mut self) -> Option<(K, V)> {
962         loop {
963             // We want the smallest element, so try to get the back of the queue
964             let op = match self.traversals.back_mut() {
965                 None => return None,
966                 // The queue wasn't empty, so continue along the node in its head
967                 Some(iter) => match iter.next() {
968                     // The head is empty, so Pop it off and continue the process
969                     None => Pop,
970                     // The head yielded an edge, so make that the new head
971                     Some(Edge(next)) => Push(Traverse::traverse(next)),
972                     // The head yielded an entry, so yield that
973                     Some(Elem(kv)) => {
974                         self.size -= 1;
975                         return Some(kv)
976                     }
977                 }
978             };
979
980             // Handle any operation as necessary, without a conflicting borrow of the queue
981             match op {
982                 Push(item) => { self.traversals.push_back(item); },
983                 Pop => { self.traversals.pop_back(); },
984             }
985         }
986     }
987
988     fn size_hint(&self) -> (usize, Option<usize>) {
989         (self.size, Some(self.size))
990     }
991 }
992
993 impl<K, V, E, T> DoubleEndedIterator for AbsIter<T> where
994     T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>,
995 {
996     // next_back is totally symmetric to next
997     #[inline]
998     fn next_back(&mut self) -> Option<(K, V)> {
999         loop {
1000             let op = match self.traversals.front_mut() {
1001                 None => return None,
1002                 Some(iter) => match iter.next_back() {
1003                     None => Pop,
1004                     Some(Edge(next)) => Push(Traverse::traverse(next)),
1005                     Some(Elem(kv)) => {
1006                         self.size -= 1;
1007                         return Some(kv)
1008                     }
1009                 }
1010             };
1011
1012             match op {
1013                 Push(item) => { self.traversals.push_front(item); },
1014                 Pop => { self.traversals.pop_front(); }
1015             }
1016         }
1017     }
1018 }
1019
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1022     type Item = (&'a K, &'a V);
1023
1024     fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1025     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1026 }
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1029     fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next_back() }
1030 }
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {}
1033
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1036     type Item = (&'a K, &'a mut V);
1037
1038     fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1039     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1040 }
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1043     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next_back() }
1044 }
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {}
1047
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 impl<K, V> Iterator for IntoIter<K, V> {
1050     type Item = (K, V);
1051
1052     fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1053     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1054 }
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1057     fn next_back(&mut self) -> Option<(K, V)> { self.inner.next_back() }
1058 }
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
1061
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1064     type Item = &'a K;
1065
1066     fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1067     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1068 }
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1071     fn next_back(&mut self) -> Option<(&'a K)> { self.inner.next_back() }
1072 }
1073 #[stable(feature = "rust1", since = "1.0.0")]
1074 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {}
1075
1076
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 impl<'a, K, V> Iterator for Values<'a, K, V> {
1079     type Item = &'a V;
1080
1081     fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1082     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1083 }
1084 #[stable(feature = "rust1", since = "1.0.0")]
1085 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1086     fn next_back(&mut self) -> Option<(&'a V)> { self.inner.next_back() }
1087 }
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}
1090
1091 impl<'a, K, V> Iterator for Range<'a, K, V> {
1092     type Item = (&'a K, &'a V);
1093
1094     fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1095 }
1096 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1097     fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next_back() }
1098 }
1099
1100 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1101     type Item = (&'a K, &'a mut V);
1102
1103     fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1104 }
1105 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1106     fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next_back() }
1107 }
1108
1109 impl<'a, K: Ord, V> Entry<'a, K, V> {
1110     #[unstable(feature = "collections",
1111                reason = "matches collection reform v2 specification, waiting for dust to settle")]
1112     /// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
1113     pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
1114         match self {
1115             Occupied(entry) => Ok(entry.into_mut()),
1116             Vacant(entry) => Err(entry),
1117         }
1118     }
1119 }
1120
1121 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
1122     /// Sets the value of the entry with the VacantEntry's key,
1123     /// and returns a mutable reference to it.
1124     #[stable(feature = "rust1", since = "1.0.0")]
1125     pub fn insert(self, value: V) -> &'a mut V {
1126         self.stack.insert(self.key, value)
1127     }
1128 }
1129
1130 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
1131     /// Gets a reference to the value in the entry.
1132     #[stable(feature = "rust1", since = "1.0.0")]
1133     pub fn get(&self) -> &V {
1134         self.stack.peek()
1135     }
1136
1137     /// Gets a mutable reference to the value in the entry.
1138     #[stable(feature = "rust1", since = "1.0.0")]
1139     pub fn get_mut(&mut self) -> &mut V {
1140         self.stack.peek_mut()
1141     }
1142
1143     /// Converts the entry into a mutable reference to its value.
1144     #[stable(feature = "rust1", since = "1.0.0")]
1145     pub fn into_mut(self) -> &'a mut V {
1146         self.stack.into_top()
1147     }
1148
1149     /// Sets the value of the entry with the OccupiedEntry's key,
1150     /// and returns the entry's old value.
1151     #[stable(feature = "rust1", since = "1.0.0")]
1152     pub fn insert(&mut self, mut value: V) -> V {
1153         mem::swap(self.stack.peek_mut(), &mut value);
1154         value
1155     }
1156
1157     /// Takes the value of the entry out of the map, and returns it.
1158     #[stable(feature = "rust1", since = "1.0.0")]
1159     pub fn remove(self) -> V {
1160         self.stack.remove()
1161     }
1162 }
1163
1164 impl<K, V> BTreeMap<K, V> {
1165     /// Gets an iterator over the entries of the map.
1166     ///
1167     /// # Example
1168     ///
1169     /// ```
1170     /// use std::collections::BTreeMap;
1171     ///
1172     /// let mut map = BTreeMap::new();
1173     /// map.insert(1, "a");
1174     /// map.insert(2, "b");
1175     /// map.insert(3, "c");
1176     ///
1177     /// for (key, value) in map.iter() {
1178     ///     println!("{}: {}", key, value);
1179     /// }
1180     ///
1181     /// let (first_key, first_value) = map.iter().next().unwrap();
1182     /// assert_eq!((*first_key, *first_value), (1, "a"));
1183     /// ```
1184     #[stable(feature = "rust1", since = "1.0.0")]
1185     pub fn iter(&self) -> Iter<K, V> {
1186         let len = self.len();
1187         // NB. The initial capacity for ringbuf is large enough to avoid reallocs in many cases.
1188         let mut lca = RingBuf::new();
1189         lca.push_back(Traverse::traverse(&self.root));
1190         Iter {
1191             inner: AbsIter {
1192                 traversals: lca,
1193                 size: len,
1194             }
1195         }
1196     }
1197
1198     /// Gets a mutable iterator over the entries of the map.
1199     ///
1200     /// # Examples
1201     ///
1202     /// ```
1203     /// use std::collections::BTreeMap;
1204     ///
1205     /// let mut map = BTreeMap::new();
1206     /// map.insert("a", 1);
1207     /// map.insert("b", 2);
1208     /// map.insert("c", 3);
1209     ///
1210     /// // add 10 to the value if the key isn't "a"
1211     /// for (key, value) in map.iter_mut() {
1212     ///     if key != &"a" {
1213     ///         *value += 10;
1214     ///     }
1215     /// }
1216     /// ```
1217     #[stable(feature = "rust1", since = "1.0.0")]
1218     pub fn iter_mut(&mut self) -> IterMut<K, V> {
1219         let len = self.len();
1220         let mut lca = RingBuf::new();
1221         lca.push_back(Traverse::traverse(&mut self.root));
1222         IterMut {
1223             inner: AbsIter {
1224                 traversals: lca,
1225                 size: len,
1226             }
1227         }
1228     }
1229
1230     /// Gets an owning iterator over the entries of the map.
1231     ///
1232     /// # Examples
1233     ///
1234     /// ```
1235     /// use std::collections::BTreeMap;
1236     ///
1237     /// let mut map = BTreeMap::new();
1238     /// map.insert(1, "a");
1239     /// map.insert(2, "b");
1240     /// map.insert(3, "c");
1241     ///
1242     /// for (key, value) in map.into_iter() {
1243     ///     println!("{}: {}", key, value);
1244     /// }
1245     /// ```
1246     #[stable(feature = "rust1", since = "1.0.0")]
1247     pub fn into_iter(self) -> IntoIter<K, V> {
1248         let len = self.len();
1249         let mut lca = RingBuf::new();
1250         lca.push_back(Traverse::traverse(self.root));
1251         IntoIter {
1252             inner: AbsIter {
1253                 traversals: lca,
1254                 size: len,
1255             }
1256         }
1257     }
1258
1259     /// Gets an iterator over the keys of the map.
1260     ///
1261     /// # Examples
1262     ///
1263     /// ```
1264     /// use std::collections::BTreeMap;
1265     ///
1266     /// let mut a = BTreeMap::new();
1267     /// a.insert(1, "a");
1268     /// a.insert(2, "b");
1269     ///
1270     /// let keys: Vec<usize> = a.keys().cloned().collect();
1271     /// assert_eq!(keys, vec![1,2,]);
1272     /// ```
1273     #[stable(feature = "rust1", since = "1.0.0")]
1274     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1275         fn first<A, B>((a, _): (A, B)) -> A { a }
1276         let first: fn((&'a K, &'a V)) -> &'a K = first; // coerce to fn pointer
1277
1278         Keys { inner: self.iter().map(first) }
1279     }
1280
1281     /// Gets an iterator over the values of the map.
1282     ///
1283     /// # Examples
1284     ///
1285     /// ```
1286     /// use std::collections::BTreeMap;
1287     ///
1288     /// let mut a = BTreeMap::new();
1289     /// a.insert(1, "a");
1290     /// a.insert(2, "b");
1291     ///
1292     /// let values: Vec<&str> = a.values().cloned().collect();
1293     /// assert_eq!(values, vec!["a","b"]);
1294     /// ```
1295     #[stable(feature = "rust1", since = "1.0.0")]
1296     pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1297         fn second<A, B>((_, b): (A, B)) -> B { b }
1298         let second: fn((&'a K, &'a V)) -> &'a V = second; // coerce to fn pointer
1299
1300         Values { inner: self.iter().map(second) }
1301     }
1302
1303     /// Return the number of elements in the map.
1304     ///
1305     /// # Examples
1306     ///
1307     /// ```
1308     /// use std::collections::BTreeMap;
1309     ///
1310     /// let mut a = BTreeMap::new();
1311     /// assert_eq!(a.len(), 0);
1312     /// a.insert(1, "a");
1313     /// assert_eq!(a.len(), 1);
1314     /// ```
1315     #[stable(feature = "rust1", since = "1.0.0")]
1316     pub fn len(&self) -> usize { self.length }
1317
1318     /// Return true if the map contains no elements.
1319     ///
1320     /// # Examples
1321     ///
1322     /// ```
1323     /// use std::collections::BTreeMap;
1324     ///
1325     /// let mut a = BTreeMap::new();
1326     /// assert!(a.is_empty());
1327     /// a.insert(1, "a");
1328     /// assert!(!a.is_empty());
1329     /// ```
1330     #[stable(feature = "rust1", since = "1.0.0")]
1331     pub fn is_empty(&self) -> bool { self.len() == 0 }
1332 }
1333
1334 macro_rules! range_impl {
1335     ($root:expr, $min:expr, $max:expr, $as_slices_internal:ident, $iter:ident, $Range:ident,
1336                                        $edges:ident, [$($mutability:ident)*]) => (
1337         {
1338             // A deque that encodes two search paths containing (left-to-right):
1339             // a series of truncated-from-the-left iterators, the LCA's doubly-truncated iterator,
1340             // and a series of truncated-from-the-right iterators.
1341             let mut traversals = RingBuf::new();
1342             let (root, min, max) = ($root, $min, $max);
1343
1344             let mut leftmost = None;
1345             let mut rightmost = None;
1346
1347             match (&min, &max) {
1348                 (&Unbounded, &Unbounded) => {
1349                     traversals.push_back(Traverse::traverse(root))
1350                 }
1351                 (&Unbounded, &Included(_)) | (&Unbounded, &Excluded(_)) => {
1352                     rightmost = Some(root);
1353                 }
1354                 (&Included(_), &Unbounded) | (&Excluded(_), &Unbounded) => {
1355                     leftmost = Some(root);
1356                 }
1357                   (&Included(min_key), &Included(max_key))
1358                 | (&Included(min_key), &Excluded(max_key))
1359                 | (&Excluded(min_key), &Included(max_key))
1360                 | (&Excluded(min_key), &Excluded(max_key)) => {
1361                     // lca represents the Lowest Common Ancestor, above which we never
1362                     // walk, since everything else is outside the range to iterate.
1363                     //       ___________________
1364                     //      |__0_|_80_|_85_|_90_|  (root)
1365                     //      |    |    |    |    |
1366                     //           |
1367                     //           v
1368                     //  ___________________
1369                     // |__5_|_15_|_30_|_73_|
1370                     // |    |    |    |    |
1371                     //                |
1372                     //                v
1373                     //       ___________________
1374                     //      |_33_|_58_|_63_|_68_|  lca for the range [41, 65]
1375                     //      |    |\___|___/|    |  iterator at traversals[2]
1376                     //           |         |
1377                     //           |         v
1378                     //           v         rightmost
1379                     //           leftmost
1380                     let mut is_leaf = root.is_leaf();
1381                     let mut lca = root.$as_slices_internal();
1382                     loop {
1383                         let slice = lca.slice_from(min_key).slice_to(max_key);
1384                         if let [ref $($mutability)* edge] = slice.edges {
1385                             // Follow the only edge that leads the node that covers the range.
1386                             is_leaf = edge.is_leaf();
1387                             lca = edge.$as_slices_internal();
1388                         } else {
1389                             let mut iter = slice.$iter();
1390                             if is_leaf {
1391                                 leftmost = None;
1392                                 rightmost = None;
1393                             } else {
1394                                 // Only change the state of nodes with edges.
1395                                 leftmost = iter.next_edge_item();
1396                                 rightmost = iter.next_edge_item_back();
1397                             }
1398                             traversals.push_back(iter);
1399                             break;
1400                         }
1401                     }
1402                 }
1403             }
1404             // Keep narrowing the range by going down.
1405             //               ___________________
1406             //              |_38_|_43_|_48_|_53_|
1407             //              |    |____|____|____/ iterator at traversals[1]
1408             //                   |
1409             //                   v
1410             //  ___________________
1411             // |_39_|_40_|_41_|_42_|  (leaf, the last leftmost)
1412             //           \_________|  iterator at traversals[0]
1413             match min {
1414                 Included(key) | Excluded(key) =>
1415                     while let Some(left) = leftmost {
1416                         let is_leaf = left.is_leaf();
1417                         let mut iter = left.$as_slices_internal().slice_from(key).$iter();
1418                         leftmost = if is_leaf {
1419                             None
1420                         } else {
1421                             // Only change the state of nodes with edges.
1422                             iter.next_edge_item()
1423                         };
1424                         traversals.push_back(iter);
1425                     },
1426                 _ => {}
1427             }
1428             // If the leftmost iterator starts with an element, then it was an exact match.
1429             if let (Excluded(_), Some(leftmost_iter)) = (min, traversals.back_mut()) {
1430                 // Drop this excluded element. `next_kv_item` has no effect when
1431                 // the next item is an edge.
1432                 leftmost_iter.next_kv_item();
1433             }
1434
1435             // The code for the right side is similar.
1436             match max {
1437                 Included(key) | Excluded(key) =>
1438                     while let Some(right) = rightmost {
1439                         let is_leaf = right.is_leaf();
1440                         let mut iter = right.$as_slices_internal().slice_to(key).$iter();
1441                         rightmost = if is_leaf {
1442                             None
1443                         } else {
1444                             iter.next_edge_item_back()
1445                         };
1446                         traversals.push_front(iter);
1447                     },
1448                 _ => {}
1449             }
1450             if let (Excluded(_), Some(rightmost_iter)) = (max, traversals.front_mut()) {
1451                 rightmost_iter.next_kv_item_back();
1452             }
1453
1454             $Range {
1455                 inner: AbsIter {
1456                     traversals: traversals,
1457                     size: 0, // unused
1458                 }
1459             }
1460         }
1461     )
1462 }
1463
1464 impl<K: Ord, V> BTreeMap<K, V> {
1465     /// Constructs a double-ended iterator over a sub-range of elements in the map, starting
1466     /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
1467     /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
1468     /// Thus range(Unbounded, Unbounded) will yield the whole collection.
1469     ///
1470     /// # Examples
1471     ///
1472     /// ```
1473     /// use std::collections::BTreeMap;
1474     /// use std::collections::Bound::{Included, Unbounded};
1475     ///
1476     /// let mut map = BTreeMap::new();
1477     /// map.insert(3, "a");
1478     /// map.insert(5, "b");
1479     /// map.insert(8, "c");
1480     /// for (&key, &value) in map.range(Included(&4), Included(&8)) {
1481     ///     println!("{}: {}", key, value);
1482     /// }
1483     /// assert_eq!(Some((&5, &"b")), map.range(Included(&4), Unbounded).next());
1484     /// ```
1485     #[unstable(feature = "collections",
1486                reason = "matches collection reform specification, waiting for dust to settle")]
1487     pub fn range<'a>(&'a self, min: Bound<&K>, max: Bound<&K>) -> Range<'a, K, V> {
1488         range_impl!(&self.root, min, max, as_slices_internal, iter, Range, edges, [])
1489     }
1490
1491     /// Constructs a mutable double-ended iterator over a sub-range of elements in the map, starting
1492     /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
1493     /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
1494     /// Thus range(Unbounded, Unbounded) will yield the whole collection.
1495     ///
1496     /// # Examples
1497     ///
1498     /// ```
1499     /// use std::collections::BTreeMap;
1500     /// use std::collections::Bound::{Included, Excluded};
1501     ///
1502     /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
1503     ///                                                                       .map(|&s| (s, 0))
1504     ///                                                                       .collect();
1505     /// for (_, balance) in map.range_mut(Included(&"B"), Excluded(&"Cheryl")) {
1506     ///     *balance += 100;
1507     /// }
1508     /// for (name, balance) in map.iter() {
1509     ///     println!("{} => {}", name, balance);
1510     /// }
1511     /// ```
1512     #[unstable(feature = "collections",
1513                reason = "matches collection reform specification, waiting for dust to settle")]
1514     pub fn range_mut<'a>(&'a mut self, min: Bound<&K>, max: Bound<&K>) -> RangeMut<'a, K, V> {
1515         range_impl!(&mut self.root, min, max, as_slices_internal_mut, iter_mut, RangeMut,
1516                                                                       edges_mut, [mut])
1517     }
1518
1519     /// Gets the given key's corresponding entry in the map for in-place manipulation.
1520     ///
1521     /// # Examples
1522     ///
1523     /// ```
1524     /// use std::collections::BTreeMap;
1525     /// use std::collections::btree_map::Entry;
1526     ///
1527     /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1528     ///
1529     /// // count the number of occurrences of letters in the vec
1530     /// for x in vec!["a","b","a","c","a","b"].iter() {
1531     ///     match count.entry(*x) {
1532     ///         Entry::Vacant(view) => {
1533     ///             view.insert(1);
1534     ///         },
1535     ///         Entry::Occupied(mut view) => {
1536     ///             let v = view.get_mut();
1537     ///             *v += 1;
1538     ///         },
1539     ///     }
1540     /// }
1541     ///
1542     /// assert_eq!(count["a"], 3);
1543     /// ```
1544     #[stable(feature = "rust1", since = "1.0.0")]
1545     pub fn entry(&mut self, mut key: K) -> Entry<K, V> {
1546         // same basic logic of `swap` and `pop`, blended together
1547         let mut stack = stack::PartialSearchStack::new(self);
1548         loop {
1549             let result = stack.with(move |pusher, node| {
1550                 return match Node::search(node, &key) {
1551                     Found(handle) => {
1552                         // Perfect match
1553                         Finished(Occupied(OccupiedEntry {
1554                             stack: pusher.seal(handle)
1555                         }))
1556                     },
1557                     GoDown(handle) => {
1558                         match handle.force() {
1559                             Leaf(leaf_handle) => {
1560                                 Finished(Vacant(VacantEntry {
1561                                     stack: pusher.seal(leaf_handle),
1562                                     key: key,
1563                                 }))
1564                             },
1565                             Internal(internal_handle) => {
1566                                 Continue((
1567                                     pusher.push(internal_handle),
1568                                     key
1569                                 ))
1570                             }
1571                         }
1572                     }
1573                 }
1574             });
1575             match result {
1576                 Finished(finished) => return finished,
1577                 Continue((new_stack, renewed_key)) => {
1578                     stack = new_stack;
1579                     key = renewed_key;
1580                 }
1581             }
1582         }
1583     }
1584 }
1585
1586
1587
1588
1589
1590 #[cfg(test)]
1591 mod test {
1592     use prelude::*;
1593     use std::iter::range_inclusive;
1594
1595     use super::BTreeMap;
1596     use super::Entry::{Occupied, Vacant};
1597     use Bound::{self, Included, Excluded, Unbounded};
1598
1599     #[test]
1600     fn test_basic_large() {
1601         let mut map = BTreeMap::new();
1602         let size = 10000;
1603         assert_eq!(map.len(), 0);
1604
1605         for i in 0..size {
1606             assert_eq!(map.insert(i, 10*i), None);
1607             assert_eq!(map.len(), i + 1);
1608         }
1609
1610         for i in 0..size {
1611             assert_eq!(map.get(&i).unwrap(), &(i*10));
1612         }
1613
1614         for i in size..size*2 {
1615             assert_eq!(map.get(&i), None);
1616         }
1617
1618         for i in 0..size {
1619             assert_eq!(map.insert(i, 100*i), Some(10*i));
1620             assert_eq!(map.len(), size);
1621         }
1622
1623         for i in 0..size {
1624             assert_eq!(map.get(&i).unwrap(), &(i*100));
1625         }
1626
1627         for i in 0..size/2 {
1628             assert_eq!(map.remove(&(i*2)), Some(i*200));
1629             assert_eq!(map.len(), size - i - 1);
1630         }
1631
1632         for i in 0..size/2 {
1633             assert_eq!(map.get(&(2*i)), None);
1634             assert_eq!(map.get(&(2*i+1)).unwrap(), &(i*200 + 100));
1635         }
1636
1637         for i in 0..size/2 {
1638             assert_eq!(map.remove(&(2*i)), None);
1639             assert_eq!(map.remove(&(2*i+1)), Some(i*200 + 100));
1640             assert_eq!(map.len(), size/2 - i - 1);
1641         }
1642     }
1643
1644     #[test]
1645     fn test_basic_small() {
1646         let mut map = BTreeMap::new();
1647         assert_eq!(map.remove(&1), None);
1648         assert_eq!(map.get(&1), None);
1649         assert_eq!(map.insert(1, 1), None);
1650         assert_eq!(map.get(&1), Some(&1));
1651         assert_eq!(map.insert(1, 2), Some(1));
1652         assert_eq!(map.get(&1), Some(&2));
1653         assert_eq!(map.insert(2, 4), None);
1654         assert_eq!(map.get(&2), Some(&4));
1655         assert_eq!(map.remove(&1), Some(2));
1656         assert_eq!(map.remove(&2), Some(4));
1657         assert_eq!(map.remove(&1), None);
1658     }
1659
1660     #[test]
1661     fn test_iter() {
1662         let size = 10000;
1663
1664         // Forwards
1665         let mut map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
1666
1667         fn test<T>(size: usize, mut iter: T) where T: Iterator<Item=(usize, usize)> {
1668             for i in 0..size {
1669                 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1670                 assert_eq!(iter.next().unwrap(), (i, i));
1671             }
1672             assert_eq!(iter.size_hint(), (0, Some(0)));
1673             assert_eq!(iter.next(), None);
1674         }
1675         test(size, map.iter().map(|(&k, &v)| (k, v)));
1676         test(size, map.iter_mut().map(|(&k, &mut v)| (k, v)));
1677         test(size, map.into_iter());
1678     }
1679
1680     #[test]
1681     fn test_iter_rev() {
1682         let size = 10000;
1683
1684         // Forwards
1685         let mut map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
1686
1687         fn test<T>(size: usize, mut iter: T) where T: Iterator<Item=(usize, usize)> {
1688             for i in 0..size {
1689                 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1690                 assert_eq!(iter.next().unwrap(), (size - i - 1, size - i - 1));
1691             }
1692             assert_eq!(iter.size_hint(), (0, Some(0)));
1693             assert_eq!(iter.next(), None);
1694         }
1695         test(size, map.iter().rev().map(|(&k, &v)| (k, v)));
1696         test(size, map.iter_mut().rev().map(|(&k, &mut v)| (k, v)));
1697         test(size, map.into_iter().rev());
1698     }
1699
1700     #[test]
1701     fn test_iter_mixed() {
1702         let size = 10000;
1703
1704         // Forwards
1705         let mut map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
1706
1707         fn test<T>(size: usize, mut iter: T)
1708                 where T: Iterator<Item=(usize, usize)> + DoubleEndedIterator {
1709             for i in 0..size / 4 {
1710                 assert_eq!(iter.size_hint(), (size - i * 2, Some(size - i * 2)));
1711                 assert_eq!(iter.next().unwrap(), (i, i));
1712                 assert_eq!(iter.next_back().unwrap(), (size - i - 1, size - i - 1));
1713             }
1714             for i in size / 4..size * 3 / 4 {
1715                 assert_eq!(iter.size_hint(), (size * 3 / 4 - i, Some(size * 3 / 4 - i)));
1716                 assert_eq!(iter.next().unwrap(), (i, i));
1717             }
1718             assert_eq!(iter.size_hint(), (0, Some(0)));
1719             assert_eq!(iter.next(), None);
1720         }
1721         test(size, map.iter().map(|(&k, &v)| (k, v)));
1722         test(size, map.iter_mut().map(|(&k, &mut v)| (k, v)));
1723         test(size, map.into_iter());
1724     }
1725
1726     #[test]
1727     fn test_range_small() {
1728         let size = 5;
1729
1730         // Forwards
1731         let map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
1732
1733         let mut j = 0;
1734         for ((&k, &v), i) in map.range(Included(&2), Unbounded).zip(2..size) {
1735             assert_eq!(k, i);
1736             assert_eq!(v, i);
1737             j += 1;
1738         }
1739         assert_eq!(j, size - 2);
1740     }
1741
1742     #[test]
1743     fn test_range_1000() {
1744         let size = 1000;
1745         let map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
1746
1747         fn test(map: &BTreeMap<u32, u32>, size: u32, min: Bound<&u32>, max: Bound<&u32>) {
1748             let mut kvs = map.range(min, max).map(|(&k, &v)| (k, v));
1749             let mut pairs = (0..size).map(|i| (i, i));
1750
1751             for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) {
1752                 assert_eq!(kv, pair);
1753             }
1754             assert_eq!(kvs.next(), None);
1755             assert_eq!(pairs.next(), None);
1756         }
1757         test(&map, size, Included(&0), Excluded(&size));
1758         test(&map, size, Unbounded, Excluded(&size));
1759         test(&map, size, Included(&0), Included(&(size - 1)));
1760         test(&map, size, Unbounded, Included(&(size - 1)));
1761         test(&map, size, Included(&0), Unbounded);
1762         test(&map, size, Unbounded, Unbounded);
1763     }
1764
1765     #[test]
1766     fn test_range() {
1767         let size = 200;
1768         let map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
1769
1770         for i in 0..size {
1771             for j in i..size {
1772                 let mut kvs = map.range(Included(&i), Included(&j)).map(|(&k, &v)| (k, v));
1773                 let mut pairs = range_inclusive(i, j).map(|i| (i, i));
1774
1775                 for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) {
1776                     assert_eq!(kv, pair);
1777                 }
1778                 assert_eq!(kvs.next(), None);
1779                 assert_eq!(pairs.next(), None);
1780             }
1781         }
1782     }
1783
1784     #[test]
1785     fn test_entry(){
1786         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1787
1788         let mut map: BTreeMap<_, _> = xs.iter().map(|&x| x).collect();
1789
1790         // Existing key (insert)
1791         match map.entry(1) {
1792             Vacant(_) => unreachable!(),
1793             Occupied(mut view) => {
1794                 assert_eq!(view.get(), &10);
1795                 assert_eq!(view.insert(100), 10);
1796             }
1797         }
1798         assert_eq!(map.get(&1).unwrap(), &100);
1799         assert_eq!(map.len(), 6);
1800
1801
1802         // Existing key (update)
1803         match map.entry(2) {
1804             Vacant(_) => unreachable!(),
1805             Occupied(mut view) => {
1806                 let v = view.get_mut();
1807                 *v *= 10;
1808             }
1809         }
1810         assert_eq!(map.get(&2).unwrap(), &200);
1811         assert_eq!(map.len(), 6);
1812
1813         // Existing key (take)
1814         match map.entry(3) {
1815             Vacant(_) => unreachable!(),
1816             Occupied(view) => {
1817                 assert_eq!(view.remove(), 30);
1818             }
1819         }
1820         assert_eq!(map.get(&3), None);
1821         assert_eq!(map.len(), 5);
1822
1823
1824         // Inexistent key (insert)
1825         match map.entry(10) {
1826             Occupied(_) => unreachable!(),
1827             Vacant(view) => {
1828                 assert_eq!(*view.insert(1000), 1000);
1829             }
1830         }
1831         assert_eq!(map.get(&10).unwrap(), &1000);
1832         assert_eq!(map.len(), 6);
1833     }
1834 }
1835
1836
1837
1838
1839
1840
1841 #[cfg(test)]
1842 mod bench {
1843     use prelude::*;
1844     use std::rand::{weak_rng, Rng};
1845     use test::{Bencher, black_box};
1846
1847     use super::BTreeMap;
1848     use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1849
1850     #[bench]
1851     pub fn insert_rand_100(b: &mut Bencher) {
1852         let mut m = BTreeMap::new();
1853         insert_rand_n(100, &mut m, b,
1854                       |m, i| { m.insert(i, 1); },
1855                       |m, i| { m.remove(&i); });
1856     }
1857
1858     #[bench]
1859     pub fn insert_rand_10_000(b: &mut Bencher) {
1860         let mut m = BTreeMap::new();
1861         insert_rand_n(10_000, &mut m, b,
1862                       |m, i| { m.insert(i, 1); },
1863                       |m, i| { m.remove(&i); });
1864     }
1865
1866     // Insert seq
1867     #[bench]
1868     pub fn insert_seq_100(b: &mut Bencher) {
1869         let mut m = BTreeMap::new();
1870         insert_seq_n(100, &mut m, b,
1871                      |m, i| { m.insert(i, 1); },
1872                      |m, i| { m.remove(&i); });
1873     }
1874
1875     #[bench]
1876     pub fn insert_seq_10_000(b: &mut Bencher) {
1877         let mut m = BTreeMap::new();
1878         insert_seq_n(10_000, &mut m, b,
1879                      |m, i| { m.insert(i, 1); },
1880                      |m, i| { m.remove(&i); });
1881     }
1882
1883     // Find rand
1884     #[bench]
1885     pub fn find_rand_100(b: &mut Bencher) {
1886         let mut m = BTreeMap::new();
1887         find_rand_n(100, &mut m, b,
1888                     |m, i| { m.insert(i, 1); },
1889                     |m, i| { m.get(&i); });
1890     }
1891
1892     #[bench]
1893     pub fn find_rand_10_000(b: &mut Bencher) {
1894         let mut m = BTreeMap::new();
1895         find_rand_n(10_000, &mut m, b,
1896                     |m, i| { m.insert(i, 1); },
1897                     |m, i| { m.get(&i); });
1898     }
1899
1900     // Find seq
1901     #[bench]
1902     pub fn find_seq_100(b: &mut Bencher) {
1903         let mut m = BTreeMap::new();
1904         find_seq_n(100, &mut m, b,
1905                    |m, i| { m.insert(i, 1); },
1906                    |m, i| { m.get(&i); });
1907     }
1908
1909     #[bench]
1910     pub fn find_seq_10_000(b: &mut Bencher) {
1911         let mut m = BTreeMap::new();
1912         find_seq_n(10_000, &mut m, b,
1913                    |m, i| { m.insert(i, 1); },
1914                    |m, i| { m.get(&i); });
1915     }
1916
1917     fn bench_iter(b: &mut Bencher, size: i32) {
1918         let mut map = BTreeMap::<i32, i32>::new();
1919         let mut rng = weak_rng();
1920
1921         for _ in 0..size {
1922             map.insert(rng.gen(), rng.gen());
1923         }
1924
1925         b.iter(|| {
1926             for entry in &map {
1927                 black_box(entry);
1928             }
1929         });
1930     }
1931
1932     #[bench]
1933     pub fn iter_20(b: &mut Bencher) {
1934         bench_iter(b, 20);
1935     }
1936
1937     #[bench]
1938     pub fn iter_1000(b: &mut Bencher) {
1939         bench_iter(b, 1000);
1940     }
1941
1942     #[bench]
1943     pub fn iter_100000(b: &mut Bencher) {
1944         bench_iter(b, 100000);
1945     }
1946 }