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 drop(ptr::read(self).into_iter());
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
151 fn clone(&self) -> BTreeMap<K, V> {
152 fn clone_subtree<K: Clone, V: Clone>(node: node::NodeRef<marker::Immut,
155 marker::LeafOrInternal>)
160 let mut out_tree = BTreeMap {
161 root: node::Root::new_leaf(),
166 let mut out_node = match out_tree.root.as_mut().force() {
168 Internal(_) => unreachable!(),
171 let mut in_edge = leaf.first_edge();
172 while let Ok(kv) = in_edge.right_kv() {
173 let (k, v) = kv.into_kv();
174 in_edge = kv.right_edge();
176 out_node.push(k.clone(), v.clone());
177 out_tree.length += 1;
183 Internal(internal) => {
184 let mut out_tree = clone_subtree(internal.first_edge().descend());
187 let mut out_node = out_tree.root.push_level();
188 let mut in_edge = internal.first_edge();
189 while let Ok(kv) = in_edge.right_kv() {
190 let (k, v) = kv.into_kv();
191 in_edge = kv.right_edge();
193 let k = (*k).clone();
194 let v = (*v).clone();
195 let subtree = clone_subtree(in_edge.descend());
197 // We can't destructure subtree directly
198 // because BTreeMap implements Drop
199 let (subroot, sublength) = unsafe {
200 let root = ptr::read(&subtree.root);
201 let length = subtree.length;
202 mem::forget(subtree);
206 out_node.push(k, v, subroot);
207 out_tree.length += 1 + sublength;
216 clone_subtree(self.root.as_ref())
220 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
221 where K: Borrow<Q> + Ord,
226 fn get(&self, key: &Q) -> Option<&K> {
227 match search::search_tree(self.root.as_ref(), key) {
228 Found(handle) => Some(handle.into_kv().0),
233 fn take(&mut self, key: &Q) -> Option<K> {
234 match search::search_tree(self.root.as_mut(), key) {
238 length: &mut self.length,
239 _marker: PhantomData,
248 fn replace(&mut self, key: K) -> Option<K> {
249 match search::search_tree::<marker::Mut, K, (), K>(self.root.as_mut(), &key) {
250 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
255 length: &mut self.length,
256 _marker: PhantomData,
265 /// An iterator over a BTreeMap's entries.
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub struct Iter<'a, K: 'a, V: 'a> {
268 range: Range<'a, K, V>,
272 #[stable(feature = "collection_debug", since = "1.17.0")]
273 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Iter<'a, K, V> {
274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
275 f.debug_list().entries(self.clone()).finish()
279 /// A mutable iterator over a BTreeMap's entries.
280 #[stable(feature = "rust1", since = "1.0.0")]
282 pub struct IterMut<'a, K: 'a, V: 'a> {
283 range: RangeMut<'a, K, V>,
287 /// An owning iterator over a BTreeMap's entries.
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub struct IntoIter<K, V> {
290 front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
291 back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
295 #[stable(feature = "collection_debug", since = "1.17.0")]
296 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
299 front: self.front.reborrow(),
300 back: self.back.reborrow(),
302 f.debug_list().entries(range).finish()
306 /// An iterator over a BTreeMap's keys.
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub struct Keys<'a, K: 'a, V: 'a> {
309 inner: Iter<'a, K, V>,
312 #[stable(feature = "collection_debug", since = "1.17.0")]
313 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Keys<'a, K, V> {
314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315 f.debug_list().entries(self.inner.clone()).finish()
319 /// An iterator over a BTreeMap's values.
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub struct Values<'a, K: 'a, V: 'a> {
322 inner: Iter<'a, K, V>,
325 #[stable(feature = "collection_debug", since = "1.17.0")]
326 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Values<'a, K, V> {
327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
328 f.debug_list().entries(self.inner.clone()).finish()
332 /// A mutable iterator over a BTreeMap's values.
333 #[stable(feature = "map_values_mut", since = "1.10.0")]
335 pub struct ValuesMut<'a, K: 'a, V: 'a> {
336 inner: IterMut<'a, K, V>,
339 /// An iterator over a sub-range of BTreeMap's entries.
340 #[stable(feature = "btree_range", since = "1.17.0")]
341 pub struct Range<'a, K: 'a, V: 'a> {
342 front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
343 back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
346 #[stable(feature = "collection_debug", since = "1.17.0")]
347 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Range<'a, K, V> {
348 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
349 f.debug_list().entries(self.clone()).finish()
353 /// A mutable iterator over a sub-range of BTreeMap's entries.
354 #[stable(feature = "btree_range", since = "1.17.0")]
355 pub struct RangeMut<'a, K: 'a, V: 'a> {
356 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
357 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
359 // Be invariant in `K` and `V`
360 _marker: PhantomData<&'a mut (K, V)>,
363 #[stable(feature = "collection_debug", since = "1.17.0")]
364 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for RangeMut<'a, K, V> {
365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
367 front: self.front.reborrow(),
368 back: self.back.reborrow(),
370 f.debug_list().entries(range).finish()
374 /// A view into a single entry in a map, which may either be vacant or occupied.
375 /// This enum is constructed from the [`entry`] method on [`BTreeMap`].
377 /// [`BTreeMap`]: struct.BTreeMap.html
378 /// [`entry`]: struct.BTreeMap.html#method.entry
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub enum Entry<'a, K: 'a, V: 'a> {
382 #[stable(feature = "rust1", since = "1.0.0")]
383 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
384 VacantEntry<'a, K, V>),
386 /// An occupied Entry
387 #[stable(feature = "rust1", since = "1.0.0")]
388 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
389 OccupiedEntry<'a, K, V>),
392 #[stable(feature= "debug_btree_map", since = "1.12.0")]
393 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for Entry<'a, K, V> {
394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
396 Vacant(ref v) => f.debug_tuple("Entry")
399 Occupied(ref o) => f.debug_tuple("Entry")
406 /// A vacant Entry. It is part of the [`Entry`] enum.
408 /// [`Entry`]: enum.Entry.html
409 #[stable(feature = "rust1", since = "1.0.0")]
410 pub struct VacantEntry<'a, K: 'a, V: 'a> {
412 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
413 length: &'a mut usize,
415 // Be invariant in `K` and `V`
416 _marker: PhantomData<&'a mut (K, V)>,
419 #[stable(feature= "debug_btree_map", since = "1.12.0")]
420 impl<'a, K: 'a + Debug + Ord, V: 'a> Debug for VacantEntry<'a, K, V> {
421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
422 f.debug_tuple("VacantEntry")
428 /// An occupied Entry. It is part of the [`Entry`] enum.
430 /// [`Entry`]: enum.Entry.html
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
433 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
435 length: &'a mut usize,
437 // Be invariant in `K` and `V`
438 _marker: PhantomData<&'a mut (K, V)>,
441 #[stable(feature= "debug_btree_map", since = "1.12.0")]
442 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
443 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
444 f.debug_struct("OccupiedEntry")
445 .field("key", self.key())
446 .field("value", self.get())
451 // An iterator for merging two sorted sequences into one
452 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
457 impl<K: Ord, V> BTreeMap<K, V> {
458 /// Makes a new empty BTreeMap with a reasonable choice for B.
465 /// use std::collections::BTreeMap;
467 /// let mut map = BTreeMap::new();
469 /// // entries can now be inserted into the empty map
470 /// map.insert(1, "a");
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn new() -> BTreeMap<K, V> {
475 root: node::Root::new_leaf(),
480 /// Clears the map, removing all values.
487 /// use std::collections::BTreeMap;
489 /// let mut a = BTreeMap::new();
490 /// a.insert(1, "a");
492 /// assert!(a.is_empty());
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn clear(&mut self) {
496 // FIXME(gereeter) .clear() allocates
497 *self = BTreeMap::new();
500 /// Returns a 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 /// assert_eq!(map.get(&1), Some(&"a"));
515 /// assert_eq!(map.get(&2), None);
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
522 match search::search_tree(self.root.as_ref(), key) {
523 Found(handle) => Some(handle.into_kv().1),
528 /// Returns `true` if the map contains a value for the specified key.
530 /// The key may be any borrowed form of the map's key type, but the ordering
531 /// on the borrowed form *must* match the ordering on the key type.
538 /// use std::collections::BTreeMap;
540 /// let mut map = BTreeMap::new();
541 /// map.insert(1, "a");
542 /// assert_eq!(map.contains_key(&1), true);
543 /// assert_eq!(map.contains_key(&2), false);
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
550 self.get(key).is_some()
553 /// Returns a mutable reference to the value corresponding to the key.
555 /// The key may be any borrowed form of the map's key type, but the ordering
556 /// on the borrowed form *must* match the ordering on the key type.
563 /// use std::collections::BTreeMap;
565 /// let mut map = BTreeMap::new();
566 /// map.insert(1, "a");
567 /// if let Some(x) = map.get_mut(&1) {
570 /// assert_eq!(map[&1], "b");
572 // See `get` for implementation notes, this is basically a copy-paste with mut's added
573 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
578 match search::search_tree(self.root.as_mut(), key) {
579 Found(handle) => Some(handle.into_kv_mut().1),
584 /// Inserts a key-value pair into the map.
586 /// If the map did not have this key present, `None` is returned.
588 /// If the map did have this key present, the value is updated, and the old
589 /// value is returned. The key is not updated, though; this matters for
590 /// types that can be `==` without being identical. See the [module-level
591 /// documentation] for more.
593 /// [module-level documentation]: index.html#insert-and-complex-keys
600 /// use std::collections::BTreeMap;
602 /// let mut map = BTreeMap::new();
603 /// assert_eq!(map.insert(37, "a"), None);
604 /// assert_eq!(map.is_empty(), false);
606 /// map.insert(37, "b");
607 /// assert_eq!(map.insert(37, "c"), Some("b"));
608 /// assert_eq!(map[&37], "c");
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
612 match self.entry(key) {
613 Occupied(mut entry) => Some(entry.insert(value)),
621 /// Removes a key from the map, returning the value at the key if the key
622 /// was previously in the map.
624 /// The key may be any borrowed form of the map's key type, but the ordering
625 /// on the borrowed form *must* match the ordering on the key type.
632 /// use std::collections::BTreeMap;
634 /// let mut map = BTreeMap::new();
635 /// map.insert(1, "a");
636 /// assert_eq!(map.remove(&1), Some("a"));
637 /// assert_eq!(map.remove(&1), None);
639 #[stable(feature = "rust1", since = "1.0.0")]
640 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
644 match search::search_tree(self.root.as_mut(), key) {
648 length: &mut self.length,
649 _marker: PhantomData,
657 /// Moves all elements from `other` into `Self`, leaving `other` empty.
662 /// use std::collections::BTreeMap;
664 /// let mut a = BTreeMap::new();
665 /// a.insert(1, "a");
666 /// a.insert(2, "b");
667 /// a.insert(3, "c");
669 /// let mut b = BTreeMap::new();
670 /// b.insert(3, "d");
671 /// b.insert(4, "e");
672 /// b.insert(5, "f");
674 /// a.append(&mut b);
676 /// assert_eq!(a.len(), 5);
677 /// assert_eq!(b.len(), 0);
679 /// assert_eq!(a[&1], "a");
680 /// assert_eq!(a[&2], "b");
681 /// assert_eq!(a[&3], "d");
682 /// assert_eq!(a[&4], "e");
683 /// assert_eq!(a[&5], "f");
685 #[stable(feature = "btree_append", since = "1.11.0")]
686 pub fn append(&mut self, other: &mut Self) {
687 // Do we have to append anything at all?
688 if other.len() == 0 {
692 // We can just swap `self` and `other` if `self` is empty.
694 mem::swap(self, other);
698 // First, we merge `self` and `other` into a sorted sequence in linear time.
699 let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
700 let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
701 let iter = MergeIter {
702 left: self_iter.peekable(),
703 right: other_iter.peekable(),
706 // Second, we build a tree from the sorted sequence in linear time.
707 self.from_sorted_iter(iter);
708 self.fix_right_edge();
711 /// Constructs a double-ended iterator over a sub-range of elements in the map.
712 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
713 /// yield elements from min (inclusive) to max (exclusive).
714 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
715 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
716 /// range from 4 to 10.
720 /// Panics if range `start > end`.
721 /// Panics if range `start == end` and both bounds are `Excluded`.
728 /// use std::collections::BTreeMap;
729 /// use std::collections::Bound::Included;
731 /// let mut map = BTreeMap::new();
732 /// map.insert(3, "a");
733 /// map.insert(5, "b");
734 /// map.insert(8, "c");
735 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
736 /// println!("{}: {}", key, value);
738 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
740 #[stable(feature = "btree_range", since = "1.17.0")]
741 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V>
742 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
744 let root1 = self.root.as_ref();
745 let root2 = self.root.as_ref();
746 let (f, b) = range_search(root1, root2, range);
748 Range { front: f, back: b}
751 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
752 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
753 /// yield elements from min (inclusive) to max (exclusive).
754 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
755 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
756 /// range from 4 to 10.
760 /// Panics if range `start > end`.
761 /// Panics if range `start == end` and both bounds are `Excluded`.
768 /// use std::collections::BTreeMap;
770 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
771 /// .map(|&s| (s, 0))
773 /// for (_, balance) in map.range_mut("B".."Cheryl") {
776 /// for (name, balance) in &map {
777 /// println!("{} => {}", name, balance);
780 #[stable(feature = "btree_range", since = "1.17.0")]
781 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V>
782 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
784 let root1 = self.root.as_mut();
785 let root2 = unsafe { ptr::read(&root1) };
786 let (f, b) = range_search(root1, root2, range);
791 _marker: PhantomData,
795 /// Gets the given key's corresponding entry in the map for in-place manipulation.
802 /// use std::collections::BTreeMap;
804 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
806 /// // count the number of occurrences of letters in the vec
807 /// for x in vec!["a","b","a","c","a","b"] {
808 /// *count.entry(x).or_insert(0) += 1;
811 /// assert_eq!(count["a"], 3);
813 #[stable(feature = "rust1", since = "1.0.0")]
814 pub fn entry(&mut self, key: K) -> Entry<K, V> {
815 match search::search_tree(self.root.as_mut(), &key) {
817 Occupied(OccupiedEntry {
819 length: &mut self.length,
820 _marker: PhantomData,
827 length: &mut self.length,
828 _marker: PhantomData,
834 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
835 let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
836 // Iterate through all key-value pairs, pushing them into nodes at the right level.
837 for (key, value) in iter {
838 // Try to push key-value pair into the current leaf node.
839 if cur_node.len() < node::CAPACITY {
840 cur_node.push(key, value);
842 // No space left, go up and push there.
844 let mut test_node = cur_node.forget_type();
846 match test_node.ascend() {
848 let parent = parent.into_node();
849 if parent.len() < node::CAPACITY {
850 // Found a node with space left, push here.
855 test_node = parent.forget_type();
859 // We are at the top, create a new root node and push there.
860 open_node = node.into_root_mut().push_level();
866 // Push key-value pair and new right subtree.
867 let tree_height = open_node.height() - 1;
868 let mut right_tree = node::Root::new_leaf();
869 for _ in 0..tree_height {
870 right_tree.push_level();
872 open_node.push(key, value, right_tree);
874 // Go down to the right-most leaf again.
875 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
882 fn fix_right_edge(&mut self) {
883 // Handle underfull nodes, start from the top.
884 let mut cur_node = self.root.as_mut();
885 while let Internal(internal) = cur_node.force() {
886 // Check if right-most child is underfull.
887 let mut last_edge = internal.last_edge();
888 let right_child_len = last_edge.reborrow().descend().len();
889 if right_child_len < node::MIN_LEN {
891 let mut last_kv = match last_edge.left_kv() {
893 Err(_) => unreachable!(),
895 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
896 last_edge = last_kv.right_edge();
900 cur_node = last_edge.descend();
904 /// Splits the collection into two at the given key. Returns everything after the given key,
905 /// including the key.
912 /// use std::collections::BTreeMap;
914 /// let mut a = BTreeMap::new();
915 /// a.insert(1, "a");
916 /// a.insert(2, "b");
917 /// a.insert(3, "c");
918 /// a.insert(17, "d");
919 /// a.insert(41, "e");
921 /// let b = a.split_off(&3);
923 /// assert_eq!(a.len(), 2);
924 /// assert_eq!(b.len(), 3);
926 /// assert_eq!(a[&1], "a");
927 /// assert_eq!(a[&2], "b");
929 /// assert_eq!(b[&3], "c");
930 /// assert_eq!(b[&17], "d");
931 /// assert_eq!(b[&41], "e");
933 #[stable(feature = "btree_split_off", since = "1.11.0")]
934 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
941 let total_num = self.len();
943 let mut right = Self::new();
944 for _ in 0..(self.root.as_ref().height()) {
945 right.root.push_level();
949 let mut left_node = self.root.as_mut();
950 let mut right_node = right.root.as_mut();
953 let mut split_edge = match search::search_node(left_node, key) {
954 // key is going to the right tree
955 Found(handle) => handle.left_edge(),
956 GoDown(handle) => handle,
959 split_edge.move_suffix(&mut right_node);
961 match (split_edge.force(), right_node.force()) {
962 (Internal(edge), Internal(node)) => {
963 left_node = edge.descend();
964 right_node = node.first_edge().descend();
966 (Leaf(_), Leaf(_)) => {
976 self.fix_right_border();
977 right.fix_left_border();
979 if self.root.as_ref().height() < right.root.as_ref().height() {
980 self.recalc_length();
981 right.length = total_num - self.len();
983 right.recalc_length();
984 self.length = total_num - right.len();
990 /// Calculates the number of elements if it is incorrect.
991 fn recalc_length(&mut self) {
992 fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize {
993 let mut res = node.len();
995 if let Internal(node) = node.force() {
996 let mut edge = node.first_edge();
998 res += dfs(edge.reborrow().descend());
999 match edge.right_kv() {
1001 edge = right_kv.right_edge();
1013 self.length = dfs(self.root.as_ref());
1016 /// Removes empty levels on the top.
1017 fn fix_top(&mut self) {
1020 let node = self.root.as_ref();
1021 if node.height() == 0 || node.len() > 0 {
1025 self.root.pop_level();
1029 fn fix_right_border(&mut self) {
1033 let mut cur_node = self.root.as_mut();
1035 while let Internal(node) = cur_node.force() {
1036 let mut last_kv = node.last_kv();
1038 if last_kv.can_merge() {
1039 cur_node = last_kv.merge().descend();
1041 let right_len = last_kv.reborrow().right_edge().descend().len();
1042 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1043 if right_len < node::MIN_LEN + 1 {
1044 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1046 cur_node = last_kv.right_edge().descend();
1054 /// The symmetric clone of `fix_right_border`.
1055 fn fix_left_border(&mut self) {
1059 let mut cur_node = self.root.as_mut();
1061 while let Internal(node) = cur_node.force() {
1062 let mut first_kv = node.first_kv();
1064 if first_kv.can_merge() {
1065 cur_node = first_kv.merge().descend();
1067 let left_len = first_kv.reborrow().left_edge().descend().len();
1068 if left_len < node::MIN_LEN + 1 {
1069 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1071 cur_node = first_kv.left_edge().descend();
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1082 type Item = (&'a K, &'a V);
1083 type IntoIter = Iter<'a, K, V>;
1085 fn into_iter(self) -> Iter<'a, K, V> {
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1092 type Item = (&'a K, &'a V);
1094 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1095 if self.length == 0 {
1099 unsafe { Some(self.range.next_unchecked()) }
1103 fn size_hint(&self) -> (usize, Option<usize>) {
1104 (self.length, Some(self.length))
1108 #[unstable(feature = "fused", issue = "35602")]
1109 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1113 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1114 if self.length == 0 {
1118 unsafe { Some(self.range.next_back_unchecked()) }
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1125 fn len(&self) -> usize {
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 impl<'a, K, V> Clone for Iter<'a, K, V> {
1132 fn clone(&self) -> Iter<'a, K, V> {
1134 range: self.range.clone(),
1135 length: self.length,
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1142 type Item = (&'a K, &'a mut V);
1143 type IntoIter = IterMut<'a, K, V>;
1145 fn into_iter(self) -> IterMut<'a, K, V> {
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1152 type Item = (&'a K, &'a mut V);
1154 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1155 if self.length == 0 {
1159 unsafe { Some(self.range.next_unchecked()) }
1163 fn size_hint(&self) -> (usize, Option<usize>) {
1164 (self.length, Some(self.length))
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1170 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1171 if self.length == 0 {
1175 unsafe { Some(self.range.next_back_unchecked()) }
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1182 fn len(&self) -> usize {
1187 #[unstable(feature = "fused", issue = "35602")]
1188 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<K, V> IntoIterator for BTreeMap<K, V> {
1193 type IntoIter = IntoIter<K, V>;
1195 fn into_iter(self) -> IntoIter<K, V> {
1196 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1197 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1198 let len = self.length;
1202 front: first_leaf_edge(root1),
1203 back: last_leaf_edge(root2),
1209 #[stable(feature = "btree_drop", since = "1.7.0")]
1210 impl<K, V> Drop for IntoIter<K, V> {
1211 fn drop(&mut self) {
1212 for _ in &mut *self {
1215 let leaf_node = ptr::read(&self.front).into_node();
1216 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1217 let mut cur_node = first_parent.into_node();
1218 while let Some(parent) = cur_node.deallocate_and_ascend() {
1219 cur_node = parent.into_node()
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<K, V> Iterator for IntoIter<K, V> {
1230 fn next(&mut self) -> Option<(K, V)> {
1231 if self.length == 0 {
1237 let handle = unsafe { ptr::read(&self.front) };
1239 let mut cur_handle = match handle.right_kv() {
1241 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1242 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1243 self.front = kv.right_edge();
1244 return Some((k, v));
1246 Err(last_edge) => unsafe {
1247 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1252 match cur_handle.right_kv() {
1254 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1255 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1256 self.front = first_leaf_edge(kv.right_edge().descend());
1257 return Some((k, v));
1259 Err(last_edge) => unsafe {
1260 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1266 fn size_hint(&self) -> (usize, Option<usize>) {
1267 (self.length, Some(self.length))
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1273 fn next_back(&mut self) -> Option<(K, V)> {
1274 if self.length == 0 {
1280 let handle = unsafe { ptr::read(&self.back) };
1282 let mut cur_handle = match handle.left_kv() {
1284 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1285 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1286 self.back = kv.left_edge();
1287 return Some((k, v));
1289 Err(last_edge) => unsafe {
1290 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1295 match cur_handle.left_kv() {
1297 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1298 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1299 self.back = last_leaf_edge(kv.left_edge().descend());
1300 return Some((k, v));
1302 Err(last_edge) => unsafe {
1303 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1310 #[stable(feature = "rust1", since = "1.0.0")]
1311 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1312 fn len(&self) -> usize {
1317 #[unstable(feature = "fused", issue = "35602")]
1318 impl<K, V> FusedIterator for IntoIter<K, V> {}
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1324 fn next(&mut self) -> Option<&'a K> {
1325 self.inner.next().map(|(k, _)| k)
1328 fn size_hint(&self) -> (usize, Option<usize>) {
1329 self.inner.size_hint()
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1335 fn next_back(&mut self) -> Option<&'a K> {
1336 self.inner.next_back().map(|(k, _)| k)
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1342 fn len(&self) -> usize {
1347 #[unstable(feature = "fused", issue = "35602")]
1348 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<'a, K, V> Clone for Keys<'a, K, V> {
1352 fn clone(&self) -> Keys<'a, K, V> {
1353 Keys { inner: self.inner.clone() }
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 impl<'a, K, V> Iterator for Values<'a, K, V> {
1361 fn next(&mut self) -> Option<&'a V> {
1362 self.inner.next().map(|(_, v)| v)
1365 fn size_hint(&self) -> (usize, Option<usize>) {
1366 self.inner.size_hint()
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1372 fn next_back(&mut self) -> Option<&'a V> {
1373 self.inner.next_back().map(|(_, v)| v)
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1379 fn len(&self) -> usize {
1384 #[unstable(feature = "fused", issue = "35602")]
1385 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 impl<'a, K, V> Clone for Values<'a, K, V> {
1389 fn clone(&self) -> Values<'a, K, V> {
1390 Values { inner: self.inner.clone() }
1394 impl<'a, K, V> Iterator for Range<'a, K, V> {
1395 type Item = (&'a K, &'a V);
1397 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1398 if self.front == self.back {
1401 unsafe { Some(self.next_unchecked()) }
1406 #[stable(feature = "map_values_mut", since = "1.10.0")]
1407 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1408 type Item = &'a mut V;
1410 fn next(&mut self) -> Option<&'a mut V> {
1411 self.inner.next().map(|(_, v)| v)
1414 fn size_hint(&self) -> (usize, Option<usize>) {
1415 self.inner.size_hint()
1419 #[stable(feature = "map_values_mut", since = "1.10.0")]
1420 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1421 fn next_back(&mut self) -> Option<&'a mut V> {
1422 self.inner.next_back().map(|(_, v)| v)
1426 #[stable(feature = "map_values_mut", since = "1.10.0")]
1427 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1428 fn len(&self) -> usize {
1433 #[unstable(feature = "fused", issue = "35602")]
1434 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1437 impl<'a, K, V> Range<'a, K, V> {
1438 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1439 let handle = self.front;
1441 let mut cur_handle = match handle.right_kv() {
1443 let ret = kv.into_kv();
1444 self.front = kv.right_edge();
1448 let next_level = last_edge.into_node().ascend().ok();
1449 unwrap_unchecked(next_level)
1454 match cur_handle.right_kv() {
1456 let ret = kv.into_kv();
1457 self.front = first_leaf_edge(kv.right_edge().descend());
1461 let next_level = last_edge.into_node().ascend().ok();
1462 cur_handle = unwrap_unchecked(next_level);
1469 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1470 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1471 if self.front == self.back {
1474 unsafe { Some(self.next_back_unchecked()) }
1479 impl<'a, K, V> Range<'a, K, V> {
1480 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1481 let handle = self.back;
1483 let mut cur_handle = match handle.left_kv() {
1485 let ret = kv.into_kv();
1486 self.back = kv.left_edge();
1490 let next_level = last_edge.into_node().ascend().ok();
1491 unwrap_unchecked(next_level)
1496 match cur_handle.left_kv() {
1498 let ret = kv.into_kv();
1499 self.back = last_leaf_edge(kv.left_edge().descend());
1503 let next_level = last_edge.into_node().ascend().ok();
1504 cur_handle = unwrap_unchecked(next_level);
1511 #[unstable(feature = "fused", issue = "35602")]
1512 impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
1514 impl<'a, K, V> Clone for Range<'a, K, V> {
1515 fn clone(&self) -> Range<'a, K, V> {
1523 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1524 type Item = (&'a K, &'a mut V);
1526 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1527 if self.front == self.back {
1530 unsafe { Some(self.next_unchecked()) }
1535 impl<'a, K, V> RangeMut<'a, K, V> {
1536 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1537 let handle = ptr::read(&self.front);
1539 let mut cur_handle = match handle.right_kv() {
1541 let (k, v) = ptr::read(&kv).into_kv_mut();
1542 self.front = kv.right_edge();
1546 let next_level = last_edge.into_node().ascend().ok();
1547 unwrap_unchecked(next_level)
1552 match cur_handle.right_kv() {
1554 let (k, v) = ptr::read(&kv).into_kv_mut();
1555 self.front = first_leaf_edge(kv.right_edge().descend());
1559 let next_level = last_edge.into_node().ascend().ok();
1560 cur_handle = unwrap_unchecked(next_level);
1567 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1568 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1569 if self.front == self.back {
1572 unsafe { Some(self.next_back_unchecked()) }
1577 #[unstable(feature = "fused", issue = "35602")]
1578 impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1580 impl<'a, K, V> RangeMut<'a, K, V> {
1581 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1582 let handle = ptr::read(&self.back);
1584 let mut cur_handle = match handle.left_kv() {
1586 let (k, v) = ptr::read(&kv).into_kv_mut();
1587 self.back = kv.left_edge();
1591 let next_level = last_edge.into_node().ascend().ok();
1592 unwrap_unchecked(next_level)
1597 match cur_handle.left_kv() {
1599 let (k, v) = ptr::read(&kv).into_kv_mut();
1600 self.back = last_leaf_edge(kv.left_edge().descend());
1604 let next_level = last_edge.into_node().ascend().ok();
1605 cur_handle = unwrap_unchecked(next_level);
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1614 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1615 let mut map = BTreeMap::new();
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1624 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1625 for (k, v) in iter {
1631 #[stable(feature = "extend_ref", since = "1.2.0")]
1632 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1633 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1634 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1640 fn hash<H: Hasher>(&self, state: &mut H) {
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<K: Ord, V> Default for BTreeMap<K, V> {
1649 /// Creates an empty `BTreeMap<K, V>`.
1650 fn default() -> BTreeMap<K, V> {
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1657 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1658 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1668 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1669 self.iter().partial_cmp(other.iter())
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1676 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1677 self.iter().cmp(other.iter())
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1684 f.debug_map().entries(self.iter()).finish()
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1696 fn index(&self, key: &Q) -> &V {
1697 self.get(key).expect("no entry found for key")
1701 fn first_leaf_edge<BorrowType, K, V>
1702 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1703 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1705 match node.force() {
1706 Leaf(leaf) => return leaf.first_edge(),
1707 Internal(internal) => {
1708 node = internal.first_edge().descend();
1714 fn last_leaf_edge<BorrowType, K, V>
1715 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1716 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1718 match node.force() {
1719 Leaf(leaf) => return leaf.last_edge(),
1720 Internal(internal) => {
1721 node = internal.last_edge().descend();
1727 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeArgument<Q>>(
1728 root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1729 root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1731 )-> (Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1732 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>)
1733 where Q: Ord, K: Borrow<Q>
1735 match (range.start(), range.end()) {
1736 (Excluded(s), Excluded(e)) if s==e =>
1737 panic!("range start and end are equal and excluded in BTreeMap"),
1738 (Included(s), Included(e)) |
1739 (Included(s), Excluded(e)) |
1740 (Excluded(s), Included(e)) |
1741 (Excluded(s), Excluded(e)) if s>e =>
1742 panic!("range start is greater than range end in BTreeMap"),
1746 let mut min_node = root1;
1747 let mut max_node = root2;
1748 let mut min_found = false;
1749 let mut max_found = false;
1750 let mut diverged = false;
1753 let min_edge = match (min_found, range.start()) {
1754 (false, Included(key)) => match search::search_linear(&min_node, key) {
1755 (i, true) => { min_found = true; i },
1758 (false, Excluded(key)) => match search::search_linear(&min_node, key) {
1759 (i, true) => { min_found = true; i+1 },
1762 (_, Unbounded) => 0,
1763 (true, Included(_)) => min_node.keys().len(),
1764 (true, Excluded(_)) => 0,
1767 let max_edge = match (max_found, range.end()) {
1768 (false, Included(key)) => match search::search_linear(&max_node, key) {
1769 (i, true) => { max_found = true; i+1 },
1772 (false, Excluded(key)) => match search::search_linear(&max_node, key) {
1773 (i, true) => { max_found = true; i },
1776 (_, Unbounded) => max_node.keys().len(),
1777 (true, Included(_)) => 0,
1778 (true, Excluded(_)) => max_node.keys().len(),
1782 if max_edge < min_edge { panic!("Ord is ill-defined in BTreeMap range") }
1783 if min_edge != max_edge { diverged = true; }
1786 let front = Handle::new_edge(min_node, min_edge);
1787 let back = Handle::new_edge(max_node, max_edge);
1788 match (front.force(), back.force()) {
1789 (Leaf(f), Leaf(b)) => {
1792 (Internal(min_int), Internal(max_int)) => {
1793 min_node = min_int.descend();
1794 max_node = max_int.descend();
1796 _ => unreachable!("BTreeMap has different depths"),
1802 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1803 val.unwrap_or_else(|| {
1804 if cfg!(debug_assertions) {
1805 panic!("'unchecked' unwrap on None in BTreeMap");
1807 intrinsics::unreachable();
1812 impl<K, V> BTreeMap<K, V> {
1813 /// Gets an iterator over the entries of the map, sorted by key.
1820 /// use std::collections::BTreeMap;
1822 /// let mut map = BTreeMap::new();
1823 /// map.insert(3, "c");
1824 /// map.insert(2, "b");
1825 /// map.insert(1, "a");
1827 /// for (key, value) in map.iter() {
1828 /// println!("{}: {}", key, value);
1831 /// let (first_key, first_value) = map.iter().next().unwrap();
1832 /// assert_eq!((*first_key, *first_value), (1, "a"));
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 pub fn iter(&self) -> Iter<K, V> {
1838 front: first_leaf_edge(self.root.as_ref()),
1839 back: last_leaf_edge(self.root.as_ref()),
1841 length: self.length,
1845 /// Gets a mutable iterator over the entries of the map, sorted by key.
1852 /// use std::collections::BTreeMap;
1854 /// let mut map = BTreeMap::new();
1855 /// map.insert("a", 1);
1856 /// map.insert("b", 2);
1857 /// map.insert("c", 3);
1859 /// // add 10 to the value if the key isn't "a"
1860 /// for (key, value) in map.iter_mut() {
1861 /// if key != &"a" {
1866 #[stable(feature = "rust1", since = "1.0.0")]
1867 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1868 let root1 = self.root.as_mut();
1869 let root2 = unsafe { ptr::read(&root1) };
1872 front: first_leaf_edge(root1),
1873 back: last_leaf_edge(root2),
1874 _marker: PhantomData,
1876 length: self.length,
1880 /// Gets an iterator over the keys of the map, in sorted order.
1887 /// use std::collections::BTreeMap;
1889 /// let mut a = BTreeMap::new();
1890 /// a.insert(2, "b");
1891 /// a.insert(1, "a");
1893 /// let keys: Vec<_> = a.keys().cloned().collect();
1894 /// assert_eq!(keys, [1, 2]);
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1898 Keys { inner: self.iter() }
1901 /// Gets an iterator over the values of the map, in order by key.
1908 /// use std::collections::BTreeMap;
1910 /// let mut a = BTreeMap::new();
1911 /// a.insert(1, "hello");
1912 /// a.insert(2, "goodbye");
1914 /// let values: Vec<&str> = a.values().cloned().collect();
1915 /// assert_eq!(values, ["hello", "goodbye"]);
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1919 Values { inner: self.iter() }
1922 /// Gets a mutable iterator over the values of the map, in order by key.
1929 /// use std::collections::BTreeMap;
1931 /// let mut a = BTreeMap::new();
1932 /// a.insert(1, String::from("hello"));
1933 /// a.insert(2, String::from("goodbye"));
1935 /// for value in a.values_mut() {
1936 /// value.push_str("!");
1939 /// let values: Vec<String> = a.values().cloned().collect();
1940 /// assert_eq!(values, [String::from("hello!"),
1941 /// String::from("goodbye!")]);
1943 #[stable(feature = "map_values_mut", since = "1.10.0")]
1944 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1945 ValuesMut { inner: self.iter_mut() }
1948 /// Returns the number of elements in the map.
1955 /// use std::collections::BTreeMap;
1957 /// let mut a = BTreeMap::new();
1958 /// assert_eq!(a.len(), 0);
1959 /// a.insert(1, "a");
1960 /// assert_eq!(a.len(), 1);
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 pub fn len(&self) -> usize {
1967 /// Returns `true` if the map contains no elements.
1974 /// use std::collections::BTreeMap;
1976 /// let mut a = BTreeMap::new();
1977 /// assert!(a.is_empty());
1978 /// a.insert(1, "a");
1979 /// assert!(!a.is_empty());
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 pub fn is_empty(&self) -> bool {
1987 impl<'a, K: Ord, V> Entry<'a, K, V> {
1988 /// Ensures a value is in the entry by inserting the default if empty, and returns
1989 /// a mutable reference to the value in the entry.
1994 /// use std::collections::BTreeMap;
1996 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1997 /// map.entry("poneyland").or_insert(12);
1999 /// assert_eq!(map["poneyland"], 12);
2001 #[stable(feature = "rust1", since = "1.0.0")]
2002 pub fn or_insert(self, default: V) -> &'a mut V {
2004 Occupied(entry) => entry.into_mut(),
2005 Vacant(entry) => entry.insert(default),
2009 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2010 /// and returns a mutable reference to the value in the entry.
2015 /// use std::collections::BTreeMap;
2017 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2018 /// let s = "hoho".to_string();
2020 /// map.entry("poneyland").or_insert_with(|| s);
2022 /// assert_eq!(map["poneyland"], "hoho".to_string());
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2027 Occupied(entry) => entry.into_mut(),
2028 Vacant(entry) => entry.insert(default()),
2032 /// Returns a reference to this entry's key.
2037 /// use std::collections::BTreeMap;
2039 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2040 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2042 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2043 pub fn key(&self) -> &K {
2045 Occupied(ref entry) => entry.key(),
2046 Vacant(ref entry) => entry.key(),
2051 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2052 /// Gets a reference to the key that would be used when inserting a value
2053 /// through the VacantEntry.
2058 /// use std::collections::BTreeMap;
2060 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2061 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2063 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2064 pub fn key(&self) -> &K {
2068 /// Take ownership of the key.
2073 /// use std::collections::BTreeMap;
2074 /// use std::collections::btree_map::Entry;
2076 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2078 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2082 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2083 pub fn into_key(self) -> K {
2087 /// Sets the value of the entry with the `VacantEntry`'s key,
2088 /// and returns a mutable reference to it.
2093 /// use std::collections::BTreeMap;
2095 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2097 /// // count the number of occurrences of letters in the vec
2098 /// for x in vec!["a","b","a","c","a","b"] {
2099 /// *count.entry(x).or_insert(0) += 1;
2102 /// assert_eq!(count["a"], 3);
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 pub fn insert(self, value: V) -> &'a mut V {
2114 let mut cur_parent = match self.handle.insert(self.key, value) {
2115 (Fit(handle), _) => return handle.into_kv_mut().1,
2116 (Split(left, k, v, right), ptr) => {
2121 left.ascend().map_err(|n| n.into_root_mut())
2128 match parent.insert(ins_k, ins_v, ins_edge) {
2129 Fit(_) => return unsafe { &mut *out_ptr },
2130 Split(left, k, v, right) => {
2134 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2139 root.push_level().push(ins_k, ins_v, ins_edge);
2140 return unsafe { &mut *out_ptr };
2147 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2148 /// Gets a reference to the key in the entry.
2153 /// use std::collections::BTreeMap;
2155 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2156 /// map.entry("poneyland").or_insert(12);
2157 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2159 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2160 pub fn key(&self) -> &K {
2161 self.handle.reborrow().into_kv().0
2164 /// Deprecated, renamed to `remove_entry`
2165 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2166 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2167 pub fn remove_pair(self) -> (K, V) {
2171 /// Take ownership of the key and value from the map.
2176 /// use std::collections::BTreeMap;
2177 /// use std::collections::btree_map::Entry;
2179 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2180 /// map.entry("poneyland").or_insert(12);
2182 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2183 /// // We delete the entry from the map.
2184 /// o.remove_entry();
2187 /// // If now try to get the value, it will panic:
2188 /// // println!("{}", map["poneyland"]);
2190 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2191 pub fn remove_entry(self) -> (K, V) {
2195 /// Gets a reference to the value in the entry.
2200 /// use std::collections::BTreeMap;
2201 /// use std::collections::btree_map::Entry;
2203 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2204 /// map.entry("poneyland").or_insert(12);
2206 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2207 /// assert_eq!(o.get(), &12);
2210 #[stable(feature = "rust1", since = "1.0.0")]
2211 pub fn get(&self) -> &V {
2212 self.handle.reborrow().into_kv().1
2215 /// Gets a mutable reference to the value in the entry.
2220 /// use std::collections::BTreeMap;
2221 /// use std::collections::btree_map::Entry;
2223 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2224 /// map.entry("poneyland").or_insert(12);
2226 /// assert_eq!(map["poneyland"], 12);
2227 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2228 /// *o.get_mut() += 10;
2230 /// assert_eq!(map["poneyland"], 22);
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 pub fn get_mut(&mut self) -> &mut V {
2234 self.handle.kv_mut().1
2237 /// Converts the entry into a mutable reference to its value.
2242 /// use std::collections::BTreeMap;
2243 /// use std::collections::btree_map::Entry;
2245 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2246 /// map.entry("poneyland").or_insert(12);
2248 /// assert_eq!(map["poneyland"], 12);
2249 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2250 /// *o.into_mut() += 10;
2252 /// assert_eq!(map["poneyland"], 22);
2254 #[stable(feature = "rust1", since = "1.0.0")]
2255 pub fn into_mut(self) -> &'a mut V {
2256 self.handle.into_kv_mut().1
2259 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2260 /// and returns the entry's old value.
2265 /// use std::collections::BTreeMap;
2266 /// use std::collections::btree_map::Entry;
2268 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2269 /// map.entry("poneyland").or_insert(12);
2271 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2272 /// assert_eq!(o.insert(15), 12);
2274 /// assert_eq!(map["poneyland"], 15);
2276 #[stable(feature = "rust1", since = "1.0.0")]
2277 pub fn insert(&mut self, value: V) -> V {
2278 mem::replace(self.get_mut(), value)
2281 /// Takes the value of the entry out of the map, and returns it.
2286 /// use std::collections::BTreeMap;
2287 /// use std::collections::btree_map::Entry;
2289 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2290 /// map.entry("poneyland").or_insert(12);
2292 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2293 /// assert_eq!(o.remove(), 12);
2295 /// // If we try to get "poneyland"'s value, it'll panic:
2296 /// // println!("{}", map["poneyland"]);
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 pub fn remove(self) -> V {
2303 fn remove_kv(self) -> (K, V) {
2306 let (small_leaf, old_key, old_val) = match self.handle.force() {
2308 let (hole, old_key, old_val) = leaf.remove();
2309 (hole.into_node(), old_key, old_val)
2311 Internal(mut internal) => {
2312 let key_loc = internal.kv_mut().0 as *mut K;
2313 let val_loc = internal.kv_mut().1 as *mut V;
2315 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2316 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2318 let (hole, key, val) = to_remove.remove();
2320 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2321 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2323 (hole.into_node(), old_key, old_val)
2328 let mut cur_node = small_leaf.forget_type();
2329 while cur_node.len() < node::CAPACITY / 2 {
2330 match handle_underfull_node(cur_node) {
2332 EmptyParent(_) => unreachable!(),
2334 if parent.len() == 0 {
2335 // We must be at the root
2336 parent.into_root_mut().pop_level();
2339 cur_node = parent.forget_type();
2350 enum UnderflowResult<'a, K, V> {
2352 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2353 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2354 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2357 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>)
2358 -> UnderflowResult<'a, K, V> {
2359 let parent = if let Ok(parent) = node.ascend() {
2365 let (is_left, mut handle) = match parent.left_kv() {
2366 Ok(left) => (true, left),
2368 match parent.right_kv() {
2369 Ok(right) => (false, right),
2371 return EmptyParent(parent.into_node());
2377 if handle.can_merge() {
2378 Merged(handle.merge().into_node())
2381 handle.steal_left();
2383 handle.steal_right();
2385 Stole(handle.into_node())
2389 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2392 fn next(&mut self) -> Option<(K, V)> {
2393 let res = match (self.left.peek(), self.right.peek()) {
2394 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2395 (Some(_), None) => Ordering::Less,
2396 (None, Some(_)) => Ordering::Greater,
2397 (None, None) => return None,
2400 // Check which elements comes first and only advance the corresponding iterator.
2401 // If two keys are equal, take the value from `right`.
2403 Ordering::Less => self.left.next(),
2404 Ordering::Greater => self.right.next(),
2405 Ordering::Equal => {