1 // Copyright 2015 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 use core::cmp::Ordering;
13 use core::hash::{Hash, Hasher};
14 use core::iter::{FromIterator, Peekable};
15 use core::marker::PhantomData;
17 use core::{fmt, intrinsics, mem, ptr};
20 use Bound::{self, Included, Excluded, Unbounded};
22 use super::node::{self, NodeRef, Handle, marker};
25 use super::node::InsertResult::*;
26 use super::node::ForceResult::*;
27 use super::search::SearchResult::*;
28 use self::UnderflowResult::*;
31 /// A map based on a B-Tree.
33 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
34 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
35 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
36 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
37 /// is done is *very* inefficient for modern computer architectures. In particular, every element
38 /// is stored in its own individually heap-allocated node. This means that every single insertion
39 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
40 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
43 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
44 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
45 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
46 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
47 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
48 /// the node using binary search. As a compromise, one could also perform a linear search
49 /// that initially only checks every i<sup>th</sup> element for some choice of i.
51 /// Currently, our implementation simply performs naive linear search. This provides excellent
52 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
53 /// would like to further explore choosing the optimal search strategy based on the choice of B,
54 /// and possibly other factors. Using linear search, searching for a random element is expected
55 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
56 /// however, performance is excellent.
58 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
59 /// any other key, as determined by the `Ord` trait, changes while it is in the map. This is
60 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
65 /// use std::collections::BTreeMap;
67 /// // type inference lets us omit an explicit type signature (which
68 /// // would be `BTreeMap<&str, &str>` in this example).
69 /// let mut movie_reviews = BTreeMap::new();
71 /// // review some movies.
72 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
73 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
74 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
75 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it alot.");
77 /// // check for a specific one.
78 /// if !movie_reviews.contains_key("Les Misérables") {
79 /// println!("We've got {} reviews, but Les Misérables ain't one.",
80 /// movie_reviews.len());
83 /// // oops, this review has a lot of spelling mistakes, let's delete it.
84 /// movie_reviews.remove("The Blues Brothers");
86 /// // look up the values associated with some keys.
87 /// let to_find = ["Up!", "Office Space"];
88 /// for book in &to_find {
89 /// match movie_reviews.get(book) {
90 /// Some(review) => println!("{}: {}", book, review),
91 /// None => println!("{} is unreviewed.", book)
95 /// // iterate over everything.
96 /// for (movie, review) in &movie_reviews {
97 /// println!("{}: \"{}\"", movie, review);
101 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
102 /// for more complex methods of getting, setting, updating and removing keys and
106 /// use std::collections::BTreeMap;
108 /// // type inference lets us omit an explicit type signature (which
109 /// // would be `BTreeMap<&str, u8>` in this example).
110 /// let mut player_stats = BTreeMap::new();
112 /// fn random_stat_buff() -> u8 {
113 /// // could actually return some random value here - let's just return
114 /// // some fixed value for now
118 /// // insert a key only if it doesn't already exist
119 /// player_stats.entry("health").or_insert(100);
121 /// // insert a key using a function that provides a new value only if it
122 /// // doesn't already exist
123 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
125 /// // update a key, guarding against the key possibly not being set
126 /// let stat = player_stats.entry("attack").or_insert(100);
127 /// *stat += random_stat_buff();
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub struct BTreeMap<K, V> {
131 root: node::Root<K, V>,
135 impl<K, V> Drop for BTreeMap<K, V> {
136 #[unsafe_destructor_blind_to_params]
139 for _ in ptr::read(self).into_iter() { }
144 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
145 fn clone(&self) -> BTreeMap<K, V> {
146 fn clone_subtree<K: Clone, V: Clone>(
147 node: node::NodeRef<marker::Immut, K, V, marker::LeafOrInternal>)
152 let mut out_tree = BTreeMap {
153 root: node::Root::new_leaf(),
158 let mut out_node = match out_tree.root.as_mut().force() {
160 Internal(_) => unreachable!()
163 let mut in_edge = leaf.first_edge();
164 while let Ok(kv) = in_edge.right_kv() {
165 let (k, v) = kv.into_kv();
166 in_edge = kv.right_edge();
168 out_node.push(k.clone(), v.clone());
169 out_tree.length += 1;
175 Internal(internal) => {
176 let mut out_tree = clone_subtree(internal.first_edge().descend());
179 let mut out_node = out_tree.root.push_level();
180 let mut in_edge = internal.first_edge();
181 while let Ok(kv) = in_edge.right_kv() {
182 let (k, v) = kv.into_kv();
183 in_edge = kv.right_edge();
185 let k = (*k).clone();
186 let v = (*v).clone();
187 let subtree = clone_subtree(in_edge.descend());
189 // We can't destructure subtree directly
190 // because BTreeMap implements Drop
191 let (subroot, sublength) = unsafe {
192 let root = ptr::read(&subtree.root);
193 let length = subtree.length;
194 mem::forget(subtree);
198 out_node.push(k, v, subroot);
199 out_tree.length += 1 + sublength;
208 clone_subtree(self.root.as_ref())
212 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
213 where K: Borrow<Q> + Ord,
218 fn get(&self, key: &Q) -> Option<&K> {
219 match search::search_tree(self.root.as_ref(), key) {
220 Found(handle) => Some(handle.into_kv().0),
225 fn take(&mut self, key: &Q) -> Option<K> {
226 match search::search_tree(self.root.as_mut(), key) {
230 length: &mut self.length,
231 _marker: PhantomData,
238 fn replace(&mut self, key: K) -> Option<K> {
239 match search::search_tree::<marker::Mut, K, (), K>(self.root.as_mut(), &key) {
240 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
245 length: &mut self.length,
246 _marker: PhantomData,
254 /// An iterator over a BTreeMap's entries.
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub struct Iter<'a, K: 'a, V: 'a> {
257 range: Range<'a, K, V>,
261 /// A mutable iterator over a BTreeMap's entries.
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub struct IterMut<'a, K: 'a, V: 'a> {
264 range: RangeMut<'a, K, V>,
268 /// An owning iterator over a BTreeMap's entries.
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub struct IntoIter<K, V> {
271 front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
272 back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
276 /// An iterator over a BTreeMap's keys.
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub struct Keys<'a, K: 'a, V: 'a> {
279 inner: Iter<'a, K, V>,
282 /// An iterator over a BTreeMap's values.
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub struct Values<'a, K: 'a, V: 'a> {
285 inner: Iter<'a, K, V>,
288 /// A mutable iterator over a BTreeMap's values.
289 #[stable(feature = "map_values_mut", since = "1.10.0")]
290 pub struct ValuesMut<'a, K: 'a, V: 'a> {
291 inner: IterMut<'a, K, V>,
294 /// An iterator over a sub-range of BTreeMap's entries.
295 pub struct Range<'a, K: 'a, V: 'a> {
296 front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
297 back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>
300 /// A mutable iterator over a sub-range of BTreeMap's entries.
301 pub struct RangeMut<'a, K: 'a, V: 'a> {
302 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
303 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
305 // Be invariant in `K` and `V`
306 _marker: PhantomData<&'a mut (K, V)>,
309 /// A view into a single entry in a map, which may either be vacant or occupied.
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub enum Entry<'a, K: 'a, V: 'a> {
313 #[stable(feature = "rust1", since = "1.0.0")]
315 #[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>
318 /// An occupied Entry
319 #[stable(feature = "rust1", since = "1.0.0")]
321 #[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub struct VacantEntry<'a, K: 'a, V: 'a> {
329 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
330 length: &'a mut usize,
332 // Be invariant in `K` and `V`
333 _marker: PhantomData<&'a mut (K, V)>,
336 /// An occupied Entry.
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
339 handle: Handle<NodeRef<
342 marker::LeafOrInternal
345 length: &'a mut usize,
347 // Be invariant in `K` and `V`
348 _marker: PhantomData<&'a mut (K, V)>,
351 // An iterator for merging two sorted sequences into one
352 struct MergeIter<K, V, I: Iterator<Item=(K, V)>> {
357 impl<K: Ord, V> BTreeMap<K, V> {
358 /// Makes a new empty BTreeMap with a reasonable choice for B.
365 /// use std::collections::BTreeMap;
367 /// let mut map = BTreeMap::new();
369 /// // entries can now be inserted into the empty map
370 /// map.insert(1, "a");
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn new() -> BTreeMap<K, V> {
375 root: node::Root::new_leaf(),
380 /// Clears the map, removing all values.
387 /// use std::collections::BTreeMap;
389 /// let mut a = BTreeMap::new();
390 /// a.insert(1, "a");
392 /// assert!(a.is_empty());
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn clear(&mut self) {
396 // FIXME(gereeter) .clear() allocates
397 *self = BTreeMap::new();
400 /// Returns a reference to the value corresponding to the key.
402 /// The key may be any borrowed form of the map's key type, but the ordering
403 /// on the borrowed form *must* match the ordering on the key type.
410 /// use std::collections::BTreeMap;
412 /// let mut map = BTreeMap::new();
413 /// map.insert(1, "a");
414 /// assert_eq!(map.get(&1), Some(&"a"));
415 /// assert_eq!(map.get(&2), None);
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where K: Borrow<Q>, Q: Ord {
419 match search::search_tree(self.root.as_ref(), key) {
420 Found(handle) => Some(handle.into_kv().1),
425 /// Returns true if the map contains a value for the specified key.
427 /// The key may be any borrowed form of the map's key type, but the ordering
428 /// 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(1, "a");
439 /// assert_eq!(map.contains_key(&1), true);
440 /// assert_eq!(map.contains_key(&2), false);
442 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where K: Borrow<Q>, Q: Ord {
444 self.get(key).is_some()
447 /// Returns a mutable reference to the value corresponding to the key.
449 /// The key may be any borrowed form of the map's key type, but the ordering
450 /// on the borrowed form *must* match the ordering on the key type.
457 /// use std::collections::BTreeMap;
459 /// let mut map = BTreeMap::new();
460 /// map.insert(1, "a");
461 /// if let Some(x) = map.get_mut(&1) {
464 /// assert_eq!(map[&1], "b");
466 // See `get` for implementation notes, this is basically a copy-paste with mut's added
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> where K: Borrow<Q>, Q: Ord {
469 match search::search_tree(self.root.as_mut(), key) {
470 Found(handle) => Some(handle.into_kv_mut().1),
475 /// Inserts a key-value pair into the map.
477 /// If the map did not have this key present, `None` is returned.
479 /// If the map did have this key present, the value is updated, and the old
480 /// value is returned. The key is not updated, though; this matters for
481 /// types that can be `==` without being identical. See the [module-level
482 /// documentation] for more.
484 /// [module-level documentation]: index.html#insert-and-complex-keys
491 /// use std::collections::BTreeMap;
493 /// let mut map = BTreeMap::new();
494 /// assert_eq!(map.insert(37, "a"), None);
495 /// assert_eq!(map.is_empty(), false);
497 /// map.insert(37, "b");
498 /// assert_eq!(map.insert(37, "c"), Some("b"));
499 /// assert_eq!(map[&37], "c");
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
503 match self.entry(key) {
504 Occupied(mut entry) => Some(entry.insert(value)),
512 /// Removes a key from the map, returning the value at the key if the key
513 /// was previously in the map.
515 /// The key may be any borrowed form of the map's key type, but the ordering
516 /// on the borrowed form *must* match the ordering on the key type.
523 /// use std::collections::BTreeMap;
525 /// let mut map = BTreeMap::new();
526 /// map.insert(1, "a");
527 /// assert_eq!(map.remove(&1), Some("a"));
528 /// assert_eq!(map.remove(&1), None);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> where K: Borrow<Q>, Q: Ord {
532 match search::search_tree(self.root.as_mut(), key) {
536 length: &mut self.length,
537 _marker: PhantomData,
544 /// Moves all elements from `other` into `Self`, leaving `other` empty.
549 /// #![feature(btree_append)]
550 /// use std::collections::BTreeMap;
552 /// let mut a = BTreeMap::new();
553 /// a.insert(1, "a");
554 /// a.insert(2, "b");
555 /// a.insert(3, "c");
557 /// let mut b = BTreeMap::new();
558 /// b.insert(3, "d");
559 /// b.insert(4, "e");
560 /// b.insert(5, "f");
562 /// a.append(&mut b);
564 /// assert_eq!(a.len(), 5);
565 /// assert_eq!(b.len(), 0);
567 /// assert_eq!(a[&1], "a");
568 /// assert_eq!(a[&2], "b");
569 /// assert_eq!(a[&3], "d");
570 /// assert_eq!(a[&4], "e");
571 /// assert_eq!(a[&5], "f");
573 #[unstable(feature = "btree_append", reason = "recently added as part of collections reform 2",
575 pub fn append(&mut self, other: &mut Self) {
576 // Do we have to append anything at all?
577 if other.len() == 0 {
581 // We can just swap `self` and `other` if `self` is empty.
583 mem::swap(self, other);
587 // First, we merge `self` and `other` into a sorted sequence in linear time.
588 let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
589 let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
590 let iter = MergeIter {
591 left: self_iter.peekable(),
592 right: other_iter.peekable(),
595 // Second, we build a tree from the sorted sequence in linear time.
596 self.from_sorted_iter(iter);
597 self.fix_right_edge();
600 /// Constructs a double-ended iterator over a sub-range of elements in the map, starting
601 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
602 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
603 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
610 /// #![feature(btree_range, collections_bound)]
612 /// use std::collections::BTreeMap;
613 /// use std::collections::Bound::{Included, Unbounded};
615 /// let mut map = BTreeMap::new();
616 /// map.insert(3, "a");
617 /// map.insert(5, "b");
618 /// map.insert(8, "c");
619 /// for (&key, &value) in map.range(Included(&4), Included(&8)) {
620 /// println!("{}: {}", key, value);
622 /// assert_eq!(Some((&5, &"b")), map.range(Included(&4), Unbounded).next());
624 #[unstable(feature = "btree_range",
625 reason = "matches collection reform specification, waiting for dust to settle",
627 pub fn range<Min: ?Sized + Ord, Max: ?Sized + Ord>(&self,
631 where K: Borrow<Min> + Borrow<Max>,
633 let front = match min {
634 Included(key) => match search::search_tree(self.root.as_ref(), key) {
635 Found(kv_handle) => match kv_handle.left_edge().force() {
636 Leaf(bottom) => bottom,
637 Internal(internal) => last_leaf_edge(internal.descend())
639 GoDown(bottom) => bottom
641 Excluded(key) => match search::search_tree(self.root.as_ref(), key) {
642 Found(kv_handle) => match kv_handle.right_edge().force() {
643 Leaf(bottom) => bottom,
644 Internal(internal) => first_leaf_edge(internal.descend())
646 GoDown(bottom) => bottom
648 Unbounded => first_leaf_edge(self.root.as_ref())
651 let back = match max {
652 Included(key) => match search::search_tree(self.root.as_ref(), key) {
653 Found(kv_handle) => match kv_handle.right_edge().force() {
654 Leaf(bottom) => bottom,
655 Internal(internal) => first_leaf_edge(internal.descend())
657 GoDown(bottom) => bottom
659 Excluded(key) => match search::search_tree(self.root.as_ref(), key) {
660 Found(kv_handle) => match kv_handle.left_edge().force() {
661 Leaf(bottom) => bottom,
662 Internal(internal) => last_leaf_edge(internal.descend())
664 GoDown(bottom) => bottom
666 Unbounded => last_leaf_edge(self.root.as_ref())
675 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map, starting
676 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
677 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
678 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
685 /// #![feature(btree_range, collections_bound)]
687 /// use std::collections::BTreeMap;
688 /// use std::collections::Bound::{Included, Excluded};
690 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
691 /// .map(|&s| (s, 0))
693 /// for (_, balance) in map.range_mut(Included("B"), Excluded("Cheryl")) {
696 /// for (name, balance) in &map {
697 /// println!("{} => {}", name, balance);
700 #[unstable(feature = "btree_range",
701 reason = "matches collection reform specification, waiting for dust to settle",
703 pub fn range_mut<Min: ?Sized + Ord, Max: ?Sized + Ord>(&mut self,
707 where K: Borrow<Min> + Borrow<Max>,
709 let root1 = self.root.as_mut();
710 let root2 = unsafe { ptr::read(&root1) };
712 let front = match min {
713 Included(key) => match search::search_tree(root1, key) {
714 Found(kv_handle) => match kv_handle.left_edge().force() {
715 Leaf(bottom) => bottom,
716 Internal(internal) => last_leaf_edge(internal.descend())
718 GoDown(bottom) => bottom
720 Excluded(key) => match search::search_tree(root1, key) {
721 Found(kv_handle) => match kv_handle.right_edge().force() {
722 Leaf(bottom) => bottom,
723 Internal(internal) => first_leaf_edge(internal.descend())
725 GoDown(bottom) => bottom
727 Unbounded => first_leaf_edge(root1)
730 let back = match max {
731 Included(key) => match search::search_tree(root2, key) {
732 Found(kv_handle) => match kv_handle.right_edge().force() {
733 Leaf(bottom) => bottom,
734 Internal(internal) => first_leaf_edge(internal.descend())
736 GoDown(bottom) => bottom
738 Excluded(key) => match search::search_tree(root2, key) {
739 Found(kv_handle) => match kv_handle.left_edge().force() {
740 Leaf(bottom) => bottom,
741 Internal(internal) => last_leaf_edge(internal.descend())
743 GoDown(bottom) => bottom
745 Unbounded => last_leaf_edge(root2)
755 /// Gets the given key's corresponding entry in the map for in-place manipulation.
762 /// use std::collections::BTreeMap;
764 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
766 /// // count the number of occurrences of letters in the vec
767 /// for x in vec!["a","b","a","c","a","b"] {
768 /// *count.entry(x).or_insert(0) += 1;
771 /// assert_eq!(count["a"], 3);
773 #[stable(feature = "rust1", since = "1.0.0")]
774 pub fn entry(&mut self, key: K) -> Entry<K, V> {
775 match search::search_tree(self.root.as_mut(), &key) {
776 Found(handle) => Occupied(OccupiedEntry {
778 length: &mut self.length,
779 _marker: PhantomData,
781 GoDown(handle) => Vacant(VacantEntry {
784 length: &mut self.length,
785 _marker: PhantomData,
790 fn from_sorted_iter<I: Iterator<Item=(K, V)>>(&mut self, iter: I) {
791 let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
792 // Iterate through all key-value pairs, pushing them into nodes at the right level.
793 for (key, value) in iter {
794 // Try to push key-value pair into the current leaf node.
795 if cur_node.len() < node::CAPACITY {
796 cur_node.push(key, value);
798 // No space left, go up and push there.
800 let mut test_node = cur_node.forget_type();
802 match test_node.ascend() {
804 let parent = parent.into_node();
805 if parent.len() < node::CAPACITY {
806 // Found a node with space left, push here.
811 test_node = parent.forget_type();
815 // We are at the top, create a new root node and push there.
816 open_node = node.into_root_mut().push_level();
822 // Push key-value pair and new right subtree.
823 let tree_height = open_node.height() - 1;
824 let mut right_tree = node::Root::new_leaf();
825 for _ in 0..tree_height {
826 right_tree.push_level();
828 open_node.push(key, value, right_tree);
830 // Go down to the right-most leaf again.
831 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
838 fn fix_right_edge(&mut self) {
839 // Handle underfull nodes, start from the top.
840 let mut cur_node = self.root.as_mut();
841 while let Internal(internal) = cur_node.force() {
842 // Check if right-most child is underfull.
843 let mut last_edge = internal.last_edge();
844 let right_child_len = last_edge.reborrow().descend().len();
845 if right_child_len < node::MIN_LEN {
847 let mut last_kv = match last_edge.left_kv() {
849 Err(_) => unreachable!(),
851 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
852 last_edge = last_kv.right_edge();
856 cur_node = last_edge.descend();
860 /// Splits the collection into two at the given key. Returns everything after the given key,
861 /// including the key.
868 /// #![feature(btree_split_off)]
869 /// use std::collections::BTreeMap;
871 /// let mut a = BTreeMap::new();
872 /// a.insert(1, "a");
873 /// a.insert(2, "b");
874 /// a.insert(3, "c");
875 /// a.insert(17, "d");
876 /// a.insert(41, "e");
878 /// let b = a.split_off(&3);
880 /// assert_eq!(a.len(), 2);
881 /// assert_eq!(b.len(), 3);
883 /// assert_eq!(a[&1], "a");
884 /// assert_eq!(a[&2], "b");
886 /// assert_eq!(b[&3], "c");
887 /// assert_eq!(b[&17], "d");
888 /// assert_eq!(b[&41], "e");
890 #[unstable(feature = "btree_split_off",
891 reason = "recently added as part of collections reform 2",
893 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self where K: Borrow<Q> {
898 let total_num = self.len();
900 let mut right = Self::new();
901 for _ in 0..(self.root.as_ref().height()) {
902 right.root.push_level();
906 let mut left_node = self.root.as_mut();
907 let mut right_node = right.root.as_mut();
910 let mut split_edge = match search::search_node(left_node, key) {
911 // key is going to the right tree
912 Found(handle) => handle.left_edge(),
913 GoDown(handle) => handle
916 split_edge.move_suffix(&mut right_node);
918 match (split_edge.force(), right_node.force()) {
919 (Internal(edge), Internal(node)) => {
920 left_node = edge.descend();
921 right_node = node.first_edge().descend();
923 (Leaf(_), Leaf(_)) => { break; },
924 _ => { unreachable!(); }
929 self.fix_right_border();
930 right.fix_left_border();
932 if self.root.as_ref().height() < right.root.as_ref().height() {
933 self.recalc_length();
934 right.length = total_num - self.len();
936 right.recalc_length();
937 self.length = total_num - right.len();
943 /// Calculates the number of elements if it is incorrect.
944 fn recalc_length(&mut self) {
945 fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize {
946 let mut res = node.len();
948 if let Internal(node) = node.force() {
949 let mut edge = node.first_edge();
951 res += dfs(edge.reborrow().descend());
952 match edge.right_kv() {
953 Ok(right_kv) => { edge = right_kv.right_edge(); },
962 self.length = dfs(self.root.as_ref());
965 /// Removes empty levels on the top.
966 fn fix_top(&mut self) {
969 let node = self.root.as_ref();
970 if node.height() == 0 || node.len() > 0 {
974 self.root.pop_level();
978 fn fix_right_border(&mut self) {
982 let mut cur_node = self.root.as_mut();
984 while let Internal(node) = cur_node.force() {
985 let mut last_kv = node.last_kv();
987 if last_kv.can_merge() {
988 cur_node = last_kv.merge().descend();
990 let right_len = last_kv.reborrow().right_edge().descend().len();
991 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
992 if right_len < node::MIN_LEN + 1 {
993 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
995 cur_node = last_kv.right_edge().descend();
1003 /// The symmetric clone of `fix_right_border`.
1004 fn fix_left_border(&mut self) {
1008 let mut cur_node = self.root.as_mut();
1010 while let Internal(node) = cur_node.force() {
1011 let mut first_kv = node.first_kv();
1013 if first_kv.can_merge() {
1014 cur_node = first_kv.merge().descend();
1016 let left_len = first_kv.reborrow().left_edge().descend().len();
1017 if left_len < node::MIN_LEN + 1 {
1018 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1020 cur_node = first_kv.left_edge().descend();
1029 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1030 type Item = (&'a K, &'a V);
1031 type IntoIter = Iter<'a, K, V>;
1033 fn into_iter(self) -> Iter<'a, K, V> {
1038 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1039 type Item = (&'a K, &'a V);
1041 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1042 if self.length == 0 {
1046 unsafe { Some(self.range.next_unchecked()) }
1050 fn size_hint(&self) -> (usize, Option<usize>) {
1051 (self.length, Some(self.length))
1055 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1056 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1057 if self.length == 0 {
1061 unsafe { Some(self.range.next_back_unchecked()) }
1066 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1067 fn len(&self) -> usize { self.length }
1070 impl<'a, K, V> Clone for Iter<'a, K, V> {
1071 fn clone(&self) -> Iter<'a, K, V> {
1073 range: self.range.clone(),
1079 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1080 type Item = (&'a K, &'a mut V);
1081 type IntoIter = IterMut<'a, K, V>;
1083 fn into_iter(self) -> IterMut<'a, K, V> {
1088 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1089 type Item = (&'a K, &'a mut V);
1091 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1092 if self.length == 0 {
1096 unsafe { Some(self.range.next_unchecked()) }
1100 fn size_hint(&self) -> (usize, Option<usize>) {
1101 (self.length, Some(self.length))
1105 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1106 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1107 if self.length == 0 {
1111 unsafe { Some(self.range.next_back_unchecked()) }
1116 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1117 fn len(&self) -> usize { self.length }
1120 impl<K, V> IntoIterator for BTreeMap<K, V> {
1122 type IntoIter = IntoIter<K, V>;
1124 fn into_iter(self) -> IntoIter<K, V> {
1125 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1126 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1127 let len = self.length;
1131 front: first_leaf_edge(root1),
1132 back: last_leaf_edge(root2),
1138 impl<K, V> Drop for IntoIter<K, V> {
1139 fn drop(&mut self) {
1140 for _ in &mut *self { }
1142 let leaf_node = ptr::read(&self.front).into_node();
1143 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1144 let mut cur_node = first_parent.into_node();
1145 while let Some(parent) = cur_node.deallocate_and_ascend() {
1146 cur_node = parent.into_node()
1153 impl<K, V> Iterator for IntoIter<K, V> {
1156 fn next(&mut self) -> Option<(K, V)> {
1157 if self.length == 0 {
1163 let handle = unsafe { ptr::read(&self.front) };
1165 let mut cur_handle = match handle.right_kv() {
1167 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1168 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1169 self.front = kv.right_edge();
1170 return Some((k, v));
1172 Err(last_edge) => unsafe {
1173 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1178 match cur_handle.right_kv() {
1180 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1181 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1182 self.front = first_leaf_edge(kv.right_edge().descend());
1183 return Some((k, v));
1185 Err(last_edge) => unsafe {
1186 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1192 fn size_hint(&self) -> (usize, Option<usize>) {
1193 (self.length, Some(self.length))
1197 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1198 fn next_back(&mut self) -> Option<(K, V)> {
1199 if self.length == 0 {
1205 let handle = unsafe { ptr::read(&self.back) };
1207 let mut cur_handle = match handle.left_kv() {
1209 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1210 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1211 self.back = kv.left_edge();
1212 return Some((k, v));
1214 Err(last_edge) => unsafe {
1215 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1220 match cur_handle.left_kv() {
1222 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1223 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1224 self.back = last_leaf_edge(kv.left_edge().descend());
1225 return Some((k, v));
1227 Err(last_edge) => unsafe {
1228 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1235 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1236 fn len(&self) -> usize { self.length }
1239 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1242 fn next(&mut self) -> Option<&'a K> {
1243 self.inner.next().map(|(k, _)| k)
1246 fn size_hint(&self) -> (usize, Option<usize>) {
1247 self.inner.size_hint()
1251 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1252 fn next_back(&mut self) -> Option<&'a K> {
1253 self.inner.next_back().map(|(k, _)| k)
1257 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1258 fn len(&self) -> usize {
1263 impl<'a, K, V> Clone for Keys<'a, K, V> {
1264 fn clone(&self) -> Keys<'a, K, V> {
1266 inner: self.inner.clone()
1271 impl<'a, K, V> Iterator for Values<'a, K, V> {
1274 fn next(&mut self) -> Option<&'a V> {
1275 self.inner.next().map(|(_, v)| v)
1278 fn size_hint(&self) -> (usize, Option<usize>) {
1279 self.inner.size_hint()
1283 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1284 fn next_back(&mut self) -> Option<&'a V> {
1285 self.inner.next_back().map(|(_, v)| v)
1289 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1290 fn len(&self) -> usize {
1295 impl<'a, K, V> Clone for Values<'a, K, V> {
1296 fn clone(&self) -> Values<'a, K, V> {
1298 inner: self.inner.clone()
1303 impl<'a, K, V> Iterator for Range<'a, K, V> {
1304 type Item = (&'a K, &'a V);
1306 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1307 if self.front == self.back {
1310 unsafe { Some(self.next_unchecked()) }
1315 #[stable(feature = "map_values_mut", since = "1.10.0")]
1316 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1317 type Item = &'a mut V;
1319 fn next(&mut self) -> Option<&'a mut V> {
1320 self.inner.next().map(|(_, v)| v)
1323 fn size_hint(&self) -> (usize, Option<usize>) {
1324 self.inner.size_hint()
1328 #[stable(feature = "map_values_mut", since = "1.10.0")]
1329 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1330 fn next_back(&mut self) -> Option<&'a mut V> {
1331 self.inner.next_back().map(|(_, v)| v)
1335 #[stable(feature = "map_values_mut", since = "1.10.0")]
1336 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1337 fn len(&self) -> usize {
1342 impl<'a, K, V> Range<'a, K, V> {
1343 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1344 let handle = self.front;
1346 let mut cur_handle = match handle.right_kv() {
1348 let ret = kv.into_kv();
1349 self.front = kv.right_edge();
1353 let next_level = last_edge.into_node().ascend().ok();
1354 unwrap_unchecked(next_level)
1359 match cur_handle.right_kv() {
1361 let ret = kv.into_kv();
1362 self.front = first_leaf_edge(kv.right_edge().descend());
1366 let next_level = last_edge.into_node().ascend().ok();
1367 cur_handle = unwrap_unchecked(next_level);
1374 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1375 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1376 if self.front == self.back {
1379 unsafe { Some(self.next_back_unchecked()) }
1384 impl<'a, K, V> Range<'a, K, V> {
1385 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1386 let handle = self.back;
1388 let mut cur_handle = match handle.left_kv() {
1390 let ret = kv.into_kv();
1391 self.back = kv.left_edge();
1395 let next_level = last_edge.into_node().ascend().ok();
1396 unwrap_unchecked(next_level)
1401 match cur_handle.left_kv() {
1403 let ret = kv.into_kv();
1404 self.back = last_leaf_edge(kv.left_edge().descend());
1408 let next_level = last_edge.into_node().ascend().ok();
1409 cur_handle = unwrap_unchecked(next_level);
1416 impl<'a, K, V> Clone for Range<'a, K, V> {
1417 fn clone(&self) -> Range<'a, K, V> {
1425 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1426 type Item = (&'a K, &'a mut V);
1428 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1429 if self.front == self.back {
1432 unsafe { Some (self.next_unchecked()) }
1437 impl<'a, K, V> RangeMut<'a, K, V> {
1438 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1439 let handle = ptr::read(&self.front);
1441 let mut cur_handle = match handle.right_kv() {
1443 let (k, v) = ptr::read(&kv).into_kv_mut();
1444 self.front = kv.right_edge();
1448 let next_level = last_edge.into_node().ascend().ok();
1449 unwrap_unchecked(next_level)
1454 match cur_handle.right_kv() {
1456 let (k, v) = ptr::read(&kv).into_kv_mut();
1457 self.front = first_leaf_edge(kv.right_edge().descend());
1461 let next_level = last_edge.into_node().ascend().ok();
1462 cur_handle = unwrap_unchecked(next_level);
1469 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1470 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1471 if self.front == self.back {
1474 unsafe { Some(self.next_back_unchecked()) }
1479 impl<'a, K, V> RangeMut<'a, K, V> {
1480 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1481 let handle = ptr::read(&self.back);
1483 let mut cur_handle = match handle.left_kv() {
1485 let (k, v) = ptr::read(&kv).into_kv_mut();
1486 self.back = kv.left_edge();
1490 let next_level = last_edge.into_node().ascend().ok();
1491 unwrap_unchecked(next_level)
1496 match cur_handle.left_kv() {
1498 let (k, v) = ptr::read(&kv).into_kv_mut();
1499 self.back = last_leaf_edge(kv.left_edge().descend());
1503 let next_level = last_edge.into_node().ascend().ok();
1504 cur_handle = unwrap_unchecked(next_level);
1511 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1512 fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> BTreeMap<K, V> {
1513 let mut map = BTreeMap::new();
1519 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1521 fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
1522 for (k, v) in iter {
1528 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1529 fn extend<I: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iter: I) {
1530 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1534 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1535 fn hash<H: Hasher>(&self, state: &mut H) {
1542 impl<K: Ord, V> Default for BTreeMap<K, V> {
1543 fn default() -> BTreeMap<K, V> {
1548 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1549 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1550 self.len() == other.len() &&
1551 self.iter().zip(other).all(|(a, b)| a == b)
1555 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1557 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1559 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1560 self.iter().partial_cmp(other.iter())
1564 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1566 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1567 self.iter().cmp(other.iter())
1571 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1572 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1573 f.debug_map().entries(self.iter()).finish()
1577 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1578 where K: Borrow<Q>, Q: Ord
1583 fn index(&self, key: &Q) -> &V {
1584 self.get(key).expect("no entry found for key")
1588 fn first_leaf_edge<BorrowType, K, V>(
1589 mut node: NodeRef<BorrowType,
1591 marker::LeafOrInternal>
1592 ) -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1594 match node.force() {
1595 Leaf(leaf) => return leaf.first_edge(),
1596 Internal(internal) => {
1597 node = internal.first_edge().descend();
1603 fn last_leaf_edge<BorrowType, K, V>(
1604 mut node: NodeRef<BorrowType,
1606 marker::LeafOrInternal>
1607 ) -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1609 match node.force() {
1610 Leaf(leaf) => return leaf.last_edge(),
1611 Internal(internal) => {
1612 node = internal.last_edge().descend();
1619 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1620 val.unwrap_or_else(|| {
1621 if cfg!(debug_assertions) {
1622 panic!("'unchecked' unwrap on None in BTreeMap");
1624 intrinsics::unreachable();
1629 impl<K, V> BTreeMap<K, V> {
1630 /// Gets an iterator over the entries of the map, sorted by key.
1637 /// use std::collections::BTreeMap;
1639 /// let mut map = BTreeMap::new();
1640 /// map.insert(3, "c");
1641 /// map.insert(2, "b");
1642 /// map.insert(1, "a");
1644 /// for (key, value) in map.iter() {
1645 /// println!("{}: {}", key, value);
1648 /// let (first_key, first_value) = map.iter().next().unwrap();
1649 /// assert_eq!((*first_key, *first_value), (1, "a"));
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 pub fn iter(&self) -> Iter<K, V> {
1655 front: first_leaf_edge(self.root.as_ref()),
1656 back: last_leaf_edge(self.root.as_ref())
1662 /// Gets a mutable iterator over the entries of the map, sorted by key.
1669 /// use std::collections::BTreeMap;
1671 /// let mut map = BTreeMap::new();
1672 /// map.insert("a", 1);
1673 /// map.insert("b", 2);
1674 /// map.insert("c", 3);
1676 /// // add 10 to the value if the key isn't "a"
1677 /// for (key, value) in map.iter_mut() {
1678 /// if key != &"a" {
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1685 let root1 = self.root.as_mut();
1686 let root2 = unsafe { ptr::read(&root1) };
1689 front: first_leaf_edge(root1),
1690 back: last_leaf_edge(root2),
1691 _marker: PhantomData,
1697 /// Gets an iterator over the keys of the map, in sorted order.
1704 /// use std::collections::BTreeMap;
1706 /// let mut a = BTreeMap::new();
1707 /// a.insert(2, "b");
1708 /// a.insert(1, "a");
1710 /// let keys: Vec<_> = a.keys().cloned().collect();
1711 /// assert_eq!(keys, [1, 2]);
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1715 Keys { inner: self.iter() }
1718 /// Gets an iterator over the values of the map, in order by key.
1725 /// use std::collections::BTreeMap;
1727 /// let mut a = BTreeMap::new();
1728 /// a.insert(1, "hello");
1729 /// a.insert(2, "goodbye");
1731 /// let values: Vec<&str> = a.values().cloned().collect();
1732 /// assert_eq!(values, ["hello", "goodbye"]);
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1736 Values { inner: self.iter() }
1739 /// Gets a mutable iterator over the values of the map, in order by key.
1746 /// use std::collections::BTreeMap;
1748 /// let mut a = BTreeMap::new();
1749 /// a.insert(1, String::from("hello"));
1750 /// a.insert(2, String::from("goodbye"));
1752 /// for value in a.values_mut() {
1753 /// value.push_str("!");
1756 /// let values: Vec<String> = a.values().cloned().collect();
1757 /// assert_eq!(values, [String::from("hello!"),
1758 /// String::from("goodbye!")]);
1760 #[stable(feature = "map_values_mut", since = "1.10.0")]
1761 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1762 ValuesMut { inner: self.iter_mut() }
1765 /// Returns the number of elements in the map.
1772 /// use std::collections::BTreeMap;
1774 /// let mut a = BTreeMap::new();
1775 /// assert_eq!(a.len(), 0);
1776 /// a.insert(1, "a");
1777 /// assert_eq!(a.len(), 1);
1779 #[stable(feature = "rust1", since = "1.0.0")]
1780 pub fn len(&self) -> usize {
1784 /// Returns true if the map contains no elements.
1791 /// use std::collections::BTreeMap;
1793 /// let mut a = BTreeMap::new();
1794 /// assert!(a.is_empty());
1795 /// a.insert(1, "a");
1796 /// assert!(!a.is_empty());
1798 #[stable(feature = "rust1", since = "1.0.0")]
1799 pub fn is_empty(&self) -> bool {
1804 impl<'a, K: Ord, V> Entry<'a, K, V> {
1805 /// Ensures a value is in the entry by inserting the default if empty, and returns
1806 /// a mutable reference to the value in the entry.
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 pub fn or_insert(self, default: V) -> &'a mut V {
1810 Occupied(entry) => entry.into_mut(),
1811 Vacant(entry) => entry.insert(default),
1815 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1816 /// and returns a mutable reference to the value in the entry.
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1820 Occupied(entry) => entry.into_mut(),
1821 Vacant(entry) => entry.insert(default()),
1825 /// Returns a reference to this entry's key.
1826 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1827 pub fn key(&self) -> &K {
1829 Occupied(ref entry) => entry.key(),
1830 Vacant(ref entry) => entry.key(),
1835 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
1836 /// Gets a reference to the key that would be used when inserting a value
1837 /// through the VacantEntry.
1838 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1839 pub fn key(&self) -> &K {
1843 /// Sets the value of the entry with the VacantEntry's key,
1844 /// and returns a mutable reference to it.
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 pub fn insert(self, value: V) -> &'a mut V {
1855 let mut cur_parent = match self.handle.insert(self.key, value) {
1856 (Fit(handle), _) => return handle.into_kv_mut().1,
1857 (Split(left, k, v, right), ptr) => {
1862 left.ascend().map_err(|n| n.into_root_mut())
1868 Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
1869 Fit(_) => return unsafe { &mut *out_ptr },
1870 Split(left, k, v, right) => {
1874 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
1878 root.push_level().push(ins_k, ins_v, ins_edge);
1879 return unsafe { &mut *out_ptr };
1886 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
1887 /// Gets a reference to the key in the entry.
1888 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1889 pub fn key(&self) -> &K {
1890 self.handle.reborrow().into_kv().0
1893 /// Gets a reference to the value in the entry.
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 pub fn get(&self) -> &V {
1896 self.handle.reborrow().into_kv().1
1899 /// Gets a mutable reference to the value in the entry.
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 pub fn get_mut(&mut self) -> &mut V {
1902 self.handle.kv_mut().1
1905 /// Converts the entry into a mutable reference to its value.
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 pub fn into_mut(self) -> &'a mut V {
1908 self.handle.into_kv_mut().1
1911 /// Sets the value of the entry with the OccupiedEntry's key,
1912 /// and returns the entry's old value.
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 pub fn insert(&mut self, value: V) -> V {
1915 mem::replace(self.get_mut(), value)
1918 /// Takes the value of the entry out of the map, and returns it.
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 pub fn remove(self) -> V {
1924 fn remove_kv(self) -> (K, V) {
1927 let (small_leaf, old_key, old_val) = match self.handle.force() {
1929 let (hole, old_key, old_val) = leaf.remove();
1930 (hole.into_node(), old_key, old_val)
1932 Internal(mut internal) => {
1933 let key_loc = internal.kv_mut().0 as *mut K;
1934 let val_loc = internal.kv_mut().1 as *mut V;
1936 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
1937 let to_remove = unsafe { unwrap_unchecked(to_remove) };
1939 let (hole, key, val) = to_remove.remove();
1941 let old_key = unsafe {
1942 mem::replace(&mut *key_loc, key)
1944 let old_val = unsafe {
1945 mem::replace(&mut *val_loc, val)
1948 (hole.into_node(), old_key, old_val)
1953 let mut cur_node = small_leaf.forget_type();
1954 while cur_node.len() < node::CAPACITY / 2 {
1955 match handle_underfull_node(cur_node) {
1957 EmptyParent(_) => unreachable!(),
1958 Merged(parent) => if parent.len() == 0 {
1959 // We must be at the root
1960 parent.into_root_mut().pop_level();
1963 cur_node = parent.forget_type();
1973 enum UnderflowResult<'a, K, V> {
1975 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
1976 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
1977 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>)
1980 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>,
1982 marker::LeafOrInternal>)
1983 -> UnderflowResult<'a, K, V> {
1984 let parent = if let Ok(parent) = node.ascend() {
1990 let (is_left, mut handle) = match parent.left_kv() {
1991 Ok(left) => (true, left),
1992 Err(parent) => match parent.right_kv() {
1993 Ok(right) => (false, right),
1995 return EmptyParent(parent.into_node());
2000 if handle.can_merge() {
2001 Merged(handle.merge().into_node())
2004 handle.steal_left();
2006 handle.steal_right();
2008 Stole(handle.into_node())
2012 impl<K: Ord, V, I: Iterator<Item=(K, V)>> Iterator for MergeIter<K, V, I> {
2015 fn next(&mut self) -> Option<(K, V)> {
2016 let res = match (self.left.peek(), self.right.peek()) {
2017 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2018 (Some(_), None) => Ordering::Less,
2019 (None, Some(_)) => Ordering::Greater,
2020 (None, None) => return None,
2023 // Check which elements comes first and only advance the corresponding iterator.
2024 // If two keys are equal, take the value from `right`.
2029 Ordering::Greater => {
2032 Ordering::Equal => {