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}
;
15 use core
::marker
::PhantomData
;
17 use core
::{fmt, intrinsics, mem, ptr}
;
20 use Bound
::{self, Excluded, Included, Unbounded}
;
22 use super::node
::{self, Handle, NodeRef, marker}
;
25 use super::node
::InsertResult
::*;
26 use super::node
::ForceResult
::*;
27 use super::search
::SearchResult
::*;
28 use self::UnderflowResult
::*;
31 /// A map based on a B-Tree.
33 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
34 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
35 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
36 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
37 /// is done is *very* inefficient for modern computer architectures. In particular, every element
38 /// is stored in its own individually heap-allocated node. This means that every single insertion
39 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
40 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
43 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
44 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
45 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
46 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
47 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
48 /// the node using binary search. As a compromise, one could also perform a linear search
49 /// that initially only checks every i<sup>th</sup> element for some choice of i.
51 /// Currently, our implementation simply performs naive linear search. This provides excellent
52 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
53 /// would like to further explore choosing the optimal search strategy based on the choice of B,
54 /// and possibly other factors. Using linear search, searching for a random element is expected
55 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
56 /// however, performance is excellent.
58 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
59 /// any other key, as determined by the `Ord` trait, changes while it is in the map. This is
60 /// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code.
65 /// use std::collections::BTreeMap;
67 /// // type inference lets us omit an explicit type signature (which
68 /// // would be `BTreeMap<&str, &str>` in this example).
69 /// let mut movie_reviews = BTreeMap::new();
71 /// // review some movies.
72 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
73 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
74 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
75 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it alot.");
77 /// // check for a specific one.
78 /// if !movie_reviews.contains_key("Les Misérables") {
79 /// println!("We've got {} reviews, but Les Misérables ain't one.",
80 /// movie_reviews.len());
83 /// // oops, this review has a lot of spelling mistakes, let's delete it.
84 /// movie_reviews.remove("The Blues Brothers");
86 /// // look up the values associated with some keys.
87 /// let to_find = ["Up!", "Office Space"];
88 /// for book in &to_find {
89 /// match movie_reviews.get(book) {
90 /// Some(review) => println!("{}: {}", book, review),
91 /// None => println!("{} is unreviewed.", book)
95 /// // iterate over everything.
96 /// for (movie, review) in &movie_reviews {
97 /// println!("{}: \"{}\"", movie, review);
101 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
102 /// for more complex methods of getting, setting, updating and removing keys and
106 /// use std::collections::BTreeMap;
108 /// // type inference lets us omit an explicit type signature (which
109 /// // would be `BTreeMap<&str, u8>` in this example).
110 /// let mut player_stats = BTreeMap::new();
112 /// fn random_stat_buff() -> u8 {
113 /// // could actually return some random value here - let's just return
114 /// // some fixed value for now
118 /// // insert a key only if it doesn't already exist
119 /// player_stats.entry("health").or_insert(100);
121 /// // insert a key using a function that provides a new value only if it
122 /// // doesn't already exist
123 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
125 /// // update a key, guarding against the key possibly not being set
126 /// let stat = player_stats.entry("attack").or_insert(100);
127 /// *stat += random_stat_buff();
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub struct BTreeMap
<K
, V
> {
131 root
: node
::Root
<K
, V
>,
135 impl<K
, V
> Drop
for BTreeMap
<K
, V
> {
136 #[unsafe_destructor_blind_to_params]
139 for _
in ptr
::read(self).into_iter() {
145 impl<K
: Clone
, V
: Clone
> Clone
for BTreeMap
<K
, V
> {
146 fn clone(&self) -> BTreeMap
<K
, V
> {
147 fn clone_subtree
<K
: Clone
, V
: Clone
>(node
: node
::NodeRef
<marker
::Immut
,
150 marker
::LeafOrInternal
>)
155 let mut out_tree
= BTreeMap
{
156 root
: node
::Root
::new_leaf(),
161 let mut out_node
= match out_tree
.root
.as_mut().force() {
163 Internal(_
) => unreachable
!(),
166 let mut in_edge
= leaf
.first_edge();
167 while let Ok(kv
) = in_edge
.right_kv() {
168 let (k
, v
) = kv
.into_kv();
169 in_edge
= kv
.right_edge();
171 out_node
.push(k
.clone(), v
.clone());
172 out_tree
.length
+= 1;
178 Internal(internal
) => {
179 let mut out_tree
= clone_subtree(internal
.first_edge().descend());
182 let mut out_node
= out_tree
.root
.push_level();
183 let mut in_edge
= internal
.first_edge();
184 while let Ok(kv
) = in_edge
.right_kv() {
185 let (k
, v
) = kv
.into_kv();
186 in_edge
= kv
.right_edge();
188 let k
= (*k
).clone();
189 let v
= (*v
).clone();
190 let subtree
= clone_subtree(in_edge
.descend());
192 // We can't destructure subtree directly
193 // because BTreeMap implements Drop
194 let (subroot
, sublength
) = unsafe {
195 let root
= ptr
::read(&subtree
.root
);
196 let length
= subtree
.length
;
197 mem
::forget(subtree
);
201 out_node
.push(k
, v
, subroot
);
202 out_tree
.length
+= 1 + sublength
;
211 clone_subtree(self.root
.as_ref())
215 impl<K
, Q
: ?Sized
> super::Recover
<Q
> for BTreeMap
<K
, ()>
216 where K
: Borrow
<Q
> + Ord
,
221 fn get(&self, key
: &Q
) -> Option
<&K
> {
222 match search
::search_tree(self.root
.as_ref(), key
) {
223 Found(handle
) => Some(handle
.into_kv().0),
228 fn take(&mut self, key
: &Q
) -> Option
<K
> {
229 match search
::search_tree(self.root
.as_mut(), key
) {
233 length
: &mut self.length
,
234 _marker
: PhantomData
,
243 fn replace(&mut self, key
: K
) -> Option
<K
> {
244 match search
::search_tree
::<marker
::Mut
, K
, (), K
>(self.root
.as_mut(), &key
) {
245 Found(handle
) => Some(mem
::replace(handle
.into_kv_mut().0, key
)),
250 length
: &mut self.length
,
251 _marker
: PhantomData
,
260 /// An iterator over a BTreeMap's entries.
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub struct Iter
<'a
, K
: 'a
, V
: 'a
> {
263 range
: Range
<'a
, K
, V
>,
267 /// A mutable iterator over a BTreeMap's entries.
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub struct IterMut
<'a
, K
: 'a
, V
: 'a
> {
270 range
: RangeMut
<'a
, K
, V
>,
274 /// An owning iterator over a BTreeMap's entries.
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub struct IntoIter
<K
, V
> {
277 front
: Handle
<NodeRef
<marker
::Owned
, K
, V
, marker
::Leaf
>, marker
::Edge
>,
278 back
: Handle
<NodeRef
<marker
::Owned
, K
, V
, marker
::Leaf
>, marker
::Edge
>,
282 /// An iterator over a BTreeMap's keys.
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub struct Keys
<'a
, K
: 'a
, V
: 'a
> {
285 inner
: Iter
<'a
, K
, V
>,
288 /// An iterator over a BTreeMap's values.
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub struct Values
<'a
, K
: 'a
, V
: 'a
> {
291 inner
: Iter
<'a
, K
, V
>,
294 /// A mutable iterator over a BTreeMap's values.
295 #[stable(feature = "map_values_mut", since = "1.10.0")]
296 pub struct ValuesMut
<'a
, K
: 'a
, V
: 'a
> {
297 inner
: IterMut
<'a
, K
, V
>,
300 /// An iterator over a sub-range of BTreeMap's entries.
301 pub struct Range
<'a
, K
: 'a
, V
: 'a
> {
302 front
: Handle
<NodeRef
<marker
::Immut
<'a
>, K
, V
, marker
::Leaf
>, marker
::Edge
>,
303 back
: Handle
<NodeRef
<marker
::Immut
<'a
>, K
, V
, marker
::Leaf
>, marker
::Edge
>,
306 /// A mutable iterator over a sub-range of BTreeMap's entries.
307 pub struct RangeMut
<'a
, K
: 'a
, V
: 'a
> {
308 front
: Handle
<NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Leaf
>, marker
::Edge
>,
309 back
: Handle
<NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Leaf
>, marker
::Edge
>,
311 // Be invariant in `K` and `V`
312 _marker
: PhantomData
<&'a
mut (K
, V
)>,
315 /// A view into a single entry in a map, which may either be vacant or occupied.
316 /// This enum is constructed from the [`entry`] method on [`BTreeMap`].
318 /// [`BTreeMap`]: struct.BTreeMap.html
319 /// [`entry`]: struct.BTreeMap.html#method.entry
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub enum Entry
<'a
, K
: 'a
, V
: 'a
> {
323 #[stable(feature = "rust1", since = "1.0.0")]
324 Vacant(#[stable(feature = "rust1", since = "1.0.0")]
325 VacantEntry
<'a
, K
, V
>),
327 /// An occupied Entry
328 #[stable(feature = "rust1", since = "1.0.0")]
329 Occupied(#[stable(feature = "rust1", since = "1.0.0")]
330 OccupiedEntry
<'a
, K
, V
>),
333 #[stable(feature= "debug_btree_map", since = "1.12.0")]
334 impl<'a
, K
: 'a
+ Debug
+ Ord
, V
: 'a
+ Debug
> Debug
for Entry
<'a
, K
, V
> {
335 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
337 Vacant(ref v
) => f
.debug_tuple("Entry")
340 Occupied(ref o
) => f
.debug_tuple("Entry")
347 /// A vacant Entry. It is part of the [`Entry`] enum.
349 /// [`Entry`]: enum.Entry.html
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub struct VacantEntry
<'a
, K
: 'a
, V
: 'a
> {
353 handle
: Handle
<NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Leaf
>, marker
::Edge
>,
354 length
: &'a
mut usize,
356 // Be invariant in `K` and `V`
357 _marker
: PhantomData
<&'a
mut (K
, V
)>,
360 #[stable(feature= "debug_btree_map", since = "1.12.0")]
361 impl<'a
, K
: 'a
+ Debug
+ Ord
, V
: 'a
> Debug
for VacantEntry
<'a
, K
, V
> {
362 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
363 f
.debug_tuple("VacantEntry")
369 /// An occupied Entry. It is part of the [`Entry`] enum.
371 /// [`Entry`]: enum.Entry.html
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub struct OccupiedEntry
<'a
, K
: 'a
, V
: 'a
> {
374 handle
: Handle
<NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::LeafOrInternal
>, marker
::KV
>,
376 length
: &'a
mut usize,
378 // Be invariant in `K` and `V`
379 _marker
: PhantomData
<&'a
mut (K
, V
)>,
382 #[stable(feature= "debug_btree_map", since = "1.12.0")]
383 impl<'a
, K
: 'a
+ Debug
+ Ord
, V
: 'a
+ Debug
> Debug
for OccupiedEntry
<'a
, K
, V
> {
384 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
385 f
.debug_struct("OccupiedEntry")
386 .field("key", self.key())
387 .field("value", self.get())
392 // An iterator for merging two sorted sequences into one
393 struct MergeIter
<K
, V
, I
: Iterator
<Item
= (K
, V
)>> {
398 impl<K
: Ord
, V
> BTreeMap
<K
, V
> {
399 /// Makes a new empty BTreeMap with a reasonable choice for B.
406 /// use std::collections::BTreeMap;
408 /// let mut map = BTreeMap::new();
410 /// // entries can now be inserted into the empty map
411 /// map.insert(1, "a");
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn new() -> BTreeMap
<K
, V
> {
416 root
: node
::Root
::new_leaf(),
421 /// Clears the map, removing all values.
428 /// use std::collections::BTreeMap;
430 /// let mut a = BTreeMap::new();
431 /// a.insert(1, "a");
433 /// assert!(a.is_empty());
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn clear(&mut self) {
437 // FIXME(gereeter) .clear() allocates
438 *self = BTreeMap
::new();
441 /// Returns a reference to the value corresponding to the key.
443 /// The key may be any borrowed form of the map's key type, but the ordering
444 /// on the borrowed form *must* match the ordering on the key type.
451 /// use std::collections::BTreeMap;
453 /// let mut map = BTreeMap::new();
454 /// map.insert(1, "a");
455 /// assert_eq!(map.get(&1), Some(&"a"));
456 /// assert_eq!(map.get(&2), None);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn get
<Q
: ?Sized
>(&self, key
: &Q
) -> Option
<&V
>
463 match search
::search_tree(self.root
.as_ref(), key
) {
464 Found(handle
) => Some(handle
.into_kv().1),
469 /// Returns true if the map contains a value for the specified key.
471 /// The key may be any borrowed form of the map's key type, but the ordering
472 /// on the borrowed form *must* match the ordering on the key type.
479 /// use std::collections::BTreeMap;
481 /// let mut map = BTreeMap::new();
482 /// map.insert(1, "a");
483 /// assert_eq!(map.contains_key(&1), true);
484 /// assert_eq!(map.contains_key(&2), false);
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn contains_key
<Q
: ?Sized
>(&self, key
: &Q
) -> bool
491 self.get(key
).is_some()
494 /// Returns a mutable reference to the value corresponding to the key.
496 /// The key may be any borrowed form of the map's key type, but the ordering
497 /// on the borrowed form *must* match the ordering on the key type.
504 /// use std::collections::BTreeMap;
506 /// let mut map = BTreeMap::new();
507 /// map.insert(1, "a");
508 /// if let Some(x) = map.get_mut(&1) {
511 /// assert_eq!(map[&1], "b");
513 // See `get` for implementation notes, this is basically a copy-paste with mut's added
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn get_mut
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<&mut V
>
519 match search
::search_tree(self.root
.as_mut(), key
) {
520 Found(handle
) => Some(handle
.into_kv_mut().1),
525 /// Inserts a key-value pair into the map.
527 /// If the map did not have this key present, `None` is returned.
529 /// If the map did have this key present, the value is updated, and the old
530 /// value is returned. The key is not updated, though; this matters for
531 /// types that can be `==` without being identical. See the [module-level
532 /// documentation] for more.
534 /// [module-level documentation]: index.html#insert-and-complex-keys
541 /// use std::collections::BTreeMap;
543 /// let mut map = BTreeMap::new();
544 /// assert_eq!(map.insert(37, "a"), None);
545 /// assert_eq!(map.is_empty(), false);
547 /// map.insert(37, "b");
548 /// assert_eq!(map.insert(37, "c"), Some("b"));
549 /// assert_eq!(map[&37], "c");
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn insert(&mut self, key
: K
, value
: V
) -> Option
<V
> {
553 match self.entry(key
) {
554 Occupied(mut entry
) => Some(entry
.insert(value
)),
562 /// Removes a key from the map, returning the value at the key if the key
563 /// was previously in the map.
565 /// The key may be any borrowed form of the map's key type, but the ordering
566 /// on the borrowed form *must* match the ordering on the key type.
573 /// use std::collections::BTreeMap;
575 /// let mut map = BTreeMap::new();
576 /// map.insert(1, "a");
577 /// assert_eq!(map.remove(&1), Some("a"));
578 /// assert_eq!(map.remove(&1), None);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn remove
<Q
: ?Sized
>(&mut self, key
: &Q
) -> Option
<V
>
585 match search
::search_tree(self.root
.as_mut(), key
) {
589 length
: &mut self.length
,
590 _marker
: PhantomData
,
598 /// Moves all elements from `other` into `Self`, leaving `other` empty.
603 /// use std::collections::BTreeMap;
605 /// let mut a = BTreeMap::new();
606 /// a.insert(1, "a");
607 /// a.insert(2, "b");
608 /// a.insert(3, "c");
610 /// let mut b = BTreeMap::new();
611 /// b.insert(3, "d");
612 /// b.insert(4, "e");
613 /// b.insert(5, "f");
615 /// a.append(&mut b);
617 /// assert_eq!(a.len(), 5);
618 /// assert_eq!(b.len(), 0);
620 /// assert_eq!(a[&1], "a");
621 /// assert_eq!(a[&2], "b");
622 /// assert_eq!(a[&3], "d");
623 /// assert_eq!(a[&4], "e");
624 /// assert_eq!(a[&5], "f");
626 #[stable(feature = "btree_append", since = "1.11.0")]
627 pub fn append(&mut self, other
: &mut Self) {
628 // Do we have to append anything at all?
629 if other
.len() == 0 {
633 // We can just swap `self` and `other` if `self` is empty.
635 mem
::swap(self, other
);
639 // First, we merge `self` and `other` into a sorted sequence in linear time.
640 let self_iter
= mem
::replace(self, BTreeMap
::new()).into_iter();
641 let other_iter
= mem
::replace(other
, BTreeMap
::new()).into_iter();
642 let iter
= MergeIter
{
643 left
: self_iter
.peekable(),
644 right
: other_iter
.peekable(),
647 // Second, we build a tree from the sorted sequence in linear time.
648 self.from_sorted_iter(iter
);
649 self.fix_right_edge();
652 /// Constructs a double-ended iterator over a sub-range of elements in the map, starting
653 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
654 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
655 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
662 /// #![feature(btree_range, collections_bound)]
664 /// use std::collections::BTreeMap;
665 /// use std::collections::Bound::{Included, Unbounded};
667 /// let mut map = BTreeMap::new();
668 /// map.insert(3, "a");
669 /// map.insert(5, "b");
670 /// map.insert(8, "c");
671 /// for (&key, &value) in map.range(Included(&4), Included(&8)) {
672 /// println!("{}: {}", key, value);
674 /// assert_eq!(Some((&5, &"b")), map.range(Included(&4), Unbounded).next());
676 #[unstable(feature = "btree_range",
677 reason
= "matches collection reform specification, waiting for dust to settle",
679 pub fn range
<Min
: ?Sized
+ Ord
, Max
: ?Sized
+ Ord
>(&self,
683 where K
: Borrow
<Min
> + Borrow
<Max
>
685 let front
= match min
{
687 match search
::search_tree(self.root
.as_ref(), key
) {
688 Found(kv_handle
) => {
689 match kv_handle
.left_edge().force() {
690 Leaf(bottom
) => bottom
,
691 Internal(internal
) => last_leaf_edge(internal
.descend()),
694 GoDown(bottom
) => bottom
,
698 match search
::search_tree(self.root
.as_ref(), key
) {
699 Found(kv_handle
) => {
700 match kv_handle
.right_edge().force() {
701 Leaf(bottom
) => bottom
,
702 Internal(internal
) => first_leaf_edge(internal
.descend()),
705 GoDown(bottom
) => bottom
,
708 Unbounded
=> first_leaf_edge(self.root
.as_ref()),
711 let back
= match max
{
713 match search
::search_tree(self.root
.as_ref(), key
) {
714 Found(kv_handle
) => {
715 match kv_handle
.right_edge().force() {
716 Leaf(bottom
) => bottom
,
717 Internal(internal
) => first_leaf_edge(internal
.descend()),
720 GoDown(bottom
) => bottom
,
724 match search
::search_tree(self.root
.as_ref(), key
) {
725 Found(kv_handle
) => {
726 match kv_handle
.left_edge().force() {
727 Leaf(bottom
) => bottom
,
728 Internal(internal
) => last_leaf_edge(internal
.descend()),
731 GoDown(bottom
) => bottom
,
734 Unbounded
=> last_leaf_edge(self.root
.as_ref()),
743 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map, starting
744 /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
745 /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
746 /// Thus range(Unbounded, Unbounded) will yield the whole collection.
753 /// #![feature(btree_range, collections_bound)]
755 /// use std::collections::BTreeMap;
756 /// use std::collections::Bound::{Included, Excluded};
758 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
759 /// .map(|&s| (s, 0))
761 /// for (_, balance) in map.range_mut(Included("B"), Excluded("Cheryl")) {
764 /// for (name, balance) in &map {
765 /// println!("{} => {}", name, balance);
768 #[unstable(feature = "btree_range",
769 reason
= "matches collection reform specification, waiting for dust to settle",
771 pub fn range_mut
<Min
: ?Sized
+ Ord
, Max
: ?Sized
+ Ord
>(&mut self,
775 where K
: Borrow
<Min
> + Borrow
<Max
>
777 let root1
= self.root
.as_mut();
778 let root2
= unsafe { ptr::read(&root1) }
;
780 let front
= match min
{
782 match search
::search_tree(root1
, key
) {
783 Found(kv_handle
) => {
784 match kv_handle
.left_edge().force() {
785 Leaf(bottom
) => bottom
,
786 Internal(internal
) => last_leaf_edge(internal
.descend()),
789 GoDown(bottom
) => bottom
,
793 match search
::search_tree(root1
, key
) {
794 Found(kv_handle
) => {
795 match kv_handle
.right_edge().force() {
796 Leaf(bottom
) => bottom
,
797 Internal(internal
) => first_leaf_edge(internal
.descend()),
800 GoDown(bottom
) => bottom
,
803 Unbounded
=> first_leaf_edge(root1
),
806 let back
= match max
{
808 match search
::search_tree(root2
, key
) {
809 Found(kv_handle
) => {
810 match kv_handle
.right_edge().force() {
811 Leaf(bottom
) => bottom
,
812 Internal(internal
) => first_leaf_edge(internal
.descend()),
815 GoDown(bottom
) => bottom
,
819 match search
::search_tree(root2
, key
) {
820 Found(kv_handle
) => {
821 match kv_handle
.left_edge().force() {
822 Leaf(bottom
) => bottom
,
823 Internal(internal
) => last_leaf_edge(internal
.descend()),
826 GoDown(bottom
) => bottom
,
829 Unbounded
=> last_leaf_edge(root2
),
835 _marker
: PhantomData
,
839 /// Gets the given key's corresponding entry in the map for in-place manipulation.
846 /// use std::collections::BTreeMap;
848 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
850 /// // count the number of occurrences of letters in the vec
851 /// for x in vec!["a","b","a","c","a","b"] {
852 /// *count.entry(x).or_insert(0) += 1;
855 /// assert_eq!(count["a"], 3);
857 #[stable(feature = "rust1", since = "1.0.0")]
858 pub fn entry(&mut self, key
: K
) -> Entry
<K
, V
> {
859 match search
::search_tree(self.root
.as_mut(), &key
) {
861 Occupied(OccupiedEntry
{
863 length
: &mut self.length
,
864 _marker
: PhantomData
,
871 length
: &mut self.length
,
872 _marker
: PhantomData
,
878 fn from_sorted_iter
<I
: Iterator
<Item
= (K
, V
)>>(&mut self, iter
: I
) {
879 let mut cur_node
= last_leaf_edge(self.root
.as_mut()).into_node();
880 // Iterate through all key-value pairs, pushing them into nodes at the right level.
881 for (key
, value
) in iter
{
882 // Try to push key-value pair into the current leaf node.
883 if cur_node
.len() < node
::CAPACITY
{
884 cur_node
.push(key
, value
);
886 // No space left, go up and push there.
888 let mut test_node
= cur_node
.forget_type();
890 match test_node
.ascend() {
892 let parent
= parent
.into_node();
893 if parent
.len() < node
::CAPACITY
{
894 // Found a node with space left, push here.
899 test_node
= parent
.forget_type();
903 // We are at the top, create a new root node and push there.
904 open_node
= node
.into_root_mut().push_level();
910 // Push key-value pair and new right subtree.
911 let tree_height
= open_node
.height() - 1;
912 let mut right_tree
= node
::Root
::new_leaf();
913 for _
in 0..tree_height
{
914 right_tree
.push_level();
916 open_node
.push(key
, value
, right_tree
);
918 // Go down to the right-most leaf again.
919 cur_node
= last_leaf_edge(open_node
.forget_type()).into_node();
926 fn fix_right_edge(&mut self) {
927 // Handle underfull nodes, start from the top.
928 let mut cur_node
= self.root
.as_mut();
929 while let Internal(internal
) = cur_node
.force() {
930 // Check if right-most child is underfull.
931 let mut last_edge
= internal
.last_edge();
932 let right_child_len
= last_edge
.reborrow().descend().len();
933 if right_child_len
< node
::MIN_LEN
{
935 let mut last_kv
= match last_edge
.left_kv() {
937 Err(_
) => unreachable
!(),
939 last_kv
.bulk_steal_left(node
::MIN_LEN
- right_child_len
);
940 last_edge
= last_kv
.right_edge();
944 cur_node
= last_edge
.descend();
948 /// Splits the collection into two at the given key. Returns everything after the given key,
949 /// including the key.
956 /// use std::collections::BTreeMap;
958 /// let mut a = BTreeMap::new();
959 /// a.insert(1, "a");
960 /// a.insert(2, "b");
961 /// a.insert(3, "c");
962 /// a.insert(17, "d");
963 /// a.insert(41, "e");
965 /// let b = a.split_off(&3);
967 /// assert_eq!(a.len(), 2);
968 /// assert_eq!(b.len(), 3);
970 /// assert_eq!(a[&1], "a");
971 /// assert_eq!(a[&2], "b");
973 /// assert_eq!(b[&3], "c");
974 /// assert_eq!(b[&17], "d");
975 /// assert_eq!(b[&41], "e");
977 #[stable(feature = "btree_split_off", since = "1.11.0")]
978 pub fn split_off
<Q
: ?Sized
+ Ord
>(&mut self, key
: &Q
) -> Self
985 let total_num
= self.len();
987 let mut right
= Self::new();
988 for _
in 0..(self.root
.as_ref().height()) {
989 right
.root
.push_level();
993 let mut left_node
= self.root
.as_mut();
994 let mut right_node
= right
.root
.as_mut();
997 let mut split_edge
= match search
::search_node(left_node
, key
) {
998 // key is going to the right tree
999 Found(handle
) => handle
.left_edge(),
1000 GoDown(handle
) => handle
,
1003 split_edge
.move_suffix(&mut right_node
);
1005 match (split_edge
.force(), right_node
.force()) {
1006 (Internal(edge
), Internal(node
)) => {
1007 left_node
= edge
.descend();
1008 right_node
= node
.first_edge().descend();
1010 (Leaf(_
), Leaf(_
)) => {
1020 self.fix_right_border();
1021 right
.fix_left_border();
1023 if self.root
.as_ref().height() < right
.root
.as_ref().height() {
1024 self.recalc_length();
1025 right
.length
= total_num
- self.len();
1027 right
.recalc_length();
1028 self.length
= total_num
- right
.len();
1034 /// Calculates the number of elements if it is incorrect.
1035 fn recalc_length(&mut self) {
1036 fn dfs
<K
, V
>(node
: NodeRef
<marker
::Immut
, K
, V
, marker
::LeafOrInternal
>) -> usize {
1037 let mut res
= node
.len();
1039 if let Internal(node
) = node
.force() {
1040 let mut edge
= node
.first_edge();
1042 res
+= dfs(edge
.reborrow().descend());
1043 match edge
.right_kv() {
1045 edge
= right_kv
.right_edge();
1057 self.length
= dfs(self.root
.as_ref());
1060 /// Removes empty levels on the top.
1061 fn fix_top(&mut self) {
1064 let node
= self.root
.as_ref();
1065 if node
.height() == 0 || node
.len() > 0 {
1069 self.root
.pop_level();
1073 fn fix_right_border(&mut self) {
1077 let mut cur_node
= self.root
.as_mut();
1079 while let Internal(node
) = cur_node
.force() {
1080 let mut last_kv
= node
.last_kv();
1082 if last_kv
.can_merge() {
1083 cur_node
= last_kv
.merge().descend();
1085 let right_len
= last_kv
.reborrow().right_edge().descend().len();
1086 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1087 if right_len
< node
::MIN_LEN
+ 1 {
1088 last_kv
.bulk_steal_left(node
::MIN_LEN
+ 1 - right_len
);
1090 cur_node
= last_kv
.right_edge().descend();
1098 /// The symmetric clone of `fix_right_border`.
1099 fn fix_left_border(&mut self) {
1103 let mut cur_node
= self.root
.as_mut();
1105 while let Internal(node
) = cur_node
.force() {
1106 let mut first_kv
= node
.first_kv();
1108 if first_kv
.can_merge() {
1109 cur_node
= first_kv
.merge().descend();
1111 let left_len
= first_kv
.reborrow().left_edge().descend().len();
1112 if left_len
< node
::MIN_LEN
+ 1 {
1113 first_kv
.bulk_steal_right(node
::MIN_LEN
+ 1 - left_len
);
1115 cur_node
= first_kv
.left_edge().descend();
1124 impl<'a
, K
: 'a
, V
: 'a
> IntoIterator
for &'a BTreeMap
<K
, V
> {
1125 type Item
= (&'a K
, &'a V
);
1126 type IntoIter
= Iter
<'a
, K
, V
>;
1128 fn into_iter(self) -> Iter
<'a
, K
, V
> {
1133 impl<'a
, K
: 'a
, V
: 'a
> Iterator
for Iter
<'a
, K
, V
> {
1134 type Item
= (&'a K
, &'a V
);
1136 fn next(&mut self) -> Option
<(&'a K
, &'a V
)> {
1137 if self.length
== 0 {
1141 unsafe { Some(self.range.next_unchecked()) }
1145 fn size_hint(&self) -> (usize, Option
<usize>) {
1146 (self.length
, Some(self.length
))
1150 impl<'a
, K
: 'a
, V
: 'a
> DoubleEndedIterator
for Iter
<'a
, K
, V
> {
1151 fn next_back(&mut self) -> Option
<(&'a K
, &'a V
)> {
1152 if self.length
== 0 {
1156 unsafe { Some(self.range.next_back_unchecked()) }
1161 impl<'a
, K
: 'a
, V
: 'a
> ExactSizeIterator
for Iter
<'a
, K
, V
> {
1162 fn len(&self) -> usize {
1167 impl<'a
, K
, V
> Clone
for Iter
<'a
, K
, V
> {
1168 fn clone(&self) -> Iter
<'a
, K
, V
> {
1170 range
: self.range
.clone(),
1171 length
: self.length
,
1176 impl<'a
, K
: 'a
, V
: 'a
> IntoIterator
for &'a
mut BTreeMap
<K
, V
> {
1177 type Item
= (&'a K
, &'a
mut V
);
1178 type IntoIter
= IterMut
<'a
, K
, V
>;
1180 fn into_iter(self) -> IterMut
<'a
, K
, V
> {
1185 impl<'a
, K
: 'a
, V
: 'a
> Iterator
for IterMut
<'a
, K
, V
> {
1186 type Item
= (&'a K
, &'a
mut V
);
1188 fn next(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1189 if self.length
== 0 {
1193 unsafe { Some(self.range.next_unchecked()) }
1197 fn size_hint(&self) -> (usize, Option
<usize>) {
1198 (self.length
, Some(self.length
))
1202 impl<'a
, K
: 'a
, V
: 'a
> DoubleEndedIterator
for IterMut
<'a
, K
, V
> {
1203 fn next_back(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1204 if self.length
== 0 {
1208 unsafe { Some(self.range.next_back_unchecked()) }
1213 impl<'a
, K
: 'a
, V
: 'a
> ExactSizeIterator
for IterMut
<'a
, K
, V
> {
1214 fn len(&self) -> usize {
1219 impl<K
, V
> IntoIterator
for BTreeMap
<K
, V
> {
1221 type IntoIter
= IntoIter
<K
, V
>;
1223 fn into_iter(self) -> IntoIter
<K
, V
> {
1224 let root1
= unsafe { ptr::read(&self.root).into_ref() }
;
1225 let root2
= unsafe { ptr::read(&self.root).into_ref() }
;
1226 let len
= self.length
;
1230 front
: first_leaf_edge(root1
),
1231 back
: last_leaf_edge(root2
),
1237 impl<K
, V
> Drop
for IntoIter
<K
, V
> {
1238 fn drop(&mut self) {
1239 for _
in &mut *self {
1242 let leaf_node
= ptr
::read(&self.front
).into_node();
1243 if let Some(first_parent
) = leaf_node
.deallocate_and_ascend() {
1244 let mut cur_node
= first_parent
.into_node();
1245 while let Some(parent
) = cur_node
.deallocate_and_ascend() {
1246 cur_node
= parent
.into_node()
1253 impl<K
, V
> Iterator
for IntoIter
<K
, V
> {
1256 fn next(&mut self) -> Option
<(K
, V
)> {
1257 if self.length
== 0 {
1263 let handle
= unsafe { ptr::read(&self.front) }
;
1265 let mut cur_handle
= match handle
.right_kv() {
1267 let k
= unsafe { ptr::read(kv.reborrow().into_kv().0) }
;
1268 let v
= unsafe { ptr::read(kv.reborrow().into_kv().1) }
;
1269 self.front
= kv
.right_edge();
1270 return Some((k
, v
));
1272 Err(last_edge
) => unsafe {
1273 unwrap_unchecked(last_edge
.into_node().deallocate_and_ascend())
1278 match cur_handle
.right_kv() {
1280 let k
= unsafe { ptr::read(kv.reborrow().into_kv().0) }
;
1281 let v
= unsafe { ptr::read(kv.reborrow().into_kv().1) }
;
1282 self.front
= first_leaf_edge(kv
.right_edge().descend());
1283 return Some((k
, v
));
1285 Err(last_edge
) => unsafe {
1286 cur_handle
= unwrap_unchecked(last_edge
.into_node().deallocate_and_ascend());
1292 fn size_hint(&self) -> (usize, Option
<usize>) {
1293 (self.length
, Some(self.length
))
1297 impl<K
, V
> DoubleEndedIterator
for IntoIter
<K
, V
> {
1298 fn next_back(&mut self) -> Option
<(K
, V
)> {
1299 if self.length
== 0 {
1305 let handle
= unsafe { ptr::read(&self.back) }
;
1307 let mut cur_handle
= match handle
.left_kv() {
1309 let k
= unsafe { ptr::read(kv.reborrow().into_kv().0) }
;
1310 let v
= unsafe { ptr::read(kv.reborrow().into_kv().1) }
;
1311 self.back
= kv
.left_edge();
1312 return Some((k
, v
));
1314 Err(last_edge
) => unsafe {
1315 unwrap_unchecked(last_edge
.into_node().deallocate_and_ascend())
1320 match cur_handle
.left_kv() {
1322 let k
= unsafe { ptr::read(kv.reborrow().into_kv().0) }
;
1323 let v
= unsafe { ptr::read(kv.reborrow().into_kv().1) }
;
1324 self.back
= last_leaf_edge(kv
.left_edge().descend());
1325 return Some((k
, v
));
1327 Err(last_edge
) => unsafe {
1328 cur_handle
= unwrap_unchecked(last_edge
.into_node().deallocate_and_ascend());
1335 impl<K
, V
> ExactSizeIterator
for IntoIter
<K
, V
> {
1336 fn len(&self) -> usize {
1341 impl<'a
, K
, V
> Iterator
for Keys
<'a
, K
, V
> {
1344 fn next(&mut self) -> Option
<&'a K
> {
1345 self.inner
.next().map(|(k
, _
)| k
)
1348 fn size_hint(&self) -> (usize, Option
<usize>) {
1349 self.inner
.size_hint()
1353 impl<'a
, K
, V
> DoubleEndedIterator
for Keys
<'a
, K
, V
> {
1354 fn next_back(&mut self) -> Option
<&'a K
> {
1355 self.inner
.next_back().map(|(k
, _
)| k
)
1359 impl<'a
, K
, V
> ExactSizeIterator
for Keys
<'a
, K
, V
> {
1360 fn len(&self) -> usize {
1365 impl<'a
, K
, V
> Clone
for Keys
<'a
, K
, V
> {
1366 fn clone(&self) -> Keys
<'a
, K
, V
> {
1367 Keys { inner: self.inner.clone() }
1371 impl<'a
, K
, V
> Iterator
for Values
<'a
, K
, V
> {
1374 fn next(&mut self) -> Option
<&'a V
> {
1375 self.inner
.next().map(|(_
, v
)| v
)
1378 fn size_hint(&self) -> (usize, Option
<usize>) {
1379 self.inner
.size_hint()
1383 impl<'a
, K
, V
> DoubleEndedIterator
for Values
<'a
, K
, V
> {
1384 fn next_back(&mut self) -> Option
<&'a V
> {
1385 self.inner
.next_back().map(|(_
, v
)| v
)
1389 impl<'a
, K
, V
> ExactSizeIterator
for Values
<'a
, K
, V
> {
1390 fn len(&self) -> usize {
1395 impl<'a
, K
, V
> Clone
for Values
<'a
, K
, V
> {
1396 fn clone(&self) -> Values
<'a
, K
, V
> {
1397 Values { inner: self.inner.clone() }
1401 impl<'a
, K
, V
> Iterator
for Range
<'a
, K
, V
> {
1402 type Item
= (&'a K
, &'a V
);
1404 fn next(&mut self) -> Option
<(&'a K
, &'a V
)> {
1405 if self.front
== self.back
{
1408 unsafe { Some(self.next_unchecked()) }
1413 #[stable(feature = "map_values_mut", since = "1.10.0")]
1414 impl<'a
, K
, V
> Iterator
for ValuesMut
<'a
, K
, V
> {
1415 type Item
= &'a
mut V
;
1417 fn next(&mut self) -> Option
<&'a
mut V
> {
1418 self.inner
.next().map(|(_
, v
)| v
)
1421 fn size_hint(&self) -> (usize, Option
<usize>) {
1422 self.inner
.size_hint()
1426 #[stable(feature = "map_values_mut", since = "1.10.0")]
1427 impl<'a
, K
, V
> DoubleEndedIterator
for ValuesMut
<'a
, K
, V
> {
1428 fn next_back(&mut self) -> Option
<&'a
mut V
> {
1429 self.inner
.next_back().map(|(_
, v
)| v
)
1433 #[stable(feature = "map_values_mut", since = "1.10.0")]
1434 impl<'a
, K
, V
> ExactSizeIterator
for ValuesMut
<'a
, K
, V
> {
1435 fn len(&self) -> usize {
1440 impl<'a
, K
, V
> Range
<'a
, K
, V
> {
1441 unsafe fn next_unchecked(&mut self) -> (&'a K
, &'a V
) {
1442 let handle
= self.front
;
1444 let mut cur_handle
= match handle
.right_kv() {
1446 let ret
= kv
.into_kv();
1447 self.front
= kv
.right_edge();
1451 let next_level
= last_edge
.into_node().ascend().ok();
1452 unwrap_unchecked(next_level
)
1457 match cur_handle
.right_kv() {
1459 let ret
= kv
.into_kv();
1460 self.front
= first_leaf_edge(kv
.right_edge().descend());
1464 let next_level
= last_edge
.into_node().ascend().ok();
1465 cur_handle
= unwrap_unchecked(next_level
);
1472 impl<'a
, K
, V
> DoubleEndedIterator
for Range
<'a
, K
, V
> {
1473 fn next_back(&mut self) -> Option
<(&'a K
, &'a V
)> {
1474 if self.front
== self.back
{
1477 unsafe { Some(self.next_back_unchecked()) }
1482 impl<'a
, K
, V
> Range
<'a
, K
, V
> {
1483 unsafe fn next_back_unchecked(&mut self) -> (&'a K
, &'a V
) {
1484 let handle
= self.back
;
1486 let mut cur_handle
= match handle
.left_kv() {
1488 let ret
= kv
.into_kv();
1489 self.back
= kv
.left_edge();
1493 let next_level
= last_edge
.into_node().ascend().ok();
1494 unwrap_unchecked(next_level
)
1499 match cur_handle
.left_kv() {
1501 let ret
= kv
.into_kv();
1502 self.back
= last_leaf_edge(kv
.left_edge().descend());
1506 let next_level
= last_edge
.into_node().ascend().ok();
1507 cur_handle
= unwrap_unchecked(next_level
);
1514 impl<'a
, K
, V
> Clone
for Range
<'a
, K
, V
> {
1515 fn clone(&self) -> Range
<'a
, K
, V
> {
1523 impl<'a
, K
, V
> Iterator
for RangeMut
<'a
, K
, V
> {
1524 type Item
= (&'a K
, &'a
mut V
);
1526 fn next(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1527 if self.front
== self.back
{
1530 unsafe { Some(self.next_unchecked()) }
1535 impl<'a
, K
, V
> RangeMut
<'a
, K
, V
> {
1536 unsafe fn next_unchecked(&mut self) -> (&'a K
, &'a
mut V
) {
1537 let handle
= ptr
::read(&self.front
);
1539 let mut cur_handle
= match handle
.right_kv() {
1541 let (k
, v
) = ptr
::read(&kv
).into_kv_mut();
1542 self.front
= kv
.right_edge();
1546 let next_level
= last_edge
.into_node().ascend().ok();
1547 unwrap_unchecked(next_level
)
1552 match cur_handle
.right_kv() {
1554 let (k
, v
) = ptr
::read(&kv
).into_kv_mut();
1555 self.front
= first_leaf_edge(kv
.right_edge().descend());
1559 let next_level
= last_edge
.into_node().ascend().ok();
1560 cur_handle
= unwrap_unchecked(next_level
);
1567 impl<'a
, K
, V
> DoubleEndedIterator
for RangeMut
<'a
, K
, V
> {
1568 fn next_back(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1569 if self.front
== self.back
{
1572 unsafe { Some(self.next_back_unchecked()) }
1577 impl<'a
, K
, V
> RangeMut
<'a
, K
, V
> {
1578 unsafe fn next_back_unchecked(&mut self) -> (&'a K
, &'a
mut V
) {
1579 let handle
= ptr
::read(&self.back
);
1581 let mut cur_handle
= match handle
.left_kv() {
1583 let (k
, v
) = ptr
::read(&kv
).into_kv_mut();
1584 self.back
= kv
.left_edge();
1588 let next_level
= last_edge
.into_node().ascend().ok();
1589 unwrap_unchecked(next_level
)
1594 match cur_handle
.left_kv() {
1596 let (k
, v
) = ptr
::read(&kv
).into_kv_mut();
1597 self.back
= last_leaf_edge(kv
.left_edge().descend());
1601 let next_level
= last_edge
.into_node().ascend().ok();
1602 cur_handle
= unwrap_unchecked(next_level
);
1609 impl<K
: Ord
, V
> FromIterator
<(K
, V
)> for BTreeMap
<K
, V
> {
1610 fn from_iter
<T
: IntoIterator
<Item
= (K
, V
)>>(iter
: T
) -> BTreeMap
<K
, V
> {
1611 let mut map
= BTreeMap
::new();
1617 impl<K
: Ord
, V
> Extend
<(K
, V
)> for BTreeMap
<K
, V
> {
1619 fn extend
<T
: IntoIterator
<Item
= (K
, V
)>>(&mut self, iter
: T
) {
1620 for (k
, v
) in iter
{
1626 impl<'a
, K
: Ord
+ Copy
, V
: Copy
> Extend
<(&'a K
, &'a V
)> for BTreeMap
<K
, V
> {
1627 fn extend
<I
: IntoIterator
<Item
= (&'a K
, &'a V
)>>(&mut self, iter
: I
) {
1628 self.extend(iter
.into_iter().map(|(&key
, &value
)| (key
, value
)));
1632 impl<K
: Hash
, V
: Hash
> Hash
for BTreeMap
<K
, V
> {
1633 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
1640 impl<K
: Ord
, V
> Default
for BTreeMap
<K
, V
> {
1641 fn default() -> BTreeMap
<K
, V
> {
1646 impl<K
: PartialEq
, V
: PartialEq
> PartialEq
for BTreeMap
<K
, V
> {
1647 fn eq(&self, other
: &BTreeMap
<K
, V
>) -> bool
{
1648 self.len() == other
.len() && self.iter().zip(other
).all(|(a
, b
)| a
== b
)
1652 impl<K
: Eq
, V
: Eq
> Eq
for BTreeMap
<K
, V
> {}
1654 impl<K
: PartialOrd
, V
: PartialOrd
> PartialOrd
for BTreeMap
<K
, V
> {
1656 fn partial_cmp(&self, other
: &BTreeMap
<K
, V
>) -> Option
<Ordering
> {
1657 self.iter().partial_cmp(other
.iter())
1661 impl<K
: Ord
, V
: Ord
> Ord
for BTreeMap
<K
, V
> {
1663 fn cmp(&self, other
: &BTreeMap
<K
, V
>) -> Ordering
{
1664 self.iter().cmp(other
.iter())
1668 impl<K
: Debug
, V
: Debug
> Debug
for BTreeMap
<K
, V
> {
1669 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1670 f
.debug_map().entries(self.iter()).finish()
1674 impl<'a
, K
: Ord
, Q
: ?Sized
, V
> Index
<&'a Q
> for BTreeMap
<K
, V
>
1681 fn index(&self, key
: &Q
) -> &V
{
1682 self.get(key
).expect("no entry found for key")
1686 fn first_leaf_edge
<BorrowType
, K
, V
>
1687 (mut node
: NodeRef
<BorrowType
, K
, V
, marker
::LeafOrInternal
>)
1688 -> Handle
<NodeRef
<BorrowType
, K
, V
, marker
::Leaf
>, marker
::Edge
> {
1690 match node
.force() {
1691 Leaf(leaf
) => return leaf
.first_edge(),
1692 Internal(internal
) => {
1693 node
= internal
.first_edge().descend();
1699 fn last_leaf_edge
<BorrowType
, K
, V
>
1700 (mut node
: NodeRef
<BorrowType
, K
, V
, marker
::LeafOrInternal
>)
1701 -> Handle
<NodeRef
<BorrowType
, K
, V
, marker
::Leaf
>, marker
::Edge
> {
1703 match node
.force() {
1704 Leaf(leaf
) => return leaf
.last_edge(),
1705 Internal(internal
) => {
1706 node
= internal
.last_edge().descend();
1713 unsafe fn unwrap_unchecked
<T
>(val
: Option
<T
>) -> T
{
1714 val
.unwrap_or_else(|| {
1715 if cfg
!(debug_assertions
) {
1716 panic
!("'unchecked' unwrap on None in BTreeMap");
1718 intrinsics
::unreachable();
1723 impl<K
, V
> BTreeMap
<K
, V
> {
1724 /// Gets an iterator over the entries of the map, sorted by key.
1731 /// use std::collections::BTreeMap;
1733 /// let mut map = BTreeMap::new();
1734 /// map.insert(3, "c");
1735 /// map.insert(2, "b");
1736 /// map.insert(1, "a");
1738 /// for (key, value) in map.iter() {
1739 /// println!("{}: {}", key, value);
1742 /// let (first_key, first_value) = map.iter().next().unwrap();
1743 /// assert_eq!((*first_key, *first_value), (1, "a"));
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub fn iter(&self) -> Iter
<K
, V
> {
1749 front
: first_leaf_edge(self.root
.as_ref()),
1750 back
: last_leaf_edge(self.root
.as_ref()),
1752 length
: self.length
,
1756 /// Gets a mutable iterator over the entries of the map, sorted by key.
1763 /// use std::collections::BTreeMap;
1765 /// let mut map = BTreeMap::new();
1766 /// map.insert("a", 1);
1767 /// map.insert("b", 2);
1768 /// map.insert("c", 3);
1770 /// // add 10 to the value if the key isn't "a"
1771 /// for (key, value) in map.iter_mut() {
1772 /// if key != &"a" {
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn iter_mut(&mut self) -> IterMut
<K
, V
> {
1779 let root1
= self.root
.as_mut();
1780 let root2
= unsafe { ptr::read(&root1) }
;
1783 front
: first_leaf_edge(root1
),
1784 back
: last_leaf_edge(root2
),
1785 _marker
: PhantomData
,
1787 length
: self.length
,
1791 /// Gets an iterator over the keys of the map, in sorted order.
1798 /// use std::collections::BTreeMap;
1800 /// let mut a = BTreeMap::new();
1801 /// a.insert(2, "b");
1802 /// a.insert(1, "a");
1804 /// let keys: Vec<_> = a.keys().cloned().collect();
1805 /// assert_eq!(keys, [1, 2]);
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 pub fn keys
<'a
>(&'a
self) -> Keys
<'a
, K
, V
> {
1809 Keys { inner: self.iter() }
1812 /// Gets an iterator over the values of the map, in order by key.
1819 /// use std::collections::BTreeMap;
1821 /// let mut a = BTreeMap::new();
1822 /// a.insert(1, "hello");
1823 /// a.insert(2, "goodbye");
1825 /// let values: Vec<&str> = a.values().cloned().collect();
1826 /// assert_eq!(values, ["hello", "goodbye"]);
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 pub fn values
<'a
>(&'a
self) -> Values
<'a
, K
, V
> {
1830 Values { inner: self.iter() }
1833 /// Gets a mutable iterator over the values of the map, in order by key.
1840 /// use std::collections::BTreeMap;
1842 /// let mut a = BTreeMap::new();
1843 /// a.insert(1, String::from("hello"));
1844 /// a.insert(2, String::from("goodbye"));
1846 /// for value in a.values_mut() {
1847 /// value.push_str("!");
1850 /// let values: Vec<String> = a.values().cloned().collect();
1851 /// assert_eq!(values, [String::from("hello!"),
1852 /// String::from("goodbye!")]);
1854 #[stable(feature = "map_values_mut", since = "1.10.0")]
1855 pub fn values_mut(&mut self) -> ValuesMut
<K
, V
> {
1856 ValuesMut { inner: self.iter_mut() }
1859 /// Returns the number of elements in the map.
1866 /// use std::collections::BTreeMap;
1868 /// let mut a = BTreeMap::new();
1869 /// assert_eq!(a.len(), 0);
1870 /// a.insert(1, "a");
1871 /// assert_eq!(a.len(), 1);
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub fn len(&self) -> usize {
1878 /// Returns true if the map contains no elements.
1885 /// use std::collections::BTreeMap;
1887 /// let mut a = BTreeMap::new();
1888 /// assert!(a.is_empty());
1889 /// a.insert(1, "a");
1890 /// assert!(!a.is_empty());
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 pub fn is_empty(&self) -> bool
{
1898 impl<'a
, K
: Ord
, V
> Entry
<'a
, K
, V
> {
1899 /// Ensures a value is in the entry by inserting the default if empty, and returns
1900 /// a mutable reference to the value in the entry.
1905 /// use std::collections::BTreeMap;
1907 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1908 /// map.entry("poneyland").or_insert(12);
1910 /// assert_eq!(map["poneyland"], 12);
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 pub fn or_insert(self, default: V
) -> &'a
mut V
{
1915 Occupied(entry
) => entry
.into_mut(),
1916 Vacant(entry
) => entry
.insert(default),
1920 /// Ensures a value is in the entry by inserting the result of the default function if empty,
1921 /// and returns a mutable reference to the value in the entry.
1926 /// use std::collections::BTreeMap;
1928 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
1929 /// let s = "hoho".to_owned();
1931 /// map.entry("poneyland").or_insert_with(|| s);
1933 /// assert_eq!(map["poneyland"], "hoho".to_owned());
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 pub fn or_insert_with
<F
: FnOnce() -> V
>(self, default: F
) -> &'a
mut V
{
1938 Occupied(entry
) => entry
.into_mut(),
1939 Vacant(entry
) => entry
.insert(default()),
1943 /// Returns a reference to this entry's key.
1948 /// use std::collections::BTreeMap;
1950 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1951 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1953 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1954 pub fn key(&self) -> &K
{
1956 Occupied(ref entry
) => entry
.key(),
1957 Vacant(ref entry
) => entry
.key(),
1962 impl<'a
, K
: Ord
, V
> VacantEntry
<'a
, K
, V
> {
1963 /// Gets a reference to the key that would be used when inserting a value
1964 /// through the VacantEntry.
1969 /// use std::collections::BTreeMap;
1971 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1972 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
1974 #[stable(feature = "map_entry_keys", since = "1.10.0")]
1975 pub fn key(&self) -> &K
{
1979 /// Take ownership of the key.
1984 /// use std::collections::BTreeMap;
1985 /// use std::collections::btree_map::Entry;
1987 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
1989 /// if let Entry::Vacant(v) = map.entry("poneyland") {
1993 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
1994 pub fn into_key(self) -> K
{
1998 /// Sets the value of the entry with the VacantEntry's key,
1999 /// and returns a mutable reference to it.
2004 /// use std::collections::BTreeMap;
2006 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2008 /// // count the number of occurrences of letters in the vec
2009 /// for x in vec!["a","b","a","c","a","b"] {
2010 /// *count.entry(x).or_insert(0) += 1;
2013 /// assert_eq!(count["a"], 3);
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 pub fn insert(self, value
: V
) -> &'a
mut V
{
2025 let mut cur_parent
= match self.handle
.insert(self.key
, value
) {
2026 (Fit(handle
), _
) => return handle
.into_kv_mut().1,
2027 (Split(left
, k
, v
, right
), ptr
) => {
2032 left
.ascend().map_err(|n
| n
.into_root_mut())
2039 match parent
.insert(ins_k
, ins_v
, ins_edge
) {
2040 Fit(_
) => return unsafe { &mut *out_ptr }
,
2041 Split(left
, k
, v
, right
) => {
2045 cur_parent
= left
.ascend().map_err(|n
| n
.into_root_mut());
2050 root
.push_level().push(ins_k
, ins_v
, ins_edge
);
2051 return unsafe { &mut *out_ptr }
;
2058 impl<'a
, K
: Ord
, V
> OccupiedEntry
<'a
, K
, V
> {
2059 /// Gets a reference to the key in the entry.
2064 /// use std::collections::BTreeMap;
2066 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2067 /// map.entry("poneyland").or_insert(12);
2068 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2070 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2071 pub fn key(&self) -> &K
{
2072 self.handle
.reborrow().into_kv().0
2075 /// Deprecated, renamed to `remove_entry`
2076 #[unstable(feature = "map_entry_recover_keys", issue = "34285")]
2077 #[rustc_deprecated(since = "1.12.0", reason = "renamed to `remove_entry`")]
2078 pub fn remove_pair(self) -> (K
, V
) {
2082 /// Take ownership of the key and value from the map.
2087 /// use std::collections::BTreeMap;
2088 /// use std::collections::btree_map::Entry;
2090 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2091 /// map.entry("poneyland").or_insert(12);
2093 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2094 /// // We delete the entry from the map.
2095 /// o.remove_entry();
2098 /// // If now try to get the value, it will panic:
2099 /// // println!("{}", map["poneyland"]);
2101 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2102 pub fn remove_entry(self) -> (K
, V
) {
2106 /// Gets a reference to the value in the entry.
2111 /// use std::collections::BTreeMap;
2112 /// use std::collections::btree_map::Entry;
2114 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2115 /// map.entry("poneyland").or_insert(12);
2117 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2118 /// assert_eq!(o.get(), &12);
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 pub fn get(&self) -> &V
{
2123 self.handle
.reborrow().into_kv().1
2126 /// Gets a mutable reference to the value in the entry.
2131 /// use std::collections::BTreeMap;
2132 /// use std::collections::btree_map::Entry;
2134 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2135 /// map.entry("poneyland").or_insert(12);
2137 /// assert_eq!(map["poneyland"], 12);
2138 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2139 /// *o.get_mut() += 10;
2141 /// assert_eq!(map["poneyland"], 22);
2143 #[stable(feature = "rust1", since = "1.0.0")]
2144 pub fn get_mut(&mut self) -> &mut V
{
2145 self.handle
.kv_mut().1
2148 /// Converts the entry into a mutable reference to its value.
2153 /// use std::collections::BTreeMap;
2154 /// use std::collections::btree_map::Entry;
2156 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2157 /// map.entry("poneyland").or_insert(12);
2159 /// assert_eq!(map["poneyland"], 12);
2160 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2161 /// *o.into_mut() += 10;
2163 /// assert_eq!(map["poneyland"], 22);
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 pub fn into_mut(self) -> &'a
mut V
{
2167 self.handle
.into_kv_mut().1
2170 /// Sets the value of the entry with the OccupiedEntry's key,
2171 /// and returns the entry's old value.
2176 /// use std::collections::BTreeMap;
2177 /// use std::collections::btree_map::Entry;
2179 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2180 /// map.entry("poneyland").or_insert(12);
2182 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2183 /// assert_eq!(o.insert(15), 12);
2185 /// assert_eq!(map["poneyland"], 15);
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 pub fn insert(&mut self, value
: V
) -> V
{
2189 mem
::replace(self.get_mut(), value
)
2192 /// Takes the value of the entry out of the map, and returns it.
2197 /// use std::collections::BTreeMap;
2198 /// use std::collections::btree_map::Entry;
2200 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2201 /// map.entry("poneyland").or_insert(12);
2203 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2204 /// assert_eq!(o.remove(), 12);
2206 /// // If we try to get "poneyland"'s value, it'll panic:
2207 /// // println!("{}", map["poneyland"]);
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 pub fn remove(self) -> V
{
2214 fn remove_kv(self) -> (K
, V
) {
2217 let (small_leaf
, old_key
, old_val
) = match self.handle
.force() {
2219 let (hole
, old_key
, old_val
) = leaf
.remove();
2220 (hole
.into_node(), old_key
, old_val
)
2222 Internal(mut internal
) => {
2223 let key_loc
= internal
.kv_mut().0 as *mut K
;
2224 let val_loc
= internal
.kv_mut().1 as *mut V
;
2226 let to_remove
= first_leaf_edge(internal
.right_edge().descend()).right_kv().ok();
2227 let to_remove
= unsafe { unwrap_unchecked(to_remove) }
;
2229 let (hole
, key
, val
) = to_remove
.remove();
2231 let old_key
= unsafe { mem::replace(&mut *key_loc, key) }
;
2232 let old_val
= unsafe { mem::replace(&mut *val_loc, val) }
;
2234 (hole
.into_node(), old_key
, old_val
)
2239 let mut cur_node
= small_leaf
.forget_type();
2240 while cur_node
.len() < node
::CAPACITY
/ 2 {
2241 match handle_underfull_node(cur_node
) {
2243 EmptyParent(_
) => unreachable
!(),
2245 if parent
.len() == 0 {
2246 // We must be at the root
2247 parent
.into_root_mut().pop_level();
2250 cur_node
= parent
.forget_type();
2261 enum UnderflowResult
<'a
, K
, V
> {
2263 EmptyParent(NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Internal
>),
2264 Merged(NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Internal
>),
2265 Stole(NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Internal
>),
2268 fn handle_underfull_node
<'a
, K
, V
>(node
: NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::LeafOrInternal
>)
2269 -> UnderflowResult
<'a
, K
, V
> {
2270 let parent
= if let Ok(parent
) = node
.ascend() {
2276 let (is_left
, mut handle
) = match parent
.left_kv() {
2277 Ok(left
) => (true, left
),
2279 match parent
.right_kv() {
2280 Ok(right
) => (false, right
),
2282 return EmptyParent(parent
.into_node());
2288 if handle
.can_merge() {
2289 Merged(handle
.merge().into_node())
2292 handle
.steal_left();
2294 handle
.steal_right();
2296 Stole(handle
.into_node())
2300 impl<K
: Ord
, V
, I
: Iterator
<Item
= (K
, V
)>> Iterator
for MergeIter
<K
, V
, I
> {
2303 fn next(&mut self) -> Option
<(K
, V
)> {
2304 let res
= match (self.left
.peek(), self.right
.peek()) {
2305 (Some(&(ref left_key
, _
)), Some(&(ref right_key
, _
))) => left_key
.cmp(right_key
),
2306 (Some(_
), None
) => Ordering
::Less
,
2307 (None
, Some(_
)) => Ordering
::Greater
,
2308 (None
, None
) => return None
,
2311 // Check which elements comes first and only advance the corresponding iterator.
2312 // If two keys are equal, take the value from `right`.
2314 Ordering
::Less
=> self.left
.next(),
2315 Ordering
::Greater
=> self.right
.next(),
2316 Ordering
::Equal
=> {