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 the entries of a `BTreeMap`.
267 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
268 /// documentation for more.
270 /// [`iter`]: struct.BTreeMap.html#method.iter
271 /// [`BTreeMap`]: struct.BTreeMap.html
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub struct Iter<'a, K: 'a, V: 'a> {
274 range: Range<'a, K, V>,
278 #[stable(feature = "collection_debug", since = "1.17.0")]
279 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Iter<'a, K, V> {
280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281 f.debug_list().entries(self.clone()).finish()
285 /// A mutable iterator over the entries of a `BTreeMap`.
287 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
288 /// documentation for more.
290 /// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut
291 /// [`BTreeMap`]: struct.BTreeMap.html
292 #[stable(feature = "rust1", since = "1.0.0")]
294 pub struct IterMut<'a, K: 'a, V: 'a> {
295 range: RangeMut<'a, K, V>,
299 /// An owning iterator over the entries of a `BTreeMap`.
301 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
302 /// (provided by the `IntoIterator` trait). See its documentation for more.
304 /// [`into_iter`]: struct.BTreeMap.html#method.into_iter
305 /// [`BTreeMap`]: struct.BTreeMap.html
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub struct IntoIter<K, V> {
308 front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
309 back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
313 #[stable(feature = "collection_debug", since = "1.17.0")]
314 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
317 front: self.front.reborrow(),
318 back: self.back.reborrow(),
320 f.debug_list().entries(range).finish()
324 /// An iterator over the keys of a `BTreeMap`.
326 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
327 /// documentation for more.
329 /// [`keys`]: struct.BTreeMap.html#method.keys
330 /// [`BTreeMap`]: struct.BTreeMap.html
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub struct Keys<'a, K: 'a, V: 'a> {
333 inner: Iter<'a, K, V>,
336 #[stable(feature = "collection_debug", since = "1.17.0")]
337 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Keys<'a, K, V> {
338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
339 f.debug_list().entries(self.inner.clone()).finish()
343 /// An iterator over the values of a `BTreeMap`.
345 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
346 /// documentation for more.
348 /// [`values`]: struct.BTreeMap.html#method.values
349 /// [`BTreeMap`]: struct.BTreeMap.html
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub struct Values<'a, K: 'a, V: 'a> {
352 inner: Iter<'a, K, V>,
355 #[stable(feature = "collection_debug", since = "1.17.0")]
356 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Values<'a, K, V> {
357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
358 f.debug_list().entries(self.inner.clone()).finish()
362 /// A mutable iterator over the values of a `BTreeMap`.
364 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
365 /// documentation for more.
367 /// [`values_mut`]: struct.BTreeMap.html#method.values_mut
368 /// [`BTreeMap`]: struct.BTreeMap.html
369 #[stable(feature = "map_values_mut", since = "1.10.0")]
371 pub struct ValuesMut<'a, K: 'a, V: 'a> {
372 inner: IterMut<'a, K, V>,
375 /// An iterator over a sub-range of entries in a `BTreeMap`.
377 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
378 /// documentation for more.
380 /// [`range`]: struct.BTreeMap.html#method.range
381 /// [`BTreeMap`]: struct.BTreeMap.html
382 #[stable(feature = "btree_range", since = "1.17.0")]
383 pub struct Range<'a, K: 'a, V: 'a> {
384 front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
385 back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
388 #[stable(feature = "collection_debug", since = "1.17.0")]
389 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Range<'a, K, V> {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 f.debug_list().entries(self.clone()).finish()
395 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
397 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
398 /// documentation for more.
400 /// [`range_mut`]: struct.BTreeMap.html#method.range_mut
401 /// [`BTreeMap`]: struct.BTreeMap.html
402 #[stable(feature = "btree_range", since = "1.17.0")]
403 pub struct RangeMut<'a, K: 'a, V: 'a> {
404 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
405 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
407 // Be invariant in `K` and `V`
408 _marker: PhantomData<&'a mut (K, V)>,
411 #[stable(feature = "collection_debug", since = "1.17.0")]
412 impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for RangeMut<'a, K, V> {
413 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 front: self.front.reborrow(),
416 back: self.back.reborrow(),
418 f.debug_list().entries(range).finish()
422 /// A view into a single entry in a map, which may either be vacant or occupied.
423 /// This enum is constructed from the [`entry`] method on [`BTreeMap`].
425 /// [`BTreeMap`]: struct.BTreeMap.html
426 /// [`entry`]: struct.BTreeMap.html#method.entry
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub enum Entry<'a, K: 'a, V: 'a> {
430 #[stable(feature = "rust1", since = "1.0.0")]
431 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
432 VacantEntry<'a, K, V>),
434 /// An occupied `Entry`
435 #[stable(feature = "rust1", since = "1.0.0")]
436 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
437 OccupiedEntry<'a, K, V>),
440 #[stable(feature= "debug_btree_map", since = "1.12.0")]
441 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for Entry<'a, K, V> {
442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
444 Vacant(ref v) => f.debug_tuple("Entry")
447 Occupied(ref o) => f.debug_tuple("Entry")
454 /// A vacant `Entry`. It is part of the [`Entry`] enum.
456 /// [`Entry`]: enum.Entry.html
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub struct VacantEntry<'a, K: 'a, V: 'a> {
460 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
461 length: &'a mut usize,
463 // Be invariant in `K` and `V`
464 _marker: PhantomData<&'a mut (K, V)>,
467 #[stable(feature= "debug_btree_map", since = "1.12.0")]
468 impl<'a, K: 'a + Debug + Ord, V: 'a> Debug for VacantEntry<'a, K, V> {
469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
470 f.debug_tuple("VacantEntry")
476 /// An occupied `Entry`. It is part of the [`Entry`] enum.
478 /// [`Entry`]: enum.Entry.html
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
481 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
483 length: &'a mut usize,
485 // Be invariant in `K` and `V`
486 _marker: PhantomData<&'a mut (K, V)>,
489 #[stable(feature= "debug_btree_map", since = "1.12.0")]
490 impl<'a, K: 'a + Debug + Ord, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> {
491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492 f.debug_struct("OccupiedEntry")
493 .field("key", self.key())
494 .field("value", self.get())
499 // An iterator for merging two sorted sequences into one
500 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
505 impl<K: Ord, V> BTreeMap<K, V> {
506 /// Makes a new empty BTreeMap with a reasonable choice for B.
513 /// use std::collections::BTreeMap;
515 /// let mut map = BTreeMap::new();
517 /// // entries can now be inserted into the empty map
518 /// map.insert(1, "a");
520 #[stable(feature = "rust1", since = "1.0.0")]
521 pub fn new() -> BTreeMap<K, V> {
523 root: node::Root::new_leaf(),
528 /// Clears the map, removing all values.
535 /// use std::collections::BTreeMap;
537 /// let mut a = BTreeMap::new();
538 /// a.insert(1, "a");
540 /// assert!(a.is_empty());
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn clear(&mut self) {
544 // FIXME(gereeter) .clear() allocates
545 *self = BTreeMap::new();
548 /// Returns a reference to the value corresponding to the key.
550 /// The key may be any borrowed form of the map's key type, but the ordering
551 /// on the borrowed form *must* match the ordering on the key type.
558 /// use std::collections::BTreeMap;
560 /// let mut map = BTreeMap::new();
561 /// map.insert(1, "a");
562 /// assert_eq!(map.get(&1), Some(&"a"));
563 /// assert_eq!(map.get(&2), None);
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
570 match search::search_tree(self.root.as_ref(), key) {
571 Found(handle) => Some(handle.into_kv().1),
576 /// Returns `true` if the map contains a value for the specified key.
578 /// The key may be any borrowed form of the map's key type, but the ordering
579 /// on the borrowed form *must* match the ordering on the key type.
586 /// use std::collections::BTreeMap;
588 /// let mut map = BTreeMap::new();
589 /// map.insert(1, "a");
590 /// assert_eq!(map.contains_key(&1), true);
591 /// assert_eq!(map.contains_key(&2), false);
593 #[stable(feature = "rust1", since = "1.0.0")]
594 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
598 self.get(key).is_some()
601 /// Returns a mutable reference to the value corresponding to the key.
603 /// The key may be any borrowed form of the map's key type, but the ordering
604 /// on the borrowed form *must* match the ordering on the key type.
611 /// use std::collections::BTreeMap;
613 /// let mut map = BTreeMap::new();
614 /// map.insert(1, "a");
615 /// if let Some(x) = map.get_mut(&1) {
618 /// assert_eq!(map[&1], "b");
620 // See `get` for implementation notes, this is basically a copy-paste with mut's added
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
626 match search::search_tree(self.root.as_mut(), key) {
627 Found(handle) => Some(handle.into_kv_mut().1),
632 /// Inserts a key-value pair into the map.
634 /// If the map did not have this key present, `None` is returned.
636 /// If the map did have this key present, the value is updated, and the old
637 /// value is returned. The key is not updated, though; this matters for
638 /// types that can be `==` without being identical. See the [module-level
639 /// documentation] for more.
641 /// [module-level documentation]: index.html#insert-and-complex-keys
648 /// use std::collections::BTreeMap;
650 /// let mut map = BTreeMap::new();
651 /// assert_eq!(map.insert(37, "a"), None);
652 /// assert_eq!(map.is_empty(), false);
654 /// map.insert(37, "b");
655 /// assert_eq!(map.insert(37, "c"), Some("b"));
656 /// assert_eq!(map[&37], "c");
658 #[stable(feature = "rust1", since = "1.0.0")]
659 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
660 match self.entry(key) {
661 Occupied(mut entry) => Some(entry.insert(value)),
669 /// Removes a key from the map, returning the value at the key if the key
670 /// was previously in the map.
672 /// The key may be any borrowed form of the map's key type, but the ordering
673 /// on the borrowed form *must* match the ordering on the key type.
680 /// use std::collections::BTreeMap;
682 /// let mut map = BTreeMap::new();
683 /// map.insert(1, "a");
684 /// assert_eq!(map.remove(&1), Some("a"));
685 /// assert_eq!(map.remove(&1), None);
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
692 match search::search_tree(self.root.as_mut(), key) {
696 length: &mut self.length,
697 _marker: PhantomData,
705 /// Moves all elements from `other` into `Self`, leaving `other` empty.
710 /// use std::collections::BTreeMap;
712 /// let mut a = BTreeMap::new();
713 /// a.insert(1, "a");
714 /// a.insert(2, "b");
715 /// a.insert(3, "c");
717 /// let mut b = BTreeMap::new();
718 /// b.insert(3, "d");
719 /// b.insert(4, "e");
720 /// b.insert(5, "f");
722 /// a.append(&mut b);
724 /// assert_eq!(a.len(), 5);
725 /// assert_eq!(b.len(), 0);
727 /// assert_eq!(a[&1], "a");
728 /// assert_eq!(a[&2], "b");
729 /// assert_eq!(a[&3], "d");
730 /// assert_eq!(a[&4], "e");
731 /// assert_eq!(a[&5], "f");
733 #[stable(feature = "btree_append", since = "1.11.0")]
734 pub fn append(&mut self, other: &mut Self) {
735 // Do we have to append anything at all?
736 if other.len() == 0 {
740 // We can just swap `self` and `other` if `self` is empty.
742 mem::swap(self, other);
746 // First, we merge `self` and `other` into a sorted sequence in linear time.
747 let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
748 let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
749 let iter = MergeIter {
750 left: self_iter.peekable(),
751 right: other_iter.peekable(),
754 // Second, we build a tree from the sorted sequence in linear time.
755 self.from_sorted_iter(iter);
756 self.fix_right_edge();
759 /// Constructs a double-ended iterator over a sub-range of elements in the map.
760 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
761 /// yield elements from min (inclusive) to max (exclusive).
762 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
763 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
764 /// range from 4 to 10.
768 /// Panics if range `start > end`.
769 /// Panics if range `start == end` and both bounds are `Excluded`.
776 /// use std::collections::BTreeMap;
777 /// use std::collections::Bound::Included;
779 /// let mut map = BTreeMap::new();
780 /// map.insert(3, "a");
781 /// map.insert(5, "b");
782 /// map.insert(8, "c");
783 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
784 /// println!("{}: {}", key, value);
786 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
788 #[stable(feature = "btree_range", since = "1.17.0")]
789 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<K, V>
790 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
792 let root1 = self.root.as_ref();
793 let root2 = self.root.as_ref();
794 let (f, b) = range_search(root1, root2, range);
796 Range { front: f, back: b}
799 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
800 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
801 /// yield elements from min (inclusive) to max (exclusive).
802 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
803 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
804 /// range from 4 to 10.
808 /// Panics if range `start > end`.
809 /// Panics if range `start == end` and both bounds are `Excluded`.
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 #[stable(feature = "btree_range", since = "1.17.0")]
829 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<K, V>
830 where T: Ord, K: Borrow<T>, R: RangeArgument<T>
832 let root1 = self.root.as_mut();
833 let root2 = unsafe { ptr::read(&root1) };
834 let (f, b) = range_search(root1, root2, range);
839 _marker: PhantomData,
843 /// Gets the given key's corresponding entry in the map for in-place manipulation.
850 /// use std::collections::BTreeMap;
852 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
854 /// // count the number of occurrences of letters in the vec
855 /// for x in vec!["a","b","a","c","a","b"] {
856 /// *count.entry(x).or_insert(0) += 1;
859 /// assert_eq!(count["a"], 3);
861 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn entry(&mut self, key: K) -> Entry<K, V> {
863 match search::search_tree(self.root.as_mut(), &key) {
865 Occupied(OccupiedEntry {
867 length: &mut self.length,
868 _marker: PhantomData,
875 length: &mut self.length,
876 _marker: PhantomData,
882 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
883 let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
884 // Iterate through all key-value pairs, pushing them into nodes at the right level.
885 for (key, value) in iter {
886 // Try to push key-value pair into the current leaf node.
887 if cur_node.len() < node::CAPACITY {
888 cur_node.push(key, value);
890 // No space left, go up and push there.
892 let mut test_node = cur_node.forget_type();
894 match test_node.ascend() {
896 let parent = parent.into_node();
897 if parent.len() < node::CAPACITY {
898 // Found a node with space left, push here.
903 test_node = parent.forget_type();
907 // We are at the top, create a new root node and push there.
908 open_node = node.into_root_mut().push_level();
914 // Push key-value pair and new right subtree.
915 let tree_height = open_node.height() - 1;
916 let mut right_tree = node::Root::new_leaf();
917 for _ in 0..tree_height {
918 right_tree.push_level();
920 open_node.push(key, value, right_tree);
922 // Go down to the right-most leaf again.
923 cur_node = last_leaf_edge(open_node.forget_type()).into_node();
930 fn fix_right_edge(&mut self) {
931 // Handle underfull nodes, start from the top.
932 let mut cur_node = self.root.as_mut();
933 while let Internal(internal) = cur_node.force() {
934 // Check if right-most child is underfull.
935 let mut last_edge = internal.last_edge();
936 let right_child_len = last_edge.reborrow().descend().len();
937 if right_child_len < node::MIN_LEN {
939 let mut last_kv = match last_edge.left_kv() {
941 Err(_) => unreachable!(),
943 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
944 last_edge = last_kv.right_edge();
948 cur_node = last_edge.descend();
952 /// Splits the collection into two at the given key. Returns everything after the given key,
953 /// including the key.
960 /// use std::collections::BTreeMap;
962 /// let mut a = BTreeMap::new();
963 /// a.insert(1, "a");
964 /// a.insert(2, "b");
965 /// a.insert(3, "c");
966 /// a.insert(17, "d");
967 /// a.insert(41, "e");
969 /// let b = a.split_off(&3);
971 /// assert_eq!(a.len(), 2);
972 /// assert_eq!(b.len(), 3);
974 /// assert_eq!(a[&1], "a");
975 /// assert_eq!(a[&2], "b");
977 /// assert_eq!(b[&3], "c");
978 /// assert_eq!(b[&17], "d");
979 /// assert_eq!(b[&41], "e");
981 #[stable(feature = "btree_split_off", since = "1.11.0")]
982 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
989 let total_num = self.len();
991 let mut right = Self::new();
992 for _ in 0..(self.root.as_ref().height()) {
993 right.root.push_level();
997 let mut left_node = self.root.as_mut();
998 let mut right_node = right.root.as_mut();
1001 let mut split_edge = match search::search_node(left_node, key) {
1002 // key is going to the right tree
1003 Found(handle) => handle.left_edge(),
1004 GoDown(handle) => handle,
1007 split_edge.move_suffix(&mut right_node);
1009 match (split_edge.force(), right_node.force()) {
1010 (Internal(edge), Internal(node)) => {
1011 left_node = edge.descend();
1012 right_node = node.first_edge().descend();
1014 (Leaf(_), Leaf(_)) => {
1024 self.fix_right_border();
1025 right.fix_left_border();
1027 if self.root.as_ref().height() < right.root.as_ref().height() {
1028 self.recalc_length();
1029 right.length = total_num - self.len();
1031 right.recalc_length();
1032 self.length = total_num - right.len();
1038 /// Calculates the number of elements if it is incorrect.
1039 fn recalc_length(&mut self) {
1040 fn dfs<K, V>(node: NodeRef<marker::Immut, K, V, marker::LeafOrInternal>) -> usize {
1041 let mut res = node.len();
1043 if let Internal(node) = node.force() {
1044 let mut edge = node.first_edge();
1046 res += dfs(edge.reborrow().descend());
1047 match edge.right_kv() {
1049 edge = right_kv.right_edge();
1061 self.length = dfs(self.root.as_ref());
1064 /// Removes empty levels on the top.
1065 fn fix_top(&mut self) {
1068 let node = self.root.as_ref();
1069 if node.height() == 0 || node.len() > 0 {
1073 self.root.pop_level();
1077 fn fix_right_border(&mut self) {
1081 let mut cur_node = self.root.as_mut();
1083 while let Internal(node) = cur_node.force() {
1084 let mut last_kv = node.last_kv();
1086 if last_kv.can_merge() {
1087 cur_node = last_kv.merge().descend();
1089 let right_len = last_kv.reborrow().right_edge().descend().len();
1090 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1091 if right_len < node::MIN_LEN + 1 {
1092 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1094 cur_node = last_kv.right_edge().descend();
1102 /// The symmetric clone of `fix_right_border`.
1103 fn fix_left_border(&mut self) {
1107 let mut cur_node = self.root.as_mut();
1109 while let Internal(node) = cur_node.force() {
1110 let mut first_kv = node.first_kv();
1112 if first_kv.can_merge() {
1113 cur_node = first_kv.merge().descend();
1115 let left_len = first_kv.reborrow().left_edge().descend().len();
1116 if left_len < node::MIN_LEN + 1 {
1117 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1119 cur_node = first_kv.left_edge().descend();
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1130 type Item = (&'a K, &'a V);
1131 type IntoIter = Iter<'a, K, V>;
1133 fn into_iter(self) -> Iter<'a, K, V> {
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1140 type Item = (&'a K, &'a V);
1142 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1143 if self.length == 0 {
1147 unsafe { Some(self.range.next_unchecked()) }
1151 fn size_hint(&self) -> (usize, Option<usize>) {
1152 (self.length, Some(self.length))
1156 #[unstable(feature = "fused", issue = "35602")]
1157 impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1161 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1162 if self.length == 0 {
1166 unsafe { Some(self.range.next_back_unchecked()) }
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<'a, K: 'a, V: 'a> ExactSizeIterator for Iter<'a, K, V> {
1173 fn len(&self) -> usize {
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<'a, K, V> Clone for Iter<'a, K, V> {
1180 fn clone(&self) -> Iter<'a, K, V> {
1182 range: self.range.clone(),
1183 length: self.length,
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1190 type Item = (&'a K, &'a mut V);
1191 type IntoIter = IterMut<'a, K, V>;
1193 fn into_iter(self) -> IterMut<'a, K, V> {
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1200 type Item = (&'a K, &'a mut V);
1202 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1203 if self.length == 0 {
1207 unsafe { Some(self.range.next_unchecked()) }
1211 fn size_hint(&self) -> (usize, Option<usize>) {
1212 (self.length, Some(self.length))
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1218 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1219 if self.length == 0 {
1223 unsafe { Some(self.range.next_back_unchecked()) }
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<'a, K: 'a, V: 'a> ExactSizeIterator for IterMut<'a, K, V> {
1230 fn len(&self) -> usize {
1235 #[unstable(feature = "fused", issue = "35602")]
1236 impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<K, V> IntoIterator for BTreeMap<K, V> {
1241 type IntoIter = IntoIter<K, V>;
1243 fn into_iter(self) -> IntoIter<K, V> {
1244 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1245 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1246 let len = self.length;
1250 front: first_leaf_edge(root1),
1251 back: last_leaf_edge(root2),
1257 #[stable(feature = "btree_drop", since = "1.7.0")]
1258 impl<K, V> Drop for IntoIter<K, V> {
1259 fn drop(&mut self) {
1260 for _ in &mut *self {
1263 let leaf_node = ptr::read(&self.front).into_node();
1264 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1265 let mut cur_node = first_parent.into_node();
1266 while let Some(parent) = cur_node.deallocate_and_ascend() {
1267 cur_node = parent.into_node()
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl<K, V> Iterator for IntoIter<K, V> {
1278 fn next(&mut self) -> Option<(K, V)> {
1279 if self.length == 0 {
1285 let handle = unsafe { ptr::read(&self.front) };
1287 let mut cur_handle = match handle.right_kv() {
1289 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1290 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1291 self.front = kv.right_edge();
1292 return Some((k, v));
1294 Err(last_edge) => unsafe {
1295 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1300 match cur_handle.right_kv() {
1302 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1303 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1304 self.front = first_leaf_edge(kv.right_edge().descend());
1305 return Some((k, v));
1307 Err(last_edge) => unsafe {
1308 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1314 fn size_hint(&self) -> (usize, Option<usize>) {
1315 (self.length, Some(self.length))
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1321 fn next_back(&mut self) -> Option<(K, V)> {
1322 if self.length == 0 {
1328 let handle = unsafe { ptr::read(&self.back) };
1330 let mut cur_handle = match handle.left_kv() {
1332 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1333 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1334 self.back = kv.left_edge();
1335 return Some((k, v));
1337 Err(last_edge) => unsafe {
1338 unwrap_unchecked(last_edge.into_node().deallocate_and_ascend())
1343 match cur_handle.left_kv() {
1345 let k = unsafe { ptr::read(kv.reborrow().into_kv().0) };
1346 let v = unsafe { ptr::read(kv.reborrow().into_kv().1) };
1347 self.back = last_leaf_edge(kv.left_edge().descend());
1348 return Some((k, v));
1350 Err(last_edge) => unsafe {
1351 cur_handle = unwrap_unchecked(last_edge.into_node().deallocate_and_ascend());
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1360 fn len(&self) -> usize {
1365 #[unstable(feature = "fused", issue = "35602")]
1366 impl<K, V> FusedIterator for IntoIter<K, V> {}
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1372 fn next(&mut self) -> Option<&'a K> {
1373 self.inner.next().map(|(k, _)| k)
1376 fn size_hint(&self) -> (usize, Option<usize>) {
1377 self.inner.size_hint()
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1383 fn next_back(&mut self) -> Option<&'a K> {
1384 self.inner.next_back().map(|(k, _)| k)
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1390 fn len(&self) -> usize {
1395 #[unstable(feature = "fused", issue = "35602")]
1396 impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<'a, K, V> Clone for Keys<'a, K, V> {
1400 fn clone(&self) -> Keys<'a, K, V> {
1401 Keys { inner: self.inner.clone() }
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl<'a, K, V> Iterator for Values<'a, K, V> {
1409 fn next(&mut self) -> Option<&'a V> {
1410 self.inner.next().map(|(_, v)| v)
1413 fn size_hint(&self) -> (usize, Option<usize>) {
1414 self.inner.size_hint()
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1420 fn next_back(&mut self) -> Option<&'a V> {
1421 self.inner.next_back().map(|(_, v)| v)
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1427 fn len(&self) -> usize {
1432 #[unstable(feature = "fused", issue = "35602")]
1433 impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl<'a, K, V> Clone for Values<'a, K, V> {
1437 fn clone(&self) -> Values<'a, K, V> {
1438 Values { inner: self.inner.clone() }
1442 impl<'a, K, V> Iterator for Range<'a, K, V> {
1443 type Item = (&'a K, &'a V);
1445 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1446 if self.front == self.back {
1449 unsafe { Some(self.next_unchecked()) }
1454 #[stable(feature = "map_values_mut", since = "1.10.0")]
1455 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1456 type Item = &'a mut V;
1458 fn next(&mut self) -> Option<&'a mut V> {
1459 self.inner.next().map(|(_, v)| v)
1462 fn size_hint(&self) -> (usize, Option<usize>) {
1463 self.inner.size_hint()
1467 #[stable(feature = "map_values_mut", since = "1.10.0")]
1468 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1469 fn next_back(&mut self) -> Option<&'a mut V> {
1470 self.inner.next_back().map(|(_, v)| v)
1474 #[stable(feature = "map_values_mut", since = "1.10.0")]
1475 impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1476 fn len(&self) -> usize {
1481 #[unstable(feature = "fused", issue = "35602")]
1482 impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1485 impl<'a, K, V> Range<'a, K, V> {
1486 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1487 let handle = self.front;
1489 let mut cur_handle = match handle.right_kv() {
1491 let ret = kv.into_kv();
1492 self.front = kv.right_edge();
1496 let next_level = last_edge.into_node().ascend().ok();
1497 unwrap_unchecked(next_level)
1502 match cur_handle.right_kv() {
1504 let ret = kv.into_kv();
1505 self.front = first_leaf_edge(kv.right_edge().descend());
1509 let next_level = last_edge.into_node().ascend().ok();
1510 cur_handle = unwrap_unchecked(next_level);
1517 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1518 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1519 if self.front == self.back {
1522 unsafe { Some(self.next_back_unchecked()) }
1527 impl<'a, K, V> Range<'a, K, V> {
1528 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1529 let handle = self.back;
1531 let mut cur_handle = match handle.left_kv() {
1533 let ret = kv.into_kv();
1534 self.back = kv.left_edge();
1538 let next_level = last_edge.into_node().ascend().ok();
1539 unwrap_unchecked(next_level)
1544 match cur_handle.left_kv() {
1546 let ret = kv.into_kv();
1547 self.back = last_leaf_edge(kv.left_edge().descend());
1551 let next_level = last_edge.into_node().ascend().ok();
1552 cur_handle = unwrap_unchecked(next_level);
1559 #[unstable(feature = "fused", issue = "35602")]
1560 impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
1562 impl<'a, K, V> Clone for Range<'a, K, V> {
1563 fn clone(&self) -> Range<'a, K, V> {
1571 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1572 type Item = (&'a K, &'a mut V);
1574 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1575 if self.front == self.back {
1578 unsafe { Some(self.next_unchecked()) }
1583 impl<'a, K, V> RangeMut<'a, K, V> {
1584 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1585 let handle = ptr::read(&self.front);
1587 let mut cur_handle = match handle.right_kv() {
1589 let (k, v) = ptr::read(&kv).into_kv_mut();
1590 self.front = kv.right_edge();
1594 let next_level = last_edge.into_node().ascend().ok();
1595 unwrap_unchecked(next_level)
1600 match cur_handle.right_kv() {
1602 let (k, v) = ptr::read(&kv).into_kv_mut();
1603 self.front = first_leaf_edge(kv.right_edge().descend());
1607 let next_level = last_edge.into_node().ascend().ok();
1608 cur_handle = unwrap_unchecked(next_level);
1615 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1616 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1617 if self.front == self.back {
1620 unsafe { Some(self.next_back_unchecked()) }
1625 #[unstable(feature = "fused", issue = "35602")]
1626 impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1628 impl<'a, K, V> RangeMut<'a, K, V> {
1629 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1630 let handle = ptr::read(&self.back);
1632 let mut cur_handle = match handle.left_kv() {
1634 let (k, v) = ptr::read(&kv).into_kv_mut();
1635 self.back = kv.left_edge();
1639 let next_level = last_edge.into_node().ascend().ok();
1640 unwrap_unchecked(next_level)
1645 match cur_handle.left_kv() {
1647 let (k, v) = ptr::read(&kv).into_kv_mut();
1648 self.back = last_leaf_edge(kv.left_edge().descend());
1652 let next_level = last_edge.into_node().ascend().ok();
1653 cur_handle = unwrap_unchecked(next_level);
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1662 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1663 let mut map = BTreeMap::new();
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1672 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1673 for (k, v) in iter {
1679 #[stable(feature = "extend_ref", since = "1.2.0")]
1680 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1681 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1682 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1688 fn hash<H: Hasher>(&self, state: &mut H) {
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<K: Ord, V> Default for BTreeMap<K, V> {
1697 /// Creates an empty `BTreeMap<K, V>`.
1698 fn default() -> BTreeMap<K, V> {
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1705 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1706 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1716 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1717 self.iter().partial_cmp(other.iter())
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1724 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1725 self.iter().cmp(other.iter())
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1732 f.debug_map().entries(self.iter()).finish()
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
1744 fn index(&self, key: &Q) -> &V {
1745 self.get(key).expect("no entry found for key")
1749 fn first_leaf_edge<BorrowType, K, V>
1750 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1751 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1753 match node.force() {
1754 Leaf(leaf) => return leaf.first_edge(),
1755 Internal(internal) => {
1756 node = internal.first_edge().descend();
1762 fn last_leaf_edge<BorrowType, K, V>
1763 (mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>)
1764 -> Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge> {
1766 match node.force() {
1767 Leaf(leaf) => return leaf.last_edge(),
1768 Internal(internal) => {
1769 node = internal.last_edge().descend();
1775 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeArgument<Q>>(
1776 root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1777 root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1779 )-> (Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1780 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>)
1781 where Q: Ord, K: Borrow<Q>
1783 match (range.start(), range.end()) {
1784 (Excluded(s), Excluded(e)) if s==e =>
1785 panic!("range start and end are equal and excluded in BTreeMap"),
1786 (Included(s), Included(e)) |
1787 (Included(s), Excluded(e)) |
1788 (Excluded(s), Included(e)) |
1789 (Excluded(s), Excluded(e)) if s>e =>
1790 panic!("range start is greater than range end in BTreeMap"),
1794 let mut min_node = root1;
1795 let mut max_node = root2;
1796 let mut min_found = false;
1797 let mut max_found = false;
1798 let mut diverged = false;
1801 let min_edge = match (min_found, range.start()) {
1802 (false, Included(key)) => match search::search_linear(&min_node, key) {
1803 (i, true) => { min_found = true; i },
1806 (false, Excluded(key)) => match search::search_linear(&min_node, key) {
1807 (i, true) => { min_found = true; i+1 },
1810 (_, Unbounded) => 0,
1811 (true, Included(_)) => min_node.keys().len(),
1812 (true, Excluded(_)) => 0,
1815 let max_edge = match (max_found, range.end()) {
1816 (false, Included(key)) => match search::search_linear(&max_node, key) {
1817 (i, true) => { max_found = true; i+1 },
1820 (false, Excluded(key)) => match search::search_linear(&max_node, key) {
1821 (i, true) => { max_found = true; i },
1824 (_, Unbounded) => max_node.keys().len(),
1825 (true, Included(_)) => 0,
1826 (true, Excluded(_)) => max_node.keys().len(),
1830 if max_edge < min_edge { panic!("Ord is ill-defined in BTreeMap range") }
1831 if min_edge != max_edge { diverged = true; }
1834 let front = Handle::new_edge(min_node, min_edge);
1835 let back = Handle::new_edge(max_node, max_edge);
1836 match (front.force(), back.force()) {
1837 (Leaf(f), Leaf(b)) => {
1840 (Internal(min_int), Internal(max_int)) => {
1841 min_node = min_int.descend();
1842 max_node = max_int.descend();
1844 _ => unreachable!("BTreeMap has different depths"),
1850 unsafe fn unwrap_unchecked<T>(val: Option<T>) -> T {
1851 val.unwrap_or_else(|| {
1852 if cfg!(debug_assertions) {
1853 panic!("'unchecked' unwrap on None in BTreeMap");
1855 intrinsics::unreachable();
1860 impl<K, V> BTreeMap<K, V> {
1861 /// Gets an iterator over the entries of the map, sorted by key.
1868 /// use std::collections::BTreeMap;
1870 /// let mut map = BTreeMap::new();
1871 /// map.insert(3, "c");
1872 /// map.insert(2, "b");
1873 /// map.insert(1, "a");
1875 /// for (key, value) in map.iter() {
1876 /// println!("{}: {}", key, value);
1879 /// let (first_key, first_value) = map.iter().next().unwrap();
1880 /// assert_eq!((*first_key, *first_value), (1, "a"));
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn iter(&self) -> Iter<K, V> {
1886 front: first_leaf_edge(self.root.as_ref()),
1887 back: last_leaf_edge(self.root.as_ref()),
1889 length: self.length,
1893 /// Gets a mutable iterator over the entries of the map, sorted by key.
1900 /// use std::collections::BTreeMap;
1902 /// let mut map = BTreeMap::new();
1903 /// map.insert("a", 1);
1904 /// map.insert("b", 2);
1905 /// map.insert("c", 3);
1907 /// // add 10 to the value if the key isn't "a"
1908 /// for (key, value) in map.iter_mut() {
1909 /// if key != &"a" {
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 pub fn iter_mut(&mut self) -> IterMut<K, V> {
1916 let root1 = self.root.as_mut();
1917 let root2 = unsafe { ptr::read(&root1) };
1920 front: first_leaf_edge(root1),
1921 back: last_leaf_edge(root2),
1922 _marker: PhantomData,
1924 length: self.length,
1928 /// Gets an iterator over the keys of the map, in sorted order.
1935 /// use std::collections::BTreeMap;
1937 /// let mut a = BTreeMap::new();
1938 /// a.insert(2, "b");
1939 /// a.insert(1, "a");
1941 /// let keys: Vec<_> = a.keys().cloned().collect();
1942 /// assert_eq!(keys, [1, 2]);
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
1946 Keys { inner: self.iter() }
1949 /// Gets an iterator over the values of the map, in order by key.
1956 /// use std::collections::BTreeMap;
1958 /// let mut a = BTreeMap::new();
1959 /// a.insert(1, "hello");
1960 /// a.insert(2, "goodbye");
1962 /// let values: Vec<&str> = a.values().cloned().collect();
1963 /// assert_eq!(values, ["hello", "goodbye"]);
1965 #[stable(feature = "rust1", since = "1.0.0")]
1966 pub fn values<'a>(&'a self) -> Values<'a, K, V> {
1967 Values { inner: self.iter() }
1970 /// Gets a mutable iterator over the values of the map, in order by key.
1977 /// use std::collections::BTreeMap;
1979 /// let mut a = BTreeMap::new();
1980 /// a.insert(1, String::from("hello"));
1981 /// a.insert(2, String::from("goodbye"));
1983 /// for value in a.values_mut() {
1984 /// value.push_str("!");
1987 /// let values: Vec<String> = a.values().cloned().collect();
1988 /// assert_eq!(values, [String::from("hello!"),
1989 /// String::from("goodbye!")]);
1991 #[stable(feature = "map_values_mut", since = "1.10.0")]
1992 pub fn values_mut(&mut self) -> ValuesMut<K, V> {
1993 ValuesMut { inner: self.iter_mut() }
1996 /// Returns the number of elements in the map.
2003 /// use std::collections::BTreeMap;
2005 /// let mut a = BTreeMap::new();
2006 /// assert_eq!(a.len(), 0);
2007 /// a.insert(1, "a");
2008 /// assert_eq!(a.len(), 1);
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 pub fn len(&self) -> usize {
2015 /// Returns `true` if the map contains no elements.
2022 /// use std::collections::BTreeMap;
2024 /// let mut a = BTreeMap::new();
2025 /// assert!(a.is_empty());
2026 /// a.insert(1, "a");
2027 /// assert!(!a.is_empty());
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 pub fn is_empty(&self) -> bool {
2035 impl<'a, K: Ord, V> Entry<'a, K, V> {
2036 /// Ensures a value is in the entry by inserting the default if empty, and returns
2037 /// a mutable reference to the value in the entry.
2042 /// use std::collections::BTreeMap;
2044 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2045 /// map.entry("poneyland").or_insert(12);
2047 /// assert_eq!(map["poneyland"], 12);
2049 #[stable(feature = "rust1", since = "1.0.0")]
2050 pub fn or_insert(self, default: V) -> &'a mut V {
2052 Occupied(entry) => entry.into_mut(),
2053 Vacant(entry) => entry.insert(default),
2057 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2058 /// and returns a mutable reference to the value in the entry.
2063 /// use std::collections::BTreeMap;
2065 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2066 /// let s = "hoho".to_string();
2068 /// map.entry("poneyland").or_insert_with(|| s);
2070 /// assert_eq!(map["poneyland"], "hoho".to_string());
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2075 Occupied(entry) => entry.into_mut(),
2076 Vacant(entry) => entry.insert(default()),
2080 /// Returns a reference to this entry's key.
2085 /// use std::collections::BTreeMap;
2087 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2088 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2090 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2091 pub fn key(&self) -> &K {
2093 Occupied(ref entry) => entry.key(),
2094 Vacant(ref entry) => entry.key(),
2099 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2100 /// Gets a reference to the key that would be used when inserting a value
2101 /// through the VacantEntry.
2106 /// use std::collections::BTreeMap;
2108 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2109 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2111 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2112 pub fn key(&self) -> &K {
2116 /// Take ownership of the key.
2121 /// use std::collections::BTreeMap;
2122 /// use std::collections::btree_map::Entry;
2124 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2126 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2130 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2131 pub fn into_key(self) -> K {
2135 /// Sets the value of the entry with the `VacantEntry`'s key,
2136 /// and returns a mutable reference to it.
2141 /// use std::collections::BTreeMap;
2143 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2145 /// // count the number of occurrences of letters in the vec
2146 /// for x in vec!["a","b","a","c","a","b"] {
2147 /// *count.entry(x).or_insert(0) += 1;
2150 /// assert_eq!(count["a"], 3);
2152 #[stable(feature = "rust1", since = "1.0.0")]
2153 pub fn insert(self, value: V) -> &'a mut V {
2162 let mut cur_parent = match self.handle.insert(self.key, value) {
2163 (Fit(handle), _) => return handle.into_kv_mut().1,
2164 (Split(left, k, v, right), ptr) => {
2169 left.ascend().map_err(|n| n.into_root_mut())
2176 match parent.insert(ins_k, ins_v, ins_edge) {
2177 Fit(_) => return unsafe { &mut *out_ptr },
2178 Split(left, k, v, right) => {
2182 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2187 root.push_level().push(ins_k, ins_v, ins_edge);
2188 return unsafe { &mut *out_ptr };
2195 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2196 /// Gets a reference to the key in the entry.
2201 /// use std::collections::BTreeMap;
2203 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2204 /// map.entry("poneyland").or_insert(12);
2205 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2207 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2208 pub fn key(&self) -> &K {
2209 self.handle.reborrow().into_kv().0
2212 /// Deprecated, renamed to `remove_entry`
2213 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2214 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2215 pub fn remove_pair(self) -> (K, V) {
2219 /// Take ownership of the key and value from the map.
2224 /// use std::collections::BTreeMap;
2225 /// use std::collections::btree_map::Entry;
2227 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2228 /// map.entry("poneyland").or_insert(12);
2230 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2231 /// // We delete the entry from the map.
2232 /// o.remove_entry();
2235 /// // If now try to get the value, it will panic:
2236 /// // println!("{}", map["poneyland"]);
2238 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2239 pub fn remove_entry(self) -> (K, V) {
2243 /// Gets a reference to the value in the entry.
2248 /// use std::collections::BTreeMap;
2249 /// use std::collections::btree_map::Entry;
2251 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2252 /// map.entry("poneyland").or_insert(12);
2254 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2255 /// assert_eq!(o.get(), &12);
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 pub fn get(&self) -> &V {
2260 self.handle.reborrow().into_kv().1
2263 /// Gets a mutable reference to the value in the entry.
2268 /// use std::collections::BTreeMap;
2269 /// use std::collections::btree_map::Entry;
2271 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2272 /// map.entry("poneyland").or_insert(12);
2274 /// assert_eq!(map["poneyland"], 12);
2275 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2276 /// *o.get_mut() += 10;
2278 /// assert_eq!(map["poneyland"], 22);
2280 #[stable(feature = "rust1", since = "1.0.0")]
2281 pub fn get_mut(&mut self) -> &mut V {
2282 self.handle.kv_mut().1
2285 /// Converts the entry into a mutable reference to its value.
2290 /// use std::collections::BTreeMap;
2291 /// use std::collections::btree_map::Entry;
2293 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2294 /// map.entry("poneyland").or_insert(12);
2296 /// assert_eq!(map["poneyland"], 12);
2297 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2298 /// *o.into_mut() += 10;
2300 /// assert_eq!(map["poneyland"], 22);
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 pub fn into_mut(self) -> &'a mut V {
2304 self.handle.into_kv_mut().1
2307 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2308 /// and returns the entry's old value.
2313 /// use std::collections::BTreeMap;
2314 /// use std::collections::btree_map::Entry;
2316 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2317 /// map.entry("poneyland").or_insert(12);
2319 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2320 /// assert_eq!(o.insert(15), 12);
2322 /// assert_eq!(map["poneyland"], 15);
2324 #[stable(feature = "rust1", since = "1.0.0")]
2325 pub fn insert(&mut self, value: V) -> V {
2326 mem::replace(self.get_mut(), value)
2329 /// Takes the value of the entry out of the map, and returns it.
2334 /// use std::collections::BTreeMap;
2335 /// use std::collections::btree_map::Entry;
2337 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2338 /// map.entry("poneyland").or_insert(12);
2340 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2341 /// assert_eq!(o.remove(), 12);
2343 /// // If we try to get "poneyland"'s value, it'll panic:
2344 /// // println!("{}", map["poneyland"]);
2346 #[stable(feature = "rust1", since = "1.0.0")]
2347 pub fn remove(self) -> V {
2351 fn remove_kv(self) -> (K, V) {
2354 let (small_leaf, old_key, old_val) = match self.handle.force() {
2356 let (hole, old_key, old_val) = leaf.remove();
2357 (hole.into_node(), old_key, old_val)
2359 Internal(mut internal) => {
2360 let key_loc = internal.kv_mut().0 as *mut K;
2361 let val_loc = internal.kv_mut().1 as *mut V;
2363 let to_remove = first_leaf_edge(internal.right_edge().descend()).right_kv().ok();
2364 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2366 let (hole, key, val) = to_remove.remove();
2368 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2369 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2371 (hole.into_node(), old_key, old_val)
2376 let mut cur_node = small_leaf.forget_type();
2377 while cur_node.len() < node::CAPACITY / 2 {
2378 match handle_underfull_node(cur_node) {
2380 EmptyParent(_) => unreachable!(),
2382 if parent.len() == 0 {
2383 // We must be at the root
2384 parent.into_root_mut().pop_level();
2387 cur_node = parent.forget_type();
2398 enum UnderflowResult<'a, K, V> {
2400 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2401 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2402 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2405 fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>)
2406 -> UnderflowResult<'a, K, V> {
2407 let parent = if let Ok(parent) = node.ascend() {
2413 let (is_left, mut handle) = match parent.left_kv() {
2414 Ok(left) => (true, left),
2416 match parent.right_kv() {
2417 Ok(right) => (false, right),
2419 return EmptyParent(parent.into_node());
2425 if handle.can_merge() {
2426 Merged(handle.merge().into_node())
2429 handle.steal_left();
2431 handle.steal_right();
2433 Stole(handle.into_node())
2437 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2440 fn next(&mut self) -> Option<(K, V)> {
2441 let res = match (self.left.peek(), self.right.peek()) {
2442 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2443 (Some(_), None) => Ordering::Less,
2444 (None, Some(_)) => Ordering::Greater,
2445 (None, None) => return None,
2448 // Check which elements comes first and only advance the corresponding iterator.
2449 // If two keys are equal, take the value from `right`.
2451 Ordering::Less => self.left.next(),
2452 Ordering::Greater => self.right.next(),
2453 Ordering::Equal => {