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::*;
23 use super::node::{mod, Node, Found, GoDown};
24 use super::node::{Traversal, MutTraversal, MoveTraversal};
25 use super::node::TraversalItem::{mod, Elem, Edge};
26 use super::node::ForceResult::{Leaf, Internal};
27 use core::borrow::BorrowFrom;
28 use std::hash::{Writer, Hash};
29 use core::default::Default;
30 use core::{iter, fmt, mem};
33 use ring_buf::RingBuf;
35 use self::Continuation::{Continue, Finished};
37 // FIXME(conventions): implement bounded iterators
39 /// A map based on a B-Tree.
41 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
42 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
43 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
44 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
45 /// is done is *very* inefficient for modern computer architectures. In particular, every element
46 /// is stored in its own individually heap-allocated node. This means that every single insertion
47 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
48 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
51 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
52 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
53 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
54 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
55 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
56 /// the node using binary search. As a compromise, one could also perform a linear search
57 /// that initially only checks every i<sup>th</sup> element for some choice of i.
59 /// Currently, our implementation simply performs naive linear search. This provides excellent
60 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
61 /// would like to further explore choosing the optimal search strategy based on the choice of B,
62 /// and possibly other factors. Using linear search, searching for a random element is expected
63 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
64 /// however, performance is excellent. `BTreeMap` is able to readily outperform `TreeMap` under
65 /// many workloads, and is competitive where it doesn't. BTreeMap also generally *scales* better
66 /// than TreeMap, making it more appropriate for large datasets.
68 /// However, `TreeMap` may still be more appropriate to use in many contexts. If elements are very
69 /// large or expensive to compare, `TreeMap` may be more appropriate. It won't allocate any
70 /// more space than is needed, and will perform the minimal number of comparisons necessary.
71 /// `TreeMap` also provides much better performance stability guarantees. Generally, very few
72 /// changes need to be made to update a BST, and two updates are expected to take about the same
73 /// amount of time on roughly equal sized BSTs. However a B-Tree's performance is much more
74 /// amortized. If a node is overfull, it must be split into two nodes. If a node is underfull, it
75 /// may be merged with another. Both of these operations are relatively expensive to perform, and
76 /// it's possible to force one to occur at every single level of the tree in a single insertion or
77 /// deletion. In fact, a malicious or otherwise unlucky sequence of insertions and deletions can
78 /// force this degenerate behaviour to occur on every operation. While the total amount of work
79 /// done on each operation isn't *catastrophic*, and *is* still bounded by O(B log<sub>B</sub>n),
80 /// it is certainly much slower when it does.
82 pub struct BTreeMap<K, V> {
89 /// An abstract base over-which all other BTree iterators are built.
90 struct AbsEntries<T> {
97 /// An iterator over a BTreeMap's entries.
98 pub struct Entries<'a, K: 'a, V: 'a> {
99 inner: AbsEntries<Traversal<'a, K, V>>
102 /// A mutable iterator over a BTreeMap's entries.
103 pub struct MutEntries<'a, K: 'a, V: 'a> {
104 inner: AbsEntries<MutTraversal<'a, K, V>>
107 /// An owning iterator over a BTreeMap's entries.
108 pub struct MoveEntries<K, V> {
109 inner: AbsEntries<MoveTraversal<K, V>>
112 /// An iterator over a BTreeMap's keys.
113 pub type Keys<'a, K, V> =
114 iter::Map<(&'a K, &'a V), &'a K, Entries<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>;
116 /// An iterator over a BTreeMap's values.
117 pub type Values<'a, K, V> =
118 iter::Map<(&'a K, &'a V), &'a V, Entries<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>;
120 /// A view into a single entry in a map, which may either be vacant or occupied.
121 pub enum Entry<'a, K:'a, V:'a> {
123 Vacant(VacantEntry<'a, K, V>),
124 /// An occupied Entry
125 Occupied(OccupiedEntry<'a, K, V>),
129 pub struct VacantEntry<'a, K:'a, V:'a> {
131 stack: stack::SearchStack<'a, K, V, node::Edge, node::Leaf>,
134 /// An occupied Entry.
135 pub struct OccupiedEntry<'a, K:'a, V:'a> {
136 stack: stack::SearchStack<'a, K, V, node::KV, node::LeafOrInternal>,
139 impl<K: Ord, V> BTreeMap<K, V> {
140 /// Makes a new empty BTreeMap with a reasonable choice for B.
141 #[unstable = "matches collection reform specification, waiting for dust to settle"]
142 pub fn new() -> BTreeMap<K, V> {
143 //FIXME(Gankro): Tune this as a function of size_of<K/V>?
147 /// Makes a new empty BTreeMap with the given B.
149 /// B cannot be less than 2.
150 pub fn with_b(b: uint) -> BTreeMap<K, V> {
151 assert!(b > 1, "B must be greater than 1");
155 root: Node::make_leaf_root(b),
160 /// Clears the map, removing all values.
165 /// use std::collections::BTreeMap;
167 /// let mut a = BTreeMap::new();
168 /// a.insert(1u, "a");
170 /// assert!(a.is_empty());
172 #[unstable = "matches collection reform specification, waiting for dust to settle"]
173 pub fn clear(&mut self) {
175 // avoid recursive destructors by manually traversing the tree
176 for _ in mem::replace(self, BTreeMap::with_b(b)).into_iter() {};
179 /// Deprecated: renamed to `get`.
180 #[deprecated = "renamed to `get`"]
181 pub fn find(&self, key: &K) -> Option<&V> {
185 // Searching in a B-Tree is pretty straightforward.
187 // Start at the root. Try to find the key in the current node. If we find it, return it.
188 // If it's not in there, follow the edge *before* the smallest key larger than
189 // the search key. If no such key exists (they're *all* smaller), then just take the last
190 // edge in the node. If we're in a leaf and we don't find our key, then it's not
193 /// Returns a reference to the value corresponding to the key.
195 /// The key may be any borrowed form of the map's key type, but the ordering
196 /// on the borrowed form *must* match the ordering on the key type.
201 /// use std::collections::BTreeMap;
203 /// let mut map = BTreeMap::new();
204 /// map.insert(1u, "a");
205 /// assert_eq!(map.get(&1), Some(&"a"));
206 /// assert_eq!(map.get(&2), None);
208 #[unstable = "matches collection reform specification, waiting for dust to settle"]
209 pub fn get<Sized? Q>(&self, key: &Q) -> Option<&V> where Q: BorrowFrom<K> + Ord {
210 let mut cur_node = &self.root;
212 match Node::search(cur_node, key) {
213 Found(handle) => return Some(handle.into_kv().1),
214 GoDown(handle) => match handle.force() {
215 Leaf(_) => return None,
216 Internal(internal_handle) => {
217 cur_node = internal_handle.into_edge();
225 /// Returns true if the map contains a value for the specified key.
227 /// The key may be any borrowed form of the map's key type, but the ordering
228 /// on the borrowed form *must* match the ordering on the key type.
233 /// use std::collections::BTreeMap;
235 /// let mut map = BTreeMap::new();
236 /// map.insert(1u, "a");
237 /// assert_eq!(map.contains_key(&1), true);
238 /// assert_eq!(map.contains_key(&2), false);
240 #[unstable = "matches collection reform specification, waiting for dust to settle"]
241 pub fn contains_key<Sized? Q>(&self, key: &Q) -> bool where Q: BorrowFrom<K> + Ord {
242 self.get(key).is_some()
245 /// Deprecated: renamed to `get_mut`.
246 #[deprecated = "renamed to `get_mut`"]
247 pub fn find_mut(&mut self, key: &K) -> Option<&mut V> {
251 /// Returns a mutable reference to the value corresponding to the key.
253 /// The key may be any borrowed form of the map's key type, but the ordering
254 /// on the borrowed form *must* match the ordering on the key type.
259 /// use std::collections::BTreeMap;
261 /// let mut map = BTreeMap::new();
262 /// map.insert(1u, "a");
263 /// match map.get_mut(&1) {
264 /// Some(x) => *x = "b",
267 /// assert_eq!(map[1], "b");
269 // See `get` for implementation notes, this is basically a copy-paste with mut's added
270 #[unstable = "matches collection reform specification, waiting for dust to settle"]
271 pub fn get_mut<Sized? Q>(&mut self, key: &Q) -> Option<&mut V> where Q: BorrowFrom<K> + Ord {
272 // temp_node is a Borrowck hack for having a mutable value outlive a loop iteration
273 let mut temp_node = &mut self.root;
275 let cur_node = temp_node;
276 match Node::search(cur_node, key) {
277 Found(handle) => return Some(handle.into_kv_mut().1),
278 GoDown(handle) => match handle.force() {
279 Leaf(_) => return None,
280 Internal(internal_handle) => {
281 temp_node = internal_handle.into_edge_mut();
289 /// Deprecated: renamed to `insert`.
290 #[deprecated = "renamed to `insert`"]
291 pub fn swap(&mut self, key: K, value: V) -> Option<V> {
292 self.insert(key, value)
295 // Insertion in a B-Tree is a bit complicated.
297 // First we do the same kind of search described in `find`. But we need to maintain a stack of
298 // all the nodes/edges in our search path. If we find a match for the key we're trying to
299 // insert, just swap the vals and return the old ones. However, when we bottom out in a leaf,
300 // we attempt to insert our key-value pair at the same location we would want to follow another
303 // If the node has room, then this is done in the obvious way by shifting elements. However,
304 // if the node itself is full, we split node into two, and give its median key-value
305 // pair to its parent to insert the new node with. Of course, the parent may also be
306 // full, and insertion can propagate until we reach the root. If we reach the root, and
307 // it is *also* full, then we split the root and place the two nodes under a newly made root.
309 // Note that we subtly deviate from Open Data Structures in our implementation of split.
310 // ODS describes inserting into the node *regardless* of its capacity, and then
311 // splitting *afterwards* if it happens to be overfull. However, this is inefficient.
312 // Instead, we split beforehand, and then insert the key-value pair into the appropriate
313 // result node. This has two consequences:
315 // 1) While ODS produces a left node of size B-1, and a right node of size B,
316 // we may potentially reverse this. However, this shouldn't effect the analysis.
318 // 2) While ODS may potentially return the pair we *just* inserted after
319 // the split, we will never do this. Again, this shouldn't effect the analysis.
321 /// Inserts a key-value pair from the map. If the key already had a value
322 /// present in the map, that value is returned. Otherwise, `None` is returned.
327 /// use std::collections::BTreeMap;
329 /// let mut map = BTreeMap::new();
330 /// assert_eq!(map.insert(37u, "a"), None);
331 /// assert_eq!(map.is_empty(), false);
333 /// map.insert(37, "b");
334 /// assert_eq!(map.insert(37, "c"), Some("b"));
335 /// assert_eq!(map[37], "c");
337 #[unstable = "matches collection reform specification, waiting for dust to settle"]
338 pub fn insert(&mut self, mut key: K, mut value: V) -> Option<V> {
339 // This is a stack of rawptrs to nodes paired with indices, respectively
340 // representing the nodes and edges of our search path. We have to store rawptrs
341 // because as far as Rust is concerned, we can mutate aliased data with such a
342 // stack. It is of course correct, but what it doesn't know is that we will only
343 // be popping and using these ptrs one at a time in child-to-parent order. The alternative
344 // to doing this is to take the Nodes from their parents. This actually makes
345 // borrowck *really* happy and everything is pretty smooth. However, this creates
346 // *tons* of pointless writes, and requires us to always walk all the way back to
347 // the root after an insertion, even if we only needed to change a leaf. Therefore,
348 // we accept this potential unsafety and complexity in the name of performance.
350 // Regardless, the actual dangerous logic is completely abstracted away from BTreeMap
351 // by the stack module. All it can do is immutably read nodes, and ask the search stack
352 // to proceed down some edge by index. This makes the search logic we'll be reusing in a
353 // few different methods much neater, and of course drastically improves safety.
354 let mut stack = stack::PartialSearchStack::new(self);
357 let result = stack.with(move |pusher, node| {
358 // Same basic logic as found in `find`, but with PartialSearchStack mediating the
359 // actual nodes for us
360 return match Node::search(node, &key) {
361 Found(mut handle) => {
362 // Perfect match, swap the values and return the old one
363 mem::swap(handle.val_mut(), &mut value);
364 Finished(Some(value))
367 // We need to keep searching, try to get the search stack
368 // to go down further
369 match handle.force() {
370 Leaf(leaf_handle) => {
371 // We've reached a leaf, perform the insertion here
372 pusher.seal(leaf_handle).insert(key, value);
375 Internal(internal_handle) => {
376 // We've found the subtree to insert this key/value pair in,
378 Continue((pusher.push(internal_handle), key, value))
385 Finished(ret) => { return ret; },
386 Continue((new_stack, renewed_key, renewed_val)) => {
395 // Deletion is the most complicated operation for a B-Tree.
397 // First we do the same kind of search described in
398 // `find`. But we need to maintain a stack of all the nodes/edges in our search path.
399 // If we don't find the key, then we just return `None` and do nothing. If we do find the
400 // key, we perform two operations: remove the item, and then possibly handle underflow.
402 // # removing the item
403 // If the node is a leaf, we just remove the item, and shift
404 // any items after it back to fill the hole.
406 // If the node is an internal node, we *swap* the item with the smallest item in
407 // in its right subtree (which must reside in a leaf), and then revert to the leaf
410 // # handling underflow
411 // After removing an item, there may be too few items in the node. We want nodes
412 // to be mostly full for efficiency, although we make an exception for the root, which
413 // may have as few as one item. If this is the case, we may first try to steal
414 // an item from our left or right neighbour.
416 // To steal from the left (right) neighbour,
417 // we take the largest (smallest) item and child from it. We then swap the taken item
418 // with the item in their mutual parent that separates them, and then insert the
419 // parent's item and the taken child into the first (last) index of the underflowed node.
421 // However, stealing has the possibility of underflowing our neighbour. If this is the
422 // case, we instead *merge* with our neighbour. This of course reduces the number of
423 // children in the parent. Therefore, we also steal the item that separates the now
424 // merged nodes, and insert it into the merged node.
426 // Merging may cause the parent to underflow. If this is the case, then we must repeat
427 // the underflow handling process on the parent. If merging merges the last two children
428 // of the root, then we replace the root with the merged node.
430 /// Deprecated: renamed to `remove`.
431 #[deprecated = "renamed to `remove`"]
432 pub fn pop(&mut self, key: &K) -> Option<V> {
436 /// Removes a key from the map, returning the value at the key if the key
437 /// was previously in the map.
439 /// The key may be any borrowed form of the map's key type, but the ordering
440 /// on the borrowed form *must* match the ordering on the key type.
445 /// use std::collections::BTreeMap;
447 /// let mut map = BTreeMap::new();
448 /// map.insert(1u, "a");
449 /// assert_eq!(map.remove(&1), Some("a"));
450 /// assert_eq!(map.remove(&1), None);
452 #[unstable = "matches collection reform specification, waiting for dust to settle"]
453 pub fn remove<Sized? Q>(&mut self, key: &Q) -> Option<V> where Q: BorrowFrom<K> + Ord {
454 // See `swap` for a more thorough description of the stuff going on in here
455 let mut stack = stack::PartialSearchStack::new(self);
457 let result = stack.with(move |pusher, node| {
458 return match Node::search(node, key) {
460 // Perfect match. Terminate the stack here, and remove the entry
461 Finished(Some(pusher.seal(handle).remove()))
464 // We need to keep searching, try to go down the next edge
465 match handle.force() {
466 // We're at a leaf; the key isn't in here
467 Leaf(_) => Finished(None),
468 Internal(internal_handle) => Continue(pusher.push(internal_handle))
474 Finished(ret) => return ret,
475 Continue(new_stack) => stack = new_stack
481 /// A helper enum useful for deciding whether to continue a loop since we can't
482 /// return from a closure
483 enum Continuation<A, B> {
488 /// The stack module provides a safe interface for constructing and manipulating a stack of ptrs
489 /// to nodes. By using this module much better safety guarantees can be made, and more search
490 /// boilerplate gets cut out.
492 use core::prelude::*;
493 use core::kinds::marker;
496 use super::super::node::{mod, Node, Fit, Split, KV, Edge, Internal, Leaf, LeafOrInternal};
499 /// A generic mutable reference, identical to `&mut` except for the fact that its lifetime
500 /// parameter is invariant. This means that wherever an `IdRef` is expected, only an `IdRef`
501 /// with the exact requested lifetime can be used. This is in contrast to normal references,
502 /// where `&'static` can be used in any function expecting any lifetime reference.
503 pub struct IdRef<'id, T: 'id> {
505 marker: marker::InvariantLifetime<'id>
508 impl<'id, T> Deref<T> for IdRef<'id, T> {
509 fn deref(&self) -> &T {
514 impl<'id, T> DerefMut<T> for IdRef<'id, T> {
515 fn deref_mut(&mut self) -> &mut T {
520 type StackItem<K, V> = node::Handle<*mut Node<K, V>, Edge, Internal>;
521 type Stack<K, V> = Vec<StackItem<K, V>>;
523 /// A `PartialSearchStack` handles the construction of a search stack.
524 pub struct PartialSearchStack<'a, K:'a, V:'a> {
525 map: &'a mut BTreeMap<K, V>,
527 next: *mut Node<K, V>,
530 /// A `SearchStack` represents a full path to an element or an edge of interest. It provides
531 /// methods depending on the type of what the path points to for removing an element, inserting
532 /// a new element, and manipulating to element at the top of the stack.
533 pub struct SearchStack<'a, K:'a, V:'a, Type, NodeType> {
534 map: &'a mut BTreeMap<K, V>,
536 top: node::Handle<*mut Node<K, V>, Type, NodeType>,
539 /// A `PartialSearchStack` that doesn't hold a a reference to the next node, and is just
540 /// just waiting for a `Handle` to that next node to be pushed. See `PartialSearchStack::with`
541 /// for more details.
542 pub struct Pusher<'id, 'a, K:'a, V:'a> {
543 map: &'a mut BTreeMap<K, V>,
545 marker: marker::InvariantLifetime<'id>
548 impl<'a, K, V> PartialSearchStack<'a, K, V> {
549 /// Creates a new PartialSearchStack from a BTreeMap by initializing the stack with the
550 /// root of the tree.
551 pub fn new(map: &'a mut BTreeMap<K, V>) -> PartialSearchStack<'a, K, V> {
552 let depth = map.depth;
555 next: &mut map.root as *mut _,
557 stack: Vec::with_capacity(depth),
561 /// Breaks up the stack into a `Pusher` and the next `Node`, allowing the given closure
562 /// to interact with, search, and finally push the `Node` onto the stack. The passed in
563 /// closure must be polymorphic on the `'id` lifetime parameter, as this statically
564 /// ensures that only `Handle`s from the correct `Node` can be pushed.
566 /// The reason this works is that the `Pusher` has an `'id` parameter, and will only accept
567 /// handles with the same `'id`. The closure could only get references with that lifetime
568 /// through its arguments or through some other `IdRef` that it has lying around. However,
569 /// no other `IdRef` could possibly work - because the `'id` is held in an invariant
570 /// parameter, it would need to have precisely the correct lifetime, which would mean that
571 /// at least one of the calls to `with` wouldn't be properly polymorphic, wanting a
572 /// specific lifetime instead of the one that `with` chooses to give it.
574 /// See also Haskell's `ST` monad, which uses a similar trick.
575 pub fn with<T, F: for<'id> FnOnce(Pusher<'id, 'a, K, V>,
576 IdRef<'id, Node<K, V>>) -> T>(self, closure: F) -> T {
577 let pusher = Pusher {
580 marker: marker::InvariantLifetime
583 inner: unsafe { &mut *self.next },
584 marker: marker::InvariantLifetime
587 closure(pusher, node)
591 impl<'id, 'a, K, V> Pusher<'id, 'a, K, V> {
592 /// Pushes the requested child of the stack's current top on top of the stack. If the child
593 /// exists, then a new PartialSearchStack is yielded. Otherwise, a VacantSearchStack is
595 pub fn push(mut self, mut edge: node::Handle<IdRef<'id, Node<K, V>>, Edge, Internal>)
596 -> PartialSearchStack<'a, K, V> {
597 self.stack.push(edge.as_raw());
601 next: edge.edge_mut() as *mut _,
605 /// Converts the PartialSearchStack into a SearchStack.
606 pub fn seal<Type, NodeType>
607 (self, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>)
608 -> SearchStack<'a, K, V, Type, NodeType> {
612 top: handle.as_raw(),
617 impl<'a, K, V, NodeType> SearchStack<'a, K, V, KV, NodeType> {
618 /// Gets a reference to the value the stack points to.
619 pub fn peek(&self) -> &V {
620 unsafe { self.top.from_raw().into_kv().1 }
623 /// Gets a mutable reference to the value the stack points to.
624 pub fn peek_mut(&mut self) -> &mut V {
625 unsafe { self.top.from_raw_mut().into_kv_mut().1 }
628 /// Converts the stack into a mutable reference to the value it points to, with a lifetime
629 /// tied to the original tree.
630 pub fn into_top(mut self) -> &'a mut V {
632 mem::copy_mut_lifetime(
634 self.top.from_raw_mut().val_mut()
640 impl<'a, K, V> SearchStack<'a, K, V, KV, Leaf> {
641 /// Removes the key and value in the top element of the stack, then handles underflows as
642 /// described in BTree's pop function.
643 fn remove_leaf(mut self) -> V {
644 self.map.length -= 1;
646 // Remove the key-value pair from the leaf that this search stack points to.
647 // Then, note if the leaf is underfull, and promptly forget the leaf and its ptr
648 // to avoid ownership issues.
649 let (value, mut underflow) = unsafe {
650 let (_, value) = self.top.from_raw_mut().remove_as_leaf();
651 let underflow = self.top.from_raw().node().is_underfull();
656 match self.stack.pop() {
658 // We've reached the root, so no matter what, we're done. We manually
659 // access the root via the tree itself to avoid creating any dangling
661 if self.map.root.len() == 0 && !self.map.root.is_leaf() {
662 // We've emptied out the root, so make its only child the new root.
663 // If it's a leaf, we just let it become empty.
665 self.map.root.hoist_lone_child();
669 Some(mut handle) => {
671 // Underflow! Handle it!
673 handle.from_raw_mut().handle_underflow();
674 underflow = handle.from_raw().node().is_underfull();
686 impl<'a, K, V> SearchStack<'a, K, V, KV, LeafOrInternal> {
687 /// Removes the key and value in the top element of the stack, then handles underflows as
688 /// described in BTree's pop function.
689 pub fn remove(self) -> V {
690 // Ensure that the search stack goes to a leaf. This is necessary to perform deletion
691 // in a BTree. Note that this may put the tree in an inconsistent state (further
692 // described in into_leaf's comments), but this is immediately fixed by the
693 // removing the value we want to remove
694 self.into_leaf().remove_leaf()
697 /// Subroutine for removal. Takes a search stack for a key that might terminate at an
698 /// internal node, and mutates the tree and search stack to *make* it a search stack
699 /// for that same key that *does* terminates at a leaf. If the mutation occurs, then this
700 /// leaves the tree in an inconsistent state that must be repaired by the caller by
701 /// removing the entry in question. Specifically the key-value pair and its successor will
703 fn into_leaf(mut self) -> SearchStack<'a, K, V, KV, Leaf> {
705 let mut top_raw = self.top;
706 let mut top = top_raw.from_raw_mut();
708 let key_ptr = top.key_mut() as *mut _;
709 let val_ptr = top.val_mut() as *mut _;
711 // Try to go into the right subtree of the found key to find its successor
713 Leaf(mut leaf_handle) => {
714 // We're a proper leaf stack, nothing to do
718 top: leaf_handle.as_raw()
721 Internal(mut internal_handle) => {
722 let mut right_handle = internal_handle.right_edge();
724 //We're not a proper leaf stack, let's get to work.
725 self.stack.push(right_handle.as_raw());
727 let mut temp_node = right_handle.edge_mut();
729 // Walk into the smallest subtree of this node
730 let node = temp_node;
732 match node.kv_handle(0).force() {
733 Leaf(mut handle) => {
734 // This node is a leaf, do the swap and return
735 mem::swap(handle.key_mut(), &mut *key_ptr);
736 mem::swap(handle.val_mut(), &mut *val_ptr);
743 Internal(kv_handle) => {
744 // This node is internal, go deeper
745 let mut handle = kv_handle.into_left_edge();
746 self.stack.push(handle.as_raw());
747 temp_node = handle.into_edge_mut();
757 impl<'a, K, V> SearchStack<'a, K, V, Edge, Leaf> {
758 /// Inserts the key and value into the top element in the stack, and if that node has to
759 /// split recursively inserts the split contents into the next element stack until
762 /// Assumes that the stack represents a search path from the root to a leaf.
764 /// An &mut V is returned to the inserted value, for callers that want a reference to this.
765 pub fn insert(mut self, key: K, val: V) -> &'a mut V {
767 self.map.length += 1;
769 // Insert the key and value into the leaf at the top of the stack
770 let (mut insertion, inserted_ptr) = self.top.from_raw_mut()
771 .insert_as_leaf(key, val);
776 // The last insertion went off without a hitch, no splits! We can stop
778 return &mut *inserted_ptr;
780 Split(key, val, right) => match self.stack.pop() {
781 // The last insertion triggered a split, so get the next element on the
782 // stack to recursively insert the split node into.
784 // The stack was empty; we've split the root, and need to make a
785 // a new one. This is done in-place because we can't move the
786 // root out of a reference to the tree.
787 Node::make_internal_root(&mut self.map.root, self.map.b,
791 return &mut *inserted_ptr;
793 Some(mut handle) => {
794 // The stack wasn't empty, do the insertion and recurse
795 insertion = handle.from_raw_mut()
796 .insert_as_internal(key, val, right);
807 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
808 fn from_iter<T: Iterator<(K, V)>>(iter: T) -> BTreeMap<K, V> {
809 let mut map = BTreeMap::new();
815 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
817 fn extend<T: Iterator<(K, V)>>(&mut self, mut iter: T) {
824 impl<S: Writer, K: Hash<S>, V: Hash<S>> Hash<S> for BTreeMap<K, V> {
825 fn hash(&self, state: &mut S) {
826 for elt in self.iter() {
832 impl<K: Ord, V> Default for BTreeMap<K, V> {
833 fn default() -> BTreeMap<K, V> {
838 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
839 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
840 self.len() == other.len() &&
841 self.iter().zip(other.iter()).all(|(a, b)| a == b)
845 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
847 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
849 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
850 iter::order::partial_cmp(self.iter(), other.iter())
854 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
856 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
857 iter::order::cmp(self.iter(), other.iter())
861 impl<K: Show, V: Show> Show for BTreeMap<K, V> {
862 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
863 try!(write!(f, "{{"));
865 for (i, (k, v)) in self.iter().enumerate() {
866 if i != 0 { try!(write!(f, ", ")); }
867 try!(write!(f, "{}: {}", *k, *v));
874 impl<K: Ord, Sized? Q, V> Index<Q, V> for BTreeMap<K, V>
875 where Q: BorrowFrom<K> + Ord
877 fn index(&self, key: &Q) -> &V {
878 self.get(key).expect("no entry found for key")
882 impl<K: Ord, Sized? Q, V> IndexMut<Q, V> for BTreeMap<K, V>
883 where Q: BorrowFrom<K> + Ord
885 fn index_mut(&mut self, key: &Q) -> &mut V {
886 self.get_mut(key).expect("no entry found for key")
890 /// Genericises over how to get the correct type of iterator from the correct type
891 /// of Node ownership.
893 fn traverse(node: N) -> Self;
896 impl<'a, K, V> Traverse<&'a Node<K, V>> for Traversal<'a, K, V> {
897 fn traverse(node: &'a Node<K, V>) -> Traversal<'a, K, V> {
902 impl<'a, K, V> Traverse<&'a mut Node<K, V>> for MutTraversal<'a, K, V> {
903 fn traverse(node: &'a mut Node<K, V>) -> MutTraversal<'a, K, V> {
908 impl<K, V> Traverse<Node<K, V>> for MoveTraversal<K, V> {
909 fn traverse(node: Node<K, V>) -> MoveTraversal<K, V> {
914 /// Represents an operation to perform inside the following iterator methods.
915 /// This is necessary to use in `next` because we want to modify self.left inside
916 /// a match that borrows it. Similarly, in `next_back` for self.right. Instead, we use this
917 /// enum to note what we want to do, and do it after the match.
923 impl<K, V, E, T: Traverse<E> + DoubleEndedIterator<TraversalItem<K, V, E>>>
924 Iterator<(K, V)> for AbsEntries<T> {
925 // This function is pretty long, but only because there's a lot of cases to consider.
926 // Our iterator represents two search paths, left and right, to the smallest and largest
927 // elements we have yet to yield. lca represents the least common ancestor of these two paths,
928 // above-which we never walk, since everything outside it has already been consumed (or was
929 // never in the range to iterate).
931 // Note that the design of these iterators permits an *arbitrary* initial pair of min and max,
932 // making these arbitrary sub-range iterators. However the logic to construct these paths
933 // efficiently is fairly involved, so this is a FIXME. The sub-range iterators also wouldn't be
934 // able to accurately predict size, so those iterators can't implement ExactSizeIterator.
935 fn next(&mut self) -> Option<(K, V)> {
937 // We want the smallest element, so try to get the top of the left stack
938 let op = match self.left.back_mut() {
939 // The left stack is empty, so try to get the next element of the two paths
940 // LCAs (the left search path is currently a subpath of the right one)
941 None => match self.lca.next() {
942 // The lca has been exhausted, walk further down the right path
943 None => match self.right.pop_front() {
944 // The right path is exhausted, so we're done
946 // The right path had something, make that the new LCA
947 // and restart the whole process
953 // The lca yielded an edge, make that the new head of the left path
954 Some(Edge(next)) => Push(Traverse::traverse(next)),
955 // The lca yielded an entry, so yield that
956 Some(Elem(k, v)) => {
961 // The left stack wasn't empty, so continue along the node in its head
962 Some(iter) => match iter.next() {
963 // The head of the left path is empty, so Pop it off and restart the process
965 // The head of the left path yielded an edge, so make that the new head
967 Some(Edge(next)) => Push(Traverse::traverse(next)),
968 // The head of the left path yielded entry, so yield that
969 Some(Elem(k, v)) => {
976 // Handle any operation on the left stack as necessary
978 Push(item) => { self.left.push_back(item); },
979 Pop => { self.left.pop_back(); },
984 fn size_hint(&self) -> (uint, Option<uint>) {
985 (self.size, Some(self.size))
989 impl<K, V, E, T: Traverse<E> + DoubleEndedIterator<TraversalItem<K, V, E>>>
990 DoubleEndedIterator<(K, V)> for AbsEntries<T> {
991 // next_back is totally symmetric to next
992 fn next_back(&mut self) -> Option<(K, V)> {
994 let op = match self.right.back_mut() {
995 None => match self.lca.next_back() {
996 None => match self.left.pop_front() {
1003 Some(Edge(next)) => Push(Traverse::traverse(next)),
1004 Some(Elem(k, v)) => {
1009 Some(iter) => match iter.next_back() {
1011 Some(Edge(next)) => Push(Traverse::traverse(next)),
1012 Some(Elem(k, v)) => {
1020 Push(item) => { self.right.push_back(item); },
1021 Pop => { self.right.pop_back(); }
1027 impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> {
1028 fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
1029 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1031 impl<'a, K, V> DoubleEndedIterator<(&'a K, &'a V)> for Entries<'a, K, V> {
1032 fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next_back() }
1034 impl<'a, K, V> ExactSizeIterator<(&'a K, &'a V)> for Entries<'a, K, V> {}
1037 impl<'a, K, V> Iterator<(&'a K, &'a mut V)> for MutEntries<'a, K, V> {
1038 fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
1039 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1041 impl<'a, K, V> DoubleEndedIterator<(&'a K, &'a mut V)> for MutEntries<'a, K, V> {
1042 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next_back() }
1044 impl<'a, K, V> ExactSizeIterator<(&'a K, &'a mut V)> for MutEntries<'a, K, V> {}
1047 impl<K, V> Iterator<(K, V)> for MoveEntries<K, V> {
1048 fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
1049 fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
1051 impl<K, V> DoubleEndedIterator<(K, V)> for MoveEntries<K, V> {
1052 fn next_back(&mut self) -> Option<(K, V)> { self.inner.next_back() }
1054 impl<K, V> ExactSizeIterator<(K, V)> for MoveEntries<K, V> {}
1058 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
1059 /// Sets the value of the entry with the VacantEntry's key,
1060 /// and returns a mutable reference to it.
1061 pub fn set(self, value: V) -> &'a mut V {
1062 self.stack.insert(self.key, value)
1066 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
1067 /// Gets a reference to the value in the entry.
1068 pub fn get(&self) -> &V {
1072 /// Gets a mutable reference to the value in the entry.
1073 pub fn get_mut(&mut self) -> &mut V {
1074 self.stack.peek_mut()
1077 /// Converts the entry into a mutable reference to its value.
1078 pub fn into_mut(self) -> &'a mut V {
1079 self.stack.into_top()
1082 /// Sets the value of the entry with the OccupiedEntry's key,
1083 /// and returns the entry's old value.
1084 pub fn set(&mut self, mut value: V) -> V {
1085 mem::swap(self.stack.peek_mut(), &mut value);
1089 /// Takes the value of the entry out of the map, and returns it.
1090 pub fn take(self) -> V {
1095 impl<K, V> BTreeMap<K, V> {
1096 /// Gets an iterator over the entries of the map.
1101 /// use std::collections::BTreeMap;
1103 /// let mut map = BTreeMap::new();
1104 /// map.insert(1u, "a");
1105 /// map.insert(2u, "b");
1106 /// map.insert(3u, "c");
1108 /// for (key, value) in map.iter() {
1109 /// println!("{}: {}", key, value);
1112 /// let (first_key, first_value) = map.iter().next().unwrap();
1113 /// assert_eq!((*first_key, *first_value), (1u, "a"));
1115 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1116 pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
1117 let len = self.len();
1120 lca: Traverse::traverse(&self.root),
1121 left: RingBuf::new(),
1122 right: RingBuf::new(),
1128 /// Gets a mutable iterator over the entries of the map.
1133 /// use std::collections::BTreeMap;
1135 /// let mut map = BTreeMap::new();
1136 /// map.insert("a", 1u);
1137 /// map.insert("b", 2u);
1138 /// map.insert("c", 3u);
1140 /// // add 10 to the value if the key isn't "a"
1141 /// for (key, value) in map.iter_mut() {
1142 /// if key != &"a" {
1147 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1148 pub fn iter_mut<'a>(&'a mut self) -> MutEntries<'a, K, V> {
1149 let len = self.len();
1152 lca: Traverse::traverse(&mut self.root),
1153 left: RingBuf::new(),
1154 right: RingBuf::new(),
1160 /// Gets an owning iterator over the entries of the map.
1165 /// use std::collections::BTreeMap;
1167 /// let mut map = BTreeMap::new();
1168 /// map.insert(1u, "a");
1169 /// map.insert(2u, "b");
1170 /// map.insert(3u, "c");
1172 /// for (key, value) in map.into_iter() {
1173 /// println!("{}: {}", key, value);
1176 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1177 pub fn into_iter(self) -> MoveEntries<K, V> {
1178 let len = self.len();
1181 lca: Traverse::traverse(self.root),
1182 left: RingBuf::new(),
1183 right: RingBuf::new(),
1189 /// Gets an iterator over the keys of the map.
1194 /// use std::collections::BTreeMap;
1196 /// let mut a = BTreeMap::new();
1197 /// a.insert(1u, "a");
1198 /// a.insert(2u, "b");
1200 /// let keys: Vec<uint> = a.keys().cloned().collect();
1201 /// assert_eq!(keys, vec![1u,2,]);
1203 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1204 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1205 fn first<A, B>((a, _): (A, B)) -> A { a }
1207 self.iter().map(first)
1210 /// Gets an iterator over the values of the map.
1215 /// use std::collections::BTreeMap;
1217 /// let mut a = BTreeMap::new();
1218 /// a.insert(1u, "a");
1219 /// a.insert(2u, "b");
1221 /// let values: Vec<&str> = a.values().cloned().collect();
1222 /// assert_eq!(values, vec!["a","b"]);
1224 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1225 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1226 fn second<A, B>((_, b): (A, B)) -> B { b }
1228 self.iter().map(second)
1231 /// Return the number of elements in the map.
1236 /// use std::collections::BTreeMap;
1238 /// let mut a = BTreeMap::new();
1239 /// assert_eq!(a.len(), 0);
1240 /// a.insert(1u, "a");
1241 /// assert_eq!(a.len(), 1);
1243 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1244 pub fn len(&self) -> uint { self.length }
1246 /// Return true if the map contains no elements.
1251 /// use std::collections::BTreeMap;
1253 /// let mut a = BTreeMap::new();
1254 /// assert!(a.is_empty());
1255 /// a.insert(1u, "a");
1256 /// assert!(!a.is_empty());
1258 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1259 pub fn is_empty(&self) -> bool { self.len() == 0 }
1262 impl<K: Ord, V> BTreeMap<K, V> {
1263 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1264 pub fn entry<'a>(&'a mut self, mut key: K) -> Entry<'a, K, V> {
1265 // same basic logic of `swap` and `pop`, blended together
1266 let mut stack = stack::PartialSearchStack::new(self);
1268 let result = stack.with(move |pusher, node| {
1269 return match Node::search(node, &key) {
1272 Finished(Occupied(OccupiedEntry {
1273 stack: pusher.seal(handle)
1277 match handle.force() {
1278 Leaf(leaf_handle) => {
1279 Finished(Vacant(VacantEntry {
1280 stack: pusher.seal(leaf_handle),
1284 Internal(internal_handle) => {
1286 pusher.push(internal_handle),
1295 Finished(finished) => return finished,
1296 Continue((new_stack, renewed_key)) => {
1311 use std::prelude::*;
1313 use super::{BTreeMap, Occupied, Vacant};
1316 fn test_basic_large() {
1317 let mut map = BTreeMap::new();
1319 assert_eq!(map.len(), 0);
1321 for i in range(0, size) {
1322 assert_eq!(map.insert(i, 10*i), None);
1323 assert_eq!(map.len(), i + 1);
1326 for i in range(0, size) {
1327 assert_eq!(map.get(&i).unwrap(), &(i*10));
1330 for i in range(size, size*2) {
1331 assert_eq!(map.get(&i), None);
1334 for i in range(0, size) {
1335 assert_eq!(map.insert(i, 100*i), Some(10*i));
1336 assert_eq!(map.len(), size);
1339 for i in range(0, size) {
1340 assert_eq!(map.get(&i).unwrap(), &(i*100));
1343 for i in range(0, size/2) {
1344 assert_eq!(map.remove(&(i*2)), Some(i*200));
1345 assert_eq!(map.len(), size - i - 1);
1348 for i in range(0, size/2) {
1349 assert_eq!(map.get(&(2*i)), None);
1350 assert_eq!(map.get(&(2*i+1)).unwrap(), &(i*200 + 100));
1353 for i in range(0, size/2) {
1354 assert_eq!(map.remove(&(2*i)), None);
1355 assert_eq!(map.remove(&(2*i+1)), Some(i*200 + 100));
1356 assert_eq!(map.len(), size/2 - i - 1);
1361 fn test_basic_small() {
1362 let mut map = BTreeMap::new();
1363 assert_eq!(map.remove(&1), None);
1364 assert_eq!(map.get(&1), None);
1365 assert_eq!(map.insert(1u, 1u), None);
1366 assert_eq!(map.get(&1), Some(&1));
1367 assert_eq!(map.insert(1, 2), Some(1));
1368 assert_eq!(map.get(&1), Some(&2));
1369 assert_eq!(map.insert(2, 4), None);
1370 assert_eq!(map.get(&2), Some(&4));
1371 assert_eq!(map.remove(&1), Some(2));
1372 assert_eq!(map.remove(&2), Some(4));
1373 assert_eq!(map.remove(&1), None);
1381 let mut map: BTreeMap<uint, uint> = Vec::from_fn(size, |i| (i, i)).into_iter().collect();
1384 let mut iter = map.iter();
1385 for i in range(0, size) {
1386 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1387 assert_eq!(iter.next().unwrap(), (&i, &i));
1389 assert_eq!(iter.size_hint(), (0, Some(0)));
1390 assert_eq!(iter.next(), None);
1394 let mut iter = map.iter_mut();
1395 for i in range(0, size) {
1396 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1397 assert_eq!(iter.next().unwrap(), (&i, &mut (i + 0)));
1399 assert_eq!(iter.size_hint(), (0, Some(0)));
1400 assert_eq!(iter.next(), None);
1404 let mut iter = map.into_iter();
1405 for i in range(0, size) {
1406 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1407 assert_eq!(iter.next().unwrap(), (i, i));
1409 assert_eq!(iter.size_hint(), (0, Some(0)));
1410 assert_eq!(iter.next(), None);
1416 fn test_iter_rev() {
1420 let mut map: BTreeMap<uint, uint> = Vec::from_fn(size, |i| (i, i)).into_iter().collect();
1423 let mut iter = map.iter().rev();
1424 for i in range(0, size) {
1425 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1426 assert_eq!(iter.next().unwrap(), (&(size - i - 1), &(size - i - 1)));
1428 assert_eq!(iter.size_hint(), (0, Some(0)));
1429 assert_eq!(iter.next(), None);
1433 let mut iter = map.iter_mut().rev();
1434 for i in range(0, size) {
1435 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1436 assert_eq!(iter.next().unwrap(), (&(size - i - 1), &mut(size - i - 1)));
1438 assert_eq!(iter.size_hint(), (0, Some(0)));
1439 assert_eq!(iter.next(), None);
1443 let mut iter = map.into_iter().rev();
1444 for i in range(0, size) {
1445 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
1446 assert_eq!(iter.next().unwrap(), (size - i - 1, size - i - 1));
1448 assert_eq!(iter.size_hint(), (0, Some(0)));
1449 assert_eq!(iter.next(), None);
1456 let xs = [(1i, 10i), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
1458 let mut map: BTreeMap<int, int> = xs.iter().map(|&x| x).collect();
1460 // Existing key (insert)
1461 match map.entry(1) {
1462 Vacant(_) => unreachable!(),
1463 Occupied(mut view) => {
1464 assert_eq!(view.get(), &10);
1465 assert_eq!(view.set(100), 10);
1468 assert_eq!(map.get(&1).unwrap(), &100);
1469 assert_eq!(map.len(), 6);
1472 // Existing key (update)
1473 match map.entry(2) {
1474 Vacant(_) => unreachable!(),
1475 Occupied(mut view) => {
1476 let v = view.get_mut();
1480 assert_eq!(map.get(&2).unwrap(), &200);
1481 assert_eq!(map.len(), 6);
1483 // Existing key (take)
1484 match map.entry(3) {
1485 Vacant(_) => unreachable!(),
1487 assert_eq!(view.take(), 30);
1490 assert_eq!(map.get(&3), None);
1491 assert_eq!(map.len(), 5);
1494 // Inexistent key (insert)
1495 match map.entry(10) {
1496 Occupied(_) => unreachable!(),
1498 assert_eq!(*view.set(1000), 1000);
1501 assert_eq!(map.get(&10).unwrap(), &1000);
1502 assert_eq!(map.len(), 6);
1513 use std::prelude::*;
1514 use std::rand::{weak_rng, Rng};
1515 use test::{Bencher, black_box};
1517 use super::BTreeMap;
1518 use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
1521 pub fn insert_rand_100(b: &mut Bencher) {
1522 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1523 insert_rand_n(100, &mut m, b,
1524 |m, i| { m.insert(i, 1); },
1525 |m, i| { m.remove(&i); });
1529 pub fn insert_rand_10_000(b: &mut Bencher) {
1530 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1531 insert_rand_n(10_000, &mut m, b,
1532 |m, i| { m.insert(i, 1); },
1533 |m, i| { m.remove(&i); });
1538 pub fn insert_seq_100(b: &mut Bencher) {
1539 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1540 insert_seq_n(100, &mut m, b,
1541 |m, i| { m.insert(i, 1); },
1542 |m, i| { m.remove(&i); });
1546 pub fn insert_seq_10_000(b: &mut Bencher) {
1547 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1548 insert_seq_n(10_000, &mut m, b,
1549 |m, i| { m.insert(i, 1); },
1550 |m, i| { m.remove(&i); });
1555 pub fn find_rand_100(b: &mut Bencher) {
1556 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1557 find_rand_n(100, &mut m, b,
1558 |m, i| { m.insert(i, 1); },
1559 |m, i| { m.get(&i); });
1563 pub fn find_rand_10_000(b: &mut Bencher) {
1564 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1565 find_rand_n(10_000, &mut m, b,
1566 |m, i| { m.insert(i, 1); },
1567 |m, i| { m.get(&i); });
1572 pub fn find_seq_100(b: &mut Bencher) {
1573 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1574 find_seq_n(100, &mut m, b,
1575 |m, i| { m.insert(i, 1); },
1576 |m, i| { m.get(&i); });
1580 pub fn find_seq_10_000(b: &mut Bencher) {
1581 let mut m : BTreeMap<uint,uint> = BTreeMap::new();
1582 find_seq_n(10_000, &mut m, b,
1583 |m, i| { m.insert(i, 1); },
1584 |m, i| { m.get(&i); });
1587 fn bench_iter(b: &mut Bencher, size: uint) {
1588 let mut map = BTreeMap::<uint, uint>::new();
1589 let mut rng = weak_rng();
1591 for _ in range(0, size) {
1592 map.insert(rng.gen(), rng.gen());
1596 for entry in map.iter() {
1603 pub fn iter_20(b: &mut Bencher) {
1608 pub fn iter_1000(b: &mut Bencher) {
1609 bench_iter(b, 1000);
1613 pub fn iter_100000(b: &mut Bencher) {
1614 bench_iter(b, 100000);