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 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 pub struct RangeMut<'a, K: 'a, V: 'a> {
355 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
356 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
358 // Be invariant in `K` and `V`
359 _marker: PhantomData<&'a mut (K, V)>,
362 #[stable(feature = "collection_debug", since = "1.17.0")]
363 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for RangeMut<'a, K, V> {
364 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
366 front: self.front.reborrow(),
367 back: self.back.reborrow(),
369 f.debug_list().entries(range).finish()
373 /// A view into a single entry in a map, which may either be vacant or occupied.
374 /// This enum is constructed from the [`entry`] method on [`BTreeMap`].
376 /// [`BTreeMap`]: struct.BTreeMap.html
377 /// [`entry`]: struct.BTreeMap.html#method.entry
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub enum Entry<'a, K: 'a, V: 'a> {
381 #[stable(feature = "rust1", since = "1.0.0")]
382 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
383 VacantEntry<'a, K, V>),
385 /// An occupied Entry
386 #[stable(feature = "rust1", since = "1.0.0")]
387 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
388 OccupiedEntry<'a, K, V>),
391 #[stable(feature= "debug_btree_map", since = "1.12.0")]
392 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for Entry<'a, K, V> {
393 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395 Vacant(ref v) => f.debug_tuple("Entry")
398 Occupied(ref o) => f.debug_tuple("Entry")
405 /// A vacant Entry. It is part of the [`Entry`] enum.
407 /// [`Entry`]: enum.Entry.html
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub struct VacantEntry<'a, K: 'a, V: 'a> {
411 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
412 length: &'a mut usize,
414 // Be invariant in `K` and `V`
415 _marker: PhantomData<&'a mut (K, V)>,
418 #[stable(feature= "debug_btree_map", since = "1.12.0")]
419 impl<'a, K: 'a + Debug + Ord, V: 'a> Debug for VacantEntry<'a, K, V> {
420 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
421 f.debug_tuple("VacantEntry")
427 /// An occupied Entry. It is part of the [`Entry`] enum.
429 /// [`Entry`]: enum.Entry.html
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
432 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
434 length: &'a mut usize,
436 // Be invariant in `K` and `V`
437 _marker: PhantomData<&'a mut (K, V)>,
440 #[stable(feature= "debug_btree_map", since = "1.12.0")]
441 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 f.debug_struct("OccupiedEntry")
444 .field("key", self.key())
445 .field("value", self.get())
450 // An iterator for merging two sorted sequences into one
451 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
456 impl<K: Ord, V> BTreeMap<K, V> {
457 /// Makes a new empty BTreeMap with a reasonable choice for B.
464 /// use std::collections::BTreeMap;
466 /// let mut map = BTreeMap::new();
468 /// // entries can now be inserted into the empty map
469 /// map.insert(1, "a");
471 #[stable(feature = "rust1", since = "1.0.0")]
472 pub fn new() -> BTreeMap<K, V> {
474 root: node::Root::new_leaf(),
479 /// Clears the map, removing all values.
486 /// use std::collections::BTreeMap;
488 /// let mut a = BTreeMap::new();
489 /// a.insert(1, "a");
491 /// assert!(a.is_empty());
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn clear(&mut self) {
495 // FIXME(gereeter) .clear() allocates
496 *self = BTreeMap::new();
499 /// Returns a reference to the value corresponding to the key.
501 /// The key may be any borrowed form of the map's key type, but the ordering
502 /// on the borrowed form *must* match the ordering on the key type.
509 /// use std::collections::BTreeMap;
511 /// let mut map = BTreeMap::new();
512 /// map.insert(1, "a");
513 /// assert_eq!(map.get(&1), Some(&"a"));
514 /// assert_eq!(map.get(&2), None);
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
521 match search::search_tree(self.root.as_ref(), key) {
522 Found(handle) => Some(handle.into_kv().1),
527 /// Returns true if the map contains a value for the specified key.
529 /// The key may be any borrowed form of the map's key type, but the ordering
530 /// on the borrowed form *must* match the ordering on the key type.
537 /// use std::collections::BTreeMap;
539 /// let mut map = BTreeMap::new();
540 /// map.insert(1, "a");
541 /// assert_eq!(map.contains_key(&1), true);
542 /// assert_eq!(map.contains_key(&2), false);
544 #[stable(feature = "rust1", since = "1.0.0")]
545 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
549 self.get(key).is_some()
552 /// Returns a mutable reference to the value corresponding to the key.
554 /// The key may be any borrowed form of the map's key type, but the ordering
555 /// on the borrowed form *must* match the ordering on the key type.
562 /// use std::collections::BTreeMap;
564 /// let mut map = BTreeMap::new();
565 /// map.insert(1, "a");
566 /// if let Some(x) = map.get_mut(&1) {
569 /// assert_eq!(map[&1], "b");
571 // See `get` for implementation notes, this is basically a copy-paste with mut's added
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
577 match search::search_tree(self.root.as_mut(), key) {
578 Found(handle) => Some(handle.into_kv_mut().1),
583 /// Inserts a key-value pair into the map.
585 /// If the map did not have this key present, `None` is returned.
587 /// If the map did have this key present, the value is updated, and the old
588 /// value is returned. The key is not updated, though; this matters for
589 /// types that can be `==` without being identical. See the [module-level
590 /// documentation] for more.
592 /// [module-level documentation]: index.html#insert-and-complex-keys
599 /// use std::collections::BTreeMap;
601 /// let mut map = BTreeMap::new();
602 /// assert_eq!(map.insert(37, "a"), None);
603 /// assert_eq!(map.is_empty(), false);
605 /// map.insert(37, "b");
606 /// assert_eq!(map.insert(37, "c"), Some("b"));
607 /// assert_eq!(map[&37], "c");
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
611 match self.entry(key) {
612 Occupied(mut entry) => Some(entry.insert(value)),
620 /// Removes a key from the map, returning the value at the key if the key
621 /// was previously in the map.
623 /// The key may be any borrowed form of the map's key type, but the ordering
624 /// on the borrowed form *must* match the ordering on the key type.
631 /// use std::collections::BTreeMap;
633 /// let mut map = BTreeMap::new();
634 /// map.insert(1, "a");
635 /// assert_eq!(map.remove(&1), Some("a"));
636 /// assert_eq!(map.remove(&1), None);
638 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
643 match search::search_tree(self.root.as_mut(), key) {
647 length: &mut self.length,
648 _marker: PhantomData,
656 /// Moves all elements from `other` into `Self`, leaving `other` empty.
661 /// use std::collections::BTreeMap;
663 /// let mut a = BTreeMap::new();
664 /// a.insert(1, "a");
665 /// a.insert(2, "b");
666 /// a.insert(3, "c");
668 /// let mut b = BTreeMap::new();
669 /// b.insert(3, "d");
670 /// b.insert(4, "e");
671 /// b.insert(5, "f");
673 /// a.append(&mut b);
675 /// assert_eq!(a.len(), 5);
676 /// assert_eq!(b.len(), 0);
678 /// assert_eq!(a[&1], "a");
679 /// assert_eq!(a[&2], "b");
680 /// assert_eq!(a[&3], "d");
681 /// assert_eq!(a[&4], "e");
682 /// assert_eq!(a[&5], "f");
684 #[stable(feature = "btree_append", since = "1.11.0")]
685 pub fn append(&mut self, other: &mut Self) {
686 // Do we have to append anything at all?
687 if other.len() == 0 {
691 // We can just swap `self` and `other` if `self` is empty.
693 mem::swap(self, other);
697 // First, we merge `self` and `other` into a sorted sequence in linear time.
698 let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
699 let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
700 let iter = MergeIter {
701 left: self_iter.peekable(),
702 right: other_iter.peekable(),
705 // Second, we build a tree from the sorted sequence in linear time.
706 self.from_sorted_iter(iter);
707 self.fix_right_edge();
710 /// Constructs a double-ended iterator over a sub-range of elements in the map.
711 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
712 /// yield elements from min (inclusive) to max (exclusive).
713 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
714 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
715 /// range from 4 to 10.
722 /// #![feature(btree_range, collections_bound)]
724 /// use std::collections::BTreeMap;
725 /// use std::collections::Bound::Included;
727 /// let mut map = BTreeMap::new();
728 /// map.insert(3, "a");
729 /// map.insert(5, "b");
730 /// map.insert(8, "c");
731 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
732 /// println!("{}: {}", key, value);
734 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
736 #[unstable(feature = "btree_range",
737 reason = "matches collection reform specification, waiting for dust to settle",
739 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V>
740 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
742 let min = range.start();
743 let max = range.end();
744 let front = match min {
746 match search::search_tree(self.root.as_ref(), key) {
747 Found(kv_handle) => {
748 match kv_handle.left_edge().force() {
749 Leaf(bottom) => bottom,
750 Internal(internal) => last_leaf_edge(internal.descend()),
753 GoDown(bottom) => bottom,
757 match search::search_tree(self.root.as_ref(), key) {
758 Found(kv_handle) => {
759 match kv_handle.right_edge().force() {
760 Leaf(bottom) => bottom,
761 Internal(internal) => first_leaf_edge(internal.descend()),
764 GoDown(bottom) => bottom,
767 Unbounded => first_leaf_edge(self.root.as_ref()),
770 let back = match max {
772 match search::search_tree(self.root.as_ref(), key) {
773 Found(kv_handle) => {
774 match kv_handle.right_edge().force() {
775 Leaf(bottom) => bottom,
776 Internal(internal) => first_leaf_edge(internal.descend()),
779 GoDown(bottom) => bottom,
783 match search::search_tree(self.root.as_ref(), key) {
784 Found(kv_handle) => {
785 match kv_handle.left_edge().force() {
786 Leaf(bottom) => bottom,
787 Internal(internal) => last_leaf_edge(internal.descend()),
790 GoDown(bottom) => bottom,
793 Unbounded => last_leaf_edge(self.root.as_ref()),
802 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
803 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
804 /// yield elements from min (inclusive) to max (exclusive).
805 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
806 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
807 /// range from 4 to 10.
814 /// #![feature(btree_range)]
816 /// use std::collections::BTreeMap;
818 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
819 /// .map(|&s| (s, 0))
821 /// for (_, balance) in map.range_mut("B".."Cheryl") {
824 /// for (name, balance) in &map {
825 /// println!("{} => {}", name, balance);
828 #[unstable(feature = "btree_range",
829 reason = "matches collection reform specification, waiting for dust to settle",
831 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V>
832 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
834 let min = range.start();
835 let max = range.end();
836 let root1 = self.root.as_mut();
837 let root2 = unsafe { ptr::read(&root1) };
839 let front = match min {
841 match search::search_tree(root1, key) {
842 Found(kv_handle) => {
843 match kv_handle.left_edge().force() {
844 Leaf(bottom) => bottom,
845 Internal(internal) => last_leaf_edge(internal.descend()),
848 GoDown(bottom) => bottom,
852 match search::search_tree(root1, key) {
853 Found(kv_handle) => {
854 match kv_handle.right_edge().force() {
855 Leaf(bottom) => bottom,
856 Internal(internal) => first_leaf_edge(internal.descend()),
859 GoDown(bottom) => bottom,
862 Unbounded => first_leaf_edge(root1),
865 let back = match max {
867 match search::search_tree(root2, key) {
868 Found(kv_handle) => {
869 match kv_handle.right_edge().force() {
870 Leaf(bottom) => bottom,
871 Internal(internal) => first_leaf_edge(internal.descend()),
874 GoDown(bottom) => bottom,
878 match search::search_tree(root2, key) {
879 Found(kv_handle) => {
880 match kv_handle.left_edge().force() {
881 Leaf(bottom) => bottom,
882 Internal(internal) => last_leaf_edge(internal.descend()),
885 GoDown(bottom) => bottom,
888 Unbounded => last_leaf_edge(root2),
894 _marker: PhantomData,
898 /// Gets the given key's corresponding entry in the map for in-place manipulation.
905 /// use std::collections::BTreeMap;
907 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
909 /// // count the number of occurrences of letters in the vec
910 /// for x in vec!["a","b","a","c","a","b"] {
911 /// *count.entry(x).or_insert(0) += 1;
914 /// assert_eq!(count["a"], 3);
916 #[stable(feature = "rust1", since = "1.0.0")]
917 pub fn entry(&mut self, key: K) -> Entry<K, V> {
918 match search::search_tree(self.root.as_mut(), &key) {
920 Occupied(OccupiedEntry {
922 length: &mut self.length,
923 _marker: PhantomData,
930 length: &mut self.length,
931 _marker: PhantomData,
937 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
938 let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
939 // Iterate through all key-value pairs, pushing them into nodes at the right level.
940 for (key, value) in iter {
941 // Try to push key-value pair into the current leaf node.
942 if cur_node.len() < node::CAPACITY {
943 cur_node.push(key, value);
945 // No space left, go up and push there.
947 let mut test_node = cur_node.forget_type();
949 match test_node.ascend() {
951 let parent = parent.into_node();
952 if parent.len() < node::CAPACITY {
953 // Found a node with space left, push here.
958 test_node = parent.forget_type();
962 // We are at the top, create a new root node and push there.
963 open_node = node.into_root_mut().push_level();
969 // Push key-value pair and new right subtree.
970 let tree_height = open_node.height() - 1;
971 let mut right_tree = node::Root::new_leaf();
972 for _ in 0..tree_height {
973 right_tree.push_level();
975 open_node.push(key, value, right_tree);
977 // Go down to the right-most leaf again.
978 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
985 fn fix_right_edge(&mut self) {
986 // Handle underfull nodes, start from the top.
987 let mut cur_node = self.root.as_mut();
988 while let Internal(internal) = cur_node.force() {
989 // Check if right-most child is underfull.
990 let mut last_edge = internal.last_edge();
991 let right_child_len = last_edge.reborrow().descend().len();
992 if right_child_len < node::MIN_LEN {
994 let mut last_kv = match last_edge.left_kv() {
996 Err(_) => unreachable!(),
998 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
999 last_edge = last_kv.right_edge();
1003 cur_node = last_edge.descend();
1007 /// Splits the collection into two at the given key. Returns everything after the given key,
1008 /// including the key.
1015 /// use std::collections::BTreeMap;
1017 /// let mut a = BTreeMap::new();
1018 /// a.insert(1, "a");
1019 /// a.insert(2, "b");
1020 /// a.insert(3, "c");
1021 /// a.insert(17, "d");
1022 /// a.insert(41, "e");
1024 /// let b = a.split_off(&3);
1026 /// assert_eq!(a.len(), 2);
1027 /// assert_eq!(b.len(), 3);
1029 /// assert_eq!(a[&1], "a");
1030 /// assert_eq!(a[&2], "b");
1032 /// assert_eq!(b[&3], "c");
1033 /// assert_eq!(b[&17], "d");
1034 /// assert_eq!(b[&41], "e");
1036 #[stable(feature = "btree_split_off", since = "1.11.0")]
1037 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1040 if self.is_empty() {
1044 let total_num = self.len();
1046 let mut right = Self::new();
1047 for _ in 0..(self.root.as_ref().height()) {
1048 right.root.push_level();
1052 let mut left_node = self.root.as_mut();
1053 let mut right_node = right.root.as_mut();
1056 let mut split_edge = match search::search_node(left_node, key) {
1057 // key is going to the right tree
1058 Found(handle) => handle.left_edge(),
1059 GoDown(handle) => handle,
1062 split_edge.move_suffix(&mut right_node);
1064 match (split_edge.force(), right_node.force()) {
1065 (Internal(edge), Internal(node)) => {
1066 left_node = edge.descend();
1067 right_node = node.first_edge().descend();
1069 (Leaf(_), Leaf(_)) => {
1079 self.fix_right_border();
1080 right.fix_left_border();
1082 if self.root.as_ref().height() < right.root.as_ref().height() {
1083 self.recalc_length();
1084 right.length = total_num - self.len();
1086 right.recalc_length();
1087 self.length = total_num - right.len();
1093 /// Calculates the number of elements if it is incorrect.
1094 fn recalc_length(&mut self) {
1095 fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize {
1096 let mut res = node.len();
1098 if let Internal(node) = node.force() {
1099 let mut edge = node.first_edge();
1101 res += dfs(edge.reborrow().descend());
1102 match edge.right_kv() {
1104 edge = right_kv.right_edge();
1116 self.length = dfs(self.root.as_ref());
1119 /// Removes empty levels on the top.
1120 fn fix_top(&mut self) {
1123 let node = self.root.as_ref();
1124 if node.height() == 0 || node.len() > 0 {
1128 self.root.pop_level();
1132 fn fix_right_border(&mut self) {
1136 let mut cur_node = self.root.as_mut();
1138 while let Internal(node) = cur_node.force() {
1139 let mut last_kv = node.last_kv();
1141 if last_kv.can_merge() {
1142 cur_node = last_kv.merge().descend();
1144 let right_len = last_kv.reborrow().right_edge().descend().len();
1145 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1146 if right_len < node::MIN_LEN + 1 {
1147 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1149 cur_node = last_kv.right_edge().descend();
1157 /// The symmetric clone of `fix_right_border`.
1158 fn fix_left_border(&mut self) {
1162 let mut cur_node = self.root.as_mut();
1164 while let Internal(node) = cur_node.force() {
1165 let mut first_kv = node.first_kv();
1167 if first_kv.can_merge() {
1168 cur_node = first_kv.merge().descend();
1170 let left_len = first_kv.reborrow().left_edge().descend().len();
1171 if left_len < node::MIN_LEN + 1 {
1172 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1174 cur_node = first_kv.left_edge().descend();
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1185 type Item = (&'a K, &'a V);
1186 type IntoIter = Iter<'a, K, V>;
1188 fn into_iter(self) -> Iter<'a, K, V> {
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1195 type Item = (&'a K, &'a V);
1197 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1198 if self.length == 0 {
1202 unsafe { Some(self.range.next_unchecked()) }
1206 fn size_hint(&self) -> (usize, Option<usize>) {
1207 (self.length, Some(self.length))
1211 #[unstable(feature = "fused", issue = "35602")]
1212 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1216 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1217 if self.length == 0 {
1221 unsafe { Some(self.range.next_back_unchecked()) }
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1228 fn len(&self) -> usize {
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl<'a, K, V> Clone for Iter<'a, K, V> {
1235 fn clone(&self) -> Iter<'a, K, V> {
1237 range: self.range.clone(),
1238 length: self.length,
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1245 type Item = (&'a K, &'a mut V);
1246 type IntoIter = IterMut<'a, K, V>;
1248 fn into_iter(self) -> IterMut<'a, K, V> {
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1255 type Item = (&'a K, &'a mut V);
1257 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1258 if self.length == 0 {
1262 unsafe { Some(self.range.next_unchecked()) }
1266 fn size_hint(&self) -> (usize, Option<usize>) {
1267 (self.length, Some(self.length))
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1273 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1274 if self.length == 0 {
1278 unsafe { Some(self.range.next_back_unchecked()) }
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1285 fn len(&self) -> usize {
1290 #[unstable(feature = "fused", issue = "35602")]
1291 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<K, V> IntoIterator for BTreeMap<K, V> {
1296 type IntoIter = IntoIter<K, V>;
1298 fn into_iter(self) -> IntoIter<K, V> {
1299 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1300 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1301 let len = self.length;
1305 front: first_leaf_edge(root1),
1306 back: last_leaf_edge(root2),
1312 #[stable(feature = "btree_drop", since = "1.7.0")]
1313 impl<K, V> Drop for IntoIter<K, V> {
1314 fn drop(&mut self) {
1315 for _ in &mut *self {
1318 let leaf_node = ptr::read(&self.front).into_node();
1319 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1320 let mut cur_node = first_parent.into_node();
1321 while let Some(parent) = cur_node.deallocate_and_ascend() {
1322 cur_node = parent.into_node()
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 impl<K, V> Iterator for IntoIter<K, V> {
1333 fn next(&mut self) -> Option<(K, V)> {
1334 if self.length == 0 {
1340 let handle = unsafe { ptr::read(&self.front) };
1342 let mut cur_handle = match handle.right_kv() {
1344 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1345 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1346 self.front = kv.right_edge();
1347 return Some((k, v));
1349 Err(last_edge) => unsafe {
1350 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1355 match cur_handle.right_kv() {
1357 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1358 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1359 self.front = first_leaf_edge(kv.right_edge().descend());
1360 return Some((k, v));
1362 Err(last_edge) => unsafe {
1363 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1369 fn size_hint(&self) -> (usize, Option<usize>) {
1370 (self.length, Some(self.length))
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1376 fn next_back(&mut self) -> Option<(K, V)> {
1377 if self.length == 0 {
1383 let handle = unsafe { ptr::read(&self.back) };
1385 let mut cur_handle = match handle.left_kv() {
1387 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1388 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1389 self.back = kv.left_edge();
1390 return Some((k, v));
1392 Err(last_edge) => unsafe {
1393 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1398 match cur_handle.left_kv() {
1400 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1401 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1402 self.back = last_leaf_edge(kv.left_edge().descend());
1403 return Some((k, v));
1405 Err(last_edge) => unsafe {
1406 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1415 fn len(&self) -> usize {
1420 #[unstable(feature = "fused", issue = "35602")]
1421 impl<K, V> FusedIterator for IntoIter<K, V> {}
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1427 fn next(&mut self) -> Option<&'a K> {
1428 self.inner.next().map(|(k, _)| k)
1431 fn size_hint(&self) -> (usize, Option<usize>) {
1432 self.inner.size_hint()
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1438 fn next_back(&mut self) -> Option<&'a K> {
1439 self.inner.next_back().map(|(k, _)| k)
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1445 fn len(&self) -> usize {
1450 #[unstable(feature = "fused", issue = "35602")]
1451 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<'a, K, V> Clone for Keys<'a, K, V> {
1455 fn clone(&self) -> Keys<'a, K, V> {
1456 Keys { inner: self.inner.clone() }
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 impl<'a, K, V> Iterator for Values<'a, K, V> {
1464 fn next(&mut self) -> Option<&'a V> {
1465 self.inner.next().map(|(_, v)| v)
1468 fn size_hint(&self) -> (usize, Option<usize>) {
1469 self.inner.size_hint()
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1475 fn next_back(&mut self) -> Option<&'a V> {
1476 self.inner.next_back().map(|(_, v)| v)
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1482 fn len(&self) -> usize {
1487 #[unstable(feature = "fused", issue = "35602")]
1488 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1490 #[stable(feature = "rust1", since = "1.0.0")]
1491 impl<'a, K, V> Clone for Values<'a, K, V> {
1492 fn clone(&self) -> Values<'a, K, V> {
1493 Values { inner: self.inner.clone() }
1497 impl<'a, K, V> Iterator for Range<'a, K, V> {
1498 type Item = (&'a K, &'a V);
1500 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1501 if self.front == self.back {
1504 unsafe { Some(self.next_unchecked()) }
1509 #[stable(feature = "map_values_mut", since = "1.10.0")]
1510 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1511 type Item = &'a mut V;
1513 fn next(&mut self) -> Option<&'a mut V> {
1514 self.inner.next().map(|(_, v)| v)
1517 fn size_hint(&self) -> (usize, Option<usize>) {
1518 self.inner.size_hint()
1522 #[stable(feature = "map_values_mut", since = "1.10.0")]
1523 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1524 fn next_back(&mut self) -> Option<&'a mut V> {
1525 self.inner.next_back().map(|(_, v)| v)
1529 #[stable(feature = "map_values_mut", since = "1.10.0")]
1530 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1531 fn len(&self) -> usize {
1536 #[unstable(feature = "fused", issue = "35602")]
1537 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1540 impl<'a, K, V> Range<'a, K, V> {
1541 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1542 let handle = self.front;
1544 let mut cur_handle = match handle.right_kv() {
1546 let ret = kv.into_kv();
1547 self.front = kv.right_edge();
1551 let next_level = last_edge.into_node().ascend().ok();
1552 unwrap_unchecked(next_level)
1557 match cur_handle.right_kv() {
1559 let ret = kv.into_kv();
1560 self.front = first_leaf_edge(kv.right_edge().descend());
1564 let next_level = last_edge.into_node().ascend().ok();
1565 cur_handle = unwrap_unchecked(next_level);
1572 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1573 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1574 if self.front == self.back {
1577 unsafe { Some(self.next_back_unchecked()) }
1582 impl<'a, K, V> Range<'a, K, V> {
1583 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1584 let handle = self.back;
1586 let mut cur_handle = match handle.left_kv() {
1588 let ret = kv.into_kv();
1589 self.back = kv.left_edge();
1593 let next_level = last_edge.into_node().ascend().ok();
1594 unwrap_unchecked(next_level)
1599 match cur_handle.left_kv() {
1601 let ret = kv.into_kv();
1602 self.back = last_leaf_edge(kv.left_edge().descend());
1606 let next_level = last_edge.into_node().ascend().ok();
1607 cur_handle = unwrap_unchecked(next_level);
1614 #[unstable(feature = "fused", issue = "35602")]
1615 impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
1617 impl<'a, K, V> Clone for Range<'a, K, V> {
1618 fn clone(&self) -> Range<'a, K, V> {
1626 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1627 type Item = (&'a K, &'a mut V);
1629 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1630 if self.front == self.back {
1633 unsafe { Some(self.next_unchecked()) }
1638 impl<'a, K, V> RangeMut<'a, K, V> {
1639 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1640 let handle = ptr::read(&self.front);
1642 let mut cur_handle = match handle.right_kv() {
1644 let (k, v) = ptr::read(&kv).into_kv_mut();
1645 self.front = kv.right_edge();
1649 let next_level = last_edge.into_node().ascend().ok();
1650 unwrap_unchecked(next_level)
1655 match cur_handle.right_kv() {
1657 let (k, v) = ptr::read(&kv).into_kv_mut();
1658 self.front = first_leaf_edge(kv.right_edge().descend());
1662 let next_level = last_edge.into_node().ascend().ok();
1663 cur_handle = unwrap_unchecked(next_level);
1670 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1671 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1672 if self.front == self.back {
1675 unsafe { Some(self.next_back_unchecked()) }
1680 #[unstable(feature = "fused", issue = "35602")]
1681 impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1683 impl<'a, K, V> RangeMut<'a, K, V> {
1684 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1685 let handle = ptr::read(&self.back);
1687 let mut cur_handle = match handle.left_kv() {
1689 let (k, v) = ptr::read(&kv).into_kv_mut();
1690 self.back = kv.left_edge();
1694 let next_level = last_edge.into_node().ascend().ok();
1695 unwrap_unchecked(next_level)
1700 match cur_handle.left_kv() {
1702 let (k, v) = ptr::read(&kv).into_kv_mut();
1703 self.back = last_leaf_edge(kv.left_edge().descend());
1707 let next_level = last_edge.into_node().ascend().ok();
1708 cur_handle = unwrap_unchecked(next_level);
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1717 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1718 let mut map = BTreeMap::new();
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1727 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1728 for (k, v) in iter {
1734 #[stable(feature = "extend_ref", since = "1.2.0")]
1735 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1736 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1737 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1743 fn hash<H: Hasher>(&self, state: &mut H) {
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<K: Ord, V> Default for BTreeMap<K, V> {
1752 /// Creates an empty `BTreeMap<K, V>`.
1753 fn default() -> BTreeMap<K, V> {
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1760 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1761 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1771 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1772 self.iter().partial_cmp(other.iter())
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1779 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1780 self.iter().cmp(other.iter())
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1787 f.debug_map().entries(self.iter()).finish()
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1799 fn index(&self, key: &Q) -> &V {
1800 self.get(key).expect("no entry found for key")
1804 fn first_leaf_edge<BorrowType, K, V>
1805 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1806 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1808 match node.force() {
1809 Leaf(leaf) => return leaf.first_edge(),
1810 Internal(internal) => {
1811 node = internal.first_edge().descend();
1817 fn last_leaf_edge<BorrowType, K, V>
1818 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1819 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1821 match node.force() {
1822 Leaf(leaf) => return leaf.last_edge(),
1823 Internal(internal) => {
1824 node = internal.last_edge().descend();
1831 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1832 val.unwrap_or_else(|| {
1833 if cfg!(debug_assertions) {
1834 panic!("'unchecked' unwrap on None in BTreeMap");
1836 intrinsics::unreachable();
1841 impl<K, V> BTreeMap<K, V> {
1842 /// Gets an iterator over the entries of the map, sorted by key.
1849 /// use std::collections::BTreeMap;
1851 /// let mut map = BTreeMap::new();
1852 /// map.insert(3, "c");
1853 /// map.insert(2, "b");
1854 /// map.insert(1, "a");
1856 /// for (key, value) in map.iter() {
1857 /// println!("{}: {}", key, value);
1860 /// let (first_key, first_value) = map.iter().next().unwrap();
1861 /// assert_eq!((*first_key, *first_value), (1, "a"));
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 pub fn iter(&self) -> Iter<K, V> {
1867 front: first_leaf_edge(self.root.as_ref()),
1868 back: last_leaf_edge(self.root.as_ref()),
1870 length: self.length,
1874 /// Gets a mutable iterator over the entries of the map, sorted by key.
1881 /// use std::collections::BTreeMap;
1883 /// let mut map = BTreeMap::new();
1884 /// map.insert("a", 1);
1885 /// map.insert("b", 2);
1886 /// map.insert("c", 3);
1888 /// // add 10 to the value if the key isn't "a"
1889 /// for (key, value) in map.iter_mut() {
1890 /// if key != &"a" {
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1897 let root1 = self.root.as_mut();
1898 let root2 = unsafe { ptr::read(&root1) };
1901 front: first_leaf_edge(root1),
1902 back: last_leaf_edge(root2),
1903 _marker: PhantomData,
1905 length: self.length,
1909 /// Gets an iterator over the keys of the map, in sorted order.
1916 /// use std::collections::BTreeMap;
1918 /// let mut a = BTreeMap::new();
1919 /// a.insert(2, "b");
1920 /// a.insert(1, "a");
1922 /// let keys: Vec<_> = a.keys().cloned().collect();
1923 /// assert_eq!(keys, [1, 2]);
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1927 Keys { inner: self.iter() }
1930 /// Gets an iterator over the values of the map, in order by key.
1937 /// use std::collections::BTreeMap;
1939 /// let mut a = BTreeMap::new();
1940 /// a.insert(1, "hello");
1941 /// a.insert(2, "goodbye");
1943 /// let values: Vec<&str> = a.values().cloned().collect();
1944 /// assert_eq!(values, ["hello", "goodbye"]);
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1948 Values { inner: self.iter() }
1951 /// Gets a mutable iterator over the values of the map, in order by key.
1958 /// use std::collections::BTreeMap;
1960 /// let mut a = BTreeMap::new();
1961 /// a.insert(1, String::from("hello"));
1962 /// a.insert(2, String::from("goodbye"));
1964 /// for value in a.values_mut() {
1965 /// value.push_str("!");
1968 /// let values: Vec<String> = a.values().cloned().collect();
1969 /// assert_eq!(values, [String::from("hello!"),
1970 /// String::from("goodbye!")]);
1972 #[stable(feature = "map_values_mut", since = "1.10.0")]
1973 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1974 ValuesMut { inner: self.iter_mut() }
1977 /// Returns the number of elements in the map.
1984 /// use std::collections::BTreeMap;
1986 /// let mut a = BTreeMap::new();
1987 /// assert_eq!(a.len(), 0);
1988 /// a.insert(1, "a");
1989 /// assert_eq!(a.len(), 1);
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 pub fn len(&self) -> usize {
1996 /// Returns true if the map contains no elements.
2003 /// use std::collections::BTreeMap;
2005 /// let mut a = BTreeMap::new();
2006 /// assert!(a.is_empty());
2007 /// a.insert(1, "a");
2008 /// assert!(!a.is_empty());
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 pub fn is_empty(&self) -> bool {
2016 impl<'a, K: Ord, V> Entry<'a, K, V> {
2017 /// Ensures a value is in the entry by inserting the default if empty, and returns
2018 /// a mutable reference to the value in the entry.
2023 /// use std::collections::BTreeMap;
2025 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2026 /// map.entry("poneyland").or_insert(12);
2028 /// assert_eq!(map["poneyland"], 12);
2030 #[stable(feature = "rust1", since = "1.0.0")]
2031 pub fn or_insert(self, default: V) -> &'a mut V {
2033 Occupied(entry) => entry.into_mut(),
2034 Vacant(entry) => entry.insert(default),
2038 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2039 /// and returns a mutable reference to the value in the entry.
2044 /// use std::collections::BTreeMap;
2046 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2047 /// let s = "hoho".to_string();
2049 /// map.entry("poneyland").or_insert_with(|| s);
2051 /// assert_eq!(map["poneyland"], "hoho".to_string());
2053 #[stable(feature = "rust1", since = "1.0.0")]
2054 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2056 Occupied(entry) => entry.into_mut(),
2057 Vacant(entry) => entry.insert(default()),
2061 /// Returns a reference to this entry's key.
2066 /// use std::collections::BTreeMap;
2068 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2069 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2071 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2072 pub fn key(&self) -> &K {
2074 Occupied(ref entry) => entry.key(),
2075 Vacant(ref entry) => entry.key(),
2080 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2081 /// Gets a reference to the key that would be used when inserting a value
2082 /// through the VacantEntry.
2087 /// use std::collections::BTreeMap;
2089 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2090 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2092 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2093 pub fn key(&self) -> &K {
2097 /// Take ownership of the key.
2102 /// use std::collections::BTreeMap;
2103 /// use std::collections::btree_map::Entry;
2105 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2107 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2111 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2112 pub fn into_key(self) -> K {
2116 /// Sets the value of the entry with the `VacantEntry`'s key,
2117 /// and returns a mutable reference to it.
2122 /// use std::collections::BTreeMap;
2124 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2126 /// // count the number of occurrences of letters in the vec
2127 /// for x in vec!["a","b","a","c","a","b"] {
2128 /// *count.entry(x).or_insert(0) += 1;
2131 /// assert_eq!(count["a"], 3);
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 pub fn insert(self, value: V) -> &'a mut V {
2143 let mut cur_parent = match self.handle.insert(self.key, value) {
2144 (Fit(handle), _) => return handle.into_kv_mut().1,
2145 (Split(left, k, v, right), ptr) => {
2150 left.ascend().map_err(|n| n.into_root_mut())
2157 match parent.insert(ins_k, ins_v, ins_edge) {
2158 Fit(_) => return unsafe { &mut *out_ptr },
2159 Split(left, k, v, right) => {
2163 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2168 root.push_level().push(ins_k, ins_v, ins_edge);
2169 return unsafe { &mut *out_ptr };
2176 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2177 /// Gets a reference to the key in the entry.
2182 /// use std::collections::BTreeMap;
2184 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2185 /// map.entry("poneyland").or_insert(12);
2186 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2188 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2189 pub fn key(&self) -> &K {
2190 self.handle.reborrow().into_kv().0
2193 /// Deprecated, renamed to `remove_entry`
2194 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2195 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2196 pub fn remove_pair(self) -> (K, V) {
2200 /// Take ownership of the key and value from the map.
2205 /// use std::collections::BTreeMap;
2206 /// use std::collections::btree_map::Entry;
2208 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2209 /// map.entry("poneyland").or_insert(12);
2211 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2212 /// // We delete the entry from the map.
2213 /// o.remove_entry();
2216 /// // If now try to get the value, it will panic:
2217 /// // println!("{}", map["poneyland"]);
2219 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2220 pub fn remove_entry(self) -> (K, V) {
2224 /// Gets a reference to the value in the entry.
2229 /// use std::collections::BTreeMap;
2230 /// use std::collections::btree_map::Entry;
2232 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2233 /// map.entry("poneyland").or_insert(12);
2235 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2236 /// assert_eq!(o.get(), &12);
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 pub fn get(&self) -> &V {
2241 self.handle.reborrow().into_kv().1
2244 /// Gets a mutable reference to the value in the entry.
2249 /// use std::collections::BTreeMap;
2250 /// use std::collections::btree_map::Entry;
2252 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2253 /// map.entry("poneyland").or_insert(12);
2255 /// assert_eq!(map["poneyland"], 12);
2256 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2257 /// *o.get_mut() += 10;
2259 /// assert_eq!(map["poneyland"], 22);
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 pub fn get_mut(&mut self) -> &mut V {
2263 self.handle.kv_mut().1
2266 /// Converts the entry into a mutable reference to its value.
2271 /// use std::collections::BTreeMap;
2272 /// use std::collections::btree_map::Entry;
2274 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2275 /// map.entry("poneyland").or_insert(12);
2277 /// assert_eq!(map["poneyland"], 12);
2278 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2279 /// *o.into_mut() += 10;
2281 /// assert_eq!(map["poneyland"], 22);
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 pub fn into_mut(self) -> &'a mut V {
2285 self.handle.into_kv_mut().1
2288 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2289 /// and returns the entry's old value.
2294 /// use std::collections::BTreeMap;
2295 /// use std::collections::btree_map::Entry;
2297 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2298 /// map.entry("poneyland").or_insert(12);
2300 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2301 /// assert_eq!(o.insert(15), 12);
2303 /// assert_eq!(map["poneyland"], 15);
2305 #[stable(feature = "rust1", since = "1.0.0")]
2306 pub fn insert(&mut self, value: V) -> V {
2307 mem::replace(self.get_mut(), value)
2310 /// Takes the value of the entry out of the map, and returns it.
2315 /// use std::collections::BTreeMap;
2316 /// use std::collections::btree_map::Entry;
2318 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2319 /// map.entry("poneyland").or_insert(12);
2321 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2322 /// assert_eq!(o.remove(), 12);
2324 /// // If we try to get "poneyland"'s value, it'll panic:
2325 /// // println!("{}", map["poneyland"]);
2327 #[stable(feature = "rust1", since = "1.0.0")]
2328 pub fn remove(self) -> V {
2332 fn remove_kv(self) -> (K, V) {
2335 let (small_leaf, old_key, old_val) = match self.handle.force() {
2337 let (hole, old_key, old_val) = leaf.remove();
2338 (hole.into_node(), old_key, old_val)
2340 Internal(mut internal) => {
2341 let key_loc = internal.kv_mut().0 as *mut K;
2342 let val_loc = internal.kv_mut().1 as *mut V;
2344 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2345 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2347 let (hole, key, val) = to_remove.remove();
2349 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2350 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2352 (hole.into_node(), old_key, old_val)
2357 let mut cur_node = small_leaf.forget_type();
2358 while cur_node.len() < node::CAPACITY / 2 {
2359 match handle_underfull_node(cur_node) {
2361 EmptyParent(_) => unreachable!(),
2363 if parent.len() == 0 {
2364 // We must be at the root
2365 parent.into_root_mut().pop_level();
2368 cur_node = parent.forget_type();
2379 enum UnderflowResult<'a, K, V> {
2381 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2382 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2383 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2386 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>)
2387 -> UnderflowResult<'a, K, V> {
2388 let parent = if let Ok(parent) = node.ascend() {
2394 let (is_left, mut handle) = match parent.left_kv() {
2395 Ok(left) => (true, left),
2397 match parent.right_kv() {
2398 Ok(right) => (false, right),
2400 return EmptyParent(parent.into_node());
2406 if handle.can_merge() {
2407 Merged(handle.merge().into_node())
2410 handle.steal_left();
2412 handle.steal_right();
2414 Stole(handle.into_node())
2418 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2421 fn next(&mut self) -> Option<(K, V)> {
2422 let res = match (self.left.peek(), self.right.peek()) {
2423 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2424 (Some(_), None) => Ordering::Less,
2425 (None, Some(_)) => Ordering::Greater,
2426 (None, None) => return None,
2429 // Check which elements comes first and only advance the corresponding iterator.
2430 // If two keys are equal, take the value from `right`.
2432 Ordering::Less => self.left.next(),
2433 Ordering::Greater => self.right.next(),
2434 Ordering::Equal => {