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