1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator, Peekable};
6 use core::marker::PhantomData;
7 use core::ops::Bound::{Excluded, Included, Unbounded};
8 use core::ops::{Index, RangeBounds};
9 use core::{fmt, mem, ptr};
11 use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
12 use super::search::{self, SearchResult::*};
13 use super::unwrap_unchecked;
16 use UnderflowResult::*;
18 /// A map based on a B-Tree.
20 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
21 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
22 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
23 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
24 /// is done is *very* inefficient for modern computer architectures. In particular, every element
25 /// is stored in its own individually heap-allocated node. This means that every single insertion
26 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
27 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
30 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
31 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
32 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
33 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
34 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
35 /// the node using binary search. As a compromise, one could also perform a linear search
36 /// that initially only checks every i<sup>th</sup> element for some choice of i.
38 /// Currently, our implementation simply performs naive linear search. This provides excellent
39 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
40 /// would like to further explore choosing the optimal search strategy based on the choice of B,
41 /// and possibly other factors. Using linear search, searching for a random element is expected
42 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
43 /// however, performance is excellent.
45 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
46 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
47 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
49 /// [`Ord`]: ../../std/cmp/trait.Ord.html
50 /// [`Cell`]: ../../std/cell/struct.Cell.html
51 /// [`RefCell`]: ../../std/cell/struct.RefCell.html
56 /// use std::collections::BTreeMap;
58 /// // type inference lets us omit an explicit type signature (which
59 /// // would be `BTreeMap<&str, &str>` in this example).
60 /// let mut movie_reviews = BTreeMap::new();
62 /// // review some movies.
63 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
64 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
65 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
66 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
68 /// // check for a specific one.
69 /// if !movie_reviews.contains_key("Les Misérables") {
70 /// println!("We've got {} reviews, but Les Misérables ain't one.",
71 /// movie_reviews.len());
74 /// // oops, this review has a lot of spelling mistakes, let's delete it.
75 /// movie_reviews.remove("The Blues Brothers");
77 /// // look up the values associated with some keys.
78 /// let to_find = ["Up!", "Office Space"];
79 /// for movie in &to_find {
80 /// match movie_reviews.get(movie) {
81 /// Some(review) => println!("{}: {}", movie, review),
82 /// None => println!("{} is unreviewed.", movie)
86 /// // Look up the value for a key (will panic if the key is not found).
87 /// println!("Movie review: {}", movie_reviews["Office Space"]);
89 /// // iterate over everything.
90 /// for (movie, review) in &movie_reviews {
91 /// println!("{}: \"{}\"", movie, review);
95 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
96 /// for more complex methods of getting, setting, updating and removing keys and
100 /// use std::collections::BTreeMap;
102 /// // type inference lets us omit an explicit type signature (which
103 /// // would be `BTreeMap<&str, u8>` in this example).
104 /// let mut player_stats = BTreeMap::new();
106 /// fn random_stat_buff() -> u8 {
107 /// // could actually return some random value here - let's just return
108 /// // some fixed value for now
112 /// // insert a key only if it doesn't already exist
113 /// player_stats.entry("health").or_insert(100);
115 /// // insert a key using a function that provides a new value only if it
116 /// // doesn't already exist
117 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
119 /// // update a key, guarding against the key possibly not being set
120 /// let stat = player_stats.entry("attack").or_insert(100);
121 /// *stat += random_stat_buff();
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub struct BTreeMap<K, V> {
125 root: node::Root<K, V>,
129 #[stable(feature = "btree_drop", since = "1.7.0")]
130 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
133 drop(ptr::read(self).into_iter());
138 #[stable(feature = "rust1", since = "1.0.0")]
139 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
140 fn clone(&self) -> BTreeMap<K, V> {
141 fn clone_subtree<'a, K: Clone, V: Clone>(
142 node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
150 let mut out_tree = BTreeMap { root: node::Root::new_leaf(), length: 0 };
153 let mut out_node = match out_tree.root.as_mut().force() {
155 Internal(_) => unreachable!(),
158 let mut in_edge = leaf.first_edge();
159 while let Ok(kv) = in_edge.right_kv() {
160 let (k, v) = kv.into_kv();
161 in_edge = kv.right_edge();
163 out_node.push(k.clone(), v.clone());
164 out_tree.length += 1;
170 Internal(internal) => {
171 let mut out_tree = clone_subtree(internal.first_edge().descend());
174 let mut out_node = out_tree.root.push_level();
175 let mut in_edge = internal.first_edge();
176 while let Ok(kv) = in_edge.right_kv() {
177 let (k, v) = kv.into_kv();
178 in_edge = kv.right_edge();
180 let k = (*k).clone();
181 let v = (*v).clone();
182 let subtree = clone_subtree(in_edge.descend());
184 // We can't destructure subtree directly
185 // because BTreeMap implements Drop
186 let (subroot, sublength) = unsafe {
187 let root = ptr::read(&subtree.root);
188 let length = subtree.length;
189 mem::forget(subtree);
193 out_node.push(k, v, subroot);
194 out_tree.length += 1 + sublength;
204 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
205 // Ord` constraint, which this method lacks.
206 BTreeMap { root: node::Root::shared_empty_root(), length: 0 }
208 clone_subtree(self.root.as_ref())
212 fn clone_from(&mut self, other: &Self) {
213 BTreeClone::clone_from(self, other);
218 fn clone_from(&mut self, other: &Self);
221 impl<K: Clone, V: Clone> BTreeClone for BTreeMap<K, V> {
222 default fn clone_from(&mut self, other: &Self) {
223 *self = other.clone();
227 impl<K: Clone + Ord, V: Clone> BTreeClone for BTreeMap<K, V> {
228 fn clone_from(&mut self, other: &Self) {
229 // This truncates `self` to `other.len()` by calling `split_off` on
230 // the first key after `other.len()` elements if it exists
231 let split_off_key = if self.len() > other.len() {
232 let diff = self.len() - other.len();
233 if diff <= other.len() {
234 self.iter().nth_back(diff - 1).map(|pair| (*pair.0).clone())
236 self.iter().nth(other.len()).map(|pair| (*pair.0).clone())
241 if let Some(key) = split_off_key {
242 self.split_off(&key);
245 let mut siter = self.range_mut(..);
246 let mut oiter = other.iter();
247 // After truncation, `self` is at most as long as `other` so this loop
248 // replaces every key-value pair in `self`. Since `oiter` is in sorted
249 // order and the structure of the `BTreeMap` stays the same,
250 // the BTree invariants are maintained at the end of the loop
251 while !siter.is_empty() {
252 if let Some((ok, ov)) = oiter.next() {
253 // SAFETY: This is safe because the `siter.front != siter.back` check
254 // ensures that `siter` is nonempty
255 let (sk, sv) = unsafe { siter.next_unchecked() };
262 // If `other` is longer than `self`, the remaining elements are inserted
263 self.extend(oiter.map(|(k, v)| ((*k).clone(), (*v).clone())));
267 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
274 fn get(&self, key: &Q) -> Option<&K> {
275 match search::search_tree(self.root.as_ref(), key) {
276 Found(handle) => Some(handle.into_kv().0),
281 fn take(&mut self, key: &Q) -> Option<K> {
282 match search::search_tree(self.root.as_mut(), key) {
283 Found(handle) => Some(
284 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
292 fn replace(&mut self, key: K) -> Option<K> {
293 self.ensure_root_is_owned();
294 match search::search_tree::<marker::Mut<'_>, K, (), K>(self.root.as_mut(), &key) {
295 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
297 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
305 /// An iterator over the entries of a `BTreeMap`.
307 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
308 /// documentation for more.
310 /// [`iter`]: struct.BTreeMap.html#method.iter
311 /// [`BTreeMap`]: struct.BTreeMap.html
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub struct Iter<'a, K: 'a, V: 'a> {
314 range: Range<'a, K, V>,
318 #[stable(feature = "collection_debug", since = "1.17.0")]
319 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 f.debug_list().entries(self.clone()).finish()
325 /// A mutable iterator over the entries of a `BTreeMap`.
327 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
328 /// documentation for more.
330 /// [`iter_mut`]: struct.BTreeMap.html#method.iter_mut
331 /// [`BTreeMap`]: struct.BTreeMap.html
332 #[stable(feature = "rust1", since = "1.0.0")]
334 pub struct IterMut<'a, K: 'a, V: 'a> {
335 range: RangeMut<'a, K, V>,
339 /// An owning iterator over the entries of a `BTreeMap`.
341 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
342 /// (provided by the `IntoIterator` trait). See its documentation for more.
344 /// [`into_iter`]: struct.BTreeMap.html#method.into_iter
345 /// [`BTreeMap`]: struct.BTreeMap.html
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub struct IntoIter<K, V> {
348 front: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
349 back: Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>,
353 #[stable(feature = "collection_debug", since = "1.17.0")]
354 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 let range = Range { front: self.front.reborrow(), back: self.back.reborrow() };
357 f.debug_list().entries(range).finish()
361 /// An iterator over the keys of a `BTreeMap`.
363 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
364 /// documentation for more.
366 /// [`keys`]: struct.BTreeMap.html#method.keys
367 /// [`BTreeMap`]: struct.BTreeMap.html
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub struct Keys<'a, K: 'a, V: 'a> {
370 inner: Iter<'a, K, V>,
373 #[stable(feature = "collection_debug", since = "1.17.0")]
374 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.debug_list().entries(self.clone()).finish()
380 /// An iterator over the values of a `BTreeMap`.
382 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
383 /// documentation for more.
385 /// [`values`]: struct.BTreeMap.html#method.values
386 /// [`BTreeMap`]: struct.BTreeMap.html
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub struct Values<'a, K: 'a, V: 'a> {
389 inner: Iter<'a, K, V>,
392 #[stable(feature = "collection_debug", since = "1.17.0")]
393 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395 f.debug_list().entries(self.clone()).finish()
399 /// A mutable iterator over the values of a `BTreeMap`.
401 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
402 /// documentation for more.
404 /// [`values_mut`]: struct.BTreeMap.html#method.values_mut
405 /// [`BTreeMap`]: struct.BTreeMap.html
406 #[stable(feature = "map_values_mut", since = "1.10.0")]
408 pub struct ValuesMut<'a, K: 'a, V: 'a> {
409 inner: IterMut<'a, K, V>,
412 /// An iterator over a sub-range of entries in a `BTreeMap`.
414 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
415 /// documentation for more.
417 /// [`range`]: struct.BTreeMap.html#method.range
418 /// [`BTreeMap`]: struct.BTreeMap.html
419 #[stable(feature = "btree_range", since = "1.17.0")]
420 pub struct Range<'a, K: 'a, V: 'a> {
421 front: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
422 back: Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>,
425 #[stable(feature = "collection_debug", since = "1.17.0")]
426 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428 f.debug_list().entries(self.clone()).finish()
432 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
434 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
435 /// documentation for more.
437 /// [`range_mut`]: struct.BTreeMap.html#method.range_mut
438 /// [`BTreeMap`]: struct.BTreeMap.html
439 #[stable(feature = "btree_range", since = "1.17.0")]
440 pub struct RangeMut<'a, K: 'a, V: 'a> {
441 front: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
442 back: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
444 // Be invariant in `K` and `V`
445 _marker: PhantomData<&'a mut (K, V)>,
448 #[stable(feature = "collection_debug", since = "1.17.0")]
449 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
450 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 let range = Range { front: self.front.reborrow(), back: self.back.reborrow() };
452 f.debug_list().entries(range).finish()
456 /// A view into a single entry in a map, which may either be vacant or occupied.
458 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
460 /// [`BTreeMap`]: struct.BTreeMap.html
461 /// [`entry`]: struct.BTreeMap.html#method.entry
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub enum Entry<'a, K: 'a, V: 'a> {
465 #[stable(feature = "rust1", since = "1.0.0")]
466 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
468 /// An occupied entry.
469 #[stable(feature = "rust1", since = "1.0.0")]
470 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
473 #[stable(feature = "debug_btree_map", since = "1.12.0")]
474 impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
478 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
483 /// A view into a vacant entry in a `BTreeMap`.
484 /// It is part of the [`Entry`] enum.
486 /// [`Entry`]: enum.Entry.html
487 #[stable(feature = "rust1", since = "1.0.0")]
488 pub struct VacantEntry<'a, K: 'a, V: 'a> {
490 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
491 length: &'a mut usize,
493 // Be invariant in `K` and `V`
494 _marker: PhantomData<&'a mut (K, V)>,
497 #[stable(feature = "debug_btree_map", since = "1.12.0")]
498 impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 f.debug_tuple("VacantEntry").field(self.key()).finish()
504 /// A view into an occupied entry in a `BTreeMap`.
505 /// It is part of the [`Entry`] enum.
507 /// [`Entry`]: enum.Entry.html
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
510 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
512 length: &'a mut usize,
514 // Be invariant in `K` and `V`
515 _marker: PhantomData<&'a mut (K, V)>,
518 #[stable(feature = "debug_btree_map", since = "1.12.0")]
519 impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
525 // An iterator for merging two sorted sequences into one
526 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
531 impl<K: Ord, V> BTreeMap<K, V> {
532 /// Makes a new empty BTreeMap with a reasonable choice for B.
539 /// use std::collections::BTreeMap;
541 /// let mut map = BTreeMap::new();
543 /// // entries can now be inserted into the empty map
544 /// map.insert(1, "a");
546 #[stable(feature = "rust1", since = "1.0.0")]
547 pub fn new() -> BTreeMap<K, V> {
548 BTreeMap { root: node::Root::shared_empty_root(), length: 0 }
551 /// Clears the map, removing all elements.
558 /// use std::collections::BTreeMap;
560 /// let mut a = BTreeMap::new();
561 /// a.insert(1, "a");
563 /// assert!(a.is_empty());
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn clear(&mut self) {
567 *self = BTreeMap::new();
570 /// Returns a reference to the value corresponding to the key.
572 /// The key may be any borrowed form of the map's key type, but the ordering
573 /// on the borrowed form *must* match the ordering on the key type.
580 /// use std::collections::BTreeMap;
582 /// let mut map = BTreeMap::new();
583 /// map.insert(1, "a");
584 /// assert_eq!(map.get(&1), Some(&"a"));
585 /// assert_eq!(map.get(&2), None);
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
593 match search::search_tree(self.root.as_ref(), key) {
594 Found(handle) => Some(handle.into_kv().1),
599 /// Returns the key-value pair corresponding to the supplied key.
601 /// The supplied key may be any borrowed form of the map's key type, but the ordering
602 /// on the borrowed form *must* match the ordering on the key type.
607 /// use std::collections::BTreeMap;
609 /// let mut map = BTreeMap::new();
610 /// map.insert(1, "a");
611 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
612 /// assert_eq!(map.get_key_value(&2), None);
614 #[stable(feature = "map_get_key_value", since = "1.40.0")]
615 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
620 match search::search_tree(self.root.as_ref(), k) {
621 Found(handle) => Some(handle.into_kv()),
626 /// Returns the first key-value pair in the map.
627 /// The key in this pair is the minimum key in the map.
634 /// #![feature(map_first_last)]
635 /// use std::collections::BTreeMap;
637 /// let mut map = BTreeMap::new();
638 /// assert_eq!(map.first_key_value(), None);
639 /// map.insert(1, "b");
640 /// map.insert(2, "a");
641 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
643 #[unstable(feature = "map_first_last", issue = "62924")]
644 pub fn first_key_value<T: ?Sized>(&self) -> Option<(&K, &V)>
649 let front = self.root.as_ref().first_leaf_edge();
650 front.right_kv().ok().map(Handle::into_kv)
653 /// Returns the first entry in the map for in-place manipulation.
654 /// The key of this entry is the minimum key in the map.
658 /// Contrived way to `clear` a map:
661 /// #![feature(map_first_last)]
662 /// use std::collections::BTreeMap;
664 /// let mut map = BTreeMap::new();
665 /// map.insert(1, "a");
666 /// map.insert(2, "b");
667 /// while let Some(entry) = map.first_entry() {
668 /// let (key, val) = entry.remove_entry();
669 /// assert!(!map.contains_key(&key));
672 #[unstable(feature = "map_first_last", issue = "62924")]
673 pub fn first_entry<T: ?Sized>(&mut self) -> Option<OccupiedEntry<'_, K, V>>
678 let front = self.root.as_mut().first_leaf_edge();
679 if let Ok(kv) = front.right_kv() {
681 handle: kv.forget_node_type(),
682 length: &mut self.length,
683 _marker: PhantomData,
690 /// Returns the last key-value pair in the map.
691 /// The key in this pair is the maximum key in the map.
698 /// #![feature(map_first_last)]
699 /// use std::collections::BTreeMap;
701 /// let mut map = BTreeMap::new();
702 /// map.insert(1, "b");
703 /// map.insert(2, "a");
704 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
706 #[unstable(feature = "map_first_last", issue = "62924")]
707 pub fn last_key_value<T: ?Sized>(&self) -> Option<(&K, &V)>
712 let back = self.root.as_ref().last_leaf_edge();
713 back.left_kv().ok().map(Handle::into_kv)
716 /// Returns the last entry in the map for in-place manipulation.
717 /// The key of this entry is the maximum key in the map.
721 /// Contrived way to `clear` a map:
724 /// #![feature(map_first_last)]
725 /// use std::collections::BTreeMap;
727 /// let mut map = BTreeMap::new();
728 /// map.insert(1, "a");
729 /// map.insert(2, "b");
730 /// while let Some(entry) = map.last_entry() {
731 /// let (key, val) = entry.remove_entry();
732 /// assert!(!map.contains_key(&key));
735 #[unstable(feature = "map_first_last", issue = "62924")]
736 pub fn last_entry<T: ?Sized>(&mut self) -> Option<OccupiedEntry<'_, K, V>>
741 let back = self.root.as_mut().last_leaf_edge();
742 if let Ok(kv) = back.left_kv() {
744 handle: kv.forget_node_type(),
745 length: &mut self.length,
746 _marker: PhantomData,
753 /// Returns `true` if the map contains a value for the specified key.
755 /// The key may be any borrowed form of the map's key type, but the ordering
756 /// on the borrowed form *must* match the ordering on the key type.
763 /// use std::collections::BTreeMap;
765 /// let mut map = BTreeMap::new();
766 /// map.insert(1, "a");
767 /// assert_eq!(map.contains_key(&1), true);
768 /// assert_eq!(map.contains_key(&2), false);
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
776 self.get(key).is_some()
779 /// Returns a mutable reference to the value corresponding to the key.
781 /// The key may be any borrowed form of the map's key type, but the ordering
782 /// on the borrowed form *must* match the ordering on the key type.
789 /// use std::collections::BTreeMap;
791 /// let mut map = BTreeMap::new();
792 /// map.insert(1, "a");
793 /// if let Some(x) = map.get_mut(&1) {
796 /// assert_eq!(map[&1], "b");
798 // See `get` for implementation notes, this is basically a copy-paste with mut's added
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
805 match search::search_tree(self.root.as_mut(), key) {
806 Found(handle) => Some(handle.into_kv_mut().1),
811 /// Inserts a key-value pair into the map.
813 /// If the map did not have this key present, `None` is returned.
815 /// If the map did have this key present, the value is updated, and the old
816 /// value is returned. The key is not updated, though; this matters for
817 /// types that can be `==` without being identical. See the [module-level
818 /// documentation] for more.
820 /// [module-level documentation]: index.html#insert-and-complex-keys
827 /// use std::collections::BTreeMap;
829 /// let mut map = BTreeMap::new();
830 /// assert_eq!(map.insert(37, "a"), None);
831 /// assert_eq!(map.is_empty(), false);
833 /// map.insert(37, "b");
834 /// assert_eq!(map.insert(37, "c"), Some("b"));
835 /// assert_eq!(map[&37], "c");
837 #[stable(feature = "rust1", since = "1.0.0")]
838 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
839 match self.entry(key) {
840 Occupied(mut entry) => Some(entry.insert(value)),
848 /// Removes a key from the map, returning the value at the key if the key
849 /// was previously in the map.
851 /// The key may be any borrowed form of the map's key type, but the ordering
852 /// on the borrowed form *must* match the ordering on the key type.
859 /// use std::collections::BTreeMap;
861 /// let mut map = BTreeMap::new();
862 /// map.insert(1, "a");
863 /// assert_eq!(map.remove(&1), Some("a"));
864 /// assert_eq!(map.remove(&1), None);
866 #[stable(feature = "rust1", since = "1.0.0")]
867 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
872 self.remove_entry(key).map(|(_, v)| v)
875 /// Removes a key from the map, returning the stored key and value if the key
876 /// was previously in the map.
878 /// The key may be any borrowed form of the map's key type, but the ordering
879 /// on the borrowed form *must* match the ordering on the key type.
886 /// #![feature(btreemap_remove_entry)]
887 /// use std::collections::BTreeMap;
889 /// let mut map = BTreeMap::new();
890 /// map.insert(1, "a");
891 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
892 /// assert_eq!(map.remove_entry(&1), None);
894 #[unstable(feature = "btreemap_remove_entry", issue = "66714")]
895 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
900 match search::search_tree(self.root.as_mut(), key) {
901 Found(handle) => Some(
902 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
909 /// Moves all elements from `other` into `Self`, leaving `other` empty.
914 /// use std::collections::BTreeMap;
916 /// let mut a = BTreeMap::new();
917 /// a.insert(1, "a");
918 /// a.insert(2, "b");
919 /// a.insert(3, "c");
921 /// let mut b = BTreeMap::new();
922 /// b.insert(3, "d");
923 /// b.insert(4, "e");
924 /// b.insert(5, "f");
926 /// a.append(&mut b);
928 /// assert_eq!(a.len(), 5);
929 /// assert_eq!(b.len(), 0);
931 /// assert_eq!(a[&1], "a");
932 /// assert_eq!(a[&2], "b");
933 /// assert_eq!(a[&3], "d");
934 /// assert_eq!(a[&4], "e");
935 /// assert_eq!(a[&5], "f");
937 #[stable(feature = "btree_append", since = "1.11.0")]
938 pub fn append(&mut self, other: &mut Self) {
939 // Do we have to append anything at all?
940 if other.is_empty() {
944 // We can just swap `self` and `other` if `self` is empty.
946 mem::swap(self, other);
950 // First, we merge `self` and `other` into a sorted sequence in linear time.
951 let self_iter = mem::take(self).into_iter();
952 let other_iter = mem::take(other).into_iter();
953 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
955 // Second, we build a tree from the sorted sequence in linear time.
956 self.from_sorted_iter(iter);
957 self.fix_right_edge();
960 /// Constructs a double-ended iterator over a sub-range of elements in the map.
961 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
962 /// yield elements from min (inclusive) to max (exclusive).
963 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
964 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
965 /// range from 4 to 10.
969 /// Panics if range `start > end`.
970 /// Panics if range `start == end` and both bounds are `Excluded`.
977 /// use std::collections::BTreeMap;
978 /// use std::ops::Bound::Included;
980 /// let mut map = BTreeMap::new();
981 /// map.insert(3, "a");
982 /// map.insert(5, "b");
983 /// map.insert(8, "c");
984 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
985 /// println!("{}: {}", key, value);
987 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
989 #[stable(feature = "btree_range", since = "1.17.0")]
990 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
996 let root1 = self.root.as_ref();
997 let root2 = self.root.as_ref();
998 let (f, b) = range_search(root1, root2, range);
1000 Range { front: f, back: b }
1003 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1004 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1005 /// yield elements from min (inclusive) to max (exclusive).
1006 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1007 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1008 /// range from 4 to 10.
1012 /// Panics if range `start > end`.
1013 /// Panics if range `start == end` and both bounds are `Excluded`.
1020 /// use std::collections::BTreeMap;
1022 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1024 /// .map(|&s| (s, 0))
1026 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1027 /// *balance += 100;
1029 /// for (name, balance) in &map {
1030 /// println!("{} => {}", name, balance);
1033 #[stable(feature = "btree_range", since = "1.17.0")]
1034 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1040 let root1 = self.root.as_mut();
1041 let root2 = unsafe { ptr::read(&root1) };
1042 let (f, b) = range_search(root1, root2, range);
1044 RangeMut { front: f, back: b, _marker: PhantomData }
1047 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1054 /// use std::collections::BTreeMap;
1056 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1058 /// // count the number of occurrences of letters in the vec
1059 /// for x in vec!["a","b","a","c","a","b"] {
1060 /// *count.entry(x).or_insert(0) += 1;
1063 /// assert_eq!(count["a"], 3);
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1067 // FIXME(@porglezomp) Avoid allocating if we don't insert
1068 self.ensure_root_is_owned();
1069 match search::search_tree(self.root.as_mut(), &key) {
1071 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1074 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1079 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1080 self.ensure_root_is_owned();
1081 let mut cur_node = self.root.as_mut().last_leaf_edge().into_node();
1082 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1083 for (key, value) in iter {
1084 // Try to push key-value pair into the current leaf node.
1085 if cur_node.len() < node::CAPACITY {
1086 cur_node.push(key, value);
1088 // No space left, go up and push there.
1090 let mut test_node = cur_node.forget_type();
1092 match test_node.ascend() {
1094 let parent = parent.into_node();
1095 if parent.len() < node::CAPACITY {
1096 // Found a node with space left, push here.
1101 test_node = parent.forget_type();
1105 // We are at the top, create a new root node and push there.
1106 open_node = node.into_root_mut().push_level();
1112 // Push key-value pair and new right subtree.
1113 let tree_height = open_node.height() - 1;
1114 let mut right_tree = node::Root::new_leaf();
1115 for _ in 0..tree_height {
1116 right_tree.push_level();
1118 open_node.push(key, value, right_tree);
1120 // Go down to the right-most leaf again.
1121 cur_node = open_node.forget_type().last_leaf_edge().into_node();
1128 fn fix_right_edge(&mut self) {
1129 // Handle underfull nodes, start from the top.
1130 let mut cur_node = self.root.as_mut();
1131 while let Internal(internal) = cur_node.force() {
1132 // Check if right-most child is underfull.
1133 let mut last_edge = internal.last_edge();
1134 let right_child_len = last_edge.reborrow().descend().len();
1135 if right_child_len < node::MIN_LEN {
1136 // We need to steal.
1137 let mut last_kv = match last_edge.left_kv() {
1139 Err(_) => unreachable!(),
1141 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1142 last_edge = last_kv.right_edge();
1146 cur_node = last_edge.descend();
1150 /// Splits the collection into two at the given key. Returns everything after the given key,
1151 /// including the key.
1158 /// use std::collections::BTreeMap;
1160 /// let mut a = BTreeMap::new();
1161 /// a.insert(1, "a");
1162 /// a.insert(2, "b");
1163 /// a.insert(3, "c");
1164 /// a.insert(17, "d");
1165 /// a.insert(41, "e");
1167 /// let b = a.split_off(&3);
1169 /// assert_eq!(a.len(), 2);
1170 /// assert_eq!(b.len(), 3);
1172 /// assert_eq!(a[&1], "a");
1173 /// assert_eq!(a[&2], "b");
1175 /// assert_eq!(b[&3], "c");
1176 /// assert_eq!(b[&17], "d");
1177 /// assert_eq!(b[&41], "e");
1179 #[stable(feature = "btree_split_off", since = "1.11.0")]
1180 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1184 if self.is_empty() {
1188 let total_num = self.len();
1190 let mut right = Self::new();
1191 right.root = node::Root::new_leaf();
1192 for _ in 0..(self.root.as_ref().height()) {
1193 right.root.push_level();
1197 let mut left_node = self.root.as_mut();
1198 let mut right_node = right.root.as_mut();
1201 let mut split_edge = match search::search_node(left_node, key) {
1202 // key is going to the right tree
1203 Found(handle) => handle.left_edge(),
1204 GoDown(handle) => handle,
1207 split_edge.move_suffix(&mut right_node);
1209 match (split_edge.force(), right_node.force()) {
1210 (Internal(edge), Internal(node)) => {
1211 left_node = edge.descend();
1212 right_node = node.first_edge().descend();
1214 (Leaf(_), Leaf(_)) => {
1224 self.fix_right_border();
1225 right.fix_left_border();
1227 if self.root.as_ref().height() < right.root.as_ref().height() {
1228 self.recalc_length();
1229 right.length = total_num - self.len();
1231 right.recalc_length();
1232 self.length = total_num - right.len();
1238 /// Calculates the number of elements if it is incorrect.
1239 fn recalc_length(&mut self) {
1240 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1245 let mut res = node.len();
1247 if let Internal(node) = node.force() {
1248 let mut edge = node.first_edge();
1250 res += dfs(edge.reborrow().descend());
1251 match edge.right_kv() {
1253 edge = right_kv.right_edge();
1265 self.length = dfs(self.root.as_ref());
1268 /// Removes empty levels on the top.
1269 fn fix_top(&mut self) {
1272 let node = self.root.as_ref();
1273 if node.height() == 0 || node.len() > 0 {
1277 self.root.pop_level();
1281 fn fix_right_border(&mut self) {
1285 let mut cur_node = self.root.as_mut();
1287 while let Internal(node) = cur_node.force() {
1288 let mut last_kv = node.last_kv();
1290 if last_kv.can_merge() {
1291 cur_node = last_kv.merge().descend();
1293 let right_len = last_kv.reborrow().right_edge().descend().len();
1294 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
1295 if right_len < node::MIN_LEN + 1 {
1296 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
1298 cur_node = last_kv.right_edge().descend();
1306 /// The symmetric clone of `fix_right_border`.
1307 fn fix_left_border(&mut self) {
1311 let mut cur_node = self.root.as_mut();
1313 while let Internal(node) = cur_node.force() {
1314 let mut first_kv = node.first_kv();
1316 if first_kv.can_merge() {
1317 cur_node = first_kv.merge().descend();
1319 let left_len = first_kv.reborrow().left_edge().descend().len();
1320 if left_len < node::MIN_LEN + 1 {
1321 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
1323 cur_node = first_kv.left_edge().descend();
1331 /// If the root node is the shared root node, allocate our own node.
1332 fn ensure_root_is_owned(&mut self) {
1333 if self.root.is_shared_root() {
1334 self.root = node::Root::new_leaf();
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1341 type Item = (&'a K, &'a V);
1342 type IntoIter = Iter<'a, K, V>;
1344 fn into_iter(self) -> Iter<'a, K, V> {
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1351 type Item = (&'a K, &'a V);
1353 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1354 if self.length == 0 {
1358 unsafe { Some(self.range.next_unchecked()) }
1362 fn size_hint(&self) -> (usize, Option<usize>) {
1363 (self.length, Some(self.length))
1366 fn last(mut self) -> Option<(&'a K, &'a V)> {
1371 #[stable(feature = "fused", since = "1.26.0")]
1372 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1376 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1377 if self.length == 0 {
1381 unsafe { Some(self.range.next_back_unchecked()) }
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1388 fn len(&self) -> usize {
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl<K, V> Clone for Iter<'_, K, V> {
1395 fn clone(&self) -> Self {
1396 Iter { range: self.range.clone(), length: self.length }
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1402 type Item = (&'a K, &'a mut V);
1403 type IntoIter = IterMut<'a, K, V>;
1405 fn into_iter(self) -> IterMut<'a, K, V> {
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1412 type Item = (&'a K, &'a mut V);
1414 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1415 if self.length == 0 {
1419 let (k, v) = unsafe { self.range.next_unchecked() };
1420 Some((k, v)) // coerce k from `&mut K` to `&K`
1424 fn size_hint(&self) -> (usize, Option<usize>) {
1425 (self.length, Some(self.length))
1428 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1435 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1436 if self.length == 0 {
1440 let (k, v) = unsafe { self.range.next_back_unchecked() };
1441 Some((k, v)) // coerce k from `&mut K` to `&K`
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1448 fn len(&self) -> usize {
1453 #[stable(feature = "fused", since = "1.26.0")]
1454 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<K, V> IntoIterator for BTreeMap<K, V> {
1459 type IntoIter = IntoIter<K, V>;
1461 fn into_iter(self) -> IntoIter<K, V> {
1462 let root1 = unsafe { ptr::read(&self.root).into_ref() };
1463 let root2 = unsafe { ptr::read(&self.root).into_ref() };
1464 let len = self.length;
1467 IntoIter { front: root1.first_leaf_edge(), back: root2.last_leaf_edge(), length: len }
1471 #[stable(feature = "btree_drop", since = "1.7.0")]
1472 impl<K, V> Drop for IntoIter<K, V> {
1473 fn drop(&mut self) {
1474 self.for_each(drop);
1476 let leaf_node = ptr::read(&self.front).into_node();
1477 if leaf_node.is_shared_root() {
1481 if let Some(first_parent) = leaf_node.deallocate_and_ascend() {
1482 let mut cur_internal_node = first_parent.into_node();
1483 while let Some(parent) = cur_internal_node.deallocate_and_ascend() {
1484 cur_internal_node = parent.into_node()
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<K, V> Iterator for IntoIter<K, V> {
1495 fn next(&mut self) -> Option<(K, V)> {
1496 if self.length == 0 {
1500 Some(unsafe { self.front.next_unchecked() })
1504 fn size_hint(&self) -> (usize, Option<usize>) {
1505 (self.length, Some(self.length))
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1511 fn next_back(&mut self) -> Option<(K, V)> {
1512 if self.length == 0 {
1516 Some(unsafe { self.back.next_back_unchecked() })
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1523 fn len(&self) -> usize {
1528 #[stable(feature = "fused", since = "1.26.0")]
1529 impl<K, V> FusedIterator for IntoIter<K, V> {}
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1535 fn next(&mut self) -> Option<&'a K> {
1536 self.inner.next().map(|(k, _)| k)
1539 fn size_hint(&self) -> (usize, Option<usize>) {
1540 self.inner.size_hint()
1543 fn last(mut self) -> Option<&'a K> {
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1550 fn next_back(&mut self) -> Option<&'a K> {
1551 self.inner.next_back().map(|(k, _)| k)
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1557 fn len(&self) -> usize {
1562 #[stable(feature = "fused", since = "1.26.0")]
1563 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl<K, V> Clone for Keys<'_, K, V> {
1567 fn clone(&self) -> Self {
1568 Keys { inner: self.inner.clone() }
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<'a, K, V> Iterator for Values<'a, K, V> {
1576 fn next(&mut self) -> Option<&'a V> {
1577 self.inner.next().map(|(_, v)| v)
1580 fn size_hint(&self) -> (usize, Option<usize>) {
1581 self.inner.size_hint()
1584 fn last(mut self) -> Option<&'a V> {
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1591 fn next_back(&mut self) -> Option<&'a V> {
1592 self.inner.next_back().map(|(_, v)| v)
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1598 fn len(&self) -> usize {
1603 #[stable(feature = "fused", since = "1.26.0")]
1604 impl<K, V> FusedIterator for Values<'_, K, V> {}
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 impl<K, V> Clone for Values<'_, K, V> {
1608 fn clone(&self) -> Self {
1609 Values { inner: self.inner.clone() }
1613 #[stable(feature = "btree_range", since = "1.17.0")]
1614 impl<'a, K, V> Iterator for Range<'a, K, V> {
1615 type Item = (&'a K, &'a V);
1617 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1618 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1621 fn last(mut self) -> Option<(&'a K, &'a V)> {
1626 #[stable(feature = "map_values_mut", since = "1.10.0")]
1627 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1628 type Item = &'a mut V;
1630 fn next(&mut self) -> Option<&'a mut V> {
1631 self.inner.next().map(|(_, v)| v)
1634 fn size_hint(&self) -> (usize, Option<usize>) {
1635 self.inner.size_hint()
1638 fn last(mut self) -> Option<&'a mut V> {
1643 #[stable(feature = "map_values_mut", since = "1.10.0")]
1644 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1645 fn next_back(&mut self) -> Option<&'a mut V> {
1646 self.inner.next_back().map(|(_, v)| v)
1650 #[stable(feature = "map_values_mut", since = "1.10.0")]
1651 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1652 fn len(&self) -> usize {
1657 #[stable(feature = "fused", since = "1.26.0")]
1658 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1660 impl<'a, K, V> Range<'a, K, V> {
1661 fn is_empty(&self) -> bool {
1662 self.front == self.back
1665 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1666 self.front.next_unchecked()
1670 #[stable(feature = "btree_range", since = "1.17.0")]
1671 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1672 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1673 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1677 impl<'a, K, V> Range<'a, K, V> {
1678 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1679 self.back.next_back_unchecked()
1683 #[stable(feature = "fused", since = "1.26.0")]
1684 impl<K, V> FusedIterator for Range<'_, K, V> {}
1686 #[stable(feature = "btree_range", since = "1.17.0")]
1687 impl<K, V> Clone for Range<'_, K, V> {
1688 fn clone(&self) -> Self {
1689 Range { front: self.front, back: self.back }
1693 #[stable(feature = "btree_range", since = "1.17.0")]
1694 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1695 type Item = (&'a K, &'a mut V);
1697 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1698 if self.is_empty() {
1701 let (k, v) = unsafe { self.next_unchecked() };
1702 Some((k, v)) // coerce k from `&mut K` to `&K`
1706 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1711 impl<'a, K, V> RangeMut<'a, K, V> {
1712 fn is_empty(&self) -> bool {
1713 self.front == self.back
1716 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1717 self.front.next_unchecked()
1721 #[stable(feature = "btree_range", since = "1.17.0")]
1722 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1723 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1724 if self.is_empty() {
1727 let (k, v) = unsafe { self.next_back_unchecked() };
1728 Some((k, v)) // coerce k from `&mut K` to `&K`
1733 #[stable(feature = "fused", since = "1.26.0")]
1734 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1736 impl<'a, K, V> RangeMut<'a, K, V> {
1737 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1738 self.back.next_back_unchecked()
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1744 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1745 let mut map = BTreeMap::new();
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1754 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1755 iter.into_iter().for_each(move |(k, v)| {
1761 #[stable(feature = "extend_ref", since = "1.2.0")]
1762 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1763 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1764 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1770 fn hash<H: Hasher>(&self, state: &mut H) {
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 impl<K: Ord, V> Default for BTreeMap<K, V> {
1779 /// Creates an empty `BTreeMap<K, V>`.
1780 fn default() -> BTreeMap<K, V> {
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1787 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1788 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1798 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1799 self.iter().partial_cmp(other.iter())
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1806 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1807 self.iter().cmp(other.iter())
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1813 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1814 f.debug_map().entries(self.iter()).finish()
1818 #[stable(feature = "rust1", since = "1.0.0")]
1819 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1826 /// Returns a reference to the value corresponding to the supplied key.
1830 /// Panics if the key is not present in the `BTreeMap`.
1832 fn index(&self, key: &Q) -> &V {
1833 self.get(key).expect("no entry found for key")
1837 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
1838 root1: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1839 root2: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1842 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1843 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1849 match (range.start_bound(), range.end_bound()) {
1850 (Excluded(s), Excluded(e)) if s == e => {
1851 panic!("range start and end are equal and excluded in BTreeMap")
1853 (Included(s), Included(e))
1854 | (Included(s), Excluded(e))
1855 | (Excluded(s), Included(e))
1856 | (Excluded(s), Excluded(e))
1859 panic!("range start is greater than range end in BTreeMap")
1864 let mut min_node = root1;
1865 let mut max_node = root2;
1866 let mut min_found = false;
1867 let mut max_found = false;
1870 let front = match (min_found, range.start_bound()) {
1871 (false, Included(key)) => match search::search_node(min_node, key) {
1876 GoDown(edge) => edge,
1878 (false, Excluded(key)) => match search::search_node(min_node, key) {
1883 GoDown(edge) => edge,
1885 (true, Included(_)) => min_node.last_edge(),
1886 (true, Excluded(_)) => min_node.first_edge(),
1887 (_, Unbounded) => min_node.first_edge(),
1890 let back = match (max_found, range.end_bound()) {
1891 (false, Included(key)) => match search::search_node(max_node, key) {
1896 GoDown(edge) => edge,
1898 (false, Excluded(key)) => match search::search_node(max_node, key) {
1903 GoDown(edge) => edge,
1905 (true, Included(_)) => max_node.first_edge(),
1906 (true, Excluded(_)) => max_node.last_edge(),
1907 (_, Unbounded) => max_node.last_edge(),
1910 if front.partial_cmp(&back) == Some(Ordering::Greater) {
1911 panic!("Ord is ill-defined in BTreeMap range");
1913 match (front.force(), back.force()) {
1914 (Leaf(f), Leaf(b)) => {
1917 (Internal(min_int), Internal(max_int)) => {
1918 min_node = min_int.descend();
1919 max_node = max_int.descend();
1921 _ => unreachable!("BTreeMap has different depths"),
1926 impl<K, V> BTreeMap<K, V> {
1927 /// Gets an iterator over the entries of the map, sorted by key.
1934 /// use std::collections::BTreeMap;
1936 /// let mut map = BTreeMap::new();
1937 /// map.insert(3, "c");
1938 /// map.insert(2, "b");
1939 /// map.insert(1, "a");
1941 /// for (key, value) in map.iter() {
1942 /// println!("{}: {}", key, value);
1945 /// let (first_key, first_value) = map.iter().next().unwrap();
1946 /// assert_eq!((*first_key, *first_value), (1, "a"));
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub fn iter(&self) -> Iter<'_, K, V> {
1952 front: self.root.as_ref().first_leaf_edge(),
1953 back: self.root.as_ref().last_leaf_edge(),
1955 length: self.length,
1959 /// Gets a mutable iterator over the entries of the map, sorted by key.
1966 /// use std::collections::BTreeMap;
1968 /// let mut map = BTreeMap::new();
1969 /// map.insert("a", 1);
1970 /// map.insert("b", 2);
1971 /// map.insert("c", 3);
1973 /// // add 10 to the value if the key isn't "a"
1974 /// for (key, value) in map.iter_mut() {
1975 /// if key != &"a" {
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
1982 let root1 = self.root.as_mut();
1983 let root2 = unsafe { ptr::read(&root1) };
1986 front: root1.first_leaf_edge(),
1987 back: root2.last_leaf_edge(),
1988 _marker: PhantomData,
1990 length: self.length,
1994 /// Gets an iterator over the keys of the map, in sorted order.
2001 /// use std::collections::BTreeMap;
2003 /// let mut a = BTreeMap::new();
2004 /// a.insert(2, "b");
2005 /// a.insert(1, "a");
2007 /// let keys: Vec<_> = a.keys().cloned().collect();
2008 /// assert_eq!(keys, [1, 2]);
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 pub fn keys(&self) -> Keys<'_, K, V> {
2012 Keys { inner: self.iter() }
2015 /// Gets an iterator over the values of the map, in order by key.
2022 /// use std::collections::BTreeMap;
2024 /// let mut a = BTreeMap::new();
2025 /// a.insert(1, "hello");
2026 /// a.insert(2, "goodbye");
2028 /// let values: Vec<&str> = a.values().cloned().collect();
2029 /// assert_eq!(values, ["hello", "goodbye"]);
2031 #[stable(feature = "rust1", since = "1.0.0")]
2032 pub fn values(&self) -> Values<'_, K, V> {
2033 Values { inner: self.iter() }
2036 /// Gets a mutable iterator over the values of the map, in order by key.
2043 /// use std::collections::BTreeMap;
2045 /// let mut a = BTreeMap::new();
2046 /// a.insert(1, String::from("hello"));
2047 /// a.insert(2, String::from("goodbye"));
2049 /// for value in a.values_mut() {
2050 /// value.push_str("!");
2053 /// let values: Vec<String> = a.values().cloned().collect();
2054 /// assert_eq!(values, [String::from("hello!"),
2055 /// String::from("goodbye!")]);
2057 #[stable(feature = "map_values_mut", since = "1.10.0")]
2058 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2059 ValuesMut { inner: self.iter_mut() }
2062 /// Returns the number of elements in the map.
2069 /// use std::collections::BTreeMap;
2071 /// let mut a = BTreeMap::new();
2072 /// assert_eq!(a.len(), 0);
2073 /// a.insert(1, "a");
2074 /// assert_eq!(a.len(), 1);
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 pub fn len(&self) -> usize {
2081 /// Returns `true` if the map contains no elements.
2088 /// use std::collections::BTreeMap;
2090 /// let mut a = BTreeMap::new();
2091 /// assert!(a.is_empty());
2092 /// a.insert(1, "a");
2093 /// assert!(!a.is_empty());
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 pub fn is_empty(&self) -> bool {
2101 impl<'a, K: Ord, V> Entry<'a, K, V> {
2102 /// Ensures a value is in the entry by inserting the default if empty, and returns
2103 /// a mutable reference to the value in the entry.
2108 /// use std::collections::BTreeMap;
2110 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2111 /// map.entry("poneyland").or_insert(12);
2113 /// assert_eq!(map["poneyland"], 12);
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 pub fn or_insert(self, default: V) -> &'a mut V {
2118 Occupied(entry) => entry.into_mut(),
2119 Vacant(entry) => entry.insert(default),
2123 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2124 /// and returns a mutable reference to the value in the entry.
2129 /// use std::collections::BTreeMap;
2131 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2132 /// let s = "hoho".to_string();
2134 /// map.entry("poneyland").or_insert_with(|| s);
2136 /// assert_eq!(map["poneyland"], "hoho".to_string());
2138 #[stable(feature = "rust1", since = "1.0.0")]
2139 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2141 Occupied(entry) => entry.into_mut(),
2142 Vacant(entry) => entry.insert(default()),
2146 /// Returns a reference to this entry's key.
2151 /// use std::collections::BTreeMap;
2153 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2154 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2156 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2157 pub fn key(&self) -> &K {
2159 Occupied(ref entry) => entry.key(),
2160 Vacant(ref entry) => entry.key(),
2164 /// Provides in-place mutable access to an occupied entry before any
2165 /// potential inserts into the map.
2170 /// use std::collections::BTreeMap;
2172 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2174 /// map.entry("poneyland")
2175 /// .and_modify(|e| { *e += 1 })
2177 /// assert_eq!(map["poneyland"], 42);
2179 /// map.entry("poneyland")
2180 /// .and_modify(|e| { *e += 1 })
2182 /// assert_eq!(map["poneyland"], 43);
2184 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2185 pub fn and_modify<F>(self, f: F) -> Self
2190 Occupied(mut entry) => {
2194 Vacant(entry) => Vacant(entry),
2199 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2200 #[stable(feature = "entry_or_default", since = "1.28.0")]
2201 /// Ensures a value is in the entry by inserting the default value if empty,
2202 /// and returns a mutable reference to the value in the entry.
2207 /// use std::collections::BTreeMap;
2209 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2210 /// map.entry("poneyland").or_default();
2212 /// assert_eq!(map["poneyland"], None);
2214 pub fn or_default(self) -> &'a mut V {
2216 Occupied(entry) => entry.into_mut(),
2217 Vacant(entry) => entry.insert(Default::default()),
2222 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2223 /// Gets a reference to the key that would be used when inserting a value
2224 /// through the VacantEntry.
2229 /// use std::collections::BTreeMap;
2231 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2232 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2234 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2235 pub fn key(&self) -> &K {
2239 /// Take ownership of the key.
2244 /// use std::collections::BTreeMap;
2245 /// use std::collections::btree_map::Entry;
2247 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2249 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2253 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2254 pub fn into_key(self) -> K {
2258 /// Sets the value of the entry with the `VacantEntry`'s key,
2259 /// and returns a mutable reference to it.
2264 /// use std::collections::BTreeMap;
2266 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
2268 /// // count the number of occurrences of letters in the vec
2269 /// for x in vec!["a","b","a","c","a","b"] {
2270 /// *count.entry(x).or_insert(0) += 1;
2273 /// assert_eq!(count["a"], 3);
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 pub fn insert(self, value: V) -> &'a mut V {
2285 let mut cur_parent = match self.handle.insert(self.key, value) {
2286 (Fit(handle), _) => return handle.into_kv_mut().1,
2287 (Split(left, k, v, right), ptr) => {
2292 left.ascend().map_err(|n| n.into_root_mut())
2298 Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
2299 Fit(_) => return unsafe { &mut *out_ptr },
2300 Split(left, k, v, right) => {
2304 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2308 root.push_level().push(ins_k, ins_v, ins_edge);
2309 return unsafe { &mut *out_ptr };
2316 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2317 /// Gets a reference to the key in the entry.
2322 /// use std::collections::BTreeMap;
2324 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2325 /// map.entry("poneyland").or_insert(12);
2326 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2328 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2329 pub fn key(&self) -> &K {
2330 self.handle.reborrow().into_kv().0
2333 /// Take ownership of the key and value from the map.
2338 /// use std::collections::BTreeMap;
2339 /// use std::collections::btree_map::Entry;
2341 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2342 /// map.entry("poneyland").or_insert(12);
2344 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2345 /// // We delete the entry from the map.
2346 /// o.remove_entry();
2349 /// // If now try to get the value, it will panic:
2350 /// // println!("{}", map["poneyland"]);
2352 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2353 pub fn remove_entry(self) -> (K, V) {
2357 /// Gets a reference to the value in the entry.
2362 /// use std::collections::BTreeMap;
2363 /// use std::collections::btree_map::Entry;
2365 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2366 /// map.entry("poneyland").or_insert(12);
2368 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2369 /// assert_eq!(o.get(), &12);
2372 #[stable(feature = "rust1", since = "1.0.0")]
2373 pub fn get(&self) -> &V {
2374 self.handle.reborrow().into_kv().1
2377 /// Gets a mutable reference to the value in the entry.
2379 /// If you need a reference to the `OccupiedEntry` that may outlive the
2380 /// destruction of the `Entry` value, see [`into_mut`].
2382 /// [`into_mut`]: #method.into_mut
2387 /// use std::collections::BTreeMap;
2388 /// use std::collections::btree_map::Entry;
2390 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2391 /// map.entry("poneyland").or_insert(12);
2393 /// assert_eq!(map["poneyland"], 12);
2394 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2395 /// *o.get_mut() += 10;
2396 /// assert_eq!(*o.get(), 22);
2398 /// // We can use the same Entry multiple times.
2399 /// *o.get_mut() += 2;
2401 /// assert_eq!(map["poneyland"], 24);
2403 #[stable(feature = "rust1", since = "1.0.0")]
2404 pub fn get_mut(&mut self) -> &mut V {
2405 self.handle.kv_mut().1
2408 /// Converts the entry into a mutable reference to its value.
2410 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2412 /// [`get_mut`]: #method.get_mut
2417 /// use std::collections::BTreeMap;
2418 /// use std::collections::btree_map::Entry;
2420 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2421 /// map.entry("poneyland").or_insert(12);
2423 /// assert_eq!(map["poneyland"], 12);
2424 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2425 /// *o.into_mut() += 10;
2427 /// assert_eq!(map["poneyland"], 22);
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 pub fn into_mut(self) -> &'a mut V {
2431 self.handle.into_kv_mut().1
2434 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2435 /// and returns the entry's old value.
2440 /// use std::collections::BTreeMap;
2441 /// use std::collections::btree_map::Entry;
2443 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2444 /// map.entry("poneyland").or_insert(12);
2446 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2447 /// assert_eq!(o.insert(15), 12);
2449 /// assert_eq!(map["poneyland"], 15);
2451 #[stable(feature = "rust1", since = "1.0.0")]
2452 pub fn insert(&mut self, value: V) -> V {
2453 mem::replace(self.get_mut(), value)
2456 /// Takes the value of the entry out of the map, and returns it.
2461 /// use std::collections::BTreeMap;
2462 /// use std::collections::btree_map::Entry;
2464 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2465 /// map.entry("poneyland").or_insert(12);
2467 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2468 /// assert_eq!(o.remove(), 12);
2470 /// // If we try to get "poneyland"'s value, it'll panic:
2471 /// // println!("{}", map["poneyland"]);
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 pub fn remove(self) -> V {
2478 fn remove_kv(self) -> (K, V) {
2481 let (small_leaf, old_key, old_val) = match self.handle.force() {
2483 let (hole, old_key, old_val) = leaf.remove();
2484 (hole.into_node(), old_key, old_val)
2486 Internal(mut internal) => {
2487 let key_loc = internal.kv_mut().0 as *mut K;
2488 let val_loc = internal.kv_mut().1 as *mut V;
2490 let to_remove = internal.right_edge().descend().first_leaf_edge().right_kv().ok();
2491 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2493 let (hole, key, val) = to_remove.remove();
2495 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2496 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2498 (hole.into_node(), old_key, old_val)
2503 let mut cur_node = small_leaf.forget_type();
2504 while cur_node.len() < node::MIN_LEN {
2505 match handle_underfull_node(cur_node) {
2507 EmptyParent(_) => unreachable!(),
2509 if parent.len() == 0 {
2510 // We must be at the root
2511 parent.into_root_mut().pop_level();
2514 cur_node = parent.forget_type();
2525 enum UnderflowResult<'a, K, V> {
2527 EmptyParent(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2528 Merged(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2529 Stole(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2532 fn handle_underfull_node<K, V>(
2533 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2534 ) -> UnderflowResult<'_, K, V> {
2535 let parent = if let Ok(parent) = node.ascend() {
2541 let (is_left, mut handle) = match parent.left_kv() {
2542 Ok(left) => (true, left),
2543 Err(parent) => match parent.right_kv() {
2544 Ok(right) => (false, right),
2546 return EmptyParent(parent.into_node());
2551 if handle.can_merge() {
2552 Merged(handle.merge().into_node())
2555 handle.steal_left();
2557 handle.steal_right();
2559 Stole(handle.into_node())
2563 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2566 fn next(&mut self) -> Option<(K, V)> {
2567 let res = match (self.left.peek(), self.right.peek()) {
2568 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2569 (Some(_), None) => Ordering::Less,
2570 (None, Some(_)) => Ordering::Greater,
2571 (None, None) => return None,
2574 // Check which elements comes first and only advance the corresponding iterator.
2575 // If two keys are equal, take the value from `right`.
2577 Ordering::Less => self.left.next(),
2578 Ordering::Greater => self.right.next(),
2579 Ordering::Equal => {