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 #[stable(feature = "collection_debug", since = "1.17.0")]
274 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Iter<'a, K, V> {
275 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276 f.debug_list().entries(self.clone()).finish()
280 /// A mutable iterator over a BTreeMap's entries.
281 #[stable(feature = "rust1", since = "1.0.0")]
283 pub struct IterMut<'a, K: 'a, V: 'a> {
284 range: RangeMut<'a, K, V>,
288 /// An owning iterator over a BTreeMap's entries.
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub struct IntoIter<K, V> {
291 front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
292 back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
296 #[stable(feature = "collection_debug", since = "1.17.0")]
297 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
300 front: self.front.reborrow(),
301 back: self.back.reborrow(),
303 f.debug_list().entries(range).finish()
307 /// An iterator over a BTreeMap's keys.
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub struct Keys<'a, K: 'a, V: 'a> {
310 inner: Iter<'a, K, V>,
313 #[stable(feature = "collection_debug", since = "1.17.0")]
314 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Keys<'a, K, V> {
315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316 f.debug_list().entries(self.inner.clone()).finish()
320 /// An iterator over a BTreeMap's values.
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub struct Values<'a, K: 'a, V: 'a> {
323 inner: Iter<'a, K, V>,
326 #[stable(feature = "collection_debug", since = "1.17.0")]
327 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Values<'a, K, V> {
328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
329 f.debug_list().entries(self.inner.clone()).finish()
333 /// A mutable iterator over a BTreeMap's values.
334 #[stable(feature = "map_values_mut", since = "1.10.0")]
336 pub struct ValuesMut<'a, K: 'a, V: 'a> {
337 inner: IterMut<'a, K, V>,
340 /// An iterator over a sub-range of BTreeMap's entries.
341 #[stable(feature = "btree_range", since = "1.17.0")]
342 pub struct Range<'a, K: 'a, V: 'a> {
343 front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
344 back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
347 #[stable(feature = "collection_debug", since = "1.17.0")]
348 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Range<'a, K, V> {
349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350 f.debug_list().entries(self.clone()).finish()
354 /// A mutable iterator over a sub-range of BTreeMap's entries.
355 #[stable(feature = "btree_range", since = "1.17.0")]
356 pub struct RangeMut<'a, K: 'a, V: 'a> {
357 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
358 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
360 // Be invariant in `K` and `V`
361 _marker: PhantomData<&'a mut (K, V)>,
364 #[stable(feature = "collection_debug", since = "1.17.0")]
365 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for RangeMut<'a, K, V> {
366 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
368 front: self.front.reborrow(),
369 back: self.back.reborrow(),
371 f.debug_list().entries(range).finish()
375 /// A view into a single entry in a map, which may either be vacant or occupied.
376 /// This enum is constructed from the [`entry`] method on [`BTreeMap`].
378 /// [`BTreeMap`]: struct.BTreeMap.html
379 /// [`entry`]: struct.BTreeMap.html#method.entry
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub enum Entry<'a, K: 'a, V: 'a> {
383 #[stable(feature = "rust1", since = "1.0.0")]
384 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
385 VacantEntry<'a, K, V>),
387 /// An occupied Entry
388 #[stable(feature = "rust1", since = "1.0.0")]
389 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
390 OccupiedEntry<'a, K, V>),
393 #[stable(feature= "debug_btree_map", since = "1.12.0")]
394 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for Entry<'a, K, V> {
395 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
397 Vacant(ref v) => f.debug_tuple("Entry")
400 Occupied(ref o) => f.debug_tuple("Entry")
407 /// A vacant Entry. It is part of the [`Entry`] enum.
409 /// [`Entry`]: enum.Entry.html
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub struct VacantEntry<'a, K: 'a, V: 'a> {
413 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
414 length: &'a mut usize,
416 // Be invariant in `K` and `V`
417 _marker: PhantomData<&'a mut (K, V)>,
420 #[stable(feature= "debug_btree_map", since = "1.12.0")]
421 impl<'a, K: 'a + Debug + Ord, V: 'a> Debug for VacantEntry<'a, K, V> {
422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
423 f.debug_tuple("VacantEntry")
429 /// An occupied Entry. It is part of the [`Entry`] enum.
431 /// [`Entry`]: enum.Entry.html
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
434 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
436 length: &'a mut usize,
438 // Be invariant in `K` and `V`
439 _marker: PhantomData<&'a mut (K, V)>,
442 #[stable(feature= "debug_btree_map", since = "1.12.0")]
443 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
444 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
445 f.debug_struct("OccupiedEntry")
446 .field("key", self.key())
447 .field("value", self.get())
452 // An iterator for merging two sorted sequences into one
453 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
458 impl<K: Ord, V> BTreeMap<K, V> {
459 /// Makes a new empty BTreeMap with a reasonable choice for B.
466 /// use std::collections::BTreeMap;
468 /// let mut map = BTreeMap::new();
470 /// // entries can now be inserted into the empty map
471 /// map.insert(1, "a");
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn new() -> BTreeMap<K, V> {
476 root: node::Root::new_leaf(),
481 /// Clears the map, removing all values.
488 /// use std::collections::BTreeMap;
490 /// let mut a = BTreeMap::new();
491 /// a.insert(1, "a");
493 /// assert!(a.is_empty());
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn clear(&mut self) {
497 // FIXME(gereeter) .clear() allocates
498 *self = BTreeMap::new();
501 /// Returns a reference to the value corresponding to the key.
503 /// The key may be any borrowed form of the map's key type, but the ordering
504 /// on the borrowed form *must* match the ordering on the key type.
511 /// use std::collections::BTreeMap;
513 /// let mut map = BTreeMap::new();
514 /// map.insert(1, "a");
515 /// assert_eq!(map.get(&1), Some(&"a"));
516 /// assert_eq!(map.get(&2), None);
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
523 match search::search_tree(self.root.as_ref(), key) {
524 Found(handle) => Some(handle.into_kv().1),
529 /// Returns `true` if the map contains a value for the specified key.
531 /// The key may be any borrowed form of the map's key type, but the ordering
532 /// on the borrowed form *must* match the ordering on the key type.
539 /// use std::collections::BTreeMap;
541 /// let mut map = BTreeMap::new();
542 /// map.insert(1, "a");
543 /// assert_eq!(map.contains_key(&1), true);
544 /// assert_eq!(map.contains_key(&2), false);
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
551 self.get(key).is_some()
554 /// Returns a mutable reference to the value corresponding to the key.
556 /// The key may be any borrowed form of the map's key type, but the ordering
557 /// on the borrowed form *must* match the ordering on the key type.
564 /// use std::collections::BTreeMap;
566 /// let mut map = BTreeMap::new();
567 /// map.insert(1, "a");
568 /// if let Some(x) = map.get_mut(&1) {
571 /// assert_eq!(map[&1], "b");
573 // See `get` for implementation notes, this is basically a copy-paste with mut's added
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
579 match search::search_tree(self.root.as_mut(), key) {
580 Found(handle) => Some(handle.into_kv_mut().1),
585 /// Inserts a key-value pair into the map.
587 /// If the map did not have this key present, `None` is returned.
589 /// If the map did have this key present, the value is updated, and the old
590 /// value is returned. The key is not updated, though; this matters for
591 /// types that can be `==` without being identical. See the [module-level
592 /// documentation] for more.
594 /// [module-level documentation]: index.html#insert-and-complex-keys
601 /// use std::collections::BTreeMap;
603 /// let mut map = BTreeMap::new();
604 /// assert_eq!(map.insert(37, "a"), None);
605 /// assert_eq!(map.is_empty(), false);
607 /// map.insert(37, "b");
608 /// assert_eq!(map.insert(37, "c"), Some("b"));
609 /// assert_eq!(map[&37], "c");
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
613 match self.entry(key) {
614 Occupied(mut entry) => Some(entry.insert(value)),
622 /// Removes a key from the map, returning the value at the key if the key
623 /// was previously in the map.
625 /// The key may be any borrowed form of the map's key type, but the ordering
626 /// on the borrowed form *must* match the ordering on the key type.
633 /// use std::collections::BTreeMap;
635 /// let mut map = BTreeMap::new();
636 /// map.insert(1, "a");
637 /// assert_eq!(map.remove(&1), Some("a"));
638 /// assert_eq!(map.remove(&1), None);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
645 match search::search_tree(self.root.as_mut(), key) {
649 length: &mut self.length,
650 _marker: PhantomData,
658 /// Moves all elements from `other` into `Self`, leaving `other` empty.
663 /// use std::collections::BTreeMap;
665 /// let mut a = BTreeMap::new();
666 /// a.insert(1, "a");
667 /// a.insert(2, "b");
668 /// a.insert(3, "c");
670 /// let mut b = BTreeMap::new();
671 /// b.insert(3, "d");
672 /// b.insert(4, "e");
673 /// b.insert(5, "f");
675 /// a.append(&mut b);
677 /// assert_eq!(a.len(), 5);
678 /// assert_eq!(b.len(), 0);
680 /// assert_eq!(a[&1], "a");
681 /// assert_eq!(a[&2], "b");
682 /// assert_eq!(a[&3], "d");
683 /// assert_eq!(a[&4], "e");
684 /// assert_eq!(a[&5], "f");
686 #[stable(feature = "btree_append", since = "1.11.0")]
687 pub fn append(&mut self, other: &mut Self) {
688 // Do we have to append anything at all?
689 if other.len() == 0 {
693 // We can just swap `self` and `other` if `self` is empty.
695 mem::swap(self, other);
699 // First, we merge `self` and `other` into a sorted sequence in linear time.
700 let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
701 let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
702 let iter = MergeIter {
703 left: self_iter.peekable(),
704 right: other_iter.peekable(),
707 // Second, we build a tree from the sorted sequence in linear time.
708 self.from_sorted_iter(iter);
709 self.fix_right_edge();
712 /// Constructs a double-ended iterator over a sub-range of elements in the map.
713 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
714 /// yield elements from min (inclusive) to max (exclusive).
715 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
716 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
717 /// range from 4 to 10.
721 /// Panics if range `start > end`.
722 /// Panics if range `start == end` and both bounds are `Excluded`.
729 /// use std::collections::BTreeMap;
730 /// use std::collections::Bound::Included;
732 /// let mut map = BTreeMap::new();
733 /// map.insert(3, "a");
734 /// map.insert(5, "b");
735 /// map.insert(8, "c");
736 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
737 /// println!("{}: {}", key, value);
739 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
741 #[stable(feature = "btree_range", since = "1.17.0")]
742 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V>
743 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
745 let root1 = self.root.as_ref();
746 let root2 = self.root.as_ref();
747 let (f, b) = range_search(root1, root2, range);
749 Range { front: f, back: b}
752 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
753 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
754 /// yield elements from min (inclusive) to max (exclusive).
755 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
756 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
757 /// range from 4 to 10.
761 /// Panics if range `start > end`.
762 /// Panics if range `start == end` and both bounds are `Excluded`.
769 /// use std::collections::BTreeMap;
771 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
772 /// .map(|&s| (s, 0))
774 /// for (_, balance) in map.range_mut("B".."Cheryl") {
777 /// for (name, balance) in &map {
778 /// println!("{} => {}", name, balance);
781 #[stable(feature = "btree_range", since = "1.17.0")]
782 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V>
783 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
785 let root1 = self.root.as_mut();
786 let root2 = unsafe { ptr::read(&root1) };
787 let (f, b) = range_search(root1, root2, range);
792 _marker: PhantomData,
796 /// Gets the given key's corresponding entry in the map for in-place manipulation.
803 /// use std::collections::BTreeMap;
805 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
807 /// // count the number of occurrences of letters in the vec
808 /// for x in vec!["a","b","a","c","a","b"] {
809 /// *count.entry(x).or_insert(0) += 1;
812 /// assert_eq!(count["a"], 3);
814 #[stable(feature = "rust1", since = "1.0.0")]
815 pub fn entry(&mut self, key: K) -> Entry<K, V> {
816 match search::search_tree(self.root.as_mut(), &key) {
818 Occupied(OccupiedEntry {
820 length: &mut self.length,
821 _marker: PhantomData,
828 length: &mut self.length,
829 _marker: PhantomData,
835 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
836 let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
837 // Iterate through all key-value pairs, pushing them into nodes at the right level.
838 for (key, value) in iter {
839 // Try to push key-value pair into the current leaf node.
840 if cur_node.len() < node::CAPACITY {
841 cur_node.push(key, value);
843 // No space left, go up and push there.
845 let mut test_node = cur_node.forget_type();
847 match test_node.ascend() {
849 let parent = parent.into_node();
850 if parent.len() < node::CAPACITY {
851 // Found a node with space left, push here.
856 test_node = parent.forget_type();
860 // We are at the top, create a new root node and push there.
861 open_node = node.into_root_mut().push_level();
867 // Push key-value pair and new right subtree.
868 let tree_height = open_node.height() - 1;
869 let mut right_tree = node::Root::new_leaf();
870 for _ in 0..tree_height {
871 right_tree.push_level();
873 open_node.push(key, value, right_tree);
875 // Go down to the right-most leaf again.
876 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
883 fn fix_right_edge(&mut self) {
884 // Handle underfull nodes, start from the top.
885 let mut cur_node = self.root.as_mut();
886 while let Internal(internal) = cur_node.force() {
887 // Check if right-most child is underfull.
888 let mut last_edge = internal.last_edge();
889 let right_child_len = last_edge.reborrow().descend().len();
890 if right_child_len < node::MIN_LEN {
892 let mut last_kv = match last_edge.left_kv() {
894 Err(_) => unreachable!(),
896 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
897 last_edge = last_kv.right_edge();
901 cur_node = last_edge.descend();
905 /// Splits the collection into two at the given key. Returns everything after the given key,
906 /// including the key.
913 /// use std::collections::BTreeMap;
915 /// let mut a = BTreeMap::new();
916 /// a.insert(1, "a");
917 /// a.insert(2, "b");
918 /// a.insert(3, "c");
919 /// a.insert(17, "d");
920 /// a.insert(41, "e");
922 /// let b = a.split_off(&3);
924 /// assert_eq!(a.len(), 2);
925 /// assert_eq!(b.len(), 3);
927 /// assert_eq!(a[&1], "a");
928 /// assert_eq!(a[&2], "b");
930 /// assert_eq!(b[&3], "c");
931 /// assert_eq!(b[&17], "d");
932 /// assert_eq!(b[&41], "e");
934 #[stable(feature = "btree_split_off", since = "1.11.0")]
935 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
942 let total_num = self.len();
944 let mut right = Self::new();
945 for _ in 0..(self.root.as_ref().height()) {
946 right.root.push_level();
950 let mut left_node = self.root.as_mut();
951 let mut right_node = right.root.as_mut();
954 let mut split_edge = match search::search_node(left_node, key) {
955 // key is going to the right tree
956 Found(handle) => handle.left_edge(),
957 GoDown(handle) => handle,
960 split_edge.move_suffix(&mut right_node);
962 match (split_edge.force(), right_node.force()) {
963 (Internal(edge), Internal(node)) => {
964 left_node = edge.descend();
965 right_node = node.first_edge().descend();
967 (Leaf(_), Leaf(_)) => {
977 self.fix_right_border();
978 right.fix_left_border();
980 if self.root.as_ref().height() < right.root.as_ref().height() {
981 self.recalc_length();
982 right.length = total_num - self.len();
984 right.recalc_length();
985 self.length = total_num - right.len();
991 /// Calculates the number of elements if it is incorrect.
992 fn recalc_length(&mut self) {
993 fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize {
994 let mut res = node.len();
996 if let Internal(node) = node.force() {
997 let mut edge = node.first_edge();
999 res += dfs(edge.reborrow().descend());
1000 match edge.right_kv() {
1002 edge = right_kv.right_edge();
1014 self.length = dfs(self.root.as_ref());
1017 /// Removes empty levels on the top.
1018 fn fix_top(&mut self) {
1021 let node = self.root.as_ref();
1022 if node.height() == 0 || node.len() > 0 {
1026 self.root.pop_level();
1030 fn fix_right_border(&mut self) {
1034 let mut cur_node = self.root.as_mut();
1036 while let Internal(node) = cur_node.force() {
1037 let mut last_kv = node.last_kv();
1039 if last_kv.can_merge() {
1040 cur_node = last_kv.merge().descend();
1042 let right_len = last_kv.reborrow().right_edge().descend().len();
1043 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1044 if right_len < node::MIN_LEN + 1 {
1045 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1047 cur_node = last_kv.right_edge().descend();
1055 /// The symmetric clone of `fix_right_border`.
1056 fn fix_left_border(&mut self) {
1060 let mut cur_node = self.root.as_mut();
1062 while let Internal(node) = cur_node.force() {
1063 let mut first_kv = node.first_kv();
1065 if first_kv.can_merge() {
1066 cur_node = first_kv.merge().descend();
1068 let left_len = first_kv.reborrow().left_edge().descend().len();
1069 if left_len < node::MIN_LEN + 1 {
1070 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1072 cur_node = first_kv.left_edge().descend();
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1083 type Item = (&'a K, &'a V);
1084 type IntoIter = Iter<'a, K, V>;
1086 fn into_iter(self) -> Iter<'a, K, V> {
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1093 type Item = (&'a K, &'a V);
1095 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1096 if self.length == 0 {
1100 unsafe { Some(self.range.next_unchecked()) }
1104 fn size_hint(&self) -> (usize, Option<usize>) {
1105 (self.length, Some(self.length))
1109 #[unstable(feature = "fused", issue = "35602")]
1110 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1114 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1115 if self.length == 0 {
1119 unsafe { Some(self.range.next_back_unchecked()) }
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1126 fn len(&self) -> usize {
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<'a, K, V> Clone for Iter<'a, K, V> {
1133 fn clone(&self) -> Iter<'a, K, V> {
1135 range: self.range.clone(),
1136 length: self.length,
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1143 type Item = (&'a K, &'a mut V);
1144 type IntoIter = IterMut<'a, K, V>;
1146 fn into_iter(self) -> IterMut<'a, K, V> {
1151 #[stable(feature = "rust1", since = "1.0.0")]
1152 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1153 type Item = (&'a K, &'a mut V);
1155 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1156 if self.length == 0 {
1160 unsafe { Some(self.range.next_unchecked()) }
1164 fn size_hint(&self) -> (usize, Option<usize>) {
1165 (self.length, Some(self.length))
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1171 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1172 if self.length == 0 {
1176 unsafe { Some(self.range.next_back_unchecked()) }
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1183 fn len(&self) -> usize {
1188 #[unstable(feature = "fused", issue = "35602")]
1189 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<K, V> IntoIterator for BTreeMap<K, V> {
1194 type IntoIter = IntoIter<K, V>;
1196 fn into_iter(self) -> IntoIter<K, V> {
1197 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1198 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1199 let len = self.length;
1203 front: first_leaf_edge(root1),
1204 back: last_leaf_edge(root2),
1210 #[stable(feature = "btree_drop", since = "1.7.0")]
1211 impl<K, V> Drop for IntoIter<K, V> {
1212 fn drop(&mut self) {
1213 for _ in &mut *self {
1216 let leaf_node = ptr::read(&self.front).into_node();
1217 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1218 let mut cur_node = first_parent.into_node();
1219 while let Some(parent) = cur_node.deallocate_and_ascend() {
1220 cur_node = parent.into_node()
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl<K, V> Iterator for IntoIter<K, V> {
1231 fn next(&mut self) -> Option<(K, V)> {
1232 if self.length == 0 {
1238 let handle = unsafe { ptr::read(&self.front) };
1240 let mut cur_handle = match handle.right_kv() {
1242 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1243 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1244 self.front = kv.right_edge();
1245 return Some((k, v));
1247 Err(last_edge) => unsafe {
1248 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1253 match cur_handle.right_kv() {
1255 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1256 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1257 self.front = first_leaf_edge(kv.right_edge().descend());
1258 return Some((k, v));
1260 Err(last_edge) => unsafe {
1261 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1267 fn size_hint(&self) -> (usize, Option<usize>) {
1268 (self.length, Some(self.length))
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1274 fn next_back(&mut self) -> Option<(K, V)> {
1275 if self.length == 0 {
1281 let handle = unsafe { ptr::read(&self.back) };
1283 let mut cur_handle = match handle.left_kv() {
1285 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1286 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1287 self.back = kv.left_edge();
1288 return Some((k, v));
1290 Err(last_edge) => unsafe {
1291 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1296 match cur_handle.left_kv() {
1298 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1299 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1300 self.back = last_leaf_edge(kv.left_edge().descend());
1301 return Some((k, v));
1303 Err(last_edge) => unsafe {
1304 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1313 fn len(&self) -> usize {
1318 #[unstable(feature = "fused", issue = "35602")]
1319 impl<K, V> FusedIterator for IntoIter<K, V> {}
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1325 fn next(&mut self) -> Option<&'a K> {
1326 self.inner.next().map(|(k, _)| k)
1329 fn size_hint(&self) -> (usize, Option<usize>) {
1330 self.inner.size_hint()
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1336 fn next_back(&mut self) -> Option<&'a K> {
1337 self.inner.next_back().map(|(k, _)| k)
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1343 fn len(&self) -> usize {
1348 #[unstable(feature = "fused", issue = "35602")]
1349 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<'a, K, V> Clone for Keys<'a, K, V> {
1353 fn clone(&self) -> Keys<'a, K, V> {
1354 Keys { inner: self.inner.clone() }
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<'a, K, V> Iterator for Values<'a, K, V> {
1362 fn next(&mut self) -> Option<&'a V> {
1363 self.inner.next().map(|(_, v)| v)
1366 fn size_hint(&self) -> (usize, Option<usize>) {
1367 self.inner.size_hint()
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1373 fn next_back(&mut self) -> Option<&'a V> {
1374 self.inner.next_back().map(|(_, v)| v)
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1380 fn len(&self) -> usize {
1385 #[unstable(feature = "fused", issue = "35602")]
1386 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 impl<'a, K, V> Clone for Values<'a, K, V> {
1390 fn clone(&self) -> Values<'a, K, V> {
1391 Values { inner: self.inner.clone() }
1395 impl<'a, K, V> Iterator for Range<'a, K, V> {
1396 type Item = (&'a K, &'a V);
1398 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1399 if self.front == self.back {
1402 unsafe { Some(self.next_unchecked()) }
1407 #[stable(feature = "map_values_mut", since = "1.10.0")]
1408 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1409 type Item = &'a mut V;
1411 fn next(&mut self) -> Option<&'a mut V> {
1412 self.inner.next().map(|(_, v)| v)
1415 fn size_hint(&self) -> (usize, Option<usize>) {
1416 self.inner.size_hint()
1420 #[stable(feature = "map_values_mut", since = "1.10.0")]
1421 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1422 fn next_back(&mut self) -> Option<&'a mut V> {
1423 self.inner.next_back().map(|(_, v)| v)
1427 #[stable(feature = "map_values_mut", since = "1.10.0")]
1428 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1429 fn len(&self) -> usize {
1434 #[unstable(feature = "fused", issue = "35602")]
1435 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1438 impl<'a, K, V> Range<'a, K, V> {
1439 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1440 let handle = self.front;
1442 let mut cur_handle = match handle.right_kv() {
1444 let ret = kv.into_kv();
1445 self.front = kv.right_edge();
1449 let next_level = last_edge.into_node().ascend().ok();
1450 unwrap_unchecked(next_level)
1455 match cur_handle.right_kv() {
1457 let ret = kv.into_kv();
1458 self.front = first_leaf_edge(kv.right_edge().descend());
1462 let next_level = last_edge.into_node().ascend().ok();
1463 cur_handle = unwrap_unchecked(next_level);
1470 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1471 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1472 if self.front == self.back {
1475 unsafe { Some(self.next_back_unchecked()) }
1480 impl<'a, K, V> Range<'a, K, V> {
1481 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1482 let handle = self.back;
1484 let mut cur_handle = match handle.left_kv() {
1486 let ret = kv.into_kv();
1487 self.back = kv.left_edge();
1491 let next_level = last_edge.into_node().ascend().ok();
1492 unwrap_unchecked(next_level)
1497 match cur_handle.left_kv() {
1499 let ret = kv.into_kv();
1500 self.back = last_leaf_edge(kv.left_edge().descend());
1504 let next_level = last_edge.into_node().ascend().ok();
1505 cur_handle = unwrap_unchecked(next_level);
1512 #[unstable(feature = "fused", issue = "35602")]
1513 impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
1515 impl<'a, K, V> Clone for Range<'a, K, V> {
1516 fn clone(&self) -> Range<'a, K, V> {
1524 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1525 type Item = (&'a K, &'a mut V);
1527 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1528 if self.front == self.back {
1531 unsafe { Some(self.next_unchecked()) }
1536 impl<'a, K, V> RangeMut<'a, K, V> {
1537 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1538 let handle = ptr::read(&self.front);
1540 let mut cur_handle = match handle.right_kv() {
1542 let (k, v) = ptr::read(&kv).into_kv_mut();
1543 self.front = kv.right_edge();
1547 let next_level = last_edge.into_node().ascend().ok();
1548 unwrap_unchecked(next_level)
1553 match cur_handle.right_kv() {
1555 let (k, v) = ptr::read(&kv).into_kv_mut();
1556 self.front = first_leaf_edge(kv.right_edge().descend());
1560 let next_level = last_edge.into_node().ascend().ok();
1561 cur_handle = unwrap_unchecked(next_level);
1568 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1569 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1570 if self.front == self.back {
1573 unsafe { Some(self.next_back_unchecked()) }
1578 #[unstable(feature = "fused", issue = "35602")]
1579 impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1581 impl<'a, K, V> RangeMut<'a, K, V> {
1582 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1583 let handle = ptr::read(&self.back);
1585 let mut cur_handle = match handle.left_kv() {
1587 let (k, v) = ptr::read(&kv).into_kv_mut();
1588 self.back = kv.left_edge();
1592 let next_level = last_edge.into_node().ascend().ok();
1593 unwrap_unchecked(next_level)
1598 match cur_handle.left_kv() {
1600 let (k, v) = ptr::read(&kv).into_kv_mut();
1601 self.back = last_leaf_edge(kv.left_edge().descend());
1605 let next_level = last_edge.into_node().ascend().ok();
1606 cur_handle = unwrap_unchecked(next_level);
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1615 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1616 let mut map = BTreeMap::new();
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1625 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1626 for (k, v) in iter {
1632 #[stable(feature = "extend_ref", since = "1.2.0")]
1633 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1634 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1635 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1641 fn hash<H: Hasher>(&self, state: &mut H) {
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 impl<K: Ord, V> Default for BTreeMap<K, V> {
1650 /// Creates an empty `BTreeMap<K, V>`.
1651 fn default() -> BTreeMap<K, V> {
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1658 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1659 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1669 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1670 self.iter().partial_cmp(other.iter())
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1677 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1678 self.iter().cmp(other.iter())
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1685 f.debug_map().entries(self.iter()).finish()
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1697 fn index(&self, key: &Q) -> &V {
1698 self.get(key).expect("no entry found for key")
1702 fn first_leaf_edge<BorrowType, K, V>
1703 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1704 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1706 match node.force() {
1707 Leaf(leaf) => return leaf.first_edge(),
1708 Internal(internal) => {
1709 node = internal.first_edge().descend();
1715 fn last_leaf_edge<BorrowType, K, V>
1716 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1717 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1719 match node.force() {
1720 Leaf(leaf) => return leaf.last_edge(),
1721 Internal(internal) => {
1722 node = internal.last_edge().descend();
1728 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeArgument<Q>>(
1729 root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1730 root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1732 )-> (Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1733 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>)
1734 where Q: Ord, K: Borrow<Q>
1736 match (range.start(), range.end()) {
1737 (Excluded(s), Excluded(e)) if s==e =>
1738 panic!("range start and end are equal and excluded in BTreeMap"),
1739 (Included(s), Included(e)) |
1740 (Included(s), Excluded(e)) |
1741 (Excluded(s), Included(e)) |
1742 (Excluded(s), Excluded(e)) if s>e =>
1743 panic!("range start is greater than range end in BTreeMap"),
1747 let mut min_node = root1;
1748 let mut max_node = root2;
1749 let mut min_found = false;
1750 let mut max_found = false;
1751 let mut diverged = false;
1754 let min_edge = match (min_found, range.start()) {
1755 (false, Included(key)) => match search::search_linear(&min_node, key) {
1756 (i, true) => { min_found = true; i },
1759 (false, Excluded(key)) => match search::search_linear(&min_node, key) {
1760 (i, true) => { min_found = true; i+1 },
1763 (_, Unbounded) => 0,
1764 (true, Included(_)) => min_node.keys().len(),
1765 (true, Excluded(_)) => 0,
1768 let max_edge = match (max_found, range.end()) {
1769 (false, Included(key)) => match search::search_linear(&max_node, key) {
1770 (i, true) => { max_found = true; i+1 },
1773 (false, Excluded(key)) => match search::search_linear(&max_node, key) {
1774 (i, true) => { max_found = true; i },
1777 (_, Unbounded) => max_node.keys().len(),
1778 (true, Included(_)) => 0,
1779 (true, Excluded(_)) => max_node.keys().len(),
1783 if max_edge < min_edge { panic!("Ord is ill-defined in BTreeMap range") }
1784 if min_edge != max_edge { diverged = true; }
1787 let front = Handle::new_edge(min_node, min_edge);
1788 let back = Handle::new_edge(max_node, max_edge);
1789 match (front.force(), back.force()) {
1790 (Leaf(f), Leaf(b)) => {
1793 (Internal(min_int), Internal(max_int)) => {
1794 min_node = min_int.descend();
1795 max_node = max_int.descend();
1797 _ => unreachable!("BTreeMap has different depths"),
1803 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1804 val.unwrap_or_else(|| {
1805 if cfg!(debug_assertions) {
1806 panic!("'unchecked' unwrap on None in BTreeMap");
1808 intrinsics::unreachable();
1813 impl<K, V> BTreeMap<K, V> {
1814 /// Gets an iterator over the entries of the map, sorted by key.
1821 /// use std::collections::BTreeMap;
1823 /// let mut map = BTreeMap::new();
1824 /// map.insert(3, "c");
1825 /// map.insert(2, "b");
1826 /// map.insert(1, "a");
1828 /// for (key, value) in map.iter() {
1829 /// println!("{}: {}", key, value);
1832 /// let (first_key, first_value) = map.iter().next().unwrap();
1833 /// assert_eq!((*first_key, *first_value), (1, "a"));
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 pub fn iter(&self) -> Iter<K, V> {
1839 front: first_leaf_edge(self.root.as_ref()),
1840 back: last_leaf_edge(self.root.as_ref()),
1842 length: self.length,
1846 /// Gets a mutable iterator over the entries of the map, sorted by key.
1853 /// use std::collections::BTreeMap;
1855 /// let mut map = BTreeMap::new();
1856 /// map.insert("a", 1);
1857 /// map.insert("b", 2);
1858 /// map.insert("c", 3);
1860 /// // add 10 to the value if the key isn't "a"
1861 /// for (key, value) in map.iter_mut() {
1862 /// if key != &"a" {
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1869 let root1 = self.root.as_mut();
1870 let root2 = unsafe { ptr::read(&root1) };
1873 front: first_leaf_edge(root1),
1874 back: last_leaf_edge(root2),
1875 _marker: PhantomData,
1877 length: self.length,
1881 /// Gets an iterator over the keys of the map, in sorted order.
1888 /// use std::collections::BTreeMap;
1890 /// let mut a = BTreeMap::new();
1891 /// a.insert(2, "b");
1892 /// a.insert(1, "a");
1894 /// let keys: Vec<_> = a.keys().cloned().collect();
1895 /// assert_eq!(keys, [1, 2]);
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1899 Keys { inner: self.iter() }
1902 /// Gets an iterator over the values of the map, in order by key.
1909 /// use std::collections::BTreeMap;
1911 /// let mut a = BTreeMap::new();
1912 /// a.insert(1, "hello");
1913 /// a.insert(2, "goodbye");
1915 /// let values: Vec<&str> = a.values().cloned().collect();
1916 /// assert_eq!(values, ["hello", "goodbye"]);
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1920 Values { inner: self.iter() }
1923 /// Gets a mutable iterator over the values of the map, in order by key.
1930 /// use std::collections::BTreeMap;
1932 /// let mut a = BTreeMap::new();
1933 /// a.insert(1, String::from("hello"));
1934 /// a.insert(2, String::from("goodbye"));
1936 /// for value in a.values_mut() {
1937 /// value.push_str("!");
1940 /// let values: Vec<String> = a.values().cloned().collect();
1941 /// assert_eq!(values, [String::from("hello!"),
1942 /// String::from("goodbye!")]);
1944 #[stable(feature = "map_values_mut", since = "1.10.0")]
1945 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1946 ValuesMut { inner: self.iter_mut() }
1949 /// Returns the number of elements in the map.
1956 /// use std::collections::BTreeMap;
1958 /// let mut a = BTreeMap::new();
1959 /// assert_eq!(a.len(), 0);
1960 /// a.insert(1, "a");
1961 /// assert_eq!(a.len(), 1);
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 pub fn len(&self) -> usize {
1968 /// Returns `true` if the map contains no elements.
1975 /// use std::collections::BTreeMap;
1977 /// let mut a = BTreeMap::new();
1978 /// assert!(a.is_empty());
1979 /// a.insert(1, "a");
1980 /// assert!(!a.is_empty());
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 pub fn is_empty(&self) -> bool {
1988 impl<'a, K: Ord, V> Entry<'a, K, V> {
1989 /// Ensures a value is in the entry by inserting the default if empty, and returns
1990 /// a mutable reference to the value in the entry.
1995 /// use std::collections::BTreeMap;
1997 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1998 /// map.entry("poneyland").or_insert(12);
2000 /// assert_eq!(map["poneyland"], 12);
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 pub fn or_insert(self, default: V) -> &'a mut V {
2005 Occupied(entry) => entry.into_mut(),
2006 Vacant(entry) => entry.insert(default),
2010 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2011 /// and returns a mutable reference to the value in the entry.
2016 /// use std::collections::BTreeMap;
2018 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2019 /// let s = "hoho".to_string();
2021 /// map.entry("poneyland").or_insert_with(|| s);
2023 /// assert_eq!(map["poneyland"], "hoho".to_string());
2025 #[stable(feature = "rust1", since = "1.0.0")]
2026 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2028 Occupied(entry) => entry.into_mut(),
2029 Vacant(entry) => entry.insert(default()),
2033 /// Returns a reference to this entry's key.
2038 /// use std::collections::BTreeMap;
2040 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2041 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2043 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2044 pub fn key(&self) -> &K {
2046 Occupied(ref entry) => entry.key(),
2047 Vacant(ref entry) => entry.key(),
2052 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2053 /// Gets a reference to the key that would be used when inserting a value
2054 /// through the VacantEntry.
2059 /// use std::collections::BTreeMap;
2061 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2062 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2064 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2065 pub fn key(&self) -> &K {
2069 /// Take ownership of the key.
2074 /// use std::collections::BTreeMap;
2075 /// use std::collections::btree_map::Entry;
2077 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2079 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2083 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2084 pub fn into_key(self) -> K {
2088 /// Sets the value of the entry with the `VacantEntry`'s key,
2089 /// and returns a mutable reference to it.
2094 /// use std::collections::BTreeMap;
2096 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2098 /// // count the number of occurrences of letters in the vec
2099 /// for x in vec!["a","b","a","c","a","b"] {
2100 /// *count.entry(x).or_insert(0) += 1;
2103 /// assert_eq!(count["a"], 3);
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 pub fn insert(self, value: V) -> &'a mut V {
2115 let mut cur_parent = match self.handle.insert(self.key, value) {
2116 (Fit(handle), _) => return handle.into_kv_mut().1,
2117 (Split(left, k, v, right), ptr) => {
2122 left.ascend().map_err(|n| n.into_root_mut())
2129 match parent.insert(ins_k, ins_v, ins_edge) {
2130 Fit(_) => return unsafe { &mut *out_ptr },
2131 Split(left, k, v, right) => {
2135 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2140 root.push_level().push(ins_k, ins_v, ins_edge);
2141 return unsafe { &mut *out_ptr };
2148 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2149 /// Gets a reference to the key in the entry.
2154 /// use std::collections::BTreeMap;
2156 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2157 /// map.entry("poneyland").or_insert(12);
2158 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2160 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2161 pub fn key(&self) -> &K {
2162 self.handle.reborrow().into_kv().0
2165 /// Deprecated, renamed to `remove_entry`
2166 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2167 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2168 pub fn remove_pair(self) -> (K, V) {
2172 /// Take ownership of the key and value from the map.
2177 /// use std::collections::BTreeMap;
2178 /// use std::collections::btree_map::Entry;
2180 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2181 /// map.entry("poneyland").or_insert(12);
2183 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2184 /// // We delete the entry from the map.
2185 /// o.remove_entry();
2188 /// // If now try to get the value, it will panic:
2189 /// // println!("{}", map["poneyland"]);
2191 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2192 pub fn remove_entry(self) -> (K, V) {
2196 /// Gets a reference to the value in the entry.
2201 /// use std::collections::BTreeMap;
2202 /// use std::collections::btree_map::Entry;
2204 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2205 /// map.entry("poneyland").or_insert(12);
2207 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2208 /// assert_eq!(o.get(), &12);
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 pub fn get(&self) -> &V {
2213 self.handle.reborrow().into_kv().1
2216 /// Gets a mutable reference to the value in the entry.
2221 /// use std::collections::BTreeMap;
2222 /// use std::collections::btree_map::Entry;
2224 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2225 /// map.entry("poneyland").or_insert(12);
2227 /// assert_eq!(map["poneyland"], 12);
2228 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2229 /// *o.get_mut() += 10;
2231 /// assert_eq!(map["poneyland"], 22);
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 pub fn get_mut(&mut self) -> &mut V {
2235 self.handle.kv_mut().1
2238 /// Converts the entry into a mutable reference to its value.
2243 /// use std::collections::BTreeMap;
2244 /// use std::collections::btree_map::Entry;
2246 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2247 /// map.entry("poneyland").or_insert(12);
2249 /// assert_eq!(map["poneyland"], 12);
2250 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2251 /// *o.into_mut() += 10;
2253 /// assert_eq!(map["poneyland"], 22);
2255 #[stable(feature = "rust1", since = "1.0.0")]
2256 pub fn into_mut(self) -> &'a mut V {
2257 self.handle.into_kv_mut().1
2260 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2261 /// and returns the entry's old value.
2266 /// use std::collections::BTreeMap;
2267 /// use std::collections::btree_map::Entry;
2269 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2270 /// map.entry("poneyland").or_insert(12);
2272 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2273 /// assert_eq!(o.insert(15), 12);
2275 /// assert_eq!(map["poneyland"], 15);
2277 #[stable(feature = "rust1", since = "1.0.0")]
2278 pub fn insert(&mut self, value: V) -> V {
2279 mem::replace(self.get_mut(), value)
2282 /// Takes the value of the entry out of the map, and returns it.
2287 /// use std::collections::BTreeMap;
2288 /// use std::collections::btree_map::Entry;
2290 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2291 /// map.entry("poneyland").or_insert(12);
2293 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2294 /// assert_eq!(o.remove(), 12);
2296 /// // If we try to get "poneyland"'s value, it'll panic:
2297 /// // println!("{}", map["poneyland"]);
2299 #[stable(feature = "rust1", since = "1.0.0")]
2300 pub fn remove(self) -> V {
2304 fn remove_kv(self) -> (K, V) {
2307 let (small_leaf, old_key, old_val) = match self.handle.force() {
2309 let (hole, old_key, old_val) = leaf.remove();
2310 (hole.into_node(), old_key, old_val)
2312 Internal(mut internal) => {
2313 let key_loc = internal.kv_mut().0 as *mut K;
2314 let val_loc = internal.kv_mut().1 as *mut V;
2316 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2317 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2319 let (hole, key, val) = to_remove.remove();
2321 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2322 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2324 (hole.into_node(), old_key, old_val)
2329 let mut cur_node = small_leaf.forget_type();
2330 while cur_node.len() < node::CAPACITY / 2 {
2331 match handle_underfull_node(cur_node) {
2333 EmptyParent(_) => unreachable!(),
2335 if parent.len() == 0 {
2336 // We must be at the root
2337 parent.into_root_mut().pop_level();
2340 cur_node = parent.forget_type();
2351 enum UnderflowResult<'a, K, V> {
2353 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2354 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2355 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2358 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>)
2359 -> UnderflowResult<'a, K, V> {
2360 let parent = if let Ok(parent) = node.ascend() {
2366 let (is_left, mut handle) = match parent.left_kv() {
2367 Ok(left) => (true, left),
2369 match parent.right_kv() {
2370 Ok(right) => (false, right),
2372 return EmptyParent(parent.into_node());
2378 if handle.can_merge() {
2379 Merged(handle.merge().into_node())
2382 handle.steal_left();
2384 handle.steal_right();
2386 Stole(handle.into_node())
2390 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2393 fn next(&mut self) -> Option<(K, V)> {
2394 let res = match (self.left.peek(), self.right.peek()) {
2395 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2396 (Some(_), None) => Ordering::Less,
2397 (None, Some(_)) => Ordering::Greater,
2398 (None, None) => return None,
2401 // Check which elements comes first and only advance the corresponding iterator.
2402 // If two keys are equal, take the value from `right`.
2404 Ordering::Less => self.left.next(),
2405 Ordering::Greater => self.right.next(),
2406 Ordering::Equal => {