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, FusedIterator};
15 use core::marker::PhantomData;
17 use core::{fmt, intrinsics, mem, ptr};
20 use Bound::{Excluded, Included, Unbounded};
21 use range::RangeArgument;
23 use super::node::{self, Handle, NodeRef, marker};
26 use super::node::InsertResult::*;
27 use super::node::ForceResult::*;
28 use super::search::SearchResult::*;
29 use self::UnderflowResult::*;
32 /// A map based on a B-Tree.
34 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
35 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
36 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
37 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
38 /// is done is *very* inefficient for modern computer architectures. In particular, every element
39 /// is stored in its own individually heap-allocated node. This means that every single insertion
40 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
41 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
44 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
45 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
46 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
47 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
48 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
49 /// the node using binary search. As a compromise, one could also perform a linear search
50 /// that initially only checks every i<sup>th</sup> element for some choice of i.
52 /// Currently, our implementation simply performs naive linear search. This provides excellent
53 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
54 /// would like to further explore choosing the optimal search strategy based on the choice of B,
55 /// and possibly other factors. Using linear search, searching for a random element is expected
56 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
57 /// however, performance is excellent.
59 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
60 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
61 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
63 /// [`Ord`]: ../../std/cmp/trait.Ord.html
64 /// [`Cell`]: ../../std/cell/struct.Cell.html
65 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
70 /// use std::collections::BTreeMap;
72 /// // type inference lets us omit an explicit type signature (which
73 /// // would be `BTreeMap<&str, &str>` in this example).
74 /// let mut movie_reviews = BTreeMap::new();
76 /// // review some movies.
77 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
78 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
79 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
80 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it alot.");
82 /// // check for a specific one.
83 /// if !movie_reviews.contains_key("Les Misérables") {
84 /// println!("We've got {} reviews, but Les Misérables ain't one.",
85 /// movie_reviews.len());
88 /// // oops, this review has a lot of spelling mistakes, let's delete it.
89 /// movie_reviews.remove("The Blues Brothers");
91 /// // look up the values associated with some keys.
92 /// let to_find = ["Up!", "Office Space"];
93 /// for book in &to_find {
94 /// match movie_reviews.get(book) {
95 /// Some(review) => println!("{}: {}", book, review),
96 /// None => println!("{} is unreviewed.", book)
100 /// // iterate over everything.
101 /// for (movie, review) in &movie_reviews {
102 /// println!("{}: \"{}\"", movie, review);
106 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
107 /// for more complex methods of getting, setting, updating and removing keys and
111 /// use std::collections::BTreeMap;
113 /// // type inference lets us omit an explicit type signature (which
114 /// // would be `BTreeMap<&str, u8>` in this example).
115 /// let mut player_stats = BTreeMap::new();
117 /// fn random_stat_buff() -> u8 {
118 /// // could actually return some random value here - let's just return
119 /// // some fixed value for now
123 /// // insert a key only if it doesn't already exist
124 /// player_stats.entry("health").or_insert(100);
126 /// // insert a key using a function that provides a new value only if it
127 /// // doesn't already exist
128 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
130 /// // update a key, guarding against the key possibly not being set
131 /// let stat = player_stats.entry("attack").or_insert(100);
132 /// *stat += random_stat_buff();
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub struct BTreeMap<K, V> {
136 root: node::Root<K, V>,
140 #[stable(feature = "btree_drop", since = "1.7.0")]
141 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
144 for _ in ptr::read(self).into_iter() {
150 #[stable(feature = "rust1", since = "1.0.0")]
151 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
152 fn clone(&self) -> BTreeMap<K, V> {
153 fn clone_subtree<K: Clone, V: Clone>(node: node::NodeRef<marker::Immut,
156 marker::LeafOrInternal>)
161 let mut out_tree = BTreeMap {
162 root: node::Root::new_leaf(),
167 let mut out_node = match out_tree.root.as_mut().force() {
169 Internal(_) => unreachable!(),
172 let mut in_edge = leaf.first_edge();
173 while let Ok(kv) = in_edge.right_kv() {
174 let (k, v) = kv.into_kv();
175 in_edge = kv.right_edge();
177 out_node.push(k.clone(), v.clone());
178 out_tree.length += 1;
184 Internal(internal) => {
185 let mut out_tree = clone_subtree(internal.first_edge().descend());
188 let mut out_node = out_tree.root.push_level();
189 let mut in_edge = internal.first_edge();
190 while let Ok(kv) = in_edge.right_kv() {
191 let (k, v) = kv.into_kv();
192 in_edge = kv.right_edge();
194 let k = (*k).clone();
195 let v = (*v).clone();
196 let subtree = clone_subtree(in_edge.descend());
198 // We can't destructure subtree directly
199 // because BTreeMap implements Drop
200 let (subroot, sublength) = unsafe {
201 let root = ptr::read(&subtree.root);
202 let length = subtree.length;
203 mem::forget(subtree);
207 out_node.push(k, v, subroot);
208 out_tree.length += 1 + sublength;
217 clone_subtree(self.root.as_ref())
221 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
222 where K: Borrow<Q> + Ord,
227 fn get(&self, key: &Q) -> Option<&K> {
228 match search::search_tree(self.root.as_ref(), key) {
229 Found(handle) => Some(handle.into_kv().0),
234 fn take(&mut self, key: &Q) -> Option<K> {
235 match search::search_tree(self.root.as_mut(), key) {
239 length: &mut self.length,
240 _marker: PhantomData,
249 fn replace(&mut self, key: K) -> Option<K> {
250 match search::search_tree::<marker::Mut, K, (), K>(self.root.as_mut(), &key) {
251 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
256 length: &mut self.length,
257 _marker: PhantomData,
266 /// An iterator over a BTreeMap's entries.
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub struct Iter<'a, K: 'a, V: 'a> {
269 range: Range<'a, K, V>,
273 /// A mutable iterator over a BTreeMap's entries.
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub struct IterMut<'a, K: 'a, V: 'a> {
276 range: RangeMut<'a, K, V>,
280 /// An owning iterator over a BTreeMap's entries.
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub struct IntoIter<K, V> {
283 front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
284 back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
288 /// An iterator over a BTreeMap's keys.
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub struct Keys<'a, K: 'a, V: 'a> {
291 inner: Iter<'a, K, V>,
294 /// An iterator over a BTreeMap's values.
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub struct Values<'a, K: 'a, V: 'a> {
297 inner: Iter<'a, K, V>,
300 /// A mutable iterator over a BTreeMap's values.
301 #[stable(feature = "map_values_mut", since = "1.10.0")]
302 pub struct ValuesMut<'a, K: 'a, V: 'a> {
303 inner: IterMut<'a, K, V>,
306 /// An iterator over a sub-range of BTreeMap's entries.
307 pub struct Range<'a, K: 'a, V: 'a> {
308 front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
309 back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
312 /// A mutable iterator over a sub-range of BTreeMap's entries.
313 pub struct RangeMut<'a, K: 'a, V: 'a> {
314 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
315 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
317 // Be invariant in `K` and `V`
318 _marker: PhantomData<&'a mut (K, V)>,
321 /// A view into a single entry in a map, which may either be vacant or occupied.
322 /// This enum is constructed from the [`entry`] method on [`BTreeMap`].
324 /// [`BTreeMap`]: struct.BTreeMap.html
325 /// [`entry`]: struct.BTreeMap.html#method.entry
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub enum Entry<'a, K: 'a, V: 'a> {
329 #[stable(feature = "rust1", since = "1.0.0")]
330 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
331 VacantEntry<'a, K, V>),
333 /// An occupied Entry
334 #[stable(feature = "rust1", since = "1.0.0")]
335 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
336 OccupiedEntry<'a, K, V>),
339 #[stable(feature= "debug_btree_map", since = "1.12.0")]
340 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for Entry<'a, K, V> {
341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
343 Vacant(ref v) => f.debug_tuple("Entry")
346 Occupied(ref o) => f.debug_tuple("Entry")
353 /// A vacant Entry. It is part of the [`Entry`] enum.
355 /// [`Entry`]: enum.Entry.html
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub struct VacantEntry<'a, K: 'a, V: 'a> {
359 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
360 length: &'a mut usize,
362 // Be invariant in `K` and `V`
363 _marker: PhantomData<&'a mut (K, V)>,
366 #[stable(feature= "debug_btree_map", since = "1.12.0")]
367 impl<'a, K: 'a + Debug + Ord, V: 'a> Debug for VacantEntry<'a, K, V> {
368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
369 f.debug_tuple("VacantEntry")
375 /// An occupied Entry. It is part of the [`Entry`] enum.
377 /// [`Entry`]: enum.Entry.html
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
380 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
382 length: &'a mut usize,
384 // Be invariant in `K` and `V`
385 _marker: PhantomData<&'a mut (K, V)>,
388 #[stable(feature= "debug_btree_map", since = "1.12.0")]
389 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 f.debug_struct("OccupiedEntry")
392 .field("key", self.key())
393 .field("value", self.get())
398 // An iterator for merging two sorted sequences into one
399 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
404 impl<K: Ord, V> BTreeMap<K, V> {
405 /// Makes a new empty BTreeMap with a reasonable choice for B.
412 /// use std::collections::BTreeMap;
414 /// let mut map = BTreeMap::new();
416 /// // entries can now be inserted into the empty map
417 /// map.insert(1, "a");
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn new() -> BTreeMap<K, V> {
422 root: node::Root::new_leaf(),
427 /// Clears the map, removing all values.
434 /// use std::collections::BTreeMap;
436 /// let mut a = BTreeMap::new();
437 /// a.insert(1, "a");
439 /// assert!(a.is_empty());
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn clear(&mut self) {
443 // FIXME(gereeter) .clear() allocates
444 *self = BTreeMap::new();
447 /// Returns a 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 /// assert_eq!(map.get(&1), Some(&"a"));
462 /// assert_eq!(map.get(&2), None);
464 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
469 match search::search_tree(self.root.as_ref(), key) {
470 Found(handle) => Some(handle.into_kv().1),
475 /// Returns true if the map contains a value for the specified key.
477 /// The key may be any borrowed form of the map's key type, but the ordering
478 /// on the borrowed form *must* match the ordering on the key type.
485 /// use std::collections::BTreeMap;
487 /// let mut map = BTreeMap::new();
488 /// map.insert(1, "a");
489 /// assert_eq!(map.contains_key(&1), true);
490 /// assert_eq!(map.contains_key(&2), false);
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
497 self.get(key).is_some()
500 /// Returns a mutable reference to the value corresponding to the key.
502 /// The key may be any borrowed form of the map's key type, but the ordering
503 /// on the borrowed form *must* match the ordering on the key type.
510 /// use std::collections::BTreeMap;
512 /// let mut map = BTreeMap::new();
513 /// map.insert(1, "a");
514 /// if let Some(x) = map.get_mut(&1) {
517 /// assert_eq!(map[&1], "b");
519 // See `get` for implementation notes, this is basically a copy-paste with mut's added
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
525 match search::search_tree(self.root.as_mut(), key) {
526 Found(handle) => Some(handle.into_kv_mut().1),
531 /// Inserts a key-value pair into the map.
533 /// If the map did not have this key present, `None` is returned.
535 /// If the map did have this key present, the value is updated, and the old
536 /// value is returned. The key is not updated, though; this matters for
537 /// types that can be `==` without being identical. See the [module-level
538 /// documentation] for more.
540 /// [module-level documentation]: index.html#insert-and-complex-keys
547 /// use std::collections::BTreeMap;
549 /// let mut map = BTreeMap::new();
550 /// assert_eq!(map.insert(37, "a"), None);
551 /// assert_eq!(map.is_empty(), false);
553 /// map.insert(37, "b");
554 /// assert_eq!(map.insert(37, "c"), Some("b"));
555 /// assert_eq!(map[&37], "c");
557 #[stable(feature = "rust1", since = "1.0.0")]
558 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
559 match self.entry(key) {
560 Occupied(mut entry) => Some(entry.insert(value)),
568 /// Removes a key from the map, returning the value at the key if the key
569 /// was previously in the map.
571 /// The key may be any borrowed form of the map's key type, but the ordering
572 /// on the borrowed form *must* match the ordering on the key type.
579 /// use std::collections::BTreeMap;
581 /// let mut map = BTreeMap::new();
582 /// map.insert(1, "a");
583 /// assert_eq!(map.remove(&1), Some("a"));
584 /// assert_eq!(map.remove(&1), None);
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
591 match search::search_tree(self.root.as_mut(), key) {
595 length: &mut self.length,
596 _marker: PhantomData,
604 /// Moves all elements from `other` into `Self`, leaving `other` empty.
609 /// use std::collections::BTreeMap;
611 /// let mut a = BTreeMap::new();
612 /// a.insert(1, "a");
613 /// a.insert(2, "b");
614 /// a.insert(3, "c");
616 /// let mut b = BTreeMap::new();
617 /// b.insert(3, "d");
618 /// b.insert(4, "e");
619 /// b.insert(5, "f");
621 /// a.append(&mut b);
623 /// assert_eq!(a.len(), 5);
624 /// assert_eq!(b.len(), 0);
626 /// assert_eq!(a[&1], "a");
627 /// assert_eq!(a[&2], "b");
628 /// assert_eq!(a[&3], "d");
629 /// assert_eq!(a[&4], "e");
630 /// assert_eq!(a[&5], "f");
632 #[stable(feature = "btree_append", since = "1.11.0")]
633 pub fn append(&mut self, other: &mut Self) {
634 // Do we have to append anything at all?
635 if other.len() == 0 {
639 // We can just swap `self` and `other` if `self` is empty.
641 mem::swap(self, other);
645 // First, we merge `self` and `other` into a sorted sequence in linear time.
646 let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
647 let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
648 let iter = MergeIter {
649 left: self_iter.peekable(),
650 right: other_iter.peekable(),
653 // Second, we build a tree from the sorted sequence in linear time.
654 self.from_sorted_iter(iter);
655 self.fix_right_edge();
658 /// Constructs a double-ended iterator over a sub-range of elements in the map, starting
659 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
660 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
661 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
668 /// #![feature(btree_range, collections_bound)]
670 /// use std::collections::BTreeMap;
671 /// use std::collections::Bound::{Included, Unbounded};
673 /// let mut map = BTreeMap::new();
674 /// map.insert(3, "a");
675 /// map.insert(5, "b");
676 /// map.insert(8, "c");
677 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
678 /// println!("{}: {}", key, value);
680 /// assert_eq!(Some((&5, &"b")), map.range((Included(&4), Unbounded)).next());
682 #[unstable(feature = "btree_range",
683 reason = "matches collection reform specification, waiting for dust to settle",
685 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V>
686 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
688 let min = range.start();
689 let max = range.end();
690 let front = match min {
692 match search::search_tree(self.root.as_ref(), key) {
693 Found(kv_handle) => {
694 match kv_handle.left_edge().force() {
695 Leaf(bottom) => bottom,
696 Internal(internal) => last_leaf_edge(internal.descend()),
699 GoDown(bottom) => bottom,
703 match search::search_tree(self.root.as_ref(), key) {
704 Found(kv_handle) => {
705 match kv_handle.right_edge().force() {
706 Leaf(bottom) => bottom,
707 Internal(internal) => first_leaf_edge(internal.descend()),
710 GoDown(bottom) => bottom,
713 Unbounded => first_leaf_edge(self.root.as_ref()),
716 let back = match max {
718 match search::search_tree(self.root.as_ref(), key) {
719 Found(kv_handle) => {
720 match kv_handle.right_edge().force() {
721 Leaf(bottom) => bottom,
722 Internal(internal) => first_leaf_edge(internal.descend()),
725 GoDown(bottom) => bottom,
729 match search::search_tree(self.root.as_ref(), key) {
730 Found(kv_handle) => {
731 match kv_handle.left_edge().force() {
732 Leaf(bottom) => bottom,
733 Internal(internal) => last_leaf_edge(internal.descend()),
736 GoDown(bottom) => bottom,
739 Unbounded => last_leaf_edge(self.root.as_ref()),
748 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map, starting
749 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
750 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
751 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
758 /// #![feature(btree_range, collections_bound)]
760 /// use std::collections::BTreeMap;
761 /// use std::collections::Bound::{Included, Excluded};
763 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
764 /// .map(|&s| (s, 0))
766 /// for (_, balance) in map.range_mut((Included("B"), Excluded("Cheryl"))) {
769 /// for (name, balance) in &map {
770 /// println!("{} => {}", name, balance);
773 #[unstable(feature = "btree_range",
774 reason = "matches collection reform specification, waiting for dust to settle",
776 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V>
777 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
779 let min = range.start();
780 let max = range.end();
781 let root1 = self.root.as_mut();
782 let root2 = unsafe { ptr::read(&root1) };
784 let front = match min {
786 match search::search_tree(root1, key) {
787 Found(kv_handle) => {
788 match kv_handle.left_edge().force() {
789 Leaf(bottom) => bottom,
790 Internal(internal) => last_leaf_edge(internal.descend()),
793 GoDown(bottom) => bottom,
797 match search::search_tree(root1, key) {
798 Found(kv_handle) => {
799 match kv_handle.right_edge().force() {
800 Leaf(bottom) => bottom,
801 Internal(internal) => first_leaf_edge(internal.descend()),
804 GoDown(bottom) => bottom,
807 Unbounded => first_leaf_edge(root1),
810 let back = match max {
812 match search::search_tree(root2, key) {
813 Found(kv_handle) => {
814 match kv_handle.right_edge().force() {
815 Leaf(bottom) => bottom,
816 Internal(internal) => first_leaf_edge(internal.descend()),
819 GoDown(bottom) => bottom,
823 match search::search_tree(root2, key) {
824 Found(kv_handle) => {
825 match kv_handle.left_edge().force() {
826 Leaf(bottom) => bottom,
827 Internal(internal) => last_leaf_edge(internal.descend()),
830 GoDown(bottom) => bottom,
833 Unbounded => last_leaf_edge(root2),
839 _marker: PhantomData,
843 /// Gets the given key's corresponding entry in the map for in-place manipulation.
850 /// use std::collections::BTreeMap;
852 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
854 /// // count the number of occurrences of letters in the vec
855 /// for x in vec!["a","b","a","c","a","b"] {
856 /// *count.entry(x).or_insert(0) += 1;
859 /// assert_eq!(count["a"], 3);
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn entry(&mut self, key: K) -> Entry<K, V> {
863 match search::search_tree(self.root.as_mut(), &key) {
865 Occupied(OccupiedEntry {
867 length: &mut self.length,
868 _marker: PhantomData,
875 length: &mut self.length,
876 _marker: PhantomData,
882 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
883 let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
884 // Iterate through all key-value pairs, pushing them into nodes at the right level.
885 for (key, value) in iter {
886 // Try to push key-value pair into the current leaf node.
887 if cur_node.len() < node::CAPACITY {
888 cur_node.push(key, value);
890 // No space left, go up and push there.
892 let mut test_node = cur_node.forget_type();
894 match test_node.ascend() {
896 let parent = parent.into_node();
897 if parent.len() < node::CAPACITY {
898 // Found a node with space left, push here.
903 test_node = parent.forget_type();
907 // We are at the top, create a new root node and push there.
908 open_node = node.into_root_mut().push_level();
914 // Push key-value pair and new right subtree.
915 let tree_height = open_node.height() - 1;
916 let mut right_tree = node::Root::new_leaf();
917 for _ in 0..tree_height {
918 right_tree.push_level();
920 open_node.push(key, value, right_tree);
922 // Go down to the right-most leaf again.
923 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
930 fn fix_right_edge(&mut self) {
931 // Handle underfull nodes, start from the top.
932 let mut cur_node = self.root.as_mut();
933 while let Internal(internal) = cur_node.force() {
934 // Check if right-most child is underfull.
935 let mut last_edge = internal.last_edge();
936 let right_child_len = last_edge.reborrow().descend().len();
937 if right_child_len < node::MIN_LEN {
939 let mut last_kv = match last_edge.left_kv() {
941 Err(_) => unreachable!(),
943 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
944 last_edge = last_kv.right_edge();
948 cur_node = last_edge.descend();
952 /// Splits the collection into two at the given key. Returns everything after the given key,
953 /// including the key.
960 /// use std::collections::BTreeMap;
962 /// let mut a = BTreeMap::new();
963 /// a.insert(1, "a");
964 /// a.insert(2, "b");
965 /// a.insert(3, "c");
966 /// a.insert(17, "d");
967 /// a.insert(41, "e");
969 /// let b = a.split_off(&3);
971 /// assert_eq!(a.len(), 2);
972 /// assert_eq!(b.len(), 3);
974 /// assert_eq!(a[&1], "a");
975 /// assert_eq!(a[&2], "b");
977 /// assert_eq!(b[&3], "c");
978 /// assert_eq!(b[&17], "d");
979 /// assert_eq!(b[&41], "e");
981 #[stable(feature = "btree_split_off", since = "1.11.0")]
982 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
989 let total_num = self.len();
991 let mut right = Self::new();
992 for _ in 0..(self.root.as_ref().height()) {
993 right.root.push_level();
997 let mut left_node = self.root.as_mut();
998 let mut right_node = right.root.as_mut();
1001 let mut split_edge = match search::search_node(left_node, key) {
1002 // key is going to the right tree
1003 Found(handle) => handle.left_edge(),
1004 GoDown(handle) => handle,
1007 split_edge.move_suffix(&mut right_node);
1009 match (split_edge.force(), right_node.force()) {
1010 (Internal(edge), Internal(node)) => {
1011 left_node = edge.descend();
1012 right_node = node.first_edge().descend();
1014 (Leaf(_), Leaf(_)) => {
1024 self.fix_right_border();
1025 right.fix_left_border();
1027 if self.root.as_ref().height() < right.root.as_ref().height() {
1028 self.recalc_length();
1029 right.length = total_num - self.len();
1031 right.recalc_length();
1032 self.length = total_num - right.len();
1038 /// Calculates the number of elements if it is incorrect.
1039 fn recalc_length(&mut self) {
1040 fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize {
1041 let mut res = node.len();
1043 if let Internal(node) = node.force() {
1044 let mut edge = node.first_edge();
1046 res += dfs(edge.reborrow().descend());
1047 match edge.right_kv() {
1049 edge = right_kv.right_edge();
1061 self.length = dfs(self.root.as_ref());
1064 /// Removes empty levels on the top.
1065 fn fix_top(&mut self) {
1068 let node = self.root.as_ref();
1069 if node.height() == 0 || node.len() > 0 {
1073 self.root.pop_level();
1077 fn fix_right_border(&mut self) {
1081 let mut cur_node = self.root.as_mut();
1083 while let Internal(node) = cur_node.force() {
1084 let mut last_kv = node.last_kv();
1086 if last_kv.can_merge() {
1087 cur_node = last_kv.merge().descend();
1089 let right_len = last_kv.reborrow().right_edge().descend().len();
1090 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1091 if right_len < node::MIN_LEN + 1 {
1092 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1094 cur_node = last_kv.right_edge().descend();
1102 /// The symmetric clone of `fix_right_border`.
1103 fn fix_left_border(&mut self) {
1107 let mut cur_node = self.root.as_mut();
1109 while let Internal(node) = cur_node.force() {
1110 let mut first_kv = node.first_kv();
1112 if first_kv.can_merge() {
1113 cur_node = first_kv.merge().descend();
1115 let left_len = first_kv.reborrow().left_edge().descend().len();
1116 if left_len < node::MIN_LEN + 1 {
1117 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1119 cur_node = first_kv.left_edge().descend();
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1130 type Item = (&'a K, &'a V);
1131 type IntoIter = Iter<'a, K, V>;
1133 fn into_iter(self) -> Iter<'a, K, V> {
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1140 type Item = (&'a K, &'a V);
1142 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1143 if self.length == 0 {
1147 unsafe { Some(self.range.next_unchecked()) }
1151 fn size_hint(&self) -> (usize, Option<usize>) {
1152 (self.length, Some(self.length))
1156 #[unstable(feature = "fused", issue = "35602")]
1157 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1161 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1162 if self.length == 0 {
1166 unsafe { Some(self.range.next_back_unchecked()) }
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1173 fn len(&self) -> usize {
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<'a, K, V> Clone for Iter<'a, K, V> {
1180 fn clone(&self) -> Iter<'a, K, V> {
1182 range: self.range.clone(),
1183 length: self.length,
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1190 type Item = (&'a K, &'a mut V);
1191 type IntoIter = IterMut<'a, K, V>;
1193 fn into_iter(self) -> IterMut<'a, K, V> {
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1200 type Item = (&'a K, &'a mut V);
1202 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1203 if self.length == 0 {
1207 unsafe { Some(self.range.next_unchecked()) }
1211 fn size_hint(&self) -> (usize, Option<usize>) {
1212 (self.length, Some(self.length))
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1218 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1219 if self.length == 0 {
1223 unsafe { Some(self.range.next_back_unchecked()) }
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1230 fn len(&self) -> usize {
1235 #[unstable(feature = "fused", issue = "35602")]
1236 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<K, V> IntoIterator for BTreeMap<K, V> {
1241 type IntoIter = IntoIter<K, V>;
1243 fn into_iter(self) -> IntoIter<K, V> {
1244 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1245 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1246 let len = self.length;
1250 front: first_leaf_edge(root1),
1251 back: last_leaf_edge(root2),
1257 #[stable(feature = "btree_drop", since = "1.7.0")]
1258 impl<K, V> Drop for IntoIter<K, V> {
1259 fn drop(&mut self) {
1260 for _ in &mut *self {
1263 let leaf_node = ptr::read(&self.front).into_node();
1264 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1265 let mut cur_node = first_parent.into_node();
1266 while let Some(parent) = cur_node.deallocate_and_ascend() {
1267 cur_node = parent.into_node()
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl<K, V> Iterator for IntoIter<K, V> {
1278 fn next(&mut self) -> Option<(K, V)> {
1279 if self.length == 0 {
1285 let handle = unsafe { ptr::read(&self.front) };
1287 let mut cur_handle = match handle.right_kv() {
1289 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1290 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1291 self.front = kv.right_edge();
1292 return Some((k, v));
1294 Err(last_edge) => unsafe {
1295 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1300 match cur_handle.right_kv() {
1302 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1303 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1304 self.front = first_leaf_edge(kv.right_edge().descend());
1305 return Some((k, v));
1307 Err(last_edge) => unsafe {
1308 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1314 fn size_hint(&self) -> (usize, Option<usize>) {
1315 (self.length, Some(self.length))
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1321 fn next_back(&mut self) -> Option<(K, V)> {
1322 if self.length == 0 {
1328 let handle = unsafe { ptr::read(&self.back) };
1330 let mut cur_handle = match handle.left_kv() {
1332 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1333 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1334 self.back = kv.left_edge();
1335 return Some((k, v));
1337 Err(last_edge) => unsafe {
1338 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1343 match cur_handle.left_kv() {
1345 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1346 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1347 self.back = last_leaf_edge(kv.left_edge().descend());
1348 return Some((k, v));
1350 Err(last_edge) => unsafe {
1351 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1360 fn len(&self) -> usize {
1365 #[unstable(feature = "fused", issue = "35602")]
1366 impl<K, V> FusedIterator for IntoIter<K, V> {}
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1372 fn next(&mut self) -> Option<&'a K> {
1373 self.inner.next().map(|(k, _)| k)
1376 fn size_hint(&self) -> (usize, Option<usize>) {
1377 self.inner.size_hint()
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1383 fn next_back(&mut self) -> Option<&'a K> {
1384 self.inner.next_back().map(|(k, _)| k)
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1390 fn len(&self) -> usize {
1395 #[unstable(feature = "fused", issue = "35602")]
1396 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<'a, K, V> Clone for Keys<'a, K, V> {
1400 fn clone(&self) -> Keys<'a, K, V> {
1401 Keys { inner: self.inner.clone() }
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<'a, K, V> Iterator for Values<'a, K, V> {
1409 fn next(&mut self) -> Option<&'a V> {
1410 self.inner.next().map(|(_, v)| v)
1413 fn size_hint(&self) -> (usize, Option<usize>) {
1414 self.inner.size_hint()
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1420 fn next_back(&mut self) -> Option<&'a V> {
1421 self.inner.next_back().map(|(_, v)| v)
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1427 fn len(&self) -> usize {
1432 #[unstable(feature = "fused", issue = "35602")]
1433 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl<'a, K, V> Clone for Values<'a, K, V> {
1437 fn clone(&self) -> Values<'a, K, V> {
1438 Values { inner: self.inner.clone() }
1442 impl<'a, K, V> Iterator for Range<'a, K, V> {
1443 type Item = (&'a K, &'a V);
1445 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1446 if self.front == self.back {
1449 unsafe { Some(self.next_unchecked()) }
1454 #[stable(feature = "map_values_mut", since = "1.10.0")]
1455 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1456 type Item = &'a mut V;
1458 fn next(&mut self) -> Option<&'a mut V> {
1459 self.inner.next().map(|(_, v)| v)
1462 fn size_hint(&self) -> (usize, Option<usize>) {
1463 self.inner.size_hint()
1467 #[stable(feature = "map_values_mut", since = "1.10.0")]
1468 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1469 fn next_back(&mut self) -> Option<&'a mut V> {
1470 self.inner.next_back().map(|(_, v)| v)
1474 #[stable(feature = "map_values_mut", since = "1.10.0")]
1475 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1476 fn len(&self) -> usize {
1481 #[unstable(feature = "fused", issue = "35602")]
1482 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1485 impl<'a, K, V> Range<'a, K, V> {
1486 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1487 let handle = self.front;
1489 let mut cur_handle = match handle.right_kv() {
1491 let ret = kv.into_kv();
1492 self.front = kv.right_edge();
1496 let next_level = last_edge.into_node().ascend().ok();
1497 unwrap_unchecked(next_level)
1502 match cur_handle.right_kv() {
1504 let ret = kv.into_kv();
1505 self.front = first_leaf_edge(kv.right_edge().descend());
1509 let next_level = last_edge.into_node().ascend().ok();
1510 cur_handle = unwrap_unchecked(next_level);
1517 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1518 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1519 if self.front == self.back {
1522 unsafe { Some(self.next_back_unchecked()) }
1527 impl<'a, K, V> Range<'a, K, V> {
1528 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1529 let handle = self.back;
1531 let mut cur_handle = match handle.left_kv() {
1533 let ret = kv.into_kv();
1534 self.back = kv.left_edge();
1538 let next_level = last_edge.into_node().ascend().ok();
1539 unwrap_unchecked(next_level)
1544 match cur_handle.left_kv() {
1546 let ret = kv.into_kv();
1547 self.back = last_leaf_edge(kv.left_edge().descend());
1551 let next_level = last_edge.into_node().ascend().ok();
1552 cur_handle = unwrap_unchecked(next_level);
1559 #[unstable(feature = "fused", issue = "35602")]
1560 impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
1562 impl<'a, K, V> Clone for Range<'a, K, V> {
1563 fn clone(&self) -> Range<'a, K, V> {
1571 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1572 type Item = (&'a K, &'a mut V);
1574 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1575 if self.front == self.back {
1578 unsafe { Some(self.next_unchecked()) }
1583 impl<'a, K, V> RangeMut<'a, K, V> {
1584 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1585 let handle = ptr::read(&self.front);
1587 let mut cur_handle = match handle.right_kv() {
1589 let (k, v) = ptr::read(&kv).into_kv_mut();
1590 self.front = kv.right_edge();
1594 let next_level = last_edge.into_node().ascend().ok();
1595 unwrap_unchecked(next_level)
1600 match cur_handle.right_kv() {
1602 let (k, v) = ptr::read(&kv).into_kv_mut();
1603 self.front = first_leaf_edge(kv.right_edge().descend());
1607 let next_level = last_edge.into_node().ascend().ok();
1608 cur_handle = unwrap_unchecked(next_level);
1615 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1616 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1617 if self.front == self.back {
1620 unsafe { Some(self.next_back_unchecked()) }
1625 #[unstable(feature = "fused", issue = "35602")]
1626 impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1628 impl<'a, K, V> RangeMut<'a, K, V> {
1629 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1630 let handle = ptr::read(&self.back);
1632 let mut cur_handle = match handle.left_kv() {
1634 let (k, v) = ptr::read(&kv).into_kv_mut();
1635 self.back = kv.left_edge();
1639 let next_level = last_edge.into_node().ascend().ok();
1640 unwrap_unchecked(next_level)
1645 match cur_handle.left_kv() {
1647 let (k, v) = ptr::read(&kv).into_kv_mut();
1648 self.back = last_leaf_edge(kv.left_edge().descend());
1652 let next_level = last_edge.into_node().ascend().ok();
1653 cur_handle = unwrap_unchecked(next_level);
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1662 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1663 let mut map = BTreeMap::new();
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1672 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1673 for (k, v) in iter {
1679 #[stable(feature = "extend_ref", since = "1.2.0")]
1680 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1681 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1682 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1688 fn hash<H: Hasher>(&self, state: &mut H) {
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<K: Ord, V> Default for BTreeMap<K, V> {
1697 /// Creates an empty `BTreeMap<K, V>`.
1698 fn default() -> BTreeMap<K, V> {
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1705 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1706 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1716 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1717 self.iter().partial_cmp(other.iter())
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1724 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1725 self.iter().cmp(other.iter())
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1732 f.debug_map().entries(self.iter()).finish()
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1744 fn index(&self, key: &Q) -> &V {
1745 self.get(key).expect("no entry found for key")
1749 fn first_leaf_edge<BorrowType, K, V>
1750 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1751 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1753 match node.force() {
1754 Leaf(leaf) => return leaf.first_edge(),
1755 Internal(internal) => {
1756 node = internal.first_edge().descend();
1762 fn last_leaf_edge<BorrowType, K, V>
1763 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1764 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1766 match node.force() {
1767 Leaf(leaf) => return leaf.last_edge(),
1768 Internal(internal) => {
1769 node = internal.last_edge().descend();
1776 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1777 val.unwrap_or_else(|| {
1778 if cfg!(debug_assertions) {
1779 panic!("'unchecked' unwrap on None in BTreeMap");
1781 intrinsics::unreachable();
1786 impl<K, V> BTreeMap<K, V> {
1787 /// Gets an iterator over the entries of the map, sorted by key.
1794 /// use std::collections::BTreeMap;
1796 /// let mut map = BTreeMap::new();
1797 /// map.insert(3, "c");
1798 /// map.insert(2, "b");
1799 /// map.insert(1, "a");
1801 /// for (key, value) in map.iter() {
1802 /// println!("{}: {}", key, value);
1805 /// let (first_key, first_value) = map.iter().next().unwrap();
1806 /// assert_eq!((*first_key, *first_value), (1, "a"));
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 pub fn iter(&self) -> Iter<K, V> {
1812 front: first_leaf_edge(self.root.as_ref()),
1813 back: last_leaf_edge(self.root.as_ref()),
1815 length: self.length,
1819 /// Gets a mutable iterator over the entries of the map, sorted by key.
1826 /// use std::collections::BTreeMap;
1828 /// let mut map = BTreeMap::new();
1829 /// map.insert("a", 1);
1830 /// map.insert("b", 2);
1831 /// map.insert("c", 3);
1833 /// // add 10 to the value if the key isn't "a"
1834 /// for (key, value) in map.iter_mut() {
1835 /// if key != &"a" {
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1842 let root1 = self.root.as_mut();
1843 let root2 = unsafe { ptr::read(&root1) };
1846 front: first_leaf_edge(root1),
1847 back: last_leaf_edge(root2),
1848 _marker: PhantomData,
1850 length: self.length,
1854 /// Gets an iterator over the keys of the map, in sorted order.
1861 /// use std::collections::BTreeMap;
1863 /// let mut a = BTreeMap::new();
1864 /// a.insert(2, "b");
1865 /// a.insert(1, "a");
1867 /// let keys: Vec<_> = a.keys().cloned().collect();
1868 /// assert_eq!(keys, [1, 2]);
1870 #[stable(feature = "rust1", since = "1.0.0")]
1871 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1872 Keys { inner: self.iter() }
1875 /// Gets an iterator over the values of the map, in order by key.
1882 /// use std::collections::BTreeMap;
1884 /// let mut a = BTreeMap::new();
1885 /// a.insert(1, "hello");
1886 /// a.insert(2, "goodbye");
1888 /// let values: Vec<&str> = a.values().cloned().collect();
1889 /// assert_eq!(values, ["hello", "goodbye"]);
1891 #[stable(feature = "rust1", since = "1.0.0")]
1892 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1893 Values { inner: self.iter() }
1896 /// Gets a mutable iterator over the values of the map, in order by key.
1903 /// use std::collections::BTreeMap;
1905 /// let mut a = BTreeMap::new();
1906 /// a.insert(1, String::from("hello"));
1907 /// a.insert(2, String::from("goodbye"));
1909 /// for value in a.values_mut() {
1910 /// value.push_str("!");
1913 /// let values: Vec<String> = a.values().cloned().collect();
1914 /// assert_eq!(values, [String::from("hello!"),
1915 /// String::from("goodbye!")]);
1917 #[stable(feature = "map_values_mut", since = "1.10.0")]
1918 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1919 ValuesMut { inner: self.iter_mut() }
1922 /// Returns the number of elements in the map.
1929 /// use std::collections::BTreeMap;
1931 /// let mut a = BTreeMap::new();
1932 /// assert_eq!(a.len(), 0);
1933 /// a.insert(1, "a");
1934 /// assert_eq!(a.len(), 1);
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 pub fn len(&self) -> usize {
1941 /// Returns true if the map contains no elements.
1948 /// use std::collections::BTreeMap;
1950 /// let mut a = BTreeMap::new();
1951 /// assert!(a.is_empty());
1952 /// a.insert(1, "a");
1953 /// assert!(!a.is_empty());
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 pub fn is_empty(&self) -> bool {
1961 impl<'a, K: Ord, V> Entry<'a, K, V> {
1962 /// Ensures a value is in the entry by inserting the default if empty, and returns
1963 /// a mutable reference to the value in the entry.
1968 /// use std::collections::BTreeMap;
1970 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1971 /// map.entry("poneyland").or_insert(12);
1973 /// assert_eq!(map["poneyland"], 12);
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 pub fn or_insert(self, default: V) -> &'a mut V {
1978 Occupied(entry) => entry.into_mut(),
1979 Vacant(entry) => entry.insert(default),
1983 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1984 /// and returns a mutable reference to the value in the entry.
1989 /// use std::collections::BTreeMap;
1991 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
1992 /// let s = "hoho".to_string();
1994 /// map.entry("poneyland").or_insert_with(|| s);
1996 /// assert_eq!(map["poneyland"], "hoho".to_string());
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2001 Occupied(entry) => entry.into_mut(),
2002 Vacant(entry) => entry.insert(default()),
2006 /// Returns a reference to this entry's key.
2011 /// use std::collections::BTreeMap;
2013 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2014 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2016 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2017 pub fn key(&self) -> &K {
2019 Occupied(ref entry) => entry.key(),
2020 Vacant(ref entry) => entry.key(),
2025 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2026 /// Gets a reference to the key that would be used when inserting a value
2027 /// through the VacantEntry.
2032 /// use std::collections::BTreeMap;
2034 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2035 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2037 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2038 pub fn key(&self) -> &K {
2042 /// Take ownership of the key.
2047 /// use std::collections::BTreeMap;
2048 /// use std::collections::btree_map::Entry;
2050 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2052 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2056 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2057 pub fn into_key(self) -> K {
2061 /// Sets the value of the entry with the `VacantEntry`'s key,
2062 /// and returns a mutable reference to it.
2067 /// use std::collections::BTreeMap;
2069 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2071 /// // count the number of occurrences of letters in the vec
2072 /// for x in vec!["a","b","a","c","a","b"] {
2073 /// *count.entry(x).or_insert(0) += 1;
2076 /// assert_eq!(count["a"], 3);
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 pub fn insert(self, value: V) -> &'a mut V {
2088 let mut cur_parent = match self.handle.insert(self.key, value) {
2089 (Fit(handle), _) => return handle.into_kv_mut().1,
2090 (Split(left, k, v, right), ptr) => {
2095 left.ascend().map_err(|n| n.into_root_mut())
2102 match parent.insert(ins_k, ins_v, ins_edge) {
2103 Fit(_) => return unsafe { &mut *out_ptr },
2104 Split(left, k, v, right) => {
2108 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2113 root.push_level().push(ins_k, ins_v, ins_edge);
2114 return unsafe { &mut *out_ptr };
2121 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2122 /// Gets a reference to the key in the entry.
2127 /// use std::collections::BTreeMap;
2129 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2130 /// map.entry("poneyland").or_insert(12);
2131 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2133 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2134 pub fn key(&self) -> &K {
2135 self.handle.reborrow().into_kv().0
2138 /// Deprecated, renamed to `remove_entry`
2139 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2140 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2141 pub fn remove_pair(self) -> (K, V) {
2145 /// Take ownership of the key and value from the map.
2150 /// use std::collections::BTreeMap;
2151 /// use std::collections::btree_map::Entry;
2153 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2154 /// map.entry("poneyland").or_insert(12);
2156 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2157 /// // We delete the entry from the map.
2158 /// o.remove_entry();
2161 /// // If now try to get the value, it will panic:
2162 /// // println!("{}", map["poneyland"]);
2164 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2165 pub fn remove_entry(self) -> (K, V) {
2169 /// Gets a reference to the value in the entry.
2174 /// use std::collections::BTreeMap;
2175 /// use std::collections::btree_map::Entry;
2177 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2178 /// map.entry("poneyland").or_insert(12);
2180 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2181 /// assert_eq!(o.get(), &12);
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 pub fn get(&self) -> &V {
2186 self.handle.reborrow().into_kv().1
2189 /// Gets a mutable reference to the value in the entry.
2194 /// use std::collections::BTreeMap;
2195 /// use std::collections::btree_map::Entry;
2197 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2198 /// map.entry("poneyland").or_insert(12);
2200 /// assert_eq!(map["poneyland"], 12);
2201 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2202 /// *o.get_mut() += 10;
2204 /// assert_eq!(map["poneyland"], 22);
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 pub fn get_mut(&mut self) -> &mut V {
2208 self.handle.kv_mut().1
2211 /// Converts the entry into a mutable reference to its value.
2216 /// use std::collections::BTreeMap;
2217 /// use std::collections::btree_map::Entry;
2219 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2220 /// map.entry("poneyland").or_insert(12);
2222 /// assert_eq!(map["poneyland"], 12);
2223 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2224 /// *o.into_mut() += 10;
2226 /// assert_eq!(map["poneyland"], 22);
2228 #[stable(feature = "rust1", since = "1.0.0")]
2229 pub fn into_mut(self) -> &'a mut V {
2230 self.handle.into_kv_mut().1
2233 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2234 /// and returns the entry's old value.
2239 /// use std::collections::BTreeMap;
2240 /// use std::collections::btree_map::Entry;
2242 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2243 /// map.entry("poneyland").or_insert(12);
2245 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2246 /// assert_eq!(o.insert(15), 12);
2248 /// assert_eq!(map["poneyland"], 15);
2250 #[stable(feature = "rust1", since = "1.0.0")]
2251 pub fn insert(&mut self, value: V) -> V {
2252 mem::replace(self.get_mut(), value)
2255 /// Takes the value of the entry out of the map, and returns it.
2260 /// use std::collections::BTreeMap;
2261 /// use std::collections::btree_map::Entry;
2263 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2264 /// map.entry("poneyland").or_insert(12);
2266 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2267 /// assert_eq!(o.remove(), 12);
2269 /// // If we try to get "poneyland"'s value, it'll panic:
2270 /// // println!("{}", map["poneyland"]);
2272 #[stable(feature = "rust1", since = "1.0.0")]
2273 pub fn remove(self) -> V {
2277 fn remove_kv(self) -> (K, V) {
2280 let (small_leaf, old_key, old_val) = match self.handle.force() {
2282 let (hole, old_key, old_val) = leaf.remove();
2283 (hole.into_node(), old_key, old_val)
2285 Internal(mut internal) => {
2286 let key_loc = internal.kv_mut().0 as *mut K;
2287 let val_loc = internal.kv_mut().1 as *mut V;
2289 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2290 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2292 let (hole, key, val) = to_remove.remove();
2294 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2295 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2297 (hole.into_node(), old_key, old_val)
2302 let mut cur_node = small_leaf.forget_type();
2303 while cur_node.len() < node::CAPACITY / 2 {
2304 match handle_underfull_node(cur_node) {
2306 EmptyParent(_) => unreachable!(),
2308 if parent.len() == 0 {
2309 // We must be at the root
2310 parent.into_root_mut().pop_level();
2313 cur_node = parent.forget_type();
2324 enum UnderflowResult<'a, K, V> {
2326 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2327 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2328 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2331 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>)
2332 -> UnderflowResult<'a, K, V> {
2333 let parent = if let Ok(parent) = node.ascend() {
2339 let (is_left, mut handle) = match parent.left_kv() {
2340 Ok(left) => (true, left),
2342 match parent.right_kv() {
2343 Ok(right) => (false, right),
2345 return EmptyParent(parent.into_node());
2351 if handle.can_merge() {
2352 Merged(handle.merge().into_node())
2355 handle.steal_left();
2357 handle.steal_right();
2359 Stole(handle.into_node())
2363 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2366 fn next(&mut self) -> Option<(K, V)> {
2367 let res = match (self.left.peek(), self.right.peek()) {
2368 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2369 (Some(_), None) => Ordering::Less,
2370 (None, Some(_)) => Ordering::Greater,
2371 (None, None) => return None,
2374 // Check which elements comes first and only advance the corresponding iterator.
2375 // If two keys are equal, take the value from `right`.
2377 Ordering::Less => self.left.next(),
2378 Ordering::Greater => self.right.next(),
2379 Ordering::Equal => {