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