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::mem::{self, ManuallyDrop};
8 use core::ops::Bound::{Excluded, Included, Unbounded};
9 use core::ops::{Index, RangeBounds};
12 use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
13 use super::search::{self, SearchResult::*};
14 use super::unwrap_unchecked;
17 use UnderflowResult::*;
19 /// A map based on a B-Tree.
21 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
22 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
23 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
24 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
25 /// is done is *very* inefficient for modern computer architectures. In particular, every element
26 /// is stored in its own individually heap-allocated node. This means that every single insertion
27 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
28 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
31 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
32 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
33 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
34 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
35 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
36 /// the node using binary search. As a compromise, one could also perform a linear search
37 /// that initially only checks every i<sup>th</sup> element for some choice of i.
39 /// Currently, our implementation simply performs naive linear search. This provides excellent
40 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
41 /// would like to further explore choosing the optimal search strategy based on the choice of B,
42 /// and possibly other factors. Using linear search, searching for a random element is expected
43 /// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
44 /// however, performance is excellent.
46 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
47 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
48 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
50 /// [`Ord`]: core::cmp::Ord
51 /// [`Cell`]: core::cell::Cell
52 /// [`RefCell`]: core::cell::RefCell
57 /// use std::collections::BTreeMap;
59 /// // type inference lets us omit an explicit type signature (which
60 /// // would be `BTreeMap<&str, &str>` in this example).
61 /// let mut movie_reviews = BTreeMap::new();
63 /// // review some movies.
64 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
65 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
66 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
67 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
69 /// // check for a specific one.
70 /// if !movie_reviews.contains_key("Les Misérables") {
71 /// println!("We've got {} reviews, but Les Misérables ain't one.",
72 /// movie_reviews.len());
75 /// // oops, this review has a lot of spelling mistakes, let's delete it.
76 /// movie_reviews.remove("The Blues Brothers");
78 /// // look up the values associated with some keys.
79 /// let to_find = ["Up!", "Office Space"];
80 /// for movie in &to_find {
81 /// match movie_reviews.get(movie) {
82 /// Some(review) => println!("{}: {}", movie, review),
83 /// None => println!("{} is unreviewed.", movie)
87 /// // Look up the value for a key (will panic if the key is not found).
88 /// println!("Movie review: {}", movie_reviews["Office Space"]);
90 /// // iterate over everything.
91 /// for (movie, review) in &movie_reviews {
92 /// println!("{}: \"{}\"", movie, review);
96 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
97 /// for more complex methods of getting, setting, updating and removing keys and
101 /// use std::collections::BTreeMap;
103 /// // type inference lets us omit an explicit type signature (which
104 /// // would be `BTreeMap<&str, u8>` in this example).
105 /// let mut player_stats = BTreeMap::new();
107 /// fn random_stat_buff() -> u8 {
108 /// // could actually return some random value here - let's just return
109 /// // some fixed value for now
113 /// // insert a key only if it doesn't already exist
114 /// player_stats.entry("health").or_insert(100);
116 /// // insert a key using a function that provides a new value only if it
117 /// // doesn't already exist
118 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
120 /// // update a key, guarding against the key possibly not being set
121 /// let stat = player_stats.entry("attack").or_insert(100);
122 /// *stat += random_stat_buff();
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub struct BTreeMap<K, V> {
126 root: Option<node::Root<K, V>>,
130 #[stable(feature = "btree_drop", since = "1.7.0")]
131 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
134 drop(ptr::read(self).into_iter());
139 #[stable(feature = "rust1", since = "1.0.0")]
140 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
141 fn clone(&self) -> BTreeMap<K, V> {
142 fn clone_subtree<'a, K: Clone, V: Clone>(
143 node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
151 let mut out_tree = BTreeMap { root: Some(node::Root::new_leaf()), length: 0 };
154 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
155 let mut out_node = match root.as_mut().force() {
157 Internal(_) => unreachable!(),
160 let mut in_edge = leaf.first_edge();
161 while let Ok(kv) = in_edge.right_kv() {
162 let (k, v) = kv.into_kv();
163 in_edge = kv.right_edge();
165 out_node.push(k.clone(), v.clone());
166 out_tree.length += 1;
172 Internal(internal) => {
173 let mut out_tree = clone_subtree(internal.first_edge().descend());
176 let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
177 let mut out_node = out_root.push_level();
178 let mut in_edge = internal.first_edge();
179 while let Ok(kv) = in_edge.right_kv() {
180 let (k, v) = kv.into_kv();
181 in_edge = kv.right_edge();
183 let k = (*k).clone();
184 let v = (*v).clone();
185 let subtree = clone_subtree(in_edge.descend());
187 // We can't destructure subtree directly
188 // because BTreeMap implements Drop
189 let (subroot, sublength) = unsafe {
190 let subtree = ManuallyDrop::new(subtree);
191 let root = ptr::read(&subtree.root);
192 let length = subtree.length;
196 out_node.push(k, v, subroot.unwrap_or_else(node::Root::new_leaf));
197 out_tree.length += 1 + sublength;
207 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
208 // Ord` constraint, which this method lacks.
209 BTreeMap { root: None, length: 0 }
211 clone_subtree(self.root.as_ref().unwrap().as_ref()) // unwrap succeeds because not empty
216 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
223 fn get(&self, key: &Q) -> Option<&K> {
224 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
225 Found(handle) => Some(handle.into_kv().0),
230 fn take(&mut self, key: &Q) -> Option<K> {
231 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
232 Found(handle) => Some(
233 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
241 fn replace(&mut self, key: K) -> Option<K> {
242 let root = Self::ensure_is_owned(&mut self.root);
243 match search::search_tree::<marker::Mut<'_>, K, (), K>(root.as_mut(), &key) {
244 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
246 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
254 /// An iterator over the entries of a `BTreeMap`.
256 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
257 /// documentation for more.
259 /// [`iter`]: BTreeMap::iter
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub struct Iter<'a, K: 'a, V: 'a> {
262 range: Range<'a, K, V>,
266 #[stable(feature = "collection_debug", since = "1.17.0")]
267 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 f.debug_list().entries(self.clone()).finish()
273 /// A mutable iterator over the entries of a `BTreeMap`.
275 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
276 /// documentation for more.
278 /// [`iter_mut`]: BTreeMap::iter_mut
279 #[stable(feature = "rust1", since = "1.0.0")]
281 pub struct IterMut<'a, K: 'a, V: 'a> {
282 range: RangeMut<'a, K, V>,
286 /// An owning iterator over the entries of a `BTreeMap`.
288 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
289 /// (provided by the `IntoIterator` trait). See its documentation for more.
291 /// [`into_iter`]: IntoIterator::into_iter
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub struct IntoIter<K, V> {
294 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
295 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
299 #[stable(feature = "collection_debug", since = "1.17.0")]
300 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 front: self.front.as_ref().map(|f| f.reborrow()),
304 back: self.back.as_ref().map(|b| b.reborrow()),
306 f.debug_list().entries(range).finish()
310 /// An iterator over the keys of a `BTreeMap`.
312 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
313 /// documentation for more.
315 /// [`keys`]: BTreeMap::keys
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub struct Keys<'a, K: 'a, V: 'a> {
318 inner: Iter<'a, K, V>,
321 #[stable(feature = "collection_debug", since = "1.17.0")]
322 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324 f.debug_list().entries(self.clone()).finish()
328 /// An iterator over the values of a `BTreeMap`.
330 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
331 /// documentation for more.
333 /// [`values`]: BTreeMap::values
334 #[stable(feature = "rust1", since = "1.0.0")]
335 pub struct Values<'a, K: 'a, V: 'a> {
336 inner: Iter<'a, K, V>,
339 #[stable(feature = "collection_debug", since = "1.17.0")]
340 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 f.debug_list().entries(self.clone()).finish()
346 /// A mutable iterator over the values of a `BTreeMap`.
348 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
349 /// documentation for more.
351 /// [`values_mut`]: BTreeMap::values_mut
352 #[stable(feature = "map_values_mut", since = "1.10.0")]
354 pub struct ValuesMut<'a, K: 'a, V: 'a> {
355 inner: IterMut<'a, K, V>,
358 /// An iterator over a sub-range of entries in a `BTreeMap`.
360 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
361 /// documentation for more.
363 /// [`range`]: BTreeMap::range
364 #[stable(feature = "btree_range", since = "1.17.0")]
365 pub struct Range<'a, K: 'a, V: 'a> {
366 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
367 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
370 #[stable(feature = "collection_debug", since = "1.17.0")]
371 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 f.debug_list().entries(self.clone()).finish()
377 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
379 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
380 /// documentation for more.
382 /// [`range_mut`]: BTreeMap::range_mut
383 #[stable(feature = "btree_range", since = "1.17.0")]
384 pub struct RangeMut<'a, K: 'a, V: 'a> {
385 front: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
386 back: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
388 // Be invariant in `K` and `V`
389 _marker: PhantomData<&'a mut (K, V)>,
392 #[stable(feature = "collection_debug", since = "1.17.0")]
393 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 front: self.front.as_ref().map(|f| f.reborrow()),
397 back: self.back.as_ref().map(|b| b.reborrow()),
399 f.debug_list().entries(range).finish()
403 /// A view into a single entry in a map, which may either be vacant or occupied.
405 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
407 /// [`entry`]: BTreeMap::entry
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub enum Entry<'a, K: 'a, V: 'a> {
411 #[stable(feature = "rust1", since = "1.0.0")]
412 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
414 /// An occupied entry.
415 #[stable(feature = "rust1", since = "1.0.0")]
416 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
419 #[stable(feature = "debug_btree_map", since = "1.12.0")]
420 impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
424 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
429 /// A view into a vacant entry in a `BTreeMap`.
430 /// It is part of the [`Entry`] enum.
432 /// [`Entry`]: enum.Entry.html
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub struct VacantEntry<'a, K: 'a, V: 'a> {
436 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
437 length: &'a mut usize,
439 // Be invariant in `K` and `V`
440 _marker: PhantomData<&'a mut (K, V)>,
443 #[stable(feature = "debug_btree_map", since = "1.12.0")]
444 impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
445 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446 f.debug_tuple("VacantEntry").field(self.key()).finish()
450 /// A view into an occupied entry in a `BTreeMap`.
451 /// It is part of the [`Entry`] enum.
453 /// [`Entry`]: enum.Entry.html
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
456 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
458 length: &'a mut usize,
460 // Be invariant in `K` and `V`
461 _marker: PhantomData<&'a mut (K, V)>,
464 #[stable(feature = "debug_btree_map", since = "1.12.0")]
465 impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
471 // An iterator for merging two sorted sequences into one
472 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
477 impl<K: Ord, V> BTreeMap<K, V> {
478 /// Makes a new empty BTreeMap.
480 /// Does not allocate anything on its own.
487 /// use std::collections::BTreeMap;
489 /// let mut map = BTreeMap::new();
491 /// // entries can now be inserted into the empty map
492 /// map.insert(1, "a");
494 #[stable(feature = "rust1", since = "1.0.0")]
495 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
496 pub const fn new() -> BTreeMap<K, V> {
497 BTreeMap { root: None, length: 0 }
500 /// Clears the map, removing all elements.
507 /// use std::collections::BTreeMap;
509 /// let mut a = BTreeMap::new();
510 /// a.insert(1, "a");
512 /// assert!(a.is_empty());
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn clear(&mut self) {
516 *self = BTreeMap::new();
519 /// Returns a reference to the value corresponding to the key.
521 /// The key may be any borrowed form of the map's key type, but the ordering
522 /// on the borrowed form *must* match the ordering on the key type.
529 /// use std::collections::BTreeMap;
531 /// let mut map = BTreeMap::new();
532 /// map.insert(1, "a");
533 /// assert_eq!(map.get(&1), Some(&"a"));
534 /// assert_eq!(map.get(&2), None);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
542 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
543 Found(handle) => Some(handle.into_kv().1),
548 /// Returns the key-value pair corresponding to the supplied key.
550 /// The supplied key may be any borrowed form of the map's key type, but the ordering
551 /// on the borrowed form *must* match the ordering on the key type.
556 /// use std::collections::BTreeMap;
558 /// let mut map = BTreeMap::new();
559 /// map.insert(1, "a");
560 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
561 /// assert_eq!(map.get_key_value(&2), None);
563 #[stable(feature = "map_get_key_value", since = "1.40.0")]
564 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
569 match search::search_tree(self.root.as_ref()?.as_ref(), k) {
570 Found(handle) => Some(handle.into_kv()),
575 /// Returns the first key-value pair in the map.
576 /// The key in this pair is the minimum key in the map.
583 /// #![feature(map_first_last)]
584 /// use std::collections::BTreeMap;
586 /// let mut map = BTreeMap::new();
587 /// assert_eq!(map.first_key_value(), None);
588 /// map.insert(1, "b");
589 /// map.insert(2, "a");
590 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
592 #[unstable(feature = "map_first_last", issue = "62924")]
593 pub fn first_key_value(&self) -> Option<(&K, &V)> {
594 let front = self.root.as_ref()?.as_ref().first_leaf_edge();
595 front.right_kv().ok().map(Handle::into_kv)
598 /// Returns the first entry in the map for in-place manipulation.
599 /// The key of this entry is the minimum key in the map.
604 /// #![feature(map_first_last)]
605 /// use std::collections::BTreeMap;
607 /// let mut map = BTreeMap::new();
608 /// map.insert(1, "a");
609 /// map.insert(2, "b");
610 /// if let Some(mut entry) = map.first_entry() {
611 /// if *entry.key() > 0 {
612 /// entry.insert("first");
615 /// assert_eq!(*map.get(&1).unwrap(), "first");
616 /// assert_eq!(*map.get(&2).unwrap(), "b");
618 #[unstable(feature = "map_first_last", issue = "62924")]
619 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
620 let front = self.root.as_mut()?.as_mut().first_leaf_edge();
621 let kv = front.right_kv().ok()?;
623 handle: kv.forget_node_type(),
624 length: &mut self.length,
625 _marker: PhantomData,
629 /// Removes and returns the first element in the map.
630 /// The key of this element is the minimum key that was in the map.
634 /// Draining elements in ascending order, while keeping a usable map each iteration.
637 /// #![feature(map_first_last)]
638 /// use std::collections::BTreeMap;
640 /// let mut map = BTreeMap::new();
641 /// map.insert(1, "a");
642 /// map.insert(2, "b");
643 /// while let Some((key, _val)) = map.pop_first() {
644 /// assert!(map.iter().all(|(k, _v)| *k > key));
646 /// assert!(map.is_empty());
648 #[unstable(feature = "map_first_last", issue = "62924")]
649 pub fn pop_first(&mut self) -> Option<(K, V)> {
650 self.first_entry().map(|entry| entry.remove_entry())
653 /// Returns the last key-value pair in the map.
654 /// The key in this pair is the maximum key in the map.
661 /// #![feature(map_first_last)]
662 /// use std::collections::BTreeMap;
664 /// let mut map = BTreeMap::new();
665 /// map.insert(1, "b");
666 /// map.insert(2, "a");
667 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
669 #[unstable(feature = "map_first_last", issue = "62924")]
670 pub fn last_key_value(&self) -> Option<(&K, &V)> {
671 let back = self.root.as_ref()?.as_ref().last_leaf_edge();
672 back.left_kv().ok().map(Handle::into_kv)
675 /// Returns the last entry in the map for in-place manipulation.
676 /// The key of this entry is the maximum key in the map.
681 /// #![feature(map_first_last)]
682 /// use std::collections::BTreeMap;
684 /// let mut map = BTreeMap::new();
685 /// map.insert(1, "a");
686 /// map.insert(2, "b");
687 /// if let Some(mut entry) = map.last_entry() {
688 /// if *entry.key() > 0 {
689 /// entry.insert("last");
692 /// assert_eq!(*map.get(&1).unwrap(), "a");
693 /// assert_eq!(*map.get(&2).unwrap(), "last");
695 #[unstable(feature = "map_first_last", issue = "62924")]
696 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
697 let back = self.root.as_mut()?.as_mut().last_leaf_edge();
698 let kv = back.left_kv().ok()?;
700 handle: kv.forget_node_type(),
701 length: &mut self.length,
702 _marker: PhantomData,
706 /// Removes and returns the last element in the map.
707 /// The key of this element is the maximum key that was in the map.
711 /// Draining elements in descending order, while keeping a usable map each iteration.
714 /// #![feature(map_first_last)]
715 /// use std::collections::BTreeMap;
717 /// let mut map = BTreeMap::new();
718 /// map.insert(1, "a");
719 /// map.insert(2, "b");
720 /// while let Some((key, _val)) = map.pop_last() {
721 /// assert!(map.iter().all(|(k, _v)| *k < key));
723 /// assert!(map.is_empty());
725 #[unstable(feature = "map_first_last", issue = "62924")]
726 pub fn pop_last(&mut self) -> Option<(K, V)> {
727 self.last_entry().map(|entry| entry.remove_entry())
730 /// Returns `true` if the map contains a value for the specified key.
732 /// The key may be any borrowed form of the map's key type, but the ordering
733 /// on the borrowed form *must* match the ordering on the key type.
740 /// use std::collections::BTreeMap;
742 /// let mut map = BTreeMap::new();
743 /// map.insert(1, "a");
744 /// assert_eq!(map.contains_key(&1), true);
745 /// assert_eq!(map.contains_key(&2), false);
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
753 self.get(key).is_some()
756 /// Returns a mutable reference to the value corresponding to the key.
758 /// The key may be any borrowed form of the map's key type, but the ordering
759 /// on the borrowed form *must* match the ordering on the key type.
766 /// use std::collections::BTreeMap;
768 /// let mut map = BTreeMap::new();
769 /// map.insert(1, "a");
770 /// if let Some(x) = map.get_mut(&1) {
773 /// assert_eq!(map[&1], "b");
775 // See `get` for implementation notes, this is basically a copy-paste with mut's added
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
782 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
783 Found(handle) => Some(handle.into_kv_mut().1),
788 /// Inserts a key-value pair into the map.
790 /// If the map did not have this key present, `None` is returned.
792 /// If the map did have this key present, the value is updated, and the old
793 /// value is returned. The key is not updated, though; this matters for
794 /// types that can be `==` without being identical. See the [module-level
795 /// documentation] for more.
797 /// [module-level documentation]: index.html#insert-and-complex-keys
804 /// use std::collections::BTreeMap;
806 /// let mut map = BTreeMap::new();
807 /// assert_eq!(map.insert(37, "a"), None);
808 /// assert_eq!(map.is_empty(), false);
810 /// map.insert(37, "b");
811 /// assert_eq!(map.insert(37, "c"), Some("b"));
812 /// assert_eq!(map[&37], "c");
814 #[stable(feature = "rust1", since = "1.0.0")]
815 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
816 match self.entry(key) {
817 Occupied(mut entry) => Some(entry.insert(value)),
825 /// Removes a key from the map, returning the value at the key if the key
826 /// was previously in the map.
828 /// The key may be any borrowed form of the map's key type, but the ordering
829 /// on the borrowed form *must* match the ordering on the key type.
836 /// use std::collections::BTreeMap;
838 /// let mut map = BTreeMap::new();
839 /// map.insert(1, "a");
840 /// assert_eq!(map.remove(&1), Some("a"));
841 /// assert_eq!(map.remove(&1), None);
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
849 self.remove_entry(key).map(|(_, v)| v)
852 /// Removes a key from the map, returning the stored key and value if the key
853 /// was previously in the map.
855 /// The key may be any borrowed form of the map's key type, but the ordering
856 /// on the borrowed form *must* match the ordering on the key type.
863 /// use std::collections::BTreeMap;
865 /// let mut map = BTreeMap::new();
866 /// map.insert(1, "a");
867 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
868 /// assert_eq!(map.remove_entry(&1), None);
870 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
871 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
876 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
877 Found(handle) => Some(
878 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
885 /// Moves all elements from `other` into `Self`, leaving `other` empty.
890 /// use std::collections::BTreeMap;
892 /// let mut a = BTreeMap::new();
893 /// a.insert(1, "a");
894 /// a.insert(2, "b");
895 /// a.insert(3, "c");
897 /// let mut b = BTreeMap::new();
898 /// b.insert(3, "d");
899 /// b.insert(4, "e");
900 /// b.insert(5, "f");
902 /// a.append(&mut b);
904 /// assert_eq!(a.len(), 5);
905 /// assert_eq!(b.len(), 0);
907 /// assert_eq!(a[&1], "a");
908 /// assert_eq!(a[&2], "b");
909 /// assert_eq!(a[&3], "d");
910 /// assert_eq!(a[&4], "e");
911 /// assert_eq!(a[&5], "f");
913 #[stable(feature = "btree_append", since = "1.11.0")]
914 pub fn append(&mut self, other: &mut Self) {
915 // Do we have to append anything at all?
916 if other.is_empty() {
920 // We can just swap `self` and `other` if `self` is empty.
922 mem::swap(self, other);
926 // First, we merge `self` and `other` into a sorted sequence in linear time.
927 let self_iter = mem::take(self).into_iter();
928 let other_iter = mem::take(other).into_iter();
929 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
931 // Second, we build a tree from the sorted sequence in linear time.
932 self.from_sorted_iter(iter);
935 /// Constructs a double-ended iterator over a sub-range of elements in the map.
936 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
937 /// yield elements from min (inclusive) to max (exclusive).
938 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
939 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
940 /// range from 4 to 10.
944 /// Panics if range `start > end`.
945 /// Panics if range `start == end` and both bounds are `Excluded`.
952 /// use std::collections::BTreeMap;
953 /// use std::ops::Bound::Included;
955 /// let mut map = BTreeMap::new();
956 /// map.insert(3, "a");
957 /// map.insert(5, "b");
958 /// map.insert(8, "c");
959 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
960 /// println!("{}: {}", key, value);
962 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
964 #[stable(feature = "btree_range", since = "1.17.0")]
965 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
971 if let Some(root) = &self.root {
972 let (f, b) = range_search(root.as_ref(), range);
974 Range { front: Some(f), back: Some(b) }
976 Range { front: None, back: None }
980 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
981 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
982 /// yield elements from min (inclusive) to max (exclusive).
983 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
984 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
985 /// range from 4 to 10.
989 /// Panics if range `start > end`.
990 /// Panics if range `start == end` and both bounds are `Excluded`.
997 /// use std::collections::BTreeMap;
999 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1001 /// .map(|&s| (s, 0))
1003 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1004 /// *balance += 100;
1006 /// for (name, balance) in &map {
1007 /// println!("{} => {}", name, balance);
1010 #[stable(feature = "btree_range", since = "1.17.0")]
1011 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1017 if let Some(root) = &mut self.root {
1018 let (f, b) = range_search(root.as_mut(), range);
1020 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1022 RangeMut { front: None, back: None, _marker: PhantomData }
1026 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1033 /// use std::collections::BTreeMap;
1035 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1037 /// // count the number of occurrences of letters in the vec
1038 /// for x in vec!["a","b","a","c","a","b"] {
1039 /// *count.entry(x).or_insert(0) += 1;
1042 /// assert_eq!(count["a"], 3);
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1046 // FIXME(@porglezomp) Avoid allocating if we don't insert
1047 let root = Self::ensure_is_owned(&mut self.root);
1048 match search::search_tree(root.as_mut(), &key) {
1050 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1053 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1058 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1059 let root = Self::ensure_is_owned(&mut self.root);
1060 let mut cur_node = root.as_mut().last_leaf_edge().into_node();
1061 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1062 for (key, value) in iter {
1063 // Try to push key-value pair into the current leaf node.
1064 if cur_node.len() < node::CAPACITY {
1065 cur_node.push(key, value);
1067 // No space left, go up and push there.
1069 let mut test_node = cur_node.forget_type();
1071 match test_node.ascend() {
1073 let parent = parent.into_node();
1074 if parent.len() < node::CAPACITY {
1075 // Found a node with space left, push here.
1080 test_node = parent.forget_type();
1084 // We are at the top, create a new root node and push there.
1085 open_node = node.into_root_mut().push_level();
1091 // Push key-value pair and new right subtree.
1092 let tree_height = open_node.height() - 1;
1093 let mut right_tree = node::Root::new_leaf();
1094 for _ in 0..tree_height {
1095 right_tree.push_level();
1097 open_node.push(key, value, right_tree);
1099 // Go down to the right-most leaf again.
1100 cur_node = open_node.forget_type().last_leaf_edge().into_node();
1105 Self::fix_right_edge(root)
1108 fn fix_right_edge(root: &mut node::Root<K, V>) {
1109 // Handle underfull nodes, start from the top.
1110 let mut cur_node = root.as_mut();
1111 while let Internal(internal) = cur_node.force() {
1112 // Check if right-most child is underfull.
1113 let mut last_edge = internal.last_edge();
1114 let right_child_len = last_edge.reborrow().descend().len();
1115 if right_child_len < node::MIN_LEN {
1116 // We need to steal.
1117 let mut last_kv = match last_edge.left_kv() {
1119 Err(_) => unreachable!(),
1121 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1122 last_edge = last_kv.right_edge();
1126 cur_node = last_edge.descend();
1130 /// Splits the collection into two at the given key. Returns everything after the given key,
1131 /// including the key.
1138 /// use std::collections::BTreeMap;
1140 /// let mut a = BTreeMap::new();
1141 /// a.insert(1, "a");
1142 /// a.insert(2, "b");
1143 /// a.insert(3, "c");
1144 /// a.insert(17, "d");
1145 /// a.insert(41, "e");
1147 /// let b = a.split_off(&3);
1149 /// assert_eq!(a.len(), 2);
1150 /// assert_eq!(b.len(), 3);
1152 /// assert_eq!(a[&1], "a");
1153 /// assert_eq!(a[&2], "b");
1155 /// assert_eq!(b[&3], "c");
1156 /// assert_eq!(b[&17], "d");
1157 /// assert_eq!(b[&41], "e");
1159 #[stable(feature = "btree_split_off", since = "1.11.0")]
1160 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1164 if self.is_empty() {
1168 let total_num = self.len();
1169 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1171 let mut right = Self::new();
1172 let right_root = Self::ensure_is_owned(&mut right.root);
1173 for _ in 0..left_root.height() {
1174 right_root.push_level();
1178 let mut left_node = left_root.as_mut();
1179 let mut right_node = right_root.as_mut();
1182 let mut split_edge = match search::search_node(left_node, key) {
1183 // key is going to the right tree
1184 Found(handle) => handle.left_edge(),
1185 GoDown(handle) => handle,
1188 split_edge.move_suffix(&mut right_node);
1190 match (split_edge.force(), right_node.force()) {
1191 (Internal(edge), Internal(node)) => {
1192 left_node = edge.descend();
1193 right_node = node.first_edge().descend();
1195 (Leaf(_), Leaf(_)) => {
1205 left_root.fix_right_border();
1206 right_root.fix_left_border();
1208 if left_root.height() < right_root.height() {
1209 self.recalc_length();
1210 right.length = total_num - self.len();
1212 right.recalc_length();
1213 self.length = total_num - right.len();
1219 /// Creates an iterator which uses a closure to determine if an element should be removed.
1221 /// If the closure returns true, the element is removed from the map and yielded.
1222 /// If the closure returns false, or panics, the element remains in the map and will not be
1225 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1226 /// whether you choose to keep or remove it.
1228 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1229 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1231 /// It is unspecified how many more elements will be subjected to the closure
1232 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1233 /// or if the `DrainFilter` value is leaked.
1237 /// Splitting a map into even and odd keys, reusing the original map:
1240 /// #![feature(btree_drain_filter)]
1241 /// use std::collections::BTreeMap;
1243 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1244 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1246 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1247 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1249 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1250 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1252 F: FnMut(&K, &mut V) -> bool,
1254 DrainFilter { pred, inner: self.drain_filter_inner() }
1256 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1257 let front = self.root.as_mut().map(|r| r.as_mut().first_leaf_edge());
1258 DrainFilterInner { length: &mut self.length, cur_leaf_edge: front }
1261 /// Calculates the number of elements if it is incorrect.
1262 fn recalc_length(&mut self) {
1263 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1268 let mut res = node.len();
1270 if let Internal(node) = node.force() {
1271 let mut edge = node.first_edge();
1273 res += dfs(edge.reborrow().descend());
1274 match edge.right_kv() {
1276 edge = right_kv.right_edge();
1288 self.length = dfs(self.root.as_ref().unwrap().as_ref());
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
1294 type Item = (&'a K, &'a V);
1295 type IntoIter = Iter<'a, K, V>;
1297 fn into_iter(self) -> Iter<'a, K, V> {
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1304 type Item = (&'a K, &'a V);
1306 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1307 if self.length == 0 {
1311 unsafe { Some(self.range.next_unchecked()) }
1315 fn size_hint(&self) -> (usize, Option<usize>) {
1316 (self.length, Some(self.length))
1319 fn last(mut self) -> Option<(&'a K, &'a V)> {
1323 fn min(mut self) -> Option<(&'a K, &'a V)> {
1327 fn max(mut self) -> Option<(&'a K, &'a V)> {
1332 #[stable(feature = "fused", since = "1.26.0")]
1333 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1337 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1338 if self.length == 0 {
1342 unsafe { Some(self.range.next_back_unchecked()) }
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1349 fn len(&self) -> usize {
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 impl<K, V> Clone for Iter<'_, K, V> {
1356 fn clone(&self) -> Self {
1357 Iter { range: self.range.clone(), length: self.length }
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl<'a, K: 'a, V: 'a> IntoIterator for &'a mut BTreeMap<K, V> {
1363 type Item = (&'a K, &'a mut V);
1364 type IntoIter = IterMut<'a, K, V>;
1366 fn into_iter(self) -> IterMut<'a, K, V> {
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1373 type Item = (&'a K, &'a mut V);
1375 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1376 if self.length == 0 {
1380 let (k, v) = unsafe { self.range.next_unchecked() };
1381 Some((k, v)) // coerce k from `&mut K` to `&K`
1385 fn size_hint(&self) -> (usize, Option<usize>) {
1386 (self.length, Some(self.length))
1389 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1393 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1397 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1404 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1405 if self.length == 0 {
1409 let (k, v) = unsafe { self.range.next_back_unchecked() };
1410 Some((k, v)) // coerce k from `&mut K` to `&K`
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1417 fn len(&self) -> usize {
1422 #[stable(feature = "fused", since = "1.26.0")]
1423 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<K, V> IntoIterator for BTreeMap<K, V> {
1428 type IntoIter = IntoIter<K, V>;
1430 fn into_iter(self) -> IntoIter<K, V> {
1431 let mut me = ManuallyDrop::new(self);
1432 if let Some(root) = me.root.take() {
1433 let (f, b) = full_range_search(root.into_ref());
1435 IntoIter { front: Some(f), back: Some(b), length: me.length }
1437 IntoIter { front: None, back: None, length: 0 }
1442 #[stable(feature = "btree_drop", since = "1.7.0")]
1443 impl<K, V> Drop for IntoIter<K, V> {
1444 fn drop(&mut self) {
1445 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1447 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1448 fn drop(&mut self) {
1449 // Continue the same loop we perform below. This only runs when unwinding, so we
1450 // don't have to care about panics this time (they'll abort).
1451 while let Some(_) = self.0.next() {}
1455 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1456 while let Some(parent) = node.deallocate_and_ascend() {
1457 node = parent.into_node().forget_type();
1463 while let Some(pair) = self.next() {
1464 let guard = DropGuard(self);
1470 if let Some(front) = ptr::read(&self.front) {
1471 let mut node = front.into_node().forget_type();
1472 // Most of the nodes have been deallocated while traversing
1473 // but one pile from a leaf up to the root is left standing.
1474 while let Some(parent) = node.deallocate_and_ascend() {
1475 node = parent.into_node().forget_type();
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<K, V> Iterator for IntoIter<K, V> {
1486 fn next(&mut self) -> Option<(K, V)> {
1487 if self.length == 0 {
1491 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1495 fn size_hint(&self) -> (usize, Option<usize>) {
1496 (self.length, Some(self.length))
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1502 fn next_back(&mut self) -> Option<(K, V)> {
1503 if self.length == 0 {
1507 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1514 fn len(&self) -> usize {
1519 #[stable(feature = "fused", since = "1.26.0")]
1520 impl<K, V> FusedIterator for IntoIter<K, V> {}
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1526 fn next(&mut self) -> Option<&'a K> {
1527 self.inner.next().map(|(k, _)| k)
1530 fn size_hint(&self) -> (usize, Option<usize>) {
1531 self.inner.size_hint()
1534 fn last(mut self) -> Option<&'a K> {
1538 fn min(mut self) -> Option<&'a K> {
1542 fn max(mut self) -> Option<&'a K> {
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1549 fn next_back(&mut self) -> Option<&'a K> {
1550 self.inner.next_back().map(|(k, _)| k)
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1556 fn len(&self) -> usize {
1561 #[stable(feature = "fused", since = "1.26.0")]
1562 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 impl<K, V> Clone for Keys<'_, K, V> {
1566 fn clone(&self) -> Self {
1567 Keys { inner: self.inner.clone() }
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 impl<'a, K, V> Iterator for Values<'a, K, V> {
1575 fn next(&mut self) -> Option<&'a V> {
1576 self.inner.next().map(|(_, v)| v)
1579 fn size_hint(&self) -> (usize, Option<usize>) {
1580 self.inner.size_hint()
1583 fn last(mut self) -> Option<&'a V> {
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1590 fn next_back(&mut self) -> Option<&'a V> {
1591 self.inner.next_back().map(|(_, v)| v)
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1597 fn len(&self) -> usize {
1602 #[stable(feature = "fused", since = "1.26.0")]
1603 impl<K, V> FusedIterator for Values<'_, K, V> {}
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl<K, V> Clone for Values<'_, K, V> {
1607 fn clone(&self) -> Self {
1608 Values { inner: self.inner.clone() }
1612 /// An iterator produced by calling `drain_filter` on BTreeMap.
1613 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1614 pub struct DrainFilter<'a, K, V, F>
1618 F: 'a + FnMut(&K, &mut V) -> bool,
1621 inner: DrainFilterInner<'a, K, V>,
1623 /// Most of the implementation of DrainFilter, independent of the type
1624 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1625 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1626 length: &'a mut usize,
1627 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1630 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1631 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1633 F: FnMut(&K, &mut V) -> bool,
1635 fn drop(&mut self) {
1636 self.for_each(drop);
1640 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1641 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1645 F: FnMut(&K, &mut V) -> bool,
1647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1652 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1653 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1655 F: FnMut(&K, &mut V) -> bool,
1659 fn next(&mut self) -> Option<(K, V)> {
1660 self.inner.next(&mut self.pred)
1663 fn size_hint(&self) -> (usize, Option<usize>) {
1664 self.inner.size_hint()
1668 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1669 /// Allow Debug implementations to predict the next element.
1670 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1671 let edge = self.cur_leaf_edge.as_ref()?;
1672 edge.reborrow().next_kv().ok().map(|kv| kv.into_kv())
1675 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1676 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1678 F: FnMut(&K, &mut V) -> bool,
1680 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1681 let (k, v) = kv.kv_mut();
1684 let (k, v, leaf_edge_location) = kv.remove_kv_tracking();
1685 self.cur_leaf_edge = Some(leaf_edge_location);
1686 return Some((k, v));
1688 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1693 /// Implementation of a typical `DrainFilter::size_hint` method.
1694 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1695 (0, Some(*self.length))
1699 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1700 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1702 #[stable(feature = "btree_range", since = "1.17.0")]
1703 impl<'a, K, V> Iterator for Range<'a, K, V> {
1704 type Item = (&'a K, &'a V);
1706 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1707 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1710 fn last(mut self) -> Option<(&'a K, &'a V)> {
1714 fn min(mut self) -> Option<(&'a K, &'a V)> {
1718 fn max(mut self) -> Option<(&'a K, &'a V)> {
1723 #[stable(feature = "map_values_mut", since = "1.10.0")]
1724 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1725 type Item = &'a mut V;
1727 fn next(&mut self) -> Option<&'a mut V> {
1728 self.inner.next().map(|(_, v)| v)
1731 fn size_hint(&self) -> (usize, Option<usize>) {
1732 self.inner.size_hint()
1735 fn last(mut self) -> Option<&'a mut V> {
1740 #[stable(feature = "map_values_mut", since = "1.10.0")]
1741 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1742 fn next_back(&mut self) -> Option<&'a mut V> {
1743 self.inner.next_back().map(|(_, v)| v)
1747 #[stable(feature = "map_values_mut", since = "1.10.0")]
1748 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1749 fn len(&self) -> usize {
1754 #[stable(feature = "fused", since = "1.26.0")]
1755 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1757 impl<'a, K, V> Range<'a, K, V> {
1758 fn is_empty(&self) -> bool {
1759 self.front == self.back
1762 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1763 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1767 #[stable(feature = "btree_range", since = "1.17.0")]
1768 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1769 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1770 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1774 impl<'a, K, V> Range<'a, K, V> {
1775 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1776 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1780 #[stable(feature = "fused", since = "1.26.0")]
1781 impl<K, V> FusedIterator for Range<'_, K, V> {}
1783 #[stable(feature = "btree_range", since = "1.17.0")]
1784 impl<K, V> Clone for Range<'_, K, V> {
1785 fn clone(&self) -> Self {
1786 Range { front: self.front, back: self.back }
1790 #[stable(feature = "btree_range", since = "1.17.0")]
1791 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1792 type Item = (&'a K, &'a mut V);
1794 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1795 if self.is_empty() {
1798 let (k, v) = unsafe { self.next_unchecked() };
1799 Some((k, v)) // coerce k from `&mut K` to `&K`
1803 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1807 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1811 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1816 impl<'a, K, V> RangeMut<'a, K, V> {
1817 fn is_empty(&self) -> bool {
1818 self.front == self.back
1821 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1822 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1826 #[stable(feature = "btree_range", since = "1.17.0")]
1827 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1828 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1829 if self.is_empty() {
1832 let (k, v) = unsafe { self.next_back_unchecked() };
1833 Some((k, v)) // coerce k from `&mut K` to `&K`
1838 #[stable(feature = "fused", since = "1.26.0")]
1839 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1841 impl<'a, K, V> RangeMut<'a, K, V> {
1842 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1843 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1849 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1850 let mut map = BTreeMap::new();
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1859 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1860 iter.into_iter().for_each(move |(k, v)| {
1866 fn extend_one(&mut self, (k, v): (K, V)) {
1871 #[stable(feature = "extend_ref", since = "1.2.0")]
1872 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1873 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1874 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1878 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1885 fn hash<H: Hasher>(&self, state: &mut H) {
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<K: Ord, V> Default for BTreeMap<K, V> {
1894 /// Creates an empty `BTreeMap<K, V>`.
1895 fn default() -> BTreeMap<K, V> {
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1902 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1903 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1913 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1914 self.iter().partial_cmp(other.iter())
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1921 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1922 self.iter().cmp(other.iter())
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1928 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1929 f.debug_map().entries(self.iter()).finish()
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1941 /// Returns a reference to the value corresponding to the supplied key.
1945 /// Panics if the key is not present in the `BTreeMap`.
1947 fn index(&self, key: &Q) -> &V {
1948 self.get(key).expect("no entry found for key")
1952 /// Finds the leaf edges delimiting a specified range in or underneath a node.
1953 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
1954 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
1957 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1958 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
1964 match (range.start_bound(), range.end_bound()) {
1965 (Excluded(s), Excluded(e)) if s == e => {
1966 panic!("range start and end are equal and excluded in BTreeMap")
1968 (Included(s) | Excluded(s), Included(e) | Excluded(e)) if s > e => {
1969 panic!("range start is greater than range end in BTreeMap")
1974 // We duplicate the root NodeRef here -- we will never access it in a way
1975 // that overlaps references obtained from the root.
1976 let mut min_node = unsafe { ptr::read(&root) };
1977 let mut max_node = root;
1978 let mut min_found = false;
1979 let mut max_found = false;
1982 let front = match (min_found, range.start_bound()) {
1983 (false, Included(key)) => match search::search_node(min_node, key) {
1988 GoDown(edge) => edge,
1990 (false, Excluded(key)) => match search::search_node(min_node, key) {
1995 GoDown(edge) => edge,
1997 (true, Included(_)) => min_node.last_edge(),
1998 (true, Excluded(_)) => min_node.first_edge(),
1999 (_, Unbounded) => min_node.first_edge(),
2002 let back = match (max_found, range.end_bound()) {
2003 (false, Included(key)) => match search::search_node(max_node, key) {
2008 GoDown(edge) => edge,
2010 (false, Excluded(key)) => match search::search_node(max_node, key) {
2015 GoDown(edge) => edge,
2017 (true, Included(_)) => max_node.first_edge(),
2018 (true, Excluded(_)) => max_node.last_edge(),
2019 (_, Unbounded) => max_node.last_edge(),
2022 if front.partial_cmp(&back) == Some(Ordering::Greater) {
2023 panic!("Ord is ill-defined in BTreeMap range");
2025 match (front.force(), back.force()) {
2026 (Leaf(f), Leaf(b)) => {
2029 (Internal(min_int), Internal(max_int)) => {
2030 min_node = min_int.descend();
2031 max_node = max_int.descend();
2033 _ => unreachable!("BTreeMap has different depths"),
2038 /// Equivalent to `range_search(k, v, ..)` without the `Ord` bound.
2039 fn full_range_search<BorrowType, K, V>(
2040 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2042 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2043 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2045 // We duplicate the root NodeRef here -- we will never access it in a way
2046 // that overlaps references obtained from the root.
2047 let mut min_node = unsafe { ptr::read(&root) };
2048 let mut max_node = root;
2050 let front = min_node.first_edge();
2051 let back = max_node.last_edge();
2052 match (front.force(), back.force()) {
2053 (Leaf(f), Leaf(b)) => {
2056 (Internal(min_int), Internal(max_int)) => {
2057 min_node = min_int.descend();
2058 max_node = max_int.descend();
2060 _ => unreachable!("BTreeMap has different depths"),
2065 impl<K, V> BTreeMap<K, V> {
2066 /// Gets an iterator over the entries of the map, sorted by key.
2073 /// use std::collections::BTreeMap;
2075 /// let mut map = BTreeMap::new();
2076 /// map.insert(3, "c");
2077 /// map.insert(2, "b");
2078 /// map.insert(1, "a");
2080 /// for (key, value) in map.iter() {
2081 /// println!("{}: {}", key, value);
2084 /// let (first_key, first_value) = map.iter().next().unwrap();
2085 /// assert_eq!((*first_key, *first_value), (1, "a"));
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 pub fn iter(&self) -> Iter<'_, K, V> {
2089 if let Some(root) = &self.root {
2090 let (f, b) = full_range_search(root.as_ref());
2092 Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2094 Iter { range: Range { front: None, back: None }, length: 0 }
2098 /// Gets a mutable iterator over the entries of the map, sorted by key.
2105 /// use std::collections::BTreeMap;
2107 /// let mut map = BTreeMap::new();
2108 /// map.insert("a", 1);
2109 /// map.insert("b", 2);
2110 /// map.insert("c", 3);
2112 /// // add 10 to the value if the key isn't "a"
2113 /// for (key, value) in map.iter_mut() {
2114 /// if key != &"a" {
2119 #[stable(feature = "rust1", since = "1.0.0")]
2120 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2121 if let Some(root) = &mut self.root {
2122 let (f, b) = full_range_search(root.as_mut());
2125 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2126 length: self.length,
2129 IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2133 /// Gets an iterator over the keys of the map, in sorted order.
2140 /// use std::collections::BTreeMap;
2142 /// let mut a = BTreeMap::new();
2143 /// a.insert(2, "b");
2144 /// a.insert(1, "a");
2146 /// let keys: Vec<_> = a.keys().cloned().collect();
2147 /// assert_eq!(keys, [1, 2]);
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 pub fn keys(&self) -> Keys<'_, K, V> {
2151 Keys { inner: self.iter() }
2154 /// Gets an iterator over the values of the map, in order by key.
2161 /// use std::collections::BTreeMap;
2163 /// let mut a = BTreeMap::new();
2164 /// a.insert(1, "hello");
2165 /// a.insert(2, "goodbye");
2167 /// let values: Vec<&str> = a.values().cloned().collect();
2168 /// assert_eq!(values, ["hello", "goodbye"]);
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 pub fn values(&self) -> Values<'_, K, V> {
2172 Values { inner: self.iter() }
2175 /// Gets a mutable iterator over the values of the map, in order by key.
2182 /// use std::collections::BTreeMap;
2184 /// let mut a = BTreeMap::new();
2185 /// a.insert(1, String::from("hello"));
2186 /// a.insert(2, String::from("goodbye"));
2188 /// for value in a.values_mut() {
2189 /// value.push_str("!");
2192 /// let values: Vec<String> = a.values().cloned().collect();
2193 /// assert_eq!(values, [String::from("hello!"),
2194 /// String::from("goodbye!")]);
2196 #[stable(feature = "map_values_mut", since = "1.10.0")]
2197 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2198 ValuesMut { inner: self.iter_mut() }
2201 /// Returns the number of elements in the map.
2208 /// use std::collections::BTreeMap;
2210 /// let mut a = BTreeMap::new();
2211 /// assert_eq!(a.len(), 0);
2212 /// a.insert(1, "a");
2213 /// assert_eq!(a.len(), 1);
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 pub fn len(&self) -> usize {
2220 /// Returns `true` if the map contains no elements.
2227 /// use std::collections::BTreeMap;
2229 /// let mut a = BTreeMap::new();
2230 /// assert!(a.is_empty());
2231 /// a.insert(1, "a");
2232 /// assert!(!a.is_empty());
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 pub fn is_empty(&self) -> bool {
2239 /// If the root node is the empty (non-allocated) root node, allocate our
2240 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2241 fn ensure_is_owned(root: &mut Option<node::Root<K, V>>) -> &mut node::Root<K, V> {
2242 root.get_or_insert_with(node::Root::new_leaf)
2246 impl<'a, K: Ord, V> Entry<'a, K, V> {
2247 /// Ensures a value is in the entry by inserting the default if empty, and returns
2248 /// a mutable reference to the value in the entry.
2253 /// use std::collections::BTreeMap;
2255 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2256 /// map.entry("poneyland").or_insert(12);
2258 /// assert_eq!(map["poneyland"], 12);
2260 #[stable(feature = "rust1", since = "1.0.0")]
2261 pub fn or_insert(self, default: V) -> &'a mut V {
2263 Occupied(entry) => entry.into_mut(),
2264 Vacant(entry) => entry.insert(default),
2268 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2269 /// and returns a mutable reference to the value in the entry.
2274 /// use std::collections::BTreeMap;
2276 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2277 /// let s = "hoho".to_string();
2279 /// map.entry("poneyland").or_insert_with(|| s);
2281 /// assert_eq!(map["poneyland"], "hoho".to_string());
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2286 Occupied(entry) => entry.into_mut(),
2287 Vacant(entry) => entry.insert(default()),
2291 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2292 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2293 /// which takes the key as its argument, and returns a mutable reference to the value in the
2299 /// #![feature(or_insert_with_key)]
2300 /// use std::collections::BTreeMap;
2302 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2304 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2306 /// assert_eq!(map["poneyland"], 9);
2309 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2311 Occupied(entry) => entry.into_mut(),
2313 let value = default(entry.key());
2319 /// Returns a reference to this entry's key.
2324 /// use std::collections::BTreeMap;
2326 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2327 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2329 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2330 pub fn key(&self) -> &K {
2332 Occupied(ref entry) => entry.key(),
2333 Vacant(ref entry) => entry.key(),
2337 /// Provides in-place mutable access to an occupied entry before any
2338 /// potential inserts into the map.
2343 /// use std::collections::BTreeMap;
2345 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2347 /// map.entry("poneyland")
2348 /// .and_modify(|e| { *e += 1 })
2350 /// assert_eq!(map["poneyland"], 42);
2352 /// map.entry("poneyland")
2353 /// .and_modify(|e| { *e += 1 })
2355 /// assert_eq!(map["poneyland"], 43);
2357 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2358 pub fn and_modify<F>(self, f: F) -> Self
2363 Occupied(mut entry) => {
2367 Vacant(entry) => Vacant(entry),
2372 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2373 #[stable(feature = "entry_or_default", since = "1.28.0")]
2374 /// Ensures a value is in the entry by inserting the default value if empty,
2375 /// and returns a mutable reference to the value in the entry.
2380 /// use std::collections::BTreeMap;
2382 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2383 /// map.entry("poneyland").or_default();
2385 /// assert_eq!(map["poneyland"], None);
2387 pub fn or_default(self) -> &'a mut V {
2389 Occupied(entry) => entry.into_mut(),
2390 Vacant(entry) => entry.insert(Default::default()),
2395 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2396 /// Gets a reference to the key that would be used when inserting a value
2397 /// through the VacantEntry.
2402 /// use std::collections::BTreeMap;
2404 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2405 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2407 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2408 pub fn key(&self) -> &K {
2412 /// Take ownership of the key.
2417 /// use std::collections::BTreeMap;
2418 /// use std::collections::btree_map::Entry;
2420 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2422 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2426 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2427 pub fn into_key(self) -> K {
2431 /// Sets the value of the entry with the `VacantEntry`'s key,
2432 /// and returns a mutable reference to it.
2437 /// use std::collections::BTreeMap;
2438 /// use std::collections::btree_map::Entry;
2440 /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
2442 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2445 /// assert_eq!(map["poneyland"], 37);
2447 #[stable(feature = "rust1", since = "1.0.0")]
2448 pub fn insert(self, value: V) -> &'a mut V {
2457 let mut cur_parent = match self.handle.insert(self.key, value) {
2458 (Fit(handle), _) => return handle.into_kv_mut().1,
2459 (Split(left, k, v, right), ptr) => {
2464 left.ascend().map_err(|n| n.into_root_mut())
2470 Ok(parent) => match parent.insert(ins_k, ins_v, ins_edge) {
2471 Fit(_) => return unsafe { &mut *out_ptr },
2472 Split(left, k, v, right) => {
2476 cur_parent = left.ascend().map_err(|n| n.into_root_mut());
2480 root.push_level().push(ins_k, ins_v, ins_edge);
2481 return unsafe { &mut *out_ptr };
2488 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2489 /// Gets a reference to the key in the entry.
2494 /// use std::collections::BTreeMap;
2496 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2497 /// map.entry("poneyland").or_insert(12);
2498 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2500 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2501 pub fn key(&self) -> &K {
2502 self.handle.reborrow().into_kv().0
2505 /// Take ownership of the key and value from the map.
2510 /// use std::collections::BTreeMap;
2511 /// use std::collections::btree_map::Entry;
2513 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2514 /// map.entry("poneyland").or_insert(12);
2516 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2517 /// // We delete the entry from the map.
2518 /// o.remove_entry();
2521 /// // If now try to get the value, it will panic:
2522 /// // println!("{}", map["poneyland"]);
2524 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2525 pub fn remove_entry(self) -> (K, V) {
2529 /// Gets a reference to the value in the entry.
2534 /// use std::collections::BTreeMap;
2535 /// use std::collections::btree_map::Entry;
2537 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2538 /// map.entry("poneyland").or_insert(12);
2540 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2541 /// assert_eq!(o.get(), &12);
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 pub fn get(&self) -> &V {
2546 self.handle.reborrow().into_kv().1
2549 /// Gets a mutable reference to the value in the entry.
2551 /// If you need a reference to the `OccupiedEntry` that may outlive the
2552 /// destruction of the `Entry` value, see [`into_mut`].
2554 /// [`into_mut`]: #method.into_mut
2559 /// use std::collections::BTreeMap;
2560 /// use std::collections::btree_map::Entry;
2562 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2563 /// map.entry("poneyland").or_insert(12);
2565 /// assert_eq!(map["poneyland"], 12);
2566 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2567 /// *o.get_mut() += 10;
2568 /// assert_eq!(*o.get(), 22);
2570 /// // We can use the same Entry multiple times.
2571 /// *o.get_mut() += 2;
2573 /// assert_eq!(map["poneyland"], 24);
2575 #[stable(feature = "rust1", since = "1.0.0")]
2576 pub fn get_mut(&mut self) -> &mut V {
2577 self.handle.kv_mut().1
2580 /// Converts the entry into a mutable reference to its value.
2582 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2584 /// [`get_mut`]: #method.get_mut
2589 /// use std::collections::BTreeMap;
2590 /// use std::collections::btree_map::Entry;
2592 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2593 /// map.entry("poneyland").or_insert(12);
2595 /// assert_eq!(map["poneyland"], 12);
2596 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2597 /// *o.into_mut() += 10;
2599 /// assert_eq!(map["poneyland"], 22);
2601 #[stable(feature = "rust1", since = "1.0.0")]
2602 pub fn into_mut(self) -> &'a mut V {
2603 self.handle.into_kv_mut().1
2606 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2607 /// and returns the entry's old value.
2612 /// use std::collections::BTreeMap;
2613 /// use std::collections::btree_map::Entry;
2615 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2616 /// map.entry("poneyland").or_insert(12);
2618 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2619 /// assert_eq!(o.insert(15), 12);
2621 /// assert_eq!(map["poneyland"], 15);
2623 #[stable(feature = "rust1", since = "1.0.0")]
2624 pub fn insert(&mut self, value: V) -> V {
2625 mem::replace(self.get_mut(), value)
2628 /// Takes the value of the entry out of the map, and returns it.
2633 /// use std::collections::BTreeMap;
2634 /// use std::collections::btree_map::Entry;
2636 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2637 /// map.entry("poneyland").or_insert(12);
2639 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2640 /// assert_eq!(o.remove(), 12);
2642 /// // If we try to get "poneyland"'s value, it'll panic:
2643 /// // println!("{}", map["poneyland"]);
2645 #[stable(feature = "rust1", since = "1.0.0")]
2646 pub fn remove(self) -> V {
2650 fn remove_kv(self) -> (K, V) {
2653 let (old_key, old_val, _) = self.handle.remove_kv_tracking();
2658 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
2659 /// Removes a key/value-pair from the map, and returns that pair, as well as
2660 /// the leaf edge corresponding to that former pair.
2661 fn remove_kv_tracking(
2663 ) -> (K, V, Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
2664 let (mut pos, old_key, old_val, was_internal) = match self.force() {
2666 let (hole, old_key, old_val) = leaf.remove();
2667 (hole, old_key, old_val, false)
2669 Internal(mut internal) => {
2670 // Replace the location freed in the internal node with the next KV,
2671 // and remove that next KV from its leaf.
2673 let key_loc = internal.kv_mut().0 as *mut K;
2674 let val_loc = internal.kv_mut().1 as *mut V;
2676 // Deleting from the left side is typically faster since we can
2677 // just pop an element from the end of the KV array without
2678 // needing to shift the other values.
2679 let to_remove = internal.left_edge().descend().last_leaf_edge().left_kv().ok();
2680 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2682 let (hole, key, val) = to_remove.remove();
2684 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2685 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2687 (hole, old_key, old_val, true)
2692 let mut cur_node = unsafe { ptr::read(&pos).into_node().forget_type() };
2693 let mut at_leaf = true;
2694 while cur_node.len() < node::MIN_LEN {
2695 match handle_underfull_node(cur_node) {
2697 Merged(edge, merged_with_left, offset) => {
2698 // If we merged with our right sibling then our tracked
2699 // position has not changed. However if we merged with our
2700 // left sibling then our tracked position is now dangling.
2701 if at_leaf && merged_with_left {
2702 let idx = pos.idx() + offset;
2703 let node = match unsafe { ptr::read(&edge).descend().force() } {
2705 Internal(_) => unreachable!(),
2707 pos = unsafe { Handle::new_edge(node, idx) };
2710 let parent = edge.into_node();
2711 if parent.len() == 0 {
2712 // We must be at the root
2713 parent.into_root_mut().pop_level();
2716 cur_node = parent.forget_type();
2720 Stole(stole_from_left) => {
2721 // Adjust the tracked position if we stole from a left sibling
2722 if stole_from_left && at_leaf {
2723 // SAFETY: This is safe since we just added an element to our node.
2725 pos.next_unchecked();
2733 // If we deleted from an internal node then we need to compensate for
2734 // the earlier swap and adjust the tracked position to point to the
2737 pos = unsafe { unwrap_unchecked(pos.next_kv().ok()).next_leaf_edge() };
2740 (old_key, old_val, pos)
2744 impl<K, V> node::Root<K, V> {
2745 /// Removes empty levels on the top, but keep an empty leaf if the entire tree is empty.
2746 fn fix_top(&mut self) {
2747 while self.height() > 0 && self.as_ref().len() == 0 {
2752 fn fix_right_border(&mut self) {
2756 let mut cur_node = self.as_mut();
2758 while let Internal(node) = cur_node.force() {
2759 let mut last_kv = node.last_kv();
2761 if last_kv.can_merge() {
2762 cur_node = last_kv.merge().descend();
2764 let right_len = last_kv.reborrow().right_edge().descend().len();
2765 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
2766 if right_len < node::MIN_LEN + 1 {
2767 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
2769 cur_node = last_kv.right_edge().descend();
2777 /// The symmetric clone of `fix_right_border`.
2778 fn fix_left_border(&mut self) {
2782 let mut cur_node = self.as_mut();
2784 while let Internal(node) = cur_node.force() {
2785 let mut first_kv = node.first_kv();
2787 if first_kv.can_merge() {
2788 cur_node = first_kv.merge().descend();
2790 let left_len = first_kv.reborrow().left_edge().descend().len();
2791 if left_len < node::MIN_LEN + 1 {
2792 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
2794 cur_node = first_kv.left_edge().descend();
2803 enum UnderflowResult<'a, K, V> {
2805 Merged(Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge>, bool, usize),
2809 fn handle_underfull_node<K, V>(
2810 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2811 ) -> UnderflowResult<'_, K, V> {
2812 let parent = match node.ascend() {
2813 Ok(parent) => parent,
2814 Err(_) => return AtRoot,
2817 let (is_left, mut handle) = match parent.left_kv() {
2818 Ok(left) => (true, left),
2820 let right = unsafe { unwrap_unchecked(parent.right_kv().ok()) };
2825 if handle.can_merge() {
2826 let offset = if is_left { handle.reborrow().left_edge().descend().len() + 1 } else { 0 };
2827 Merged(handle.merge(), is_left, offset)
2830 handle.steal_left();
2832 handle.steal_right();
2838 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2841 fn next(&mut self) -> Option<(K, V)> {
2842 let res = match (self.left.peek(), self.right.peek()) {
2843 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2844 (Some(_), None) => Ordering::Less,
2845 (None, Some(_)) => Ordering::Greater,
2846 (None, None) => return None,
2849 // Check which elements comes first and only advance the corresponding iterator.
2850 // If two keys are equal, take the value from `right`.
2852 Ordering::Less => self.left.next(),
2853 Ordering::Greater => self.right.next(),
2854 Ordering::Equal => {