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