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