1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
3 use core::fmt::{self, Debug};
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.node_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_internal_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().node_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 let root_node = self.root.as_ref()?.node_as_ref();
225 match search::search_tree(root_node, key) {
226 Found(handle) => Some(handle.into_kv().0),
231 fn take(&mut self, key: &Q) -> Option<K> {
232 let root_node = self.root.as_mut()?.node_as_mut();
233 match search::search_tree(root_node, key) {
234 Found(handle) => Some(
235 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
243 fn replace(&mut self, key: K) -> Option<K> {
244 let root = Self::ensure_is_owned(&mut self.root);
245 match search::search_tree::<marker::Mut<'_>, K, (), K>(root.node_as_mut(), &key) {
246 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
248 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
256 /// An iterator over the entries of a `BTreeMap`.
258 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
259 /// documentation for more.
261 /// [`iter`]: BTreeMap::iter
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub struct Iter<'a, K: 'a, V: 'a> {
264 range: Range<'a, K, V>,
268 #[stable(feature = "collection_debug", since = "1.17.0")]
269 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 f.debug_list().entries(self.clone()).finish()
275 /// A mutable iterator over the entries of a `BTreeMap`.
277 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
278 /// documentation for more.
280 /// [`iter_mut`]: BTreeMap::iter_mut
281 #[stable(feature = "rust1", since = "1.0.0")]
283 pub struct IterMut<'a, K: 'a, V: 'a> {
284 range: RangeMut<'a, K, V>,
288 /// An owning iterator over the entries of a `BTreeMap`.
290 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
291 /// (provided by the `IntoIterator` trait). See its documentation for more.
293 /// [`into_iter`]: IntoIterator::into_iter
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub struct IntoIter<K, V> {
296 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
297 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
301 #[stable(feature = "collection_debug", since = "1.17.0")]
302 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 front: self.front.as_ref().map(|f| f.reborrow()),
306 back: self.back.as_ref().map(|b| b.reborrow()),
308 f.debug_list().entries(range).finish()
312 /// An iterator over the keys of a `BTreeMap`.
314 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
315 /// documentation for more.
317 /// [`keys`]: BTreeMap::keys
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub struct Keys<'a, K: 'a, V: 'a> {
320 inner: Iter<'a, K, V>,
323 #[stable(feature = "collection_debug", since = "1.17.0")]
324 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.debug_list().entries(self.clone()).finish()
330 /// An iterator over the values of a `BTreeMap`.
332 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
333 /// documentation for more.
335 /// [`values`]: BTreeMap::values
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub struct Values<'a, K: 'a, V: 'a> {
338 inner: Iter<'a, K, V>,
341 #[stable(feature = "collection_debug", since = "1.17.0")]
342 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
344 f.debug_list().entries(self.clone()).finish()
348 /// A mutable iterator over the values of a `BTreeMap`.
350 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
351 /// documentation for more.
353 /// [`values_mut`]: BTreeMap::values_mut
354 #[stable(feature = "map_values_mut", since = "1.10.0")]
356 pub struct ValuesMut<'a, K: 'a, V: 'a> {
357 inner: IterMut<'a, K, V>,
360 /// An owning iterator over the keys of a `BTreeMap`.
362 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
363 /// See its documentation for more.
365 /// [`into_keys`]: BTreeMap::into_keys
366 #[unstable(feature = "map_into_keys_values", issue = "75294")]
368 pub struct IntoKeys<K, V> {
369 inner: IntoIter<K, V>,
372 /// An owning iterator over the values of a `BTreeMap`.
374 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
375 /// See its documentation for more.
377 /// [`into_values`]: BTreeMap::into_values
378 #[unstable(feature = "map_into_keys_values", issue = "75294")]
380 pub struct IntoValues<K, V> {
381 inner: IntoIter<K, V>,
384 /// An iterator over a sub-range of entries in a `BTreeMap`.
386 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
387 /// documentation for more.
389 /// [`range`]: BTreeMap::range
390 #[stable(feature = "btree_range", since = "1.17.0")]
391 pub struct Range<'a, K: 'a, V: 'a> {
392 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
393 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
396 #[stable(feature = "collection_debug", since = "1.17.0")]
397 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399 f.debug_list().entries(self.clone()).finish()
403 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
405 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
406 /// documentation for more.
408 /// [`range_mut`]: BTreeMap::range_mut
409 #[stable(feature = "btree_range", since = "1.17.0")]
410 pub struct RangeMut<'a, K: 'a, V: 'a> {
411 front: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
412 back: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
414 // Be invariant in `K` and `V`
415 _marker: PhantomData<&'a mut (K, V)>,
418 #[stable(feature = "collection_debug", since = "1.17.0")]
419 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 front: self.front.as_ref().map(|f| f.reborrow()),
423 back: self.back.as_ref().map(|b| b.reborrow()),
425 f.debug_list().entries(range).finish()
429 /// A view into a single entry in a map, which may either be vacant or occupied.
431 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
433 /// [`entry`]: BTreeMap::entry
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub enum Entry<'a, K: 'a, V: 'a> {
437 #[stable(feature = "rust1", since = "1.0.0")]
438 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
440 /// An occupied entry.
441 #[stable(feature = "rust1", since = "1.0.0")]
442 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
445 #[stable(feature = "debug_btree_map", since = "1.12.0")]
446 impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
450 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
455 /// A view into a vacant entry in a `BTreeMap`.
456 /// It is part of the [`Entry`] enum.
458 /// [`Entry`]: enum.Entry.html
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub struct VacantEntry<'a, K: 'a, V: 'a> {
462 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
463 length: &'a mut usize,
465 // Be invariant in `K` and `V`
466 _marker: PhantomData<&'a mut (K, V)>,
469 #[stable(feature = "debug_btree_map", since = "1.12.0")]
470 impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.debug_tuple("VacantEntry").field(self.key()).finish()
476 /// A view into an occupied entry in a `BTreeMap`.
477 /// It is part of the [`Entry`] enum.
479 /// [`Entry`]: enum.Entry.html
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
482 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
484 length: &'a mut usize,
486 // Be invariant in `K` and `V`
487 _marker: PhantomData<&'a mut (K, V)>,
490 #[stable(feature = "debug_btree_map", since = "1.12.0")]
491 impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
497 // An iterator for merging two sorted sequences into one
498 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
503 impl<K: Ord, V> BTreeMap<K, V> {
504 /// Makes a new empty BTreeMap.
506 /// Does not allocate anything on its own.
513 /// use std::collections::BTreeMap;
515 /// let mut map = BTreeMap::new();
517 /// // entries can now be inserted into the empty map
518 /// map.insert(1, "a");
520 #[stable(feature = "rust1", since = "1.0.0")]
521 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
522 pub const fn new() -> BTreeMap<K, V> {
523 BTreeMap { root: None, length: 0 }
526 /// Clears the map, removing all elements.
533 /// use std::collections::BTreeMap;
535 /// let mut a = BTreeMap::new();
536 /// a.insert(1, "a");
538 /// assert!(a.is_empty());
540 #[stable(feature = "rust1", since = "1.0.0")]
541 pub fn clear(&mut self) {
542 *self = BTreeMap::new();
545 /// Returns a reference to the value corresponding to the key.
547 /// The key may be any borrowed form of the map's key type, but the ordering
548 /// on the borrowed form *must* match the ordering on the key type.
555 /// use std::collections::BTreeMap;
557 /// let mut map = BTreeMap::new();
558 /// map.insert(1, "a");
559 /// assert_eq!(map.get(&1), Some(&"a"));
560 /// assert_eq!(map.get(&2), None);
562 #[stable(feature = "rust1", since = "1.0.0")]
563 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
568 let root_node = self.root.as_ref()?.node_as_ref();
569 match search::search_tree(root_node, key) {
570 Found(handle) => Some(handle.into_kv().1),
575 /// Returns the key-value pair corresponding to the supplied key.
577 /// The supplied key may be any borrowed form of the map's key type, but the ordering
578 /// on the borrowed form *must* match the ordering on the key type.
583 /// use std::collections::BTreeMap;
585 /// let mut map = BTreeMap::new();
586 /// map.insert(1, "a");
587 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
588 /// assert_eq!(map.get_key_value(&2), None);
590 #[stable(feature = "map_get_key_value", since = "1.40.0")]
591 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
596 let root_node = self.root.as_ref()?.node_as_ref();
597 match search::search_tree(root_node, k) {
598 Found(handle) => Some(handle.into_kv()),
603 /// Returns the first key-value pair in the map.
604 /// The key in this pair is the minimum key in the map.
611 /// #![feature(map_first_last)]
612 /// use std::collections::BTreeMap;
614 /// let mut map = BTreeMap::new();
615 /// assert_eq!(map.first_key_value(), None);
616 /// map.insert(1, "b");
617 /// map.insert(2, "a");
618 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
620 #[unstable(feature = "map_first_last", issue = "62924")]
621 pub fn first_key_value(&self) -> Option<(&K, &V)> {
622 let root_node = self.root.as_ref()?.node_as_ref();
623 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
626 /// Returns the first entry in the map for in-place manipulation.
627 /// The key of this entry is the minimum key in the map.
632 /// #![feature(map_first_last)]
633 /// use std::collections::BTreeMap;
635 /// let mut map = BTreeMap::new();
636 /// map.insert(1, "a");
637 /// map.insert(2, "b");
638 /// if let Some(mut entry) = map.first_entry() {
639 /// if *entry.key() > 0 {
640 /// entry.insert("first");
643 /// assert_eq!(*map.get(&1).unwrap(), "first");
644 /// assert_eq!(*map.get(&2).unwrap(), "b");
646 #[unstable(feature = "map_first_last", issue = "62924")]
647 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
648 let root_node = self.root.as_mut()?.node_as_mut();
649 let kv = root_node.first_leaf_edge().right_kv().ok()?;
651 handle: kv.forget_node_type(),
652 length: &mut self.length,
653 _marker: PhantomData,
657 /// Removes and returns the first element in the map.
658 /// The key of this element is the minimum key that was in the map.
662 /// Draining elements in ascending order, while keeping a usable map each iteration.
665 /// #![feature(map_first_last)]
666 /// use std::collections::BTreeMap;
668 /// let mut map = BTreeMap::new();
669 /// map.insert(1, "a");
670 /// map.insert(2, "b");
671 /// while let Some((key, _val)) = map.pop_first() {
672 /// assert!(map.iter().all(|(k, _v)| *k > key));
674 /// assert!(map.is_empty());
676 #[unstable(feature = "map_first_last", issue = "62924")]
677 pub fn pop_first(&mut self) -> Option<(K, V)> {
678 self.first_entry().map(|entry| entry.remove_entry())
681 /// Returns the last key-value pair in the map.
682 /// The key in this pair is the maximum key in the map.
689 /// #![feature(map_first_last)]
690 /// use std::collections::BTreeMap;
692 /// let mut map = BTreeMap::new();
693 /// map.insert(1, "b");
694 /// map.insert(2, "a");
695 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
697 #[unstable(feature = "map_first_last", issue = "62924")]
698 pub fn last_key_value(&self) -> Option<(&K, &V)> {
699 let root_node = self.root.as_ref()?.node_as_ref();
700 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
703 /// Returns the last entry in the map for in-place manipulation.
704 /// The key of this entry is the maximum key in the map.
709 /// #![feature(map_first_last)]
710 /// use std::collections::BTreeMap;
712 /// let mut map = BTreeMap::new();
713 /// map.insert(1, "a");
714 /// map.insert(2, "b");
715 /// if let Some(mut entry) = map.last_entry() {
716 /// if *entry.key() > 0 {
717 /// entry.insert("last");
720 /// assert_eq!(*map.get(&1).unwrap(), "a");
721 /// assert_eq!(*map.get(&2).unwrap(), "last");
723 #[unstable(feature = "map_first_last", issue = "62924")]
724 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
725 let root_node = self.root.as_mut()?.node_as_mut();
726 let kv = root_node.last_leaf_edge().left_kv().ok()?;
728 handle: kv.forget_node_type(),
729 length: &mut self.length,
730 _marker: PhantomData,
734 /// Removes and returns the last element in the map.
735 /// The key of this element is the maximum key that was in the map.
739 /// Draining elements in descending order, while keeping a usable map each iteration.
742 /// #![feature(map_first_last)]
743 /// use std::collections::BTreeMap;
745 /// let mut map = BTreeMap::new();
746 /// map.insert(1, "a");
747 /// map.insert(2, "b");
748 /// while let Some((key, _val)) = map.pop_last() {
749 /// assert!(map.iter().all(|(k, _v)| *k < key));
751 /// assert!(map.is_empty());
753 #[unstable(feature = "map_first_last", issue = "62924")]
754 pub fn pop_last(&mut self) -> Option<(K, V)> {
755 self.last_entry().map(|entry| entry.remove_entry())
758 /// Returns `true` if the map contains a value for the specified key.
760 /// The key may be any borrowed form of the map's key type, but the ordering
761 /// on the borrowed form *must* match the ordering on the key type.
768 /// use std::collections::BTreeMap;
770 /// let mut map = BTreeMap::new();
771 /// map.insert(1, "a");
772 /// assert_eq!(map.contains_key(&1), true);
773 /// assert_eq!(map.contains_key(&2), false);
775 #[stable(feature = "rust1", since = "1.0.0")]
776 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
781 self.get(key).is_some()
784 /// Returns a mutable reference to the value corresponding to the key.
786 /// The key may be any borrowed form of the map's key type, but the ordering
787 /// on the borrowed form *must* match the ordering on the key type.
794 /// use std::collections::BTreeMap;
796 /// let mut map = BTreeMap::new();
797 /// map.insert(1, "a");
798 /// if let Some(x) = map.get_mut(&1) {
801 /// assert_eq!(map[&1], "b");
803 // See `get` for implementation notes, this is basically a copy-paste with mut's added
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
810 let root_node = self.root.as_mut()?.node_as_mut();
811 match search::search_tree(root_node, key) {
812 Found(handle) => Some(handle.into_kv_mut().1),
817 /// Inserts a key-value pair into the map.
819 /// If the map did not have this key present, `None` is returned.
821 /// If the map did have this key present, the value is updated, and the old
822 /// value is returned. The key is not updated, though; this matters for
823 /// types that can be `==` without being identical. See the [module-level
824 /// documentation] for more.
826 /// [module-level documentation]: index.html#insert-and-complex-keys
833 /// use std::collections::BTreeMap;
835 /// let mut map = BTreeMap::new();
836 /// assert_eq!(map.insert(37, "a"), None);
837 /// assert_eq!(map.is_empty(), false);
839 /// map.insert(37, "b");
840 /// assert_eq!(map.insert(37, "c"), Some("b"));
841 /// assert_eq!(map[&37], "c");
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
845 match self.entry(key) {
846 Occupied(mut entry) => Some(entry.insert(value)),
854 /// Removes a key from the map, returning the value at the key if the key
855 /// was previously in the map.
857 /// The key may be any borrowed form of the map's key type, but the ordering
858 /// on the borrowed form *must* match the ordering on the key type.
865 /// use std::collections::BTreeMap;
867 /// let mut map = BTreeMap::new();
868 /// map.insert(1, "a");
869 /// assert_eq!(map.remove(&1), Some("a"));
870 /// assert_eq!(map.remove(&1), None);
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
878 self.remove_entry(key).map(|(_, v)| v)
881 /// Removes a key from the map, returning the stored key and value if the key
882 /// was previously in the map.
884 /// The key may be any borrowed form of the map's key type, but the ordering
885 /// on the borrowed form *must* match the ordering on the key type.
892 /// use std::collections::BTreeMap;
894 /// let mut map = BTreeMap::new();
895 /// map.insert(1, "a");
896 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
897 /// assert_eq!(map.remove_entry(&1), None);
899 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
900 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
905 let root_node = self.root.as_mut()?.node_as_mut();
906 match search::search_tree(root_node, key) {
907 Found(handle) => Some(
908 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
915 /// Moves all elements from `other` into `Self`, leaving `other` empty.
920 /// use std::collections::BTreeMap;
922 /// let mut a = BTreeMap::new();
923 /// a.insert(1, "a");
924 /// a.insert(2, "b");
925 /// a.insert(3, "c");
927 /// let mut b = BTreeMap::new();
928 /// b.insert(3, "d");
929 /// b.insert(4, "e");
930 /// b.insert(5, "f");
932 /// a.append(&mut b);
934 /// assert_eq!(a.len(), 5);
935 /// assert_eq!(b.len(), 0);
937 /// assert_eq!(a[&1], "a");
938 /// assert_eq!(a[&2], "b");
939 /// assert_eq!(a[&3], "d");
940 /// assert_eq!(a[&4], "e");
941 /// assert_eq!(a[&5], "f");
943 #[stable(feature = "btree_append", since = "1.11.0")]
944 pub fn append(&mut self, other: &mut Self) {
945 // Do we have to append anything at all?
946 if other.is_empty() {
950 // We can just swap `self` and `other` if `self` is empty.
952 mem::swap(self, other);
956 // First, we merge `self` and `other` into a sorted sequence in linear time.
957 let self_iter = mem::take(self).into_iter();
958 let other_iter = mem::take(other).into_iter();
959 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
961 // Second, we build a tree from the sorted sequence in linear time.
962 self.from_sorted_iter(iter);
965 /// Constructs a double-ended iterator over a sub-range of elements in the map.
966 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
967 /// yield elements from min (inclusive) to max (exclusive).
968 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
969 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
970 /// range from 4 to 10.
974 /// Panics if range `start > end`.
975 /// Panics if range `start == end` and both bounds are `Excluded`.
982 /// use std::collections::BTreeMap;
983 /// use std::ops::Bound::Included;
985 /// let mut map = BTreeMap::new();
986 /// map.insert(3, "a");
987 /// map.insert(5, "b");
988 /// map.insert(8, "c");
989 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
990 /// println!("{}: {}", key, value);
992 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
994 #[stable(feature = "btree_range", since = "1.17.0")]
995 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1001 if let Some(root) = &self.root {
1002 let (f, b) = range_search(root.node_as_ref(), range);
1004 Range { front: Some(f), back: Some(b) }
1006 Range { front: None, back: None }
1010 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1011 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1012 /// yield elements from min (inclusive) to max (exclusive).
1013 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1014 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1015 /// range from 4 to 10.
1019 /// Panics if range `start > end`.
1020 /// Panics if range `start == end` and both bounds are `Excluded`.
1027 /// use std::collections::BTreeMap;
1029 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1031 /// .map(|&s| (s, 0))
1033 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1034 /// *balance += 100;
1036 /// for (name, balance) in &map {
1037 /// println!("{} => {}", name, balance);
1040 #[stable(feature = "btree_range", since = "1.17.0")]
1041 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1047 if let Some(root) = &mut self.root {
1048 let (f, b) = range_search(root.node_as_mut(), range);
1050 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1052 RangeMut { front: None, back: None, _marker: PhantomData }
1056 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1063 /// use std::collections::BTreeMap;
1065 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1067 /// // count the number of occurrences of letters in the vec
1068 /// for x in vec!["a","b","a","c","a","b"] {
1069 /// *count.entry(x).or_insert(0) += 1;
1072 /// assert_eq!(count["a"], 3);
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1076 // FIXME(@porglezomp) Avoid allocating if we don't insert
1077 let root = Self::ensure_is_owned(&mut self.root);
1078 match search::search_tree(root.node_as_mut(), &key) {
1080 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1083 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1088 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1089 let root = Self::ensure_is_owned(&mut self.root);
1090 let mut cur_node = root.node_as_mut().last_leaf_edge().into_node();
1091 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1092 for (key, value) in iter {
1093 // Try to push key-value pair into the current leaf node.
1094 if cur_node.len() < node::CAPACITY {
1095 cur_node.push(key, value);
1097 // No space left, go up and push there.
1099 let mut test_node = cur_node.forget_type();
1101 match test_node.ascend() {
1103 let parent = parent.into_node();
1104 if parent.len() < node::CAPACITY {
1105 // Found a node with space left, push here.
1110 test_node = parent.forget_type();
1114 // We are at the top, create a new root node and push there.
1115 open_node = root.push_internal_level();
1121 // Push key-value pair and new right subtree.
1122 let tree_height = open_node.height() - 1;
1123 let mut right_tree = node::Root::new_leaf();
1124 for _ in 0..tree_height {
1125 right_tree.push_internal_level();
1127 open_node.push(key, value, right_tree);
1129 // Go down to the right-most leaf again.
1130 cur_node = open_node.forget_type().last_leaf_edge().into_node();
1135 Self::fix_right_edge(root)
1138 fn fix_right_edge(root: &mut node::Root<K, V>) {
1139 // Handle underfull nodes, start from the top.
1140 let mut cur_node = root.node_as_mut();
1141 while let Internal(internal) = cur_node.force() {
1142 // Check if right-most child is underfull.
1143 let mut last_edge = internal.last_edge();
1144 let right_child_len = last_edge.reborrow().descend().len();
1145 if right_child_len < node::MIN_LEN {
1146 // We need to steal.
1147 let mut last_kv = match last_edge.left_kv() {
1149 Err(_) => unreachable!(),
1151 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1152 last_edge = last_kv.right_edge();
1156 cur_node = last_edge.descend();
1160 /// Splits the collection into two at the given key. Returns everything after the given key,
1161 /// including the key.
1168 /// use std::collections::BTreeMap;
1170 /// let mut a = BTreeMap::new();
1171 /// a.insert(1, "a");
1172 /// a.insert(2, "b");
1173 /// a.insert(3, "c");
1174 /// a.insert(17, "d");
1175 /// a.insert(41, "e");
1177 /// let b = a.split_off(&3);
1179 /// assert_eq!(a.len(), 2);
1180 /// assert_eq!(b.len(), 3);
1182 /// assert_eq!(a[&1], "a");
1183 /// assert_eq!(a[&2], "b");
1185 /// assert_eq!(b[&3], "c");
1186 /// assert_eq!(b[&17], "d");
1187 /// assert_eq!(b[&41], "e");
1189 #[stable(feature = "btree_split_off", since = "1.11.0")]
1190 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1194 if self.is_empty() {
1198 let total_num = self.len();
1199 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1201 let mut right = Self::new();
1202 let right_root = Self::ensure_is_owned(&mut right.root);
1203 for _ in 0..left_root.height() {
1204 right_root.push_internal_level();
1208 let mut left_node = left_root.node_as_mut();
1209 let mut right_node = right_root.node_as_mut();
1212 let mut split_edge = match search::search_node(left_node, key) {
1213 // key is going to the right tree
1214 Found(handle) => handle.left_edge(),
1215 GoDown(handle) => handle,
1218 split_edge.move_suffix(&mut right_node);
1220 match (split_edge.force(), right_node.force()) {
1221 (Internal(edge), Internal(node)) => {
1222 left_node = edge.descend();
1223 right_node = node.first_edge().descend();
1225 (Leaf(_), Leaf(_)) => {
1235 left_root.fix_right_border();
1236 right_root.fix_left_border();
1238 if left_root.height() < right_root.height() {
1239 self.recalc_length();
1240 right.length = total_num - self.len();
1242 right.recalc_length();
1243 self.length = total_num - right.len();
1249 /// Creates an iterator which uses a closure to determine if an element should be removed.
1251 /// If the closure returns true, the element is removed from the map and yielded.
1252 /// If the closure returns false, or panics, the element remains in the map and will not be
1255 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1256 /// whether you choose to keep or remove it.
1258 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1259 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1261 /// It is unspecified how many more elements will be subjected to the closure
1262 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1263 /// or if the `DrainFilter` value is leaked.
1267 /// Splitting a map into even and odd keys, reusing the original map:
1270 /// #![feature(btree_drain_filter)]
1271 /// use std::collections::BTreeMap;
1273 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1274 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1276 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1277 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1279 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1280 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1282 F: FnMut(&K, &mut V) -> bool,
1284 DrainFilter { pred, inner: self.drain_filter_inner() }
1286 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1287 let root_node = self.root.as_mut().map(|r| r.node_as_mut());
1288 let front = root_node.map(|rn| rn.first_leaf_edge());
1289 DrainFilterInner { length: &mut self.length, cur_leaf_edge: front }
1292 /// Calculates the number of elements if it is incorrect.
1293 fn recalc_length(&mut self) {
1294 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1299 let mut res = node.len();
1301 if let Internal(node) = node.force() {
1302 let mut edge = node.first_edge();
1304 res += dfs(edge.reborrow().descend());
1305 match edge.right_kv() {
1307 edge = right_kv.right_edge();
1319 self.length = dfs(self.root.as_ref().unwrap().node_as_ref());
1322 /// Creates a consuming iterator visiting all the keys, in sorted order.
1323 /// The map cannot be used after calling this.
1324 /// The iterator element type is `K`.
1329 /// #![feature(map_into_keys_values)]
1330 /// use std::collections::BTreeMap;
1332 /// let mut a = BTreeMap::new();
1333 /// a.insert(2, "b");
1334 /// a.insert(1, "a");
1336 /// let keys: Vec<i32> = a.into_keys().collect();
1337 /// assert_eq!(keys, [1, 2]);
1340 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1341 pub fn into_keys(self) -> IntoKeys<K, V> {
1342 IntoKeys { inner: self.into_iter() }
1345 /// Creates a consuming iterator visiting all the values, in order by key.
1346 /// The map cannot be used after calling this.
1347 /// The iterator element type is `V`.
1352 /// #![feature(map_into_keys_values)]
1353 /// use std::collections::BTreeMap;
1355 /// let mut a = BTreeMap::new();
1356 /// a.insert(1, "hello");
1357 /// a.insert(2, "goodbye");
1359 /// let values: Vec<&str> = a.into_values().collect();
1360 /// assert_eq!(values, ["hello", "goodbye"]);
1363 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1364 pub fn into_values(self) -> IntoValues<K, V> {
1365 IntoValues { inner: self.into_iter() }
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1371 type Item = (&'a K, &'a V);
1372 type IntoIter = Iter<'a, K, V>;
1374 fn into_iter(self) -> Iter<'a, K, V> {
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1381 type Item = (&'a K, &'a V);
1383 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1384 if self.length == 0 {
1388 unsafe { Some(self.range.next_unchecked()) }
1392 fn size_hint(&self) -> (usize, Option<usize>) {
1393 (self.length, Some(self.length))
1396 fn last(mut self) -> Option<(&'a K, &'a V)> {
1400 fn min(mut self) -> Option<(&'a K, &'a V)> {
1404 fn max(mut self) -> Option<(&'a K, &'a V)> {
1409 #[stable(feature = "fused", since = "1.26.0")]
1410 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1414 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1415 if self.length == 0 {
1419 unsafe { Some(self.range.next_back_unchecked()) }
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1426 fn len(&self) -> usize {
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<K, V> Clone for Iter<'_, K, V> {
1433 fn clone(&self) -> Self {
1434 Iter { range: self.range.clone(), length: self.length }
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1440 type Item = (&'a K, &'a mut V);
1441 type IntoIter = IterMut<'a, K, V>;
1443 fn into_iter(self) -> IterMut<'a, K, V> {
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1450 type Item = (&'a K, &'a mut V);
1452 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1453 if self.length == 0 {
1457 let (k, v) = unsafe { self.range.next_unchecked() };
1458 Some((k, v)) // coerce k from `&mut K` to `&K`
1462 fn size_hint(&self) -> (usize, Option<usize>) {
1463 (self.length, Some(self.length))
1466 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1470 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1474 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1481 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1482 if self.length == 0 {
1486 let (k, v) = unsafe { self.range.next_back_unchecked() };
1487 Some((k, v)) // coerce k from `&mut K` to `&K`
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1494 fn len(&self) -> usize {
1499 #[stable(feature = "fused", since = "1.26.0")]
1500 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl<K, V> IntoIterator for BTreeMap<K, V> {
1505 type IntoIter = IntoIter<K, V>;
1507 fn into_iter(self) -> IntoIter<K, V> {
1508 let mut me = ManuallyDrop::new(self);
1509 if let Some(root) = me.root.take() {
1510 let (f, b) = full_range_search(root.into_ref());
1512 IntoIter { front: Some(f), back: Some(b), length: me.length }
1514 IntoIter { front: None, back: None, length: 0 }
1519 #[stable(feature = "btree_drop", since = "1.7.0")]
1520 impl<K, V> Drop for IntoIter<K, V> {
1521 fn drop(&mut self) {
1522 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1524 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1525 fn drop(&mut self) {
1526 // Continue the same loop we perform below. This only runs when unwinding, so we
1527 // don't have to care about panics this time (they'll abort).
1528 while let Some(_) = self.0.next() {}
1532 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1533 while let Some(parent) = node.deallocate_and_ascend() {
1534 node = parent.into_node().forget_type();
1540 while let Some(pair) = self.next() {
1541 let guard = DropGuard(self);
1547 if let Some(front) = ptr::read(&self.front) {
1548 let mut node = front.into_node().forget_type();
1549 // Most of the nodes have been deallocated while traversing
1550 // but one pile from a leaf up to the root is left standing.
1551 while let Some(parent) = node.deallocate_and_ascend() {
1552 node = parent.into_node().forget_type();
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<K, V> Iterator for IntoIter<K, V> {
1563 fn next(&mut self) -> Option<(K, V)> {
1564 if self.length == 0 {
1568 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1572 fn size_hint(&self) -> (usize, Option<usize>) {
1573 (self.length, Some(self.length))
1577 #[stable(feature = "rust1", since = "1.0.0")]
1578 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1579 fn next_back(&mut self) -> Option<(K, V)> {
1580 if self.length == 0 {
1584 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1591 fn len(&self) -> usize {
1596 #[stable(feature = "fused", since = "1.26.0")]
1597 impl<K, V> FusedIterator for IntoIter<K, V> {}
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1603 fn next(&mut self) -> Option<&'a K> {
1604 self.inner.next().map(|(k, _)| k)
1607 fn size_hint(&self) -> (usize, Option<usize>) {
1608 self.inner.size_hint()
1611 fn last(mut self) -> Option<&'a K> {
1615 fn min(mut self) -> Option<&'a K> {
1619 fn max(mut self) -> Option<&'a K> {
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1626 fn next_back(&mut self) -> Option<&'a K> {
1627 self.inner.next_back().map(|(k, _)| k)
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1633 fn len(&self) -> usize {
1638 #[stable(feature = "fused", since = "1.26.0")]
1639 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl<K, V> Clone for Keys<'_, K, V> {
1643 fn clone(&self) -> Self {
1644 Keys { inner: self.inner.clone() }
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 impl<'a, K, V> Iterator for Values<'a, K, V> {
1652 fn next(&mut self) -> Option<&'a V> {
1653 self.inner.next().map(|(_, v)| v)
1656 fn size_hint(&self) -> (usize, Option<usize>) {
1657 self.inner.size_hint()
1660 fn last(mut self) -> Option<&'a V> {
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1667 fn next_back(&mut self) -> Option<&'a V> {
1668 self.inner.next_back().map(|(_, v)| v)
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1674 fn len(&self) -> usize {
1679 #[stable(feature = "fused", since = "1.26.0")]
1680 impl<K, V> FusedIterator for Values<'_, K, V> {}
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 impl<K, V> Clone for Values<'_, K, V> {
1684 fn clone(&self) -> Self {
1685 Values { inner: self.inner.clone() }
1689 /// An iterator produced by calling `drain_filter` on BTreeMap.
1690 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1691 pub struct DrainFilter<'a, K, V, F>
1695 F: 'a + FnMut(&K, &mut V) -> bool,
1698 inner: DrainFilterInner<'a, K, V>,
1700 /// Most of the implementation of DrainFilter, independent of the type
1701 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1702 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1703 length: &'a mut usize,
1704 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1707 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1708 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1710 F: FnMut(&K, &mut V) -> bool,
1712 fn drop(&mut self) {
1713 self.for_each(drop);
1717 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1718 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1722 F: FnMut(&K, &mut V) -> bool,
1724 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1725 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1729 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1730 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1732 F: FnMut(&K, &mut V) -> bool,
1736 fn next(&mut self) -> Option<(K, V)> {
1737 self.inner.next(&mut self.pred)
1740 fn size_hint(&self) -> (usize, Option<usize>) {
1741 self.inner.size_hint()
1745 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1746 /// Allow Debug implementations to predict the next element.
1747 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1748 let edge = self.cur_leaf_edge.as_ref()?;
1749 edge.reborrow().next_kv().ok().map(|kv| kv.into_kv())
1752 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1753 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1755 F: FnMut(&K, &mut V) -> bool,
1757 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1758 let (k, v) = kv.kv_mut();
1761 let (kv, pos) = kv.remove_kv_tracking();
1762 self.cur_leaf_edge = Some(pos);
1765 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1770 /// Implementation of a typical `DrainFilter::size_hint` method.
1771 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1772 (0, Some(*self.length))
1776 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1777 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1779 #[stable(feature = "btree_range", since = "1.17.0")]
1780 impl<'a, K, V> Iterator for Range<'a, K, V> {
1781 type Item = (&'a K, &'a V);
1783 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1784 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1787 fn last(mut self) -> Option<(&'a K, &'a V)> {
1791 fn min(mut self) -> Option<(&'a K, &'a V)> {
1795 fn max(mut self) -> Option<(&'a K, &'a V)> {
1800 #[stable(feature = "map_values_mut", since = "1.10.0")]
1801 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1802 type Item = &'a mut V;
1804 fn next(&mut self) -> Option<&'a mut V> {
1805 self.inner.next().map(|(_, v)| v)
1808 fn size_hint(&self) -> (usize, Option<usize>) {
1809 self.inner.size_hint()
1812 fn last(mut self) -> Option<&'a mut V> {
1817 #[stable(feature = "map_values_mut", since = "1.10.0")]
1818 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1819 fn next_back(&mut self) -> Option<&'a mut V> {
1820 self.inner.next_back().map(|(_, v)| v)
1824 #[stable(feature = "map_values_mut", since = "1.10.0")]
1825 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1826 fn len(&self) -> usize {
1831 #[stable(feature = "fused", since = "1.26.0")]
1832 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1834 impl<'a, K, V> Range<'a, K, V> {
1835 fn is_empty(&self) -> bool {
1836 self.front == self.back
1839 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1840 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1844 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1845 impl<K, V> Iterator for IntoKeys<K, V> {
1848 fn next(&mut self) -> Option<K> {
1849 self.inner.next().map(|(k, _)| k)
1852 fn size_hint(&self) -> (usize, Option<usize>) {
1853 self.inner.size_hint()
1856 fn last(mut self) -> Option<K> {
1860 fn min(mut self) -> Option<K> {
1864 fn max(mut self) -> Option<K> {
1869 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1870 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1871 fn next_back(&mut self) -> Option<K> {
1872 self.inner.next_back().map(|(k, _)| k)
1876 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1877 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1878 fn len(&self) -> usize {
1883 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1884 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1886 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1887 impl<K, V> Iterator for IntoValues<K, V> {
1890 fn next(&mut self) -> Option<V> {
1891 self.inner.next().map(|(_, v)| v)
1894 fn size_hint(&self) -> (usize, Option<usize>) {
1895 self.inner.size_hint()
1898 fn last(mut self) -> Option<V> {
1903 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1904 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1905 fn next_back(&mut self) -> Option<V> {
1906 self.inner.next_back().map(|(_, v)| v)
1910 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1911 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1912 fn len(&self) -> usize {
1917 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1918 impl<K, V> FusedIterator for IntoValues<K, V> {}
1920 #[stable(feature = "btree_range", since = "1.17.0")]
1921 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1922 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1923 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1927 impl<'a, K, V> Range<'a, K, V> {
1928 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1929 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1933 #[stable(feature = "fused", since = "1.26.0")]
1934 impl<K, V> FusedIterator for Range<'_, K, V> {}
1936 #[stable(feature = "btree_range", since = "1.17.0")]
1937 impl<K, V> Clone for Range<'_, K, V> {
1938 fn clone(&self) -> Self {
1939 Range { front: self.front, back: self.back }
1943 #[stable(feature = "btree_range", since = "1.17.0")]
1944 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1945 type Item = (&'a K, &'a mut V);
1947 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1948 if self.is_empty() {
1951 let (k, v) = unsafe { self.next_unchecked() };
1952 Some((k, v)) // coerce k from `&mut K` to `&K`
1956 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1960 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1964 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1969 impl<'a, K, V> RangeMut<'a, K, V> {
1970 fn is_empty(&self) -> bool {
1971 self.front == self.back
1974 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1975 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1979 #[stable(feature = "btree_range", since = "1.17.0")]
1980 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1981 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1982 if self.is_empty() {
1985 let (k, v) = unsafe { self.next_back_unchecked() };
1986 Some((k, v)) // coerce k from `&mut K` to `&K`
1991 #[stable(feature = "fused", since = "1.26.0")]
1992 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1994 impl<'a, K, V> RangeMut<'a, K, V> {
1995 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1996 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2002 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2003 let mut map = BTreeMap::new();
2009 #[stable(feature = "rust1", since = "1.0.0")]
2010 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
2012 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2013 iter.into_iter().for_each(move |(k, v)| {
2019 fn extend_one(&mut self, (k, v): (K, V)) {
2024 #[stable(feature = "extend_ref", since = "1.2.0")]
2025 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
2026 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2027 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2031 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
2038 fn hash<H: Hasher>(&self, state: &mut H) {
2045 #[stable(feature = "rust1", since = "1.0.0")]
2046 impl<K: Ord, V> Default for BTreeMap<K, V> {
2047 /// Creates an empty `BTreeMap<K, V>`.
2048 fn default() -> BTreeMap<K, V> {
2053 #[stable(feature = "rust1", since = "1.0.0")]
2054 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
2055 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
2056 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
2063 #[stable(feature = "rust1", since = "1.0.0")]
2064 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
2066 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
2067 self.iter().partial_cmp(other.iter())
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
2074 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
2075 self.iter().cmp(other.iter())
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
2081 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2082 f.debug_map().entries(self.iter()).finish()
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
2094 /// Returns a reference to the value corresponding to the supplied key.
2098 /// Panics if the key is not present in the `BTreeMap`.
2100 fn index(&self, key: &Q) -> &V {
2101 self.get(key).expect("no entry found for key")
2105 /// Finds the leaf edges delimiting a specified range in or underneath a node.
2106 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
2107 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2110 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2111 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2117 match (range.start_bound(), range.end_bound()) {
2118 (Excluded(s), Excluded(e)) if s == e => {
2119 panic!("range start and end are equal and excluded in BTreeMap")
2121 (Included(s) | Excluded(s), Included(e) | Excluded(e)) if s > e => {
2122 panic!("range start is greater than range end in BTreeMap")
2127 // We duplicate the root NodeRef here -- we will never access it in a way
2128 // that overlaps references obtained from the root.
2129 let mut min_node = unsafe { ptr::read(&root) };
2130 let mut max_node = root;
2131 let mut min_found = false;
2132 let mut max_found = false;
2135 let front = match (min_found, range.start_bound()) {
2136 (false, Included(key)) => match search::search_node(min_node, key) {
2141 GoDown(edge) => edge,
2143 (false, Excluded(key)) => match search::search_node(min_node, key) {
2148 GoDown(edge) => edge,
2150 (true, Included(_)) => min_node.last_edge(),
2151 (true, Excluded(_)) => min_node.first_edge(),
2152 (_, Unbounded) => min_node.first_edge(),
2155 let back = match (max_found, range.end_bound()) {
2156 (false, Included(key)) => match search::search_node(max_node, key) {
2161 GoDown(edge) => edge,
2163 (false, Excluded(key)) => match search::search_node(max_node, key) {
2168 GoDown(edge) => edge,
2170 (true, Included(_)) => max_node.first_edge(),
2171 (true, Excluded(_)) => max_node.last_edge(),
2172 (_, Unbounded) => max_node.last_edge(),
2175 if front.partial_cmp(&back) == Some(Ordering::Greater) {
2176 panic!("Ord is ill-defined in BTreeMap range");
2178 match (front.force(), back.force()) {
2179 (Leaf(f), Leaf(b)) => {
2182 (Internal(min_int), Internal(max_int)) => {
2183 min_node = min_int.descend();
2184 max_node = max_int.descend();
2186 _ => unreachable!("BTreeMap has different depths"),
2191 /// Equivalent to `range_search(k, v, ..)` without the `Ord` bound.
2192 fn full_range_search<BorrowType, K, V>(
2193 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2195 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2196 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2198 // We duplicate the root NodeRef here -- we will never access it in a way
2199 // that overlaps references obtained from the root.
2200 let mut min_node = unsafe { ptr::read(&root) };
2201 let mut max_node = root;
2203 let front = min_node.first_edge();
2204 let back = max_node.last_edge();
2205 match (front.force(), back.force()) {
2206 (Leaf(f), Leaf(b)) => {
2209 (Internal(min_int), Internal(max_int)) => {
2210 min_node = min_int.descend();
2211 max_node = max_int.descend();
2213 _ => unreachable!("BTreeMap has different depths"),
2218 impl<K, V> BTreeMap<K, V> {
2219 /// Gets an iterator over the entries of the map, sorted by key.
2226 /// use std::collections::BTreeMap;
2228 /// let mut map = BTreeMap::new();
2229 /// map.insert(3, "c");
2230 /// map.insert(2, "b");
2231 /// map.insert(1, "a");
2233 /// for (key, value) in map.iter() {
2234 /// println!("{}: {}", key, value);
2237 /// let (first_key, first_value) = map.iter().next().unwrap();
2238 /// assert_eq!((*first_key, *first_value), (1, "a"));
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 pub fn iter(&self) -> Iter<'_, K, V> {
2242 if let Some(root) = &self.root {
2243 let (f, b) = full_range_search(root.node_as_ref());
2245 Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2247 Iter { range: Range { front: None, back: None }, length: 0 }
2251 /// Gets a mutable iterator over the entries of the map, sorted by key.
2258 /// use std::collections::BTreeMap;
2260 /// let mut map = BTreeMap::new();
2261 /// map.insert("a", 1);
2262 /// map.insert("b", 2);
2263 /// map.insert("c", 3);
2265 /// // add 10 to the value if the key isn't "a"
2266 /// for (key, value) in map.iter_mut() {
2267 /// if key != &"a" {
2272 #[stable(feature = "rust1", since = "1.0.0")]
2273 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2274 if let Some(root) = &mut self.root {
2275 let (f, b) = full_range_search(root.node_as_mut());
2278 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2279 length: self.length,
2282 IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2286 /// Gets an iterator over the keys of the map, in sorted order.
2293 /// use std::collections::BTreeMap;
2295 /// let mut a = BTreeMap::new();
2296 /// a.insert(2, "b");
2297 /// a.insert(1, "a");
2299 /// let keys: Vec<_> = a.keys().cloned().collect();
2300 /// assert_eq!(keys, [1, 2]);
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 pub fn keys(&self) -> Keys<'_, K, V> {
2304 Keys { inner: self.iter() }
2307 /// Gets an iterator over the values of the map, in order by key.
2314 /// use std::collections::BTreeMap;
2316 /// let mut a = BTreeMap::new();
2317 /// a.insert(1, "hello");
2318 /// a.insert(2, "goodbye");
2320 /// let values: Vec<&str> = a.values().cloned().collect();
2321 /// assert_eq!(values, ["hello", "goodbye"]);
2323 #[stable(feature = "rust1", since = "1.0.0")]
2324 pub fn values(&self) -> Values<'_, K, V> {
2325 Values { inner: self.iter() }
2328 /// Gets a mutable iterator over the values of the map, in order by key.
2335 /// use std::collections::BTreeMap;
2337 /// let mut a = BTreeMap::new();
2338 /// a.insert(1, String::from("hello"));
2339 /// a.insert(2, String::from("goodbye"));
2341 /// for value in a.values_mut() {
2342 /// value.push_str("!");
2345 /// let values: Vec<String> = a.values().cloned().collect();
2346 /// assert_eq!(values, [String::from("hello!"),
2347 /// String::from("goodbye!")]);
2349 #[stable(feature = "map_values_mut", since = "1.10.0")]
2350 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2351 ValuesMut { inner: self.iter_mut() }
2354 /// Returns the number of elements in the map.
2361 /// use std::collections::BTreeMap;
2363 /// let mut a = BTreeMap::new();
2364 /// assert_eq!(a.len(), 0);
2365 /// a.insert(1, "a");
2366 /// assert_eq!(a.len(), 1);
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 pub fn len(&self) -> usize {
2373 /// Returns `true` if the map contains no elements.
2380 /// use std::collections::BTreeMap;
2382 /// let mut a = BTreeMap::new();
2383 /// assert!(a.is_empty());
2384 /// a.insert(1, "a");
2385 /// assert!(!a.is_empty());
2387 #[stable(feature = "rust1", since = "1.0.0")]
2388 pub fn is_empty(&self) -> bool {
2392 /// If the root node is the empty (non-allocated) root node, allocate our
2393 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2394 fn ensure_is_owned(root: &mut Option<node::Root<K, V>>) -> &mut node::Root<K, V> {
2395 root.get_or_insert_with(node::Root::new_leaf)
2399 impl<'a, K: Ord, V> Entry<'a, K, V> {
2400 /// Ensures a value is in the entry by inserting the default if empty, and returns
2401 /// a mutable reference to the value in the entry.
2406 /// use std::collections::BTreeMap;
2408 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2409 /// map.entry("poneyland").or_insert(12);
2411 /// assert_eq!(map["poneyland"], 12);
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 pub fn or_insert(self, default: V) -> &'a mut V {
2416 Occupied(entry) => entry.into_mut(),
2417 Vacant(entry) => entry.insert(default),
2421 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2422 /// and returns a mutable reference to the value in the entry.
2427 /// use std::collections::BTreeMap;
2429 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2430 /// let s = "hoho".to_string();
2432 /// map.entry("poneyland").or_insert_with(|| s);
2434 /// assert_eq!(map["poneyland"], "hoho".to_string());
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2439 Occupied(entry) => entry.into_mut(),
2440 Vacant(entry) => entry.insert(default()),
2444 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2445 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2446 /// which takes the key as its argument, and returns a mutable reference to the value in the
2452 /// #![feature(or_insert_with_key)]
2453 /// use std::collections::BTreeMap;
2455 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2457 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2459 /// assert_eq!(map["poneyland"], 9);
2462 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2464 Occupied(entry) => entry.into_mut(),
2466 let value = default(entry.key());
2472 /// Returns a reference to this entry's key.
2477 /// use std::collections::BTreeMap;
2479 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2480 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2482 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2483 pub fn key(&self) -> &K {
2485 Occupied(ref entry) => entry.key(),
2486 Vacant(ref entry) => entry.key(),
2490 /// Provides in-place mutable access to an occupied entry before any
2491 /// potential inserts into the map.
2496 /// use std::collections::BTreeMap;
2498 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2500 /// map.entry("poneyland")
2501 /// .and_modify(|e| { *e += 1 })
2503 /// assert_eq!(map["poneyland"], 42);
2505 /// map.entry("poneyland")
2506 /// .and_modify(|e| { *e += 1 })
2508 /// assert_eq!(map["poneyland"], 43);
2510 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2511 pub fn and_modify<F>(self, f: F) -> Self
2516 Occupied(mut entry) => {
2520 Vacant(entry) => Vacant(entry),
2525 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2526 #[stable(feature = "entry_or_default", since = "1.28.0")]
2527 /// Ensures a value is in the entry by inserting the default value if empty,
2528 /// and returns a mutable reference to the value in the entry.
2533 /// use std::collections::BTreeMap;
2535 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2536 /// map.entry("poneyland").or_default();
2538 /// assert_eq!(map["poneyland"], None);
2540 pub fn or_default(self) -> &'a mut V {
2542 Occupied(entry) => entry.into_mut(),
2543 Vacant(entry) => entry.insert(Default::default()),
2548 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2549 /// Gets a reference to the key that would be used when inserting a value
2550 /// through the VacantEntry.
2555 /// use std::collections::BTreeMap;
2557 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2558 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2560 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2561 pub fn key(&self) -> &K {
2565 /// Take ownership of the key.
2570 /// use std::collections::BTreeMap;
2571 /// use std::collections::btree_map::Entry;
2573 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2575 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2579 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2580 pub fn into_key(self) -> K {
2584 /// Sets the value of the entry with the `VacantEntry`'s key,
2585 /// and returns a mutable reference to it.
2590 /// use std::collections::BTreeMap;
2591 /// use std::collections::btree_map::Entry;
2593 /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
2595 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2598 /// assert_eq!(map["poneyland"], 37);
2600 #[stable(feature = "rust1", since = "1.0.0")]
2601 pub fn insert(self, value: V) -> &'a mut V {
2604 let out_ptr = match self.handle.insert_recursing(self.key, value) {
2605 (Fit(_), val_ptr) => val_ptr,
2606 (Split(ins), val_ptr) => {
2607 let root = ins.left.into_root_mut();
2608 root.push_internal_level().push(ins.k, ins.v, ins.right);
2612 // Now that we have finished growing the tree using borrowed references,
2613 // dereference the pointer to a part of it, that we picked up along the way.
2614 unsafe { &mut *out_ptr }
2618 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2619 /// Gets a reference to the key in the entry.
2624 /// use std::collections::BTreeMap;
2626 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2627 /// map.entry("poneyland").or_insert(12);
2628 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2630 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2631 pub fn key(&self) -> &K {
2632 self.handle.reborrow().into_kv().0
2635 /// Take ownership of the key and value from the map.
2640 /// use std::collections::BTreeMap;
2641 /// use std::collections::btree_map::Entry;
2643 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2644 /// map.entry("poneyland").or_insert(12);
2646 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2647 /// // We delete the entry from the map.
2648 /// o.remove_entry();
2651 /// // If now try to get the value, it will panic:
2652 /// // println!("{}", map["poneyland"]);
2654 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2655 pub fn remove_entry(self) -> (K, V) {
2659 /// Gets a reference to the value in the entry.
2664 /// use std::collections::BTreeMap;
2665 /// use std::collections::btree_map::Entry;
2667 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2668 /// map.entry("poneyland").or_insert(12);
2670 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2671 /// assert_eq!(o.get(), &12);
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 pub fn get(&self) -> &V {
2676 self.handle.reborrow().into_kv().1
2679 /// Gets a mutable reference to the value in the entry.
2681 /// If you need a reference to the `OccupiedEntry` that may outlive the
2682 /// destruction of the `Entry` value, see [`into_mut`].
2684 /// [`into_mut`]: #method.into_mut
2689 /// use std::collections::BTreeMap;
2690 /// use std::collections::btree_map::Entry;
2692 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2693 /// map.entry("poneyland").or_insert(12);
2695 /// assert_eq!(map["poneyland"], 12);
2696 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2697 /// *o.get_mut() += 10;
2698 /// assert_eq!(*o.get(), 22);
2700 /// // We can use the same Entry multiple times.
2701 /// *o.get_mut() += 2;
2703 /// assert_eq!(map["poneyland"], 24);
2705 #[stable(feature = "rust1", since = "1.0.0")]
2706 pub fn get_mut(&mut self) -> &mut V {
2707 self.handle.kv_mut().1
2710 /// Converts the entry into a mutable reference to its value.
2712 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2714 /// [`get_mut`]: #method.get_mut
2719 /// use std::collections::BTreeMap;
2720 /// use std::collections::btree_map::Entry;
2722 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2723 /// map.entry("poneyland").or_insert(12);
2725 /// assert_eq!(map["poneyland"], 12);
2726 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2727 /// *o.into_mut() += 10;
2729 /// assert_eq!(map["poneyland"], 22);
2731 #[stable(feature = "rust1", since = "1.0.0")]
2732 pub fn into_mut(self) -> &'a mut V {
2733 self.handle.into_kv_mut().1
2736 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2737 /// and returns the entry's old value.
2742 /// use std::collections::BTreeMap;
2743 /// use std::collections::btree_map::Entry;
2745 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2746 /// map.entry("poneyland").or_insert(12);
2748 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2749 /// assert_eq!(o.insert(15), 12);
2751 /// assert_eq!(map["poneyland"], 15);
2753 #[stable(feature = "rust1", since = "1.0.0")]
2754 pub fn insert(&mut self, value: V) -> V {
2755 mem::replace(self.get_mut(), value)
2758 /// Takes the value of the entry out of the map, and returns it.
2763 /// use std::collections::BTreeMap;
2764 /// use std::collections::btree_map::Entry;
2766 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2767 /// map.entry("poneyland").or_insert(12);
2769 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2770 /// assert_eq!(o.remove(), 12);
2772 /// // If we try to get "poneyland"'s value, it'll panic:
2773 /// // println!("{}", map["poneyland"]);
2775 #[stable(feature = "rust1", since = "1.0.0")]
2776 pub fn remove(self) -> V {
2780 // Body of `remove_entry`, separate to keep the above implementations short.
2781 fn remove_kv(self) -> (K, V) {
2784 let (old_kv, _) = self.handle.remove_kv_tracking();
2789 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
2790 /// Removes a key/value-pair from the map, and returns that pair, as well as
2791 /// the leaf edge corresponding to that former pair.
2792 fn remove_kv_tracking(
2794 ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>) {
2795 let (old_kv, mut pos, was_internal) = match self.force() {
2797 let (old_kv, pos) = leaf.remove();
2798 (old_kv, pos, false)
2800 Internal(mut internal) => {
2801 // Replace the location freed in the internal node with an
2802 // adjacent KV, and remove that adjacent KV from its leaf.
2803 // Always choose the adjacent KV on the left side because
2804 // it is typically faster to pop an element from the end
2805 // of the KV arrays without needing to shift other elements.
2807 let key_loc = internal.kv_mut().0 as *mut K;
2808 let val_loc = internal.kv_mut().1 as *mut V;
2810 let to_remove = internal.left_edge().descend().last_leaf_edge().left_kv().ok();
2811 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2813 let (kv, pos) = to_remove.remove();
2815 let old_key = unsafe { mem::replace(&mut *key_loc, kv.0) };
2816 let old_val = unsafe { mem::replace(&mut *val_loc, kv.1) };
2818 ((old_key, old_val), pos, true)
2823 let mut cur_node = unsafe { ptr::read(&pos).into_node().forget_type() };
2824 let mut at_leaf = true;
2825 while cur_node.len() < node::MIN_LEN {
2826 match handle_underfull_node(cur_node) {
2828 Merged(edge, merged_with_left, offset) => {
2829 // If we merged with our right sibling then our tracked
2830 // position has not changed. However if we merged with our
2831 // left sibling then our tracked position is now dangling.
2832 if at_leaf && merged_with_left {
2833 let idx = pos.idx() + offset;
2834 let node = match unsafe { ptr::read(&edge).descend().force() } {
2836 Internal(_) => unreachable!(),
2838 pos = unsafe { Handle::new_edge(node, idx) };
2841 let parent = edge.into_node();
2842 if parent.len() == 0 {
2843 // The parent that was just emptied must be the root,
2844 // because nodes on a lower level would not have been
2845 // left with a single child.
2846 parent.into_root_mut().pop_internal_level();
2849 cur_node = parent.forget_type();
2853 Stole(stole_from_left) => {
2854 // Adjust the tracked position if we stole from a left sibling
2855 if stole_from_left && at_leaf {
2856 // SAFETY: This is safe since we just added an element to our node.
2858 pos.next_unchecked();
2866 // If we deleted from an internal node then we need to compensate for
2867 // the earlier swap and adjust the tracked position to point to the
2870 pos = unsafe { unwrap_unchecked(pos.next_kv().ok()).next_leaf_edge() };
2877 impl<K, V> node::Root<K, V> {
2878 /// Removes empty levels on the top, but keep an empty leaf if the entire tree is empty.
2879 fn fix_top(&mut self) {
2880 while self.height() > 0 && self.node_as_ref().len() == 0 {
2881 self.pop_internal_level();
2885 fn fix_right_border(&mut self) {
2889 let mut cur_node = self.node_as_mut();
2891 while let Internal(node) = cur_node.force() {
2892 let mut last_kv = node.last_kv();
2894 if last_kv.can_merge() {
2895 cur_node = last_kv.merge().descend();
2897 let right_len = last_kv.reborrow().right_edge().descend().len();
2898 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
2899 if right_len < node::MIN_LEN + 1 {
2900 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
2902 cur_node = last_kv.right_edge().descend();
2910 /// The symmetric clone of `fix_right_border`.
2911 fn fix_left_border(&mut self) {
2915 let mut cur_node = self.node_as_mut();
2917 while let Internal(node) = cur_node.force() {
2918 let mut first_kv = node.first_kv();
2920 if first_kv.can_merge() {
2921 cur_node = first_kv.merge().descend();
2923 let left_len = first_kv.reborrow().left_edge().descend().len();
2924 if left_len < node::MIN_LEN + 1 {
2925 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
2927 cur_node = first_kv.left_edge().descend();
2936 enum UnderflowResult<'a, K, V> {
2938 Merged(Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge>, bool, usize),
2942 fn handle_underfull_node<K, V>(
2943 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2944 ) -> UnderflowResult<'_, K, V> {
2945 let parent = match node.ascend() {
2946 Ok(parent) => parent,
2947 Err(_) => return AtRoot,
2950 // Prefer the left KV if it exists. Merging with the left side is faster,
2951 // since merging happens towards the left and `node` has fewer elements.
2952 // Stealing from the left side is faster, since we can pop from the end of
2954 let (is_left, mut handle) = match parent.left_kv() {
2955 Ok(left) => (true, left),
2957 let right = unsafe { unwrap_unchecked(parent.right_kv().ok()) };
2962 if handle.can_merge() {
2963 let offset = if is_left { handle.reborrow().left_edge().descend().len() + 1 } else { 0 };
2964 Merged(handle.merge(), is_left, offset)
2967 handle.steal_left();
2969 handle.steal_right();
2975 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
2978 fn next(&mut self) -> Option<(K, V)> {
2979 let res = match (self.left.peek(), self.right.peek()) {
2980 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
2981 (Some(_), None) => Ordering::Less,
2982 (None, Some(_)) => Ordering::Greater,
2983 (None, None) => return None,
2986 // Check which elements comes first and only advance the corresponding iterator.
2987 // If two keys are equal, take the value from `right`.
2989 Ordering::Less => self.left.next(),
2990 Ordering::Greater => self.right.next(),
2991 Ordering::Equal => {