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.
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.
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/).
18 pub use self::Entry::*;
22 use core::borrow::BorrowFrom;
23 use core::cmp::Ordering;
24 use core::default::Default;
26 use core::hash::{Hash, Hasher};
27 use core::iter::{Map, FromIterator};
28 use core::ops::{Index, IndexMut};
29 use core::{iter, fmt, mem};
31 use ring_buf::RingBuf;
33 use self::Continuation::{Continue, Finished};
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};
40 // FIXME(conventions): implement bounded iterators
42 /// A map based on a B-Tree.
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
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.
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.
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.
86 pub struct BTreeMap<K, V> {
93 /// An abstract base over-which all other BTree iterators are built.
101 /// An iterator over a BTreeMap's entries.
103 pub struct Iter<'a, K: 'a, V: 'a> {
104 inner: AbsIter<Traversal<'a, K, V>>
107 /// A mutable iterator over a BTreeMap's entries.
109 pub struct IterMut<'a, K: 'a, V: 'a> {
110 inner: AbsIter<MutTraversal<'a, K, V>>
113 /// An owning iterator over a BTreeMap's entries.
115 pub struct IntoIter<K, V> {
116 inner: AbsIter<MoveTraversal<K, V>>
119 /// An iterator over a BTreeMap's keys.
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>
125 /// An iterator over a BTreeMap's values.
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>
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> {
135 Vacant(VacantEntry<'a, K, V>),
136 /// An occupied Entry
137 Occupied(OccupiedEntry<'a, K, V>),
141 #[unstable = "precise API still under development"]
142 pub struct VacantEntry<'a, K:'a, V:'a> {
144 stack: stack::SearchStack<'a, K, V, node::handle::Edge, node::handle::Leaf>,
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>,
153 impl<K: Ord, V> BTreeMap<K, V> {
154 /// Makes a new empty BTreeMap with a reasonable choice for B.
156 pub fn new() -> BTreeMap<K, V> {
157 //FIXME(Gankro): Tune this as a function of size_of<K/V>?
161 /// Makes a new empty BTreeMap with the given B.
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");
169 root: Node::make_leaf_root(b),
174 /// Clears the map, removing all values.
179 /// use std::collections::BTreeMap;
181 /// let mut a = BTreeMap::new();
182 /// a.insert(1u, "a");
184 /// assert!(a.is_empty());
187 pub fn clear(&mut self) {
189 // avoid recursive destructors by manually traversing the tree
190 for _ in mem::replace(self, BTreeMap::with_b(b)).into_iter() {};
193 // Searching in a B-Tree is pretty straightforward.
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
201 /// Returns a reference to the value corresponding to the key.
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.
209 /// use std::collections::BTreeMap;
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);
217 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where Q: BorrowFrom<K> + Ord {
218 let mut cur_node = &self.root;
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();
233 /// Returns true if the map contains a value for the specified key.
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.
241 /// use std::collections::BTreeMap;
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);
249 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where Q: BorrowFrom<K> + Ord {
250 self.get(key).is_some()
253 /// Returns a mutable reference to the value corresponding to the key.
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.
261 /// use std::collections::BTreeMap;
263 /// let mut map = BTreeMap::new();
264 /// map.insert(1u, "a");
265 /// match map.get_mut(&1) {
266 /// Some(x) => *x = "b",
269 /// assert_eq!(map[1], "b");
271 // See `get` for implementation notes, this is basically a copy-paste with mut's added
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;
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();
291 // Insertion in a B-Tree is a bit complicated.
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
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.
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:
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.
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.
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.
323 /// use std::collections::BTreeMap;
325 /// let mut map = BTreeMap::new();
326 /// assert_eq!(map.insert(37u, "a"), None);
327 /// assert_eq!(map.is_empty(), false);
329 /// map.insert(37, "b");
330 /// assert_eq!(map.insert(37, "c"), Some("b"));
331 /// assert_eq!(map[37], "c");
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.
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);
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))
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);
371 Internal(internal_handle) => {
372 // We've found the subtree to insert this key/value pair in,
374 Continue((pusher.push(internal_handle), key, value))
381 Finished(ret) => { return ret; },
382 Continue((new_stack, renewed_key, renewed_val)) => {
391 // Deletion is the most complicated operation for a B-Tree.
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.
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.
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
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.
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.
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.
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.
426 /// Removes a key from the map, returning the value at the key if the key
427 /// was previously in the map.
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.
435 /// use std::collections::BTreeMap;
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);
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);
447 let result = stack.with(move |pusher, node| {
448 return match Node::search(node, key) {
450 // Perfect match. Terminate the stack here, and remove the entry
451 Finished(Some(pusher.seal(handle).remove()))
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))
464 Finished(ret) => return ret,
465 Continue(new_stack) => stack = new_stack
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> {
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.
482 use core::prelude::*;
485 use core::ops::{Deref, DerefMut};
487 use super::super::node::{self, Node, Fit, Split, Internal, Leaf};
488 use super::super::node::handle;
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> {
497 marker: marker::InvariantLifetime<'id>
500 impl<'id, T> Deref for IdRef<'id, T> {
503 fn deref(&self) -> &T {
508 impl<'id, T> DerefMut for IdRef<'id, T> {
509 fn deref_mut(&mut self) -> &mut T {
514 type StackItem<K, V> = node::Handle<*mut Node<K, V>, handle::Edge, handle::Internal>;
515 type Stack<K, V> = Vec<StackItem<K, V>>;
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>,
521 next: *mut Node<K, V>,
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>,
530 top: node::Handle<*mut Node<K, V>, Type, NodeType>,
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>,
539 marker: marker::InvariantLifetime<'id>
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;
549 next: &mut map.root as *mut _,
551 stack: Vec::with_capacity(depth),
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.
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.
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 {
574 marker: marker::InvariantLifetime
577 inner: unsafe { &mut *self.next },
578 marker: marker::InvariantLifetime
581 closure(pusher, node)
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
589 pub fn push(mut self, mut edge: node::Handle<IdRef<'id, Node<K, V>>,
592 -> PartialSearchStack<'a, K, V> {
593 self.stack.push(edge.as_raw());
597 next: edge.edge_mut() as *mut _,
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> {
608 top: handle.as_raw(),
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 }
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 }
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 {
628 mem::copy_mut_lifetime(
630 self.top.from_raw_mut().val_mut()
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;
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();
652 match self.stack.pop() {
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
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.
661 self.map.root.hoist_lone_child();
665 Some(mut handle) => {
667 // Underflow! Handle it!
669 handle.from_raw_mut().handle_underflow();
670 underflow = handle.from_raw().node().is_underfull();
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()
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
699 fn into_leaf(mut self) -> SearchStack<'a, K, V, handle::KV, handle::Leaf> {
701 let mut top_raw = self.top;
702 let mut top = top_raw.from_raw_mut();
704 let key_ptr = top.key_mut() as *mut _;
705 let val_ptr = top.val_mut() as *mut _;
707 // Try to go into the right subtree of the found key to find its successor
709 Leaf(mut leaf_handle) => {
710 // We're a proper leaf stack, nothing to do
714 top: leaf_handle.as_raw()
717 Internal(mut internal_handle) => {
718 let mut right_handle = internal_handle.right_edge();
720 //We're not a proper leaf stack, let's get to work.
721 self.stack.push(right_handle.as_raw());
723 let mut temp_node = right_handle.edge_mut();
725 // Walk into the smallest subtree of this node
726 let node = temp_node;
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);
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();
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
758 /// Assumes that the stack represents a search path from the root to a leaf.
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 {
763 self.map.length += 1;
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);
772 // The last insertion went off without a hitch, no splits! We can stop
774 return &mut *inserted_ptr;
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.
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,
787 return &mut *inserted_ptr;
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);
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();
813 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
815 fn extend<T: Iterator<Item=(K, V)>>(&mut self, mut iter: T) {
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() {
832 impl<K: Ord, V> Default for BTreeMap<K, V> {
834 fn default() -> BTreeMap<K, V> {
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)
848 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
851 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
853 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
854 iter::order::partial_cmp(self.iter(), other.iter())
859 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
861 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
862 iter::order::cmp(self.iter(), other.iter())
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 {{"));
871 for (i, (k, v)) in self.iter().enumerate() {
872 if i != 0 { try!(write!(f, ", ")); }
873 try!(write!(f, "{:?}: {:?}", *k, *v));
881 impl<K: Ord, Q: ?Sized, V> Index<Q> for BTreeMap<K, V>
882 where Q: BorrowFrom<K> + Ord
886 fn index(&self, key: &Q) -> &V {
887 self.get(key).expect("no entry found for key")
892 impl<K: Ord, Q: ?Sized, V> IndexMut<Q> for BTreeMap<K, V>
893 where Q: BorrowFrom<K> + Ord
897 fn index_mut(&mut self, key: &Q) -> &mut V {
898 self.get_mut(key).expect("no entry found for key")
902 /// Genericises over how to get the correct type of iterator from the correct type
903 /// of Node ownership.
905 fn traverse(node: N) -> Self;
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> {
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> {
920 impl<K, V> Traverse<Node<K, V>> for MoveTraversal<K, V> {
921 fn traverse(node: Node<K, V>) -> MoveTraversal<K, V> {
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.
935 impl<K, V, E, T> Iterator for AbsIter<T> where
936 T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>,
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).
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)> {
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
961 // The right path had something, make that the new LCA
962 // and restart the whole process
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)) => {
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
980 // The head of the left path yielded an edge, so make that the new head
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)) => {
991 // Handle any operation on the left stack as necessary
993 Push(item) => { self.left.push_back(item); },
994 Pop => { self.left.pop_back(); },
999 fn size_hint(&self) -> (uint, Option<uint>) {
1000 (self.size, Some(self.size))
1004 impl<K, V, E, T> DoubleEndedIterator for AbsIter<T> where
1005 T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>,
1007 // next_back is totally symmetric to next
1008 fn next_back(&mut self) -> Option<(K, V)> {
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,
1019 Some(Edge(next)) => Push(Traverse::traverse(next)),
1020 Some(Elem(k, v)) => {
1025 Some(iter) => match iter.next_back() {
1027 Some(Edge(next)) => Push(Traverse::traverse(next)),
1028 Some(Elem(k, v)) => {
1036 Push(item) => { self.right.push_back(item); },
1037 Pop => { self.right.pop_back(); }
1044 impl<'a, K, V> Iterator for Iter<'a, K, V> {
1045 type Item = (&'a K, &'a V);
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() }
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() }
1055 impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {}
1058 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1059 type Item = (&'a K, &'a mut V);
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() }
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() }
1069 impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {}
1072 impl<K, V> Iterator for IntoIter<K, V> {
1075 fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1076 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1079 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1080 fn next_back(&mut self) -> Option<(K, V)> { self.inner.next_back() }
1083 impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
1086 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1089 fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
1090 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1093 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1094 fn next_back(&mut self) -> Option<(&'a K)> { self.inner.next_back() }
1097 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {}
1101 impl<'a, K, V> Iterator for Values<'a, K, V> {
1104 fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
1105 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1108 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1109 fn next_back(&mut self) -> Option<(&'a V)> { self.inner.next_back() }
1112 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}
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>> {
1119 Occupied(entry) => Ok(entry.into_mut()),
1120 Vacant(entry) => Err(entry),
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)
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 {
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()
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()
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);
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 {
1168 impl<K, V> BTreeMap<K, V> {
1169 /// Gets an iterator over the entries of the map.
1174 /// use std::collections::BTreeMap;
1176 /// let mut map = BTreeMap::new();
1177 /// map.insert(1u, "a");
1178 /// map.insert(2u, "b");
1179 /// map.insert(3u, "c");
1181 /// for (key, value) in map.iter() {
1182 /// println!("{}: {}", key, value);
1185 /// let (first_key, first_value) = map.iter().next().unwrap();
1186 /// assert_eq!((*first_key, *first_value), (1u, "a"));
1189 pub fn iter(&self) -> Iter<K, V> {
1190 let len = self.len();
1193 lca: Traverse::traverse(&self.root),
1194 left: RingBuf::new(),
1195 right: RingBuf::new(),
1201 /// Gets a mutable iterator over the entries of the map.
1206 /// use std::collections::BTreeMap;
1208 /// let mut map = BTreeMap::new();
1209 /// map.insert("a", 1u);
1210 /// map.insert("b", 2u);
1211 /// map.insert("c", 3u);
1213 /// // add 10 to the value if the key isn't "a"
1214 /// for (key, value) in map.iter_mut() {
1215 /// if key != &"a" {
1221 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1222 let len = self.len();
1225 lca: Traverse::traverse(&mut self.root),
1226 left: RingBuf::new(),
1227 right: RingBuf::new(),
1233 /// Gets an owning iterator over the entries of the map.
1238 /// use std::collections::BTreeMap;
1240 /// let mut map = BTreeMap::new();
1241 /// map.insert(1u, "a");
1242 /// map.insert(2u, "b");
1243 /// map.insert(3u, "c");
1245 /// for (key, value) in map.into_iter() {
1246 /// println!("{}: {}", key, value);
1250 pub fn into_iter(self) -> IntoIter<K, V> {
1251 let len = self.len();
1254 lca: Traverse::traverse(self.root),
1255 left: RingBuf::new(),
1256 right: RingBuf::new(),
1262 /// Gets an iterator over the keys of the map.
1267 /// use std::collections::BTreeMap;
1269 /// let mut a = BTreeMap::new();
1270 /// a.insert(1u, "a");
1271 /// a.insert(2u, "b");
1273 /// let keys: Vec<uint> = a.keys().cloned().collect();
1274 /// assert_eq!(keys, vec![1u,2,]);
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
1281 Keys { inner: self.iter().map(first) }
1284 /// Gets an iterator over the values of the map.
1289 /// use std::collections::BTreeMap;
1291 /// let mut a = BTreeMap::new();
1292 /// a.insert(1u, "a");
1293 /// a.insert(2u, "b");
1295 /// let values: Vec<&str> = a.values().cloned().collect();
1296 /// assert_eq!(values, vec!["a","b"]);
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
1303 Values { inner: self.iter().map(second) }
1306 /// Return the number of elements in the map.
1311 /// use std::collections::BTreeMap;
1313 /// let mut a = BTreeMap::new();
1314 /// assert_eq!(a.len(), 0);
1315 /// a.insert(1u, "a");
1316 /// assert_eq!(a.len(), 1);
1319 pub fn len(&self) -> uint { self.length }
1321 /// Return true if the map contains no elements.
1326 /// use std::collections::BTreeMap;
1328 /// let mut a = BTreeMap::new();
1329 /// assert!(a.is_empty());
1330 /// a.insert(1u, "a");
1331 /// assert!(!a.is_empty());
1334 pub fn is_empty(&self) -> bool { self.len() == 0 }
1337 impl<K: Ord, V> BTreeMap<K, V> {
1338 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1343 /// use std::collections::BTreeMap;
1344 /// use std::collections::btree_map::Entry;
1346 /// let mut count: BTreeMap<&str, uint> = BTreeMap::new();
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) => {
1354 /// Entry::Occupied(mut view) => {
1355 /// let v = view.get_mut();
1361 /// assert_eq!(count["a"], 3u);
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);
1369 let result = stack.with(move |pusher, node| {
1370 return match Node::search(node, &key) {
1373 Finished(Occupied(OccupiedEntry {
1374 stack: pusher.seal(handle)
1378 match handle.force() {
1379 Leaf(leaf_handle) => {
1380 Finished(Vacant(VacantEntry {
1381 stack: pusher.seal(leaf_handle),
1385 Internal(internal_handle) => {
1387 pusher.push(internal_handle),
1396 Finished(finished) => return finished,
1397 Continue((new_stack, renewed_key)) => {
1414 use super::{BTreeMap, Occupied, Vacant};
1417 fn test_basic_large() {
1418 let mut map = BTreeMap::new();
1420 assert_eq!(map.len(), 0);
1422 for i in range(0, size) {
1423 assert_eq!(map.insert(i, 10*i), None);
1424 assert_eq!(map.len(), i + 1);
1427 for i in range(0, size) {
1428 assert_eq!(map.get(&i).unwrap(), &(i*10));
1431 for i in range(size, size*2) {
1432 assert_eq!(map.get(&i), None);
1435 for i in range(0, size) {
1436 assert_eq!(map.insert(i, 100*i), Some(10*i));
1437 assert_eq!(map.len(), size);
1440 for i in range(0, size) {
1441 assert_eq!(map.get(&i).unwrap(), &(i*100));
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);
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));
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);
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);
1482 let mut map: BTreeMap<uint, uint> = range(0, size).map(|i| (i, i)).collect();
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));
1490 assert_eq!(iter.size_hint(), (0, Some(0)));
1491 assert_eq!(iter.next(), None);
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)));
1500 assert_eq!(iter.size_hint(), (0, Some(0)));
1501 assert_eq!(iter.next(), None);
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));
1510 assert_eq!(iter.size_hint(), (0, Some(0)));
1511 assert_eq!(iter.next(), None);
1517 fn test_iter_rev() {
1521 let mut map: BTreeMap<uint, uint> = range(0, size).map(|i| (i, i)).collect();
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)));
1529 assert_eq!(iter.size_hint(), (0, Some(0)));
1530 assert_eq!(iter.next(), None);
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)));
1539 assert_eq!(iter.size_hint(), (0, Some(0)));
1540 assert_eq!(iter.next(), None);
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));
1549 assert_eq!(iter.size_hint(), (0, Some(0)));
1550 assert_eq!(iter.next(), None);
1557 let xs = [(1i, 10i), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1559 let mut map: BTreeMap<int, int> = xs.iter().map(|&x| x).collect();
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);
1569 assert_eq!(map.get(&1).unwrap(), &100);
1570 assert_eq!(map.len(), 6);
1573 // Existing key (update)
1574 match map.entry(2) {
1575 Vacant(_) => unreachable!(),
1576 Occupied(mut view) => {
1577 let v = view.get_mut();
1581 assert_eq!(map.get(&2).unwrap(), &200);
1582 assert_eq!(map.len(), 6);
1584 // Existing key (take)
1585 match map.entry(3) {
1586 Vacant(_) => unreachable!(),
1588 assert_eq!(view.remove(), 30);
1591 assert_eq!(map.get(&3), None);
1592 assert_eq!(map.len(), 5);
1595 // Inexistent key (insert)
1596 match map.entry(10) {
1597 Occupied(_) => unreachable!(),
1599 assert_eq!(*view.insert(1000), 1000);
1602 assert_eq!(map.get(&10).unwrap(), &1000);
1603 assert_eq!(map.len(), 6);
1615 use std::rand::{weak_rng, Rng};
1616 use test::{Bencher, black_box};
1618 use super::BTreeMap;
1619 use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
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); });
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); });
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); });
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); });
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); });
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); });
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); });
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); });
1688 fn bench_iter(b: &mut Bencher, size: uint) {
1689 let mut map = BTreeMap::<uint, uint>::new();
1690 let mut rng = weak_rng();
1692 for _ in range(0, size) {
1693 map.insert(rng.gen(), rng.gen());
1697 for entry in map.iter() {
1704 pub fn iter_20(b: &mut Bencher) {
1709 pub fn iter_1000(b: &mut Bencher) {
1710 bench_iter(b, 1000);
1714 pub fn iter_100000(b: &mut Bencher) {
1715 bench_iter(b, 100000);