1 // ignore-tidy-filelength
3 use core::borrow::Borrow;
4 use core::cmp::Ordering;
6 use core::hash::{Hash, Hasher};
7 use core::iter::{FromIterator, FusedIterator, Peekable};
8 use core::marker::PhantomData;
9 use core::mem::{self, ManuallyDrop};
10 use core::ops::Bound::{Excluded, Included, Unbounded};
11 use core::ops::{Index, RangeBounds};
14 use super::node::{self, marker, ForceResult::*, Handle, InsertResult::*, NodeRef};
15 use super::search::{self, SearchResult::*};
16 use super::unwrap_unchecked;
19 use UnderflowResult::*;
21 /// A map based on a B-Tree.
23 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
24 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
25 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
26 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
27 /// is done is *very* inefficient for modern computer architectures. In particular, every element
28 /// is stored in its own individually heap-allocated node. This means that every single insertion
29 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
30 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
33 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
34 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
35 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
36 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
37 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
38 /// the node using binary search. As a compromise, one could also perform a linear search
39 /// that initially only checks every i<sup>th</sup> element for some choice of i.
41 /// Currently, our implementation simply performs naive linear search. This provides excellent
42 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
43 /// would like to further explore choosing the optimal search strategy based on the choice of B,
44 /// and possibly other factors. Using linear search, searching for a random element is expected
45 /// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
46 /// however, performance is excellent.
48 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
49 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
50 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
52 /// [`Ord`]: core::cmp::Ord
53 /// [`Cell`]: core::cell::Cell
54 /// [`RefCell`]: core::cell::RefCell
59 /// use std::collections::BTreeMap;
61 /// // type inference lets us omit an explicit type signature (which
62 /// // would be `BTreeMap<&str, &str>` in this example).
63 /// let mut movie_reviews = BTreeMap::new();
65 /// // review some movies.
66 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
67 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
68 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
69 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
71 /// // check for a specific one.
72 /// if !movie_reviews.contains_key("Les Misérables") {
73 /// println!("We've got {} reviews, but Les Misérables ain't one.",
74 /// movie_reviews.len());
77 /// // oops, this review has a lot of spelling mistakes, let's delete it.
78 /// movie_reviews.remove("The Blues Brothers");
80 /// // look up the values associated with some keys.
81 /// let to_find = ["Up!", "Office Space"];
82 /// for movie in &to_find {
83 /// match movie_reviews.get(movie) {
84 /// Some(review) => println!("{}: {}", movie, review),
85 /// None => println!("{} is unreviewed.", movie)
89 /// // Look up the value for a key (will panic if the key is not found).
90 /// println!("Movie review: {}", movie_reviews["Office Space"]);
92 /// // iterate over everything.
93 /// for (movie, review) in &movie_reviews {
94 /// println!("{}: \"{}\"", movie, review);
98 /// `BTreeMap` also implements an [`Entry API`](#method.entry), which allows
99 /// for more complex methods of getting, setting, updating and removing keys and
103 /// use std::collections::BTreeMap;
105 /// // type inference lets us omit an explicit type signature (which
106 /// // would be `BTreeMap<&str, u8>` in this example).
107 /// let mut player_stats = BTreeMap::new();
109 /// fn random_stat_buff() -> u8 {
110 /// // could actually return some random value here - let's just return
111 /// // some fixed value for now
115 /// // insert a key only if it doesn't already exist
116 /// player_stats.entry("health").or_insert(100);
118 /// // insert a key using a function that provides a new value only if it
119 /// // doesn't already exist
120 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
122 /// // update a key, guarding against the key possibly not being set
123 /// let stat = player_stats.entry("attack").or_insert(100);
124 /// *stat += random_stat_buff();
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub struct BTreeMap<K, V> {
128 root: Option<node::Root<K, V>>,
132 #[stable(feature = "btree_drop", since = "1.7.0")]
133 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
136 drop(ptr::read(self).into_iter());
141 #[stable(feature = "rust1", since = "1.0.0")]
142 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
143 fn clone(&self) -> BTreeMap<K, V> {
144 fn clone_subtree<'a, K: Clone, V: Clone>(
145 node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
153 let mut out_tree = BTreeMap { root: Some(node::Root::new_leaf()), length: 0 };
156 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
157 let mut out_node = match root.as_mut().force() {
159 Internal(_) => unreachable!(),
162 let mut in_edge = leaf.first_edge();
163 while let Ok(kv) = in_edge.right_kv() {
164 let (k, v) = kv.into_kv();
165 in_edge = kv.right_edge();
167 out_node.push(k.clone(), v.clone());
168 out_tree.length += 1;
174 Internal(internal) => {
175 let mut out_tree = clone_subtree(internal.first_edge().descend());
178 let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
179 let mut out_node = out_root.push_internal_level();
180 let mut in_edge = internal.first_edge();
181 while let Ok(kv) = in_edge.right_kv() {
182 let (k, v) = kv.into_kv();
183 in_edge = kv.right_edge();
185 let k = (*k).clone();
186 let v = (*v).clone();
187 let subtree = clone_subtree(in_edge.descend());
189 // We can't destructure subtree directly
190 // because BTreeMap implements Drop
191 let (subroot, sublength) = unsafe {
192 let subtree = ManuallyDrop::new(subtree);
193 let root = ptr::read(&subtree.root);
194 let length = subtree.length;
198 out_node.push(k, v, subroot.unwrap_or_else(node::Root::new_leaf));
199 out_tree.length += 1 + sublength;
209 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
210 // Ord` constraint, which this method lacks.
211 BTreeMap { root: None, length: 0 }
213 clone_subtree(self.root.as_ref().unwrap().as_ref()) // unwrap succeeds because not empty
218 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
225 fn get(&self, key: &Q) -> Option<&K> {
226 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
227 Found(handle) => Some(handle.into_kv().0),
232 fn take(&mut self, key: &Q) -> Option<K> {
233 match search::search_tree(self.root.as_mut()?.as_mut(), 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.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 = "55214")]
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 = "55214")]
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 match search::search_tree(self.root.as_ref()?.as_ref(), key) {
569 Found(handle) => Some(handle.into_kv().1),
574 /// Returns the key-value pair corresponding to the supplied key.
576 /// The supplied key may be any borrowed form of the map's key type, but the ordering
577 /// on the borrowed form *must* match the ordering on the key type.
582 /// use std::collections::BTreeMap;
584 /// let mut map = BTreeMap::new();
585 /// map.insert(1, "a");
586 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
587 /// assert_eq!(map.get_key_value(&2), None);
589 #[stable(feature = "map_get_key_value", since = "1.40.0")]
590 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
595 match search::search_tree(self.root.as_ref()?.as_ref(), k) {
596 Found(handle) => Some(handle.into_kv()),
601 /// Returns the first key-value pair in the map.
602 /// The key in this pair is the minimum key in the map.
609 /// #![feature(map_first_last)]
610 /// use std::collections::BTreeMap;
612 /// let mut map = BTreeMap::new();
613 /// assert_eq!(map.first_key_value(), None);
614 /// map.insert(1, "b");
615 /// map.insert(2, "a");
616 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
618 #[unstable(feature = "map_first_last", issue = "62924")]
619 pub fn first_key_value(&self) -> Option<(&K, &V)> {
620 let front = self.root.as_ref()?.as_ref().first_leaf_edge();
621 front.right_kv().ok().map(Handle::into_kv)
624 /// Returns the first entry in the map for in-place manipulation.
625 /// The key of this entry is the minimum key in the map.
630 /// #![feature(map_first_last)]
631 /// use std::collections::BTreeMap;
633 /// let mut map = BTreeMap::new();
634 /// map.insert(1, "a");
635 /// map.insert(2, "b");
636 /// if let Some(mut entry) = map.first_entry() {
637 /// if *entry.key() > 0 {
638 /// entry.insert("first");
641 /// assert_eq!(*map.get(&1).unwrap(), "first");
642 /// assert_eq!(*map.get(&2).unwrap(), "b");
644 #[unstable(feature = "map_first_last", issue = "62924")]
645 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
646 let front = self.root.as_mut()?.as_mut().first_leaf_edge();
647 let kv = front.right_kv().ok()?;
649 handle: kv.forget_node_type(),
650 length: &mut self.length,
651 _marker: PhantomData,
655 /// Removes and returns the first element in the map.
656 /// The key of this element is the minimum key that was in the map.
660 /// Draining elements in ascending order, while keeping a usable map each iteration.
663 /// #![feature(map_first_last)]
664 /// use std::collections::BTreeMap;
666 /// let mut map = BTreeMap::new();
667 /// map.insert(1, "a");
668 /// map.insert(2, "b");
669 /// while let Some((key, _val)) = map.pop_first() {
670 /// assert!(map.iter().all(|(k, _v)| *k > key));
672 /// assert!(map.is_empty());
674 #[unstable(feature = "map_first_last", issue = "62924")]
675 pub fn pop_first(&mut self) -> Option<(K, V)> {
676 self.first_entry().map(|entry| entry.remove_entry())
679 /// Returns the last key-value pair in the map.
680 /// The key in this pair is the maximum key in the map.
687 /// #![feature(map_first_last)]
688 /// use std::collections::BTreeMap;
690 /// let mut map = BTreeMap::new();
691 /// map.insert(1, "b");
692 /// map.insert(2, "a");
693 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
695 #[unstable(feature = "map_first_last", issue = "62924")]
696 pub fn last_key_value(&self) -> Option<(&K, &V)> {
697 let back = self.root.as_ref()?.as_ref().last_leaf_edge();
698 back.left_kv().ok().map(Handle::into_kv)
701 /// Returns the last entry in the map for in-place manipulation.
702 /// The key of this entry is the maximum key in the map.
707 /// #![feature(map_first_last)]
708 /// use std::collections::BTreeMap;
710 /// let mut map = BTreeMap::new();
711 /// map.insert(1, "a");
712 /// map.insert(2, "b");
713 /// if let Some(mut entry) = map.last_entry() {
714 /// if *entry.key() > 0 {
715 /// entry.insert("last");
718 /// assert_eq!(*map.get(&1).unwrap(), "a");
719 /// assert_eq!(*map.get(&2).unwrap(), "last");
721 #[unstable(feature = "map_first_last", issue = "62924")]
722 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
723 let back = self.root.as_mut()?.as_mut().last_leaf_edge();
724 let kv = back.left_kv().ok()?;
726 handle: kv.forget_node_type(),
727 length: &mut self.length,
728 _marker: PhantomData,
732 /// Removes and returns the last element in the map.
733 /// The key of this element is the maximum key that was in the map.
737 /// Draining elements in descending order, while keeping a usable map each iteration.
740 /// #![feature(map_first_last)]
741 /// use std::collections::BTreeMap;
743 /// let mut map = BTreeMap::new();
744 /// map.insert(1, "a");
745 /// map.insert(2, "b");
746 /// while let Some((key, _val)) = map.pop_last() {
747 /// assert!(map.iter().all(|(k, _v)| *k < key));
749 /// assert!(map.is_empty());
751 #[unstable(feature = "map_first_last", issue = "62924")]
752 pub fn pop_last(&mut self) -> Option<(K, V)> {
753 self.last_entry().map(|entry| entry.remove_entry())
756 /// Returns `true` if the map contains a value for the specified 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 /// assert_eq!(map.contains_key(&1), true);
771 /// assert_eq!(map.contains_key(&2), false);
773 #[stable(feature = "rust1", since = "1.0.0")]
774 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
779 self.get(key).is_some()
782 /// Returns a mutable reference to the value corresponding to the key.
784 /// The key may be any borrowed form of the map's key type, but the ordering
785 /// on the borrowed form *must* match the ordering on the key type.
792 /// use std::collections::BTreeMap;
794 /// let mut map = BTreeMap::new();
795 /// map.insert(1, "a");
796 /// if let Some(x) = map.get_mut(&1) {
799 /// assert_eq!(map[&1], "b");
801 // See `get` for implementation notes, this is basically a copy-paste with mut's added
802 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
808 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
809 Found(handle) => Some(handle.into_kv_mut().1),
814 /// Inserts a key-value pair into the map.
816 /// If the map did not have this key present, `None` is returned.
818 /// If the map did have this key present, the value is updated, and the old
819 /// value is returned. The key is not updated, though; this matters for
820 /// types that can be `==` without being identical. See the [module-level
821 /// documentation] for more.
823 /// [module-level documentation]: index.html#insert-and-complex-keys
830 /// use std::collections::BTreeMap;
832 /// let mut map = BTreeMap::new();
833 /// assert_eq!(map.insert(37, "a"), None);
834 /// assert_eq!(map.is_empty(), false);
836 /// map.insert(37, "b");
837 /// assert_eq!(map.insert(37, "c"), Some("b"));
838 /// assert_eq!(map[&37], "c");
840 #[stable(feature = "rust1", since = "1.0.0")]
841 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
842 match self.entry(key) {
843 Occupied(mut entry) => Some(entry.insert(value)),
851 /// Removes a key from the map, returning the value at the key if the key
852 /// was previously in the map.
854 /// The key may be any borrowed form of the map's key type, but the ordering
855 /// on the borrowed form *must* match the ordering on the key type.
862 /// use std::collections::BTreeMap;
864 /// let mut map = BTreeMap::new();
865 /// map.insert(1, "a");
866 /// assert_eq!(map.remove(&1), Some("a"));
867 /// assert_eq!(map.remove(&1), None);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
875 self.remove_entry(key).map(|(_, v)| v)
878 /// Removes a key from the map, returning the stored key and value if the key
879 /// was previously in the map.
881 /// The key may be any borrowed form of the map's key type, but the ordering
882 /// on the borrowed form *must* match the ordering on the key type.
889 /// use std::collections::BTreeMap;
891 /// let mut map = BTreeMap::new();
892 /// map.insert(1, "a");
893 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
894 /// assert_eq!(map.remove_entry(&1), None);
896 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
897 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
902 match search::search_tree(self.root.as_mut()?.as_mut(), key) {
903 Found(handle) => Some(
904 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
911 /// Moves all elements from `other` into `Self`, leaving `other` empty.
916 /// use std::collections::BTreeMap;
918 /// let mut a = BTreeMap::new();
919 /// a.insert(1, "a");
920 /// a.insert(2, "b");
921 /// a.insert(3, "c");
923 /// let mut b = BTreeMap::new();
924 /// b.insert(3, "d");
925 /// b.insert(4, "e");
926 /// b.insert(5, "f");
928 /// a.append(&mut b);
930 /// assert_eq!(a.len(), 5);
931 /// assert_eq!(b.len(), 0);
933 /// assert_eq!(a[&1], "a");
934 /// assert_eq!(a[&2], "b");
935 /// assert_eq!(a[&3], "d");
936 /// assert_eq!(a[&4], "e");
937 /// assert_eq!(a[&5], "f");
939 #[stable(feature = "btree_append", since = "1.11.0")]
940 pub fn append(&mut self, other: &mut Self) {
941 // Do we have to append anything at all?
942 if other.is_empty() {
946 // We can just swap `self` and `other` if `self` is empty.
948 mem::swap(self, other);
952 // First, we merge `self` and `other` into a sorted sequence in linear time.
953 let self_iter = mem::take(self).into_iter();
954 let other_iter = mem::take(other).into_iter();
955 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
957 // Second, we build a tree from the sorted sequence in linear time.
958 self.from_sorted_iter(iter);
961 /// Constructs a double-ended iterator over a sub-range of elements in the map.
962 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
963 /// yield elements from min (inclusive) to max (exclusive).
964 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
965 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
966 /// range from 4 to 10.
970 /// Panics if range `start > end`.
971 /// Panics if range `start == end` and both bounds are `Excluded`.
978 /// use std::collections::BTreeMap;
979 /// use std::ops::Bound::Included;
981 /// let mut map = BTreeMap::new();
982 /// map.insert(3, "a");
983 /// map.insert(5, "b");
984 /// map.insert(8, "c");
985 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
986 /// println!("{}: {}", key, value);
988 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
990 #[stable(feature = "btree_range", since = "1.17.0")]
991 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
997 if let Some(root) = &self.root {
998 let (f, b) = range_search(root.as_ref(), range);
1000 Range { front: Some(f), back: Some(b) }
1002 Range { front: None, back: None }
1006 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1007 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1008 /// yield elements from min (inclusive) to max (exclusive).
1009 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1010 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1011 /// range from 4 to 10.
1015 /// Panics if range `start > end`.
1016 /// Panics if range `start == end` and both bounds are `Excluded`.
1023 /// use std::collections::BTreeMap;
1025 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1027 /// .map(|&s| (s, 0))
1029 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1030 /// *balance += 100;
1032 /// for (name, balance) in &map {
1033 /// println!("{} => {}", name, balance);
1036 #[stable(feature = "btree_range", since = "1.17.0")]
1037 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1043 if let Some(root) = &mut self.root {
1044 let (f, b) = range_search(root.as_mut(), range);
1046 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1048 RangeMut { front: None, back: None, _marker: PhantomData }
1052 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1059 /// use std::collections::BTreeMap;
1061 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1063 /// // count the number of occurrences of letters in the vec
1064 /// for x in vec!["a","b","a","c","a","b"] {
1065 /// *count.entry(x).or_insert(0) += 1;
1068 /// assert_eq!(count["a"], 3);
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1072 // FIXME(@porglezomp) Avoid allocating if we don't insert
1073 let root = Self::ensure_is_owned(&mut self.root);
1074 match search::search_tree(root.as_mut(), &key) {
1076 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1079 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1084 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1085 let root = Self::ensure_is_owned(&mut self.root);
1086 let mut cur_node = root.as_mut().last_leaf_edge().into_node();
1087 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1088 for (key, value) in iter {
1089 // Try to push key-value pair into the current leaf node.
1090 if cur_node.len() < node::CAPACITY {
1091 cur_node.push(key, value);
1093 // No space left, go up and push there.
1095 let mut test_node = cur_node.forget_type();
1097 match test_node.ascend() {
1099 let parent = parent.into_node();
1100 if parent.len() < node::CAPACITY {
1101 // Found a node with space left, push here.
1106 test_node = parent.forget_type();
1110 // We are at the top, create a new root node and push there.
1111 open_node = root.push_internal_level();
1117 // Push key-value pair and new right subtree.
1118 let tree_height = open_node.height() - 1;
1119 let mut right_tree = node::Root::new_leaf();
1120 for _ in 0..tree_height {
1121 right_tree.push_internal_level();
1123 open_node.push(key, value, right_tree);
1125 // Go down to the right-most leaf again.
1126 cur_node = open_node.forget_type().last_leaf_edge().into_node();
1131 Self::fix_right_edge(root)
1134 fn fix_right_edge(root: &mut node::Root<K, V>) {
1135 // Handle underfull nodes, start from the top.
1136 let mut cur_node = root.as_mut();
1137 while let Internal(internal) = cur_node.force() {
1138 // Check if right-most child is underfull.
1139 let mut last_edge = internal.last_edge();
1140 let right_child_len = last_edge.reborrow().descend().len();
1141 if right_child_len < node::MIN_LEN {
1142 // We need to steal.
1143 let mut last_kv = match last_edge.left_kv() {
1145 Err(_) => unreachable!(),
1147 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1148 last_edge = last_kv.right_edge();
1152 cur_node = last_edge.descend();
1156 /// Splits the collection into two at the given key. Returns everything after the given key,
1157 /// including the key.
1164 /// use std::collections::BTreeMap;
1166 /// let mut a = BTreeMap::new();
1167 /// a.insert(1, "a");
1168 /// a.insert(2, "b");
1169 /// a.insert(3, "c");
1170 /// a.insert(17, "d");
1171 /// a.insert(41, "e");
1173 /// let b = a.split_off(&3);
1175 /// assert_eq!(a.len(), 2);
1176 /// assert_eq!(b.len(), 3);
1178 /// assert_eq!(a[&1], "a");
1179 /// assert_eq!(a[&2], "b");
1181 /// assert_eq!(b[&3], "c");
1182 /// assert_eq!(b[&17], "d");
1183 /// assert_eq!(b[&41], "e");
1185 #[stable(feature = "btree_split_off", since = "1.11.0")]
1186 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1190 if self.is_empty() {
1194 let total_num = self.len();
1195 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1197 let mut right = Self::new();
1198 let right_root = Self::ensure_is_owned(&mut right.root);
1199 for _ in 0..left_root.height() {
1200 right_root.push_internal_level();
1204 let mut left_node = left_root.as_mut();
1205 let mut right_node = right_root.as_mut();
1208 let mut split_edge = match search::search_node(left_node, key) {
1209 // key is going to the right tree
1210 Found(handle) => handle.left_edge(),
1211 GoDown(handle) => handle,
1214 split_edge.move_suffix(&mut right_node);
1216 match (split_edge.force(), right_node.force()) {
1217 (Internal(edge), Internal(node)) => {
1218 left_node = edge.descend();
1219 right_node = node.first_edge().descend();
1221 (Leaf(_), Leaf(_)) => {
1231 left_root.fix_right_border();
1232 right_root.fix_left_border();
1234 if left_root.height() < right_root.height() {
1235 self.recalc_length();
1236 right.length = total_num - self.len();
1238 right.recalc_length();
1239 self.length = total_num - right.len();
1245 /// Creates an iterator which uses a closure to determine if an element should be removed.
1247 /// If the closure returns true, the element is removed from the map and yielded.
1248 /// If the closure returns false, or panics, the element remains in the map and will not be
1251 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1252 /// whether you choose to keep or remove it.
1254 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1255 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1257 /// It is unspecified how many more elements will be subjected to the closure
1258 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1259 /// or if the `DrainFilter` value is leaked.
1263 /// Splitting a map into even and odd keys, reusing the original map:
1266 /// #![feature(btree_drain_filter)]
1267 /// use std::collections::BTreeMap;
1269 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1270 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1272 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1273 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1275 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1276 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1278 F: FnMut(&K, &mut V) -> bool,
1280 DrainFilter { pred, inner: self.drain_filter_inner() }
1282 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1283 let front = self.root.as_mut().map(|r| r.as_mut().first_leaf_edge());
1285 length: &mut self.length,
1286 cur_leaf_edge: front,
1287 emptied_internal_root: false,
1291 /// Calculates the number of elements if it is incorrect.
1292 fn recalc_length(&mut self) {
1293 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1298 let mut res = node.len();
1300 if let Internal(node) = node.force() {
1301 let mut edge = node.first_edge();
1303 res += dfs(edge.reborrow().descend());
1304 match edge.right_kv() {
1306 edge = right_kv.right_edge();
1318 self.length = dfs(self.root.as_ref().unwrap().as_ref());
1321 /// Creates a consuming iterator visiting all the keys, in sorted order.
1322 /// The map cannot be used after calling this.
1323 /// The iterator element type is `K`.
1328 /// #![feature(map_into_keys_values)]
1329 /// use std::collections::BTreeMap;
1331 /// let mut a = BTreeMap::new();
1332 /// a.insert(2, "b");
1333 /// a.insert(1, "a");
1335 /// let keys: Vec<i32> = a.into_keys().collect();
1336 /// assert_eq!(keys, [1, 2]);
1339 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1340 pub fn into_keys(self) -> IntoKeys<K, V> {
1341 IntoKeys { inner: self.into_iter() }
1344 /// Creates a consuming iterator visiting all the values, in sorted order.
1345 /// The map cannot be used after calling this.
1346 /// The iterator element type is `V`.
1351 /// #![feature(map_into_keys_values)]
1352 /// use std::collections::BTreeMap;
1354 /// let mut a = BTreeMap::new();
1355 /// a.insert(1, "hello");
1356 /// a.insert(2, "goodbye");
1358 /// let values: Vec<&str> = a.into_values().collect();
1359 /// assert_eq!(values, ["hello", "goodbye"]);
1362 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1363 pub fn into_values(self) -> IntoValues<K, V> {
1364 IntoValues { inner: self.into_iter() }
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1370 type Item = (&'a K, &'a V);
1371 type IntoIter = Iter<'a, K, V>;
1373 fn into_iter(self) -> Iter<'a, K, V> {
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1380 type Item = (&'a K, &'a V);
1382 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1383 if self.length == 0 {
1387 unsafe { Some(self.range.next_unchecked()) }
1391 fn size_hint(&self) -> (usize, Option<usize>) {
1392 (self.length, Some(self.length))
1395 fn last(mut self) -> Option<(&'a K, &'a V)> {
1399 fn min(mut self) -> Option<(&'a K, &'a V)> {
1403 fn max(mut self) -> Option<(&'a K, &'a V)> {
1408 #[stable(feature = "fused", since = "1.26.0")]
1409 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1413 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1414 if self.length == 0 {
1418 unsafe { Some(self.range.next_back_unchecked()) }
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1425 fn len(&self) -> usize {
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 impl<K, V> Clone for Iter<'_, K, V> {
1432 fn clone(&self) -> Self {
1433 Iter { range: self.range.clone(), length: self.length }
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1439 type Item = (&'a K, &'a mut V);
1440 type IntoIter = IterMut<'a, K, V>;
1442 fn into_iter(self) -> IterMut<'a, K, V> {
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1449 type Item = (&'a K, &'a mut V);
1451 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1452 if self.length == 0 {
1456 let (k, v) = unsafe { self.range.next_unchecked() };
1457 Some((k, v)) // coerce k from `&mut K` to `&K`
1461 fn size_hint(&self) -> (usize, Option<usize>) {
1462 (self.length, Some(self.length))
1465 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1469 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1473 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1480 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1481 if self.length == 0 {
1485 let (k, v) = unsafe { self.range.next_back_unchecked() };
1486 Some((k, v)) // coerce k from `&mut K` to `&K`
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1493 fn len(&self) -> usize {
1498 #[stable(feature = "fused", since = "1.26.0")]
1499 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl<K, V> IntoIterator for BTreeMap<K, V> {
1504 type IntoIter = IntoIter<K, V>;
1506 fn into_iter(self) -> IntoIter<K, V> {
1507 let mut me = ManuallyDrop::new(self);
1508 if let Some(root) = me.root.take() {
1509 let (f, b) = full_range_search(root.into_ref());
1511 IntoIter { front: Some(f), back: Some(b), length: me.length }
1513 IntoIter { front: None, back: None, length: 0 }
1518 #[stable(feature = "btree_drop", since = "1.7.0")]
1519 impl<K, V> Drop for IntoIter<K, V> {
1520 fn drop(&mut self) {
1521 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1523 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1524 fn drop(&mut self) {
1525 // Continue the same loop we perform below. This only runs when unwinding, so we
1526 // don't have to care about panics this time (they'll abort).
1527 while let Some(_) = self.0.next() {}
1531 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1532 while let Some(parent) = node.deallocate_and_ascend() {
1533 node = parent.into_node().forget_type();
1539 while let Some(pair) = self.next() {
1540 let guard = DropGuard(self);
1546 if let Some(front) = ptr::read(&self.front) {
1547 let mut node = front.into_node().forget_type();
1548 // Most of the nodes have been deallocated while traversing
1549 // but one pile from a leaf up to the root is left standing.
1550 while let Some(parent) = node.deallocate_and_ascend() {
1551 node = parent.into_node().forget_type();
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 impl<K, V> Iterator for IntoIter<K, V> {
1562 fn next(&mut self) -> Option<(K, V)> {
1563 if self.length == 0 {
1567 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1571 fn size_hint(&self) -> (usize, Option<usize>) {
1572 (self.length, Some(self.length))
1576 #[stable(feature = "rust1", since = "1.0.0")]
1577 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1578 fn next_back(&mut self) -> Option<(K, V)> {
1579 if self.length == 0 {
1583 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1590 fn len(&self) -> usize {
1595 #[stable(feature = "fused", since = "1.26.0")]
1596 impl<K, V> FusedIterator for IntoIter<K, V> {}
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1602 fn next(&mut self) -> Option<&'a K> {
1603 self.inner.next().map(|(k, _)| k)
1606 fn size_hint(&self) -> (usize, Option<usize>) {
1607 self.inner.size_hint()
1610 fn last(mut self) -> Option<&'a K> {
1614 fn min(mut self) -> Option<&'a K> {
1618 fn max(mut self) -> Option<&'a K> {
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1625 fn next_back(&mut self) -> Option<&'a K> {
1626 self.inner.next_back().map(|(k, _)| k)
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1632 fn len(&self) -> usize {
1637 #[stable(feature = "fused", since = "1.26.0")]
1638 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 impl<K, V> Clone for Keys<'_, K, V> {
1642 fn clone(&self) -> Self {
1643 Keys { inner: self.inner.clone() }
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<'a, K, V> Iterator for Values<'a, K, V> {
1651 fn next(&mut self) -> Option<&'a V> {
1652 self.inner.next().map(|(_, v)| v)
1655 fn size_hint(&self) -> (usize, Option<usize>) {
1656 self.inner.size_hint()
1659 fn last(mut self) -> Option<&'a V> {
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1666 fn next_back(&mut self) -> Option<&'a V> {
1667 self.inner.next_back().map(|(_, v)| v)
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1673 fn len(&self) -> usize {
1678 #[stable(feature = "fused", since = "1.26.0")]
1679 impl<K, V> FusedIterator for Values<'_, K, V> {}
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<K, V> Clone for Values<'_, K, V> {
1683 fn clone(&self) -> Self {
1684 Values { inner: self.inner.clone() }
1688 /// An iterator produced by calling `drain_filter` on BTreeMap.
1689 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1690 pub struct DrainFilter<'a, K, V, F>
1694 F: 'a + FnMut(&K, &mut V) -> bool,
1697 inner: DrainFilterInner<'a, K, V>,
1699 /// Most of the implementation of DrainFilter, independent of the type
1700 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1701 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1702 length: &'a mut usize,
1703 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1704 emptied_internal_root: bool,
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<K, V> Drop for DrainFilterInner<'_, K, V> {
1746 fn drop(&mut self) {
1747 if self.emptied_internal_root {
1748 if let Some(handle) = self.cur_leaf_edge.take() {
1749 let root = handle.into_node().into_root_mut();
1750 root.pop_internal_level();
1756 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1757 /// Allow Debug implementations to predict the next element.
1758 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1759 let edge = self.cur_leaf_edge.as_ref()?;
1760 edge.reborrow().next_kv().ok().map(|kv| kv.into_kv())
1763 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1764 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1766 F: FnMut(&K, &mut V) -> bool,
1768 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1769 let (k, v) = kv.kv_mut();
1772 let RemoveResult { old_kv, pos, emptied_internal_root } = kv.remove_kv_tracking();
1773 self.cur_leaf_edge = Some(pos);
1774 self.emptied_internal_root |= emptied_internal_root;
1775 return Some(old_kv);
1777 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1782 /// Implementation of a typical `DrainFilter::size_hint` method.
1783 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1784 (0, Some(*self.length))
1788 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1789 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1791 #[stable(feature = "btree_range", since = "1.17.0")]
1792 impl<'a, K, V> Iterator for Range<'a, K, V> {
1793 type Item = (&'a K, &'a V);
1795 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1796 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1799 fn last(mut self) -> Option<(&'a K, &'a V)> {
1803 fn min(mut self) -> Option<(&'a K, &'a V)> {
1807 fn max(mut self) -> Option<(&'a K, &'a V)> {
1812 #[stable(feature = "map_values_mut", since = "1.10.0")]
1813 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1814 type Item = &'a mut V;
1816 fn next(&mut self) -> Option<&'a mut V> {
1817 self.inner.next().map(|(_, v)| v)
1820 fn size_hint(&self) -> (usize, Option<usize>) {
1821 self.inner.size_hint()
1824 fn last(mut self) -> Option<&'a mut V> {
1829 #[stable(feature = "map_values_mut", since = "1.10.0")]
1830 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1831 fn next_back(&mut self) -> Option<&'a mut V> {
1832 self.inner.next_back().map(|(_, v)| v)
1836 #[stable(feature = "map_values_mut", since = "1.10.0")]
1837 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1838 fn len(&self) -> usize {
1843 #[stable(feature = "fused", since = "1.26.0")]
1844 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1846 impl<'a, K, V> Range<'a, K, V> {
1847 fn is_empty(&self) -> bool {
1848 self.front == self.back
1851 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1852 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1856 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1857 impl<K, V> Iterator for IntoKeys<K, V> {
1860 fn next(&mut self) -> Option<K> {
1861 self.inner.next().map(|(k, _)| k)
1864 fn size_hint(&self) -> (usize, Option<usize>) {
1865 self.inner.size_hint()
1868 fn last(mut self) -> Option<K> {
1872 fn min(mut self) -> Option<K> {
1876 fn max(mut self) -> Option<K> {
1881 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1882 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1883 fn next_back(&mut self) -> Option<K> {
1884 self.inner.next_back().map(|(k, _)| k)
1888 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1889 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1890 fn len(&self) -> usize {
1895 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1896 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1898 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1899 impl<K, V> Iterator for IntoValues<K, V> {
1902 fn next(&mut self) -> Option<V> {
1903 self.inner.next().map(|(_, v)| v)
1906 fn size_hint(&self) -> (usize, Option<usize>) {
1907 self.inner.size_hint()
1910 fn last(mut self) -> Option<V> {
1914 fn min(mut self) -> Option<V> {
1918 fn max(mut self) -> Option<V> {
1923 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1924 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1925 fn next_back(&mut self) -> Option<V> {
1926 self.inner.next_back().map(|(_, v)| v)
1930 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1931 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1932 fn len(&self) -> usize {
1937 #[unstable(feature = "map_into_keys_values", issue = "55214")]
1938 impl<K, V> FusedIterator for IntoValues<K, V> {}
1940 #[stable(feature = "btree_range", since = "1.17.0")]
1941 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1942 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1943 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1947 impl<'a, K, V> Range<'a, K, V> {
1948 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1949 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1953 #[stable(feature = "fused", since = "1.26.0")]
1954 impl<K, V> FusedIterator for Range<'_, K, V> {}
1956 #[stable(feature = "btree_range", since = "1.17.0")]
1957 impl<K, V> Clone for Range<'_, K, V> {
1958 fn clone(&self) -> Self {
1959 Range { front: self.front, back: self.back }
1963 #[stable(feature = "btree_range", since = "1.17.0")]
1964 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1965 type Item = (&'a K, &'a mut V);
1967 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1968 if self.is_empty() {
1971 let (k, v) = unsafe { self.next_unchecked() };
1972 Some((k, v)) // coerce k from `&mut K` to `&K`
1976 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1980 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1984 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1989 impl<'a, K, V> RangeMut<'a, K, V> {
1990 fn is_empty(&self) -> bool {
1991 self.front == self.back
1994 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1995 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1999 #[stable(feature = "btree_range", since = "1.17.0")]
2000 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2001 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2002 if self.is_empty() {
2005 let (k, v) = unsafe { self.next_back_unchecked() };
2006 Some((k, v)) // coerce k from `&mut K` to `&K`
2011 #[stable(feature = "fused", since = "1.26.0")]
2012 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2014 impl<'a, K, V> RangeMut<'a, K, V> {
2015 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
2016 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2022 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2023 let mut map = BTreeMap::new();
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
2032 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2033 iter.into_iter().for_each(move |(k, v)| {
2039 fn extend_one(&mut self, (k, v): (K, V)) {
2044 #[stable(feature = "extend_ref", since = "1.2.0")]
2045 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
2046 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2047 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2051 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
2058 fn hash<H: Hasher>(&self, state: &mut H) {
2065 #[stable(feature = "rust1", since = "1.0.0")]
2066 impl<K: Ord, V> Default for BTreeMap<K, V> {
2067 /// Creates an empty `BTreeMap<K, V>`.
2068 fn default() -> BTreeMap<K, V> {
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
2075 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
2076 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2080 #[stable(feature = "rust1", since = "1.0.0")]
2081 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
2083 #[stable(feature = "rust1", since = "1.0.0")]
2084 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
2086 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
2087 self.iter().partial_cmp(other.iter())
2091 #[stable(feature = "rust1", since = "1.0.0")]
2092 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
2094 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
2095 self.iter().cmp(other.iter())
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
2101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2102 f.debug_map().entries(self.iter()).finish()
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
2114 /// Returns a reference to the value corresponding to the supplied key.
2118 /// Panics if the key is not present in the `BTreeMap`.
2120 fn index(&self, key: &Q) -> &V {
2121 self.get(key).expect("no entry found for key")
2125 /// Finds the leaf edges delimiting a specified range in or underneath a node.
2126 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
2127 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2130 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2131 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2137 match (range.start_bound(), range.end_bound()) {
2138 (Excluded(s), Excluded(e)) if s == e => {
2139 panic!("range start and end are equal and excluded in BTreeMap")
2141 (Included(s) | Excluded(s), Included(e) | Excluded(e)) if s > e => {
2142 panic!("range start is greater than range end in BTreeMap")
2147 // We duplicate the root NodeRef here -- we will never access it in a way
2148 // that overlaps references obtained from the root.
2149 let mut min_node = unsafe { ptr::read(&root) };
2150 let mut max_node = root;
2151 let mut min_found = false;
2152 let mut max_found = false;
2155 let front = match (min_found, range.start_bound()) {
2156 (false, Included(key)) => match search::search_node(min_node, key) {
2161 GoDown(edge) => edge,
2163 (false, Excluded(key)) => match search::search_node(min_node, key) {
2168 GoDown(edge) => edge,
2170 (true, Included(_)) => min_node.last_edge(),
2171 (true, Excluded(_)) => min_node.first_edge(),
2172 (_, Unbounded) => min_node.first_edge(),
2175 let back = match (max_found, range.end_bound()) {
2176 (false, Included(key)) => match search::search_node(max_node, key) {
2181 GoDown(edge) => edge,
2183 (false, Excluded(key)) => match search::search_node(max_node, key) {
2188 GoDown(edge) => edge,
2190 (true, Included(_)) => max_node.first_edge(),
2191 (true, Excluded(_)) => max_node.last_edge(),
2192 (_, Unbounded) => max_node.last_edge(),
2195 if front.partial_cmp(&back) == Some(Ordering::Greater) {
2196 panic!("Ord is ill-defined in BTreeMap range");
2198 match (front.force(), back.force()) {
2199 (Leaf(f), Leaf(b)) => {
2202 (Internal(min_int), Internal(max_int)) => {
2203 min_node = min_int.descend();
2204 max_node = max_int.descend();
2206 _ => unreachable!("BTreeMap has different depths"),
2211 /// Equivalent to `range_search(k, v, ..)` without the `Ord` bound.
2212 fn full_range_search<BorrowType, K, V>(
2213 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2215 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2216 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2218 // We duplicate the root NodeRef here -- we will never access it in a way
2219 // that overlaps references obtained from the root.
2220 let mut min_node = unsafe { ptr::read(&root) };
2221 let mut max_node = root;
2223 let front = min_node.first_edge();
2224 let back = max_node.last_edge();
2225 match (front.force(), back.force()) {
2226 (Leaf(f), Leaf(b)) => {
2229 (Internal(min_int), Internal(max_int)) => {
2230 min_node = min_int.descend();
2231 max_node = max_int.descend();
2233 _ => unreachable!("BTreeMap has different depths"),
2238 impl<K, V> BTreeMap<K, V> {
2239 /// Gets an iterator over the entries of the map, sorted by key.
2246 /// use std::collections::BTreeMap;
2248 /// let mut map = BTreeMap::new();
2249 /// map.insert(3, "c");
2250 /// map.insert(2, "b");
2251 /// map.insert(1, "a");
2253 /// for (key, value) in map.iter() {
2254 /// println!("{}: {}", key, value);
2257 /// let (first_key, first_value) = map.iter().next().unwrap();
2258 /// assert_eq!((*first_key, *first_value), (1, "a"));
2260 #[stable(feature = "rust1", since = "1.0.0")]
2261 pub fn iter(&self) -> Iter<'_, K, V> {
2262 if let Some(root) = &self.root {
2263 let (f, b) = full_range_search(root.as_ref());
2265 Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2267 Iter { range: Range { front: None, back: None }, length: 0 }
2271 /// Gets a mutable iterator over the entries of the map, sorted by key.
2278 /// use std::collections::BTreeMap;
2280 /// let mut map = BTreeMap::new();
2281 /// map.insert("a", 1);
2282 /// map.insert("b", 2);
2283 /// map.insert("c", 3);
2285 /// // add 10 to the value if the key isn't "a"
2286 /// for (key, value) in map.iter_mut() {
2287 /// if key != &"a" {
2292 #[stable(feature = "rust1", since = "1.0.0")]
2293 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2294 if let Some(root) = &mut self.root {
2295 let (f, b) = full_range_search(root.as_mut());
2298 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2299 length: self.length,
2302 IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2306 /// Gets an iterator over the keys of the map, in sorted order.
2313 /// use std::collections::BTreeMap;
2315 /// let mut a = BTreeMap::new();
2316 /// a.insert(2, "b");
2317 /// a.insert(1, "a");
2319 /// let keys: Vec<_> = a.keys().cloned().collect();
2320 /// assert_eq!(keys, [1, 2]);
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 pub fn keys(&self) -> Keys<'_, K, V> {
2324 Keys { inner: self.iter() }
2327 /// Gets an iterator over the values of the map, in order by key.
2334 /// use std::collections::BTreeMap;
2336 /// let mut a = BTreeMap::new();
2337 /// a.insert(1, "hello");
2338 /// a.insert(2, "goodbye");
2340 /// let values: Vec<&str> = a.values().cloned().collect();
2341 /// assert_eq!(values, ["hello", "goodbye"]);
2343 #[stable(feature = "rust1", since = "1.0.0")]
2344 pub fn values(&self) -> Values<'_, K, V> {
2345 Values { inner: self.iter() }
2348 /// Gets a mutable iterator over the values of the map, in order by key.
2355 /// use std::collections::BTreeMap;
2357 /// let mut a = BTreeMap::new();
2358 /// a.insert(1, String::from("hello"));
2359 /// a.insert(2, String::from("goodbye"));
2361 /// for value in a.values_mut() {
2362 /// value.push_str("!");
2365 /// let values: Vec<String> = a.values().cloned().collect();
2366 /// assert_eq!(values, [String::from("hello!"),
2367 /// String::from("goodbye!")]);
2369 #[stable(feature = "map_values_mut", since = "1.10.0")]
2370 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2371 ValuesMut { inner: self.iter_mut() }
2374 /// Returns the number of elements in the map.
2381 /// use std::collections::BTreeMap;
2383 /// let mut a = BTreeMap::new();
2384 /// assert_eq!(a.len(), 0);
2385 /// a.insert(1, "a");
2386 /// assert_eq!(a.len(), 1);
2388 #[stable(feature = "rust1", since = "1.0.0")]
2389 pub fn len(&self) -> usize {
2393 /// Returns `true` if the map contains no elements.
2400 /// use std::collections::BTreeMap;
2402 /// let mut a = BTreeMap::new();
2403 /// assert!(a.is_empty());
2404 /// a.insert(1, "a");
2405 /// assert!(!a.is_empty());
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 pub fn is_empty(&self) -> bool {
2412 /// If the root node is the empty (non-allocated) root node, allocate our
2413 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2414 fn ensure_is_owned(root: &mut Option<node::Root<K, V>>) -> &mut node::Root<K, V> {
2415 root.get_or_insert_with(node::Root::new_leaf)
2419 impl<'a, K: Ord, V> Entry<'a, K, V> {
2420 /// Ensures a value is in the entry by inserting the default if empty, and returns
2421 /// a mutable reference to the value in the entry.
2426 /// use std::collections::BTreeMap;
2428 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2429 /// map.entry("poneyland").or_insert(12);
2431 /// assert_eq!(map["poneyland"], 12);
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 pub fn or_insert(self, default: V) -> &'a mut V {
2436 Occupied(entry) => entry.into_mut(),
2437 Vacant(entry) => entry.insert(default),
2441 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2442 /// and returns a mutable reference to the value in the entry.
2447 /// use std::collections::BTreeMap;
2449 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2450 /// let s = "hoho".to_string();
2452 /// map.entry("poneyland").or_insert_with(|| s);
2454 /// assert_eq!(map["poneyland"], "hoho".to_string());
2456 #[stable(feature = "rust1", since = "1.0.0")]
2457 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2459 Occupied(entry) => entry.into_mut(),
2460 Vacant(entry) => entry.insert(default()),
2464 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2465 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2466 /// which takes the key as its argument, and returns a mutable reference to the value in the
2472 /// #![feature(or_insert_with_key)]
2473 /// use std::collections::BTreeMap;
2475 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2477 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2479 /// assert_eq!(map["poneyland"], 9);
2482 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2484 Occupied(entry) => entry.into_mut(),
2486 let value = default(entry.key());
2492 /// Returns a reference to this entry's key.
2497 /// use std::collections::BTreeMap;
2499 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2500 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2502 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2503 pub fn key(&self) -> &K {
2505 Occupied(ref entry) => entry.key(),
2506 Vacant(ref entry) => entry.key(),
2510 /// Provides in-place mutable access to an occupied entry before any
2511 /// potential inserts into the map.
2516 /// use std::collections::BTreeMap;
2518 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2520 /// map.entry("poneyland")
2521 /// .and_modify(|e| { *e += 1 })
2523 /// assert_eq!(map["poneyland"], 42);
2525 /// map.entry("poneyland")
2526 /// .and_modify(|e| { *e += 1 })
2528 /// assert_eq!(map["poneyland"], 43);
2530 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2531 pub fn and_modify<F>(self, f: F) -> Self
2536 Occupied(mut entry) => {
2540 Vacant(entry) => Vacant(entry),
2545 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2546 #[stable(feature = "entry_or_default", since = "1.28.0")]
2547 /// Ensures a value is in the entry by inserting the default value if empty,
2548 /// and returns a mutable reference to the value in the entry.
2553 /// use std::collections::BTreeMap;
2555 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2556 /// map.entry("poneyland").or_default();
2558 /// assert_eq!(map["poneyland"], None);
2560 pub fn or_default(self) -> &'a mut V {
2562 Occupied(entry) => entry.into_mut(),
2563 Vacant(entry) => entry.insert(Default::default()),
2568 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2569 /// Gets a reference to the key that would be used when inserting a value
2570 /// through the VacantEntry.
2575 /// use std::collections::BTreeMap;
2577 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2578 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2580 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2581 pub fn key(&self) -> &K {
2585 /// Take ownership of the key.
2590 /// use std::collections::BTreeMap;
2591 /// use std::collections::btree_map::Entry;
2593 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2595 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2599 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2600 pub fn into_key(self) -> K {
2604 /// Sets the value of the entry with the `VacantEntry`'s key,
2605 /// and returns a mutable reference to it.
2610 /// use std::collections::BTreeMap;
2611 /// use std::collections::btree_map::Entry;
2613 /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
2615 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2618 /// assert_eq!(map["poneyland"], 37);
2620 #[stable(feature = "rust1", since = "1.0.0")]
2621 pub fn insert(self, value: V) -> &'a mut V {
2624 let out_ptr = match self.handle.insert_recursing(self.key, value) {
2625 (Fit(_), val_ptr) => val_ptr,
2626 (Split(ins), val_ptr) => {
2627 let root = ins.left.into_root_mut();
2628 root.push_internal_level().push(ins.k, ins.v, ins.right);
2632 // Now that we have finished growing the tree using borrowed references,
2633 // dereference the pointer to a part of it, that we picked up along the way.
2634 unsafe { &mut *out_ptr }
2638 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2639 /// Gets a reference to the key in the entry.
2644 /// use std::collections::BTreeMap;
2646 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2647 /// map.entry("poneyland").or_insert(12);
2648 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2650 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2651 pub fn key(&self) -> &K {
2652 self.handle.reborrow().into_kv().0
2655 /// Take ownership of the key and value from the map.
2660 /// use std::collections::BTreeMap;
2661 /// use std::collections::btree_map::Entry;
2663 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2664 /// map.entry("poneyland").or_insert(12);
2666 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2667 /// // We delete the entry from the map.
2668 /// o.remove_entry();
2671 /// // If now try to get the value, it will panic:
2672 /// // println!("{}", map["poneyland"]);
2674 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2675 pub fn remove_entry(self) -> (K, V) {
2679 /// Gets a reference to the value in the entry.
2684 /// use std::collections::BTreeMap;
2685 /// use std::collections::btree_map::Entry;
2687 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2688 /// map.entry("poneyland").or_insert(12);
2690 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2691 /// assert_eq!(o.get(), &12);
2694 #[stable(feature = "rust1", since = "1.0.0")]
2695 pub fn get(&self) -> &V {
2696 self.handle.reborrow().into_kv().1
2699 /// Gets a mutable reference to the value in the entry.
2701 /// If you need a reference to the `OccupiedEntry` that may outlive the
2702 /// destruction of the `Entry` value, see [`into_mut`].
2704 /// [`into_mut`]: #method.into_mut
2709 /// use std::collections::BTreeMap;
2710 /// use std::collections::btree_map::Entry;
2712 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2713 /// map.entry("poneyland").or_insert(12);
2715 /// assert_eq!(map["poneyland"], 12);
2716 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2717 /// *o.get_mut() += 10;
2718 /// assert_eq!(*o.get(), 22);
2720 /// // We can use the same Entry multiple times.
2721 /// *o.get_mut() += 2;
2723 /// assert_eq!(map["poneyland"], 24);
2725 #[stable(feature = "rust1", since = "1.0.0")]
2726 pub fn get_mut(&mut self) -> &mut V {
2727 self.handle.kv_mut().1
2730 /// Converts the entry into a mutable reference to its value.
2732 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2734 /// [`get_mut`]: #method.get_mut
2739 /// use std::collections::BTreeMap;
2740 /// use std::collections::btree_map::Entry;
2742 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2743 /// map.entry("poneyland").or_insert(12);
2745 /// assert_eq!(map["poneyland"], 12);
2746 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2747 /// *o.into_mut() += 10;
2749 /// assert_eq!(map["poneyland"], 22);
2751 #[stable(feature = "rust1", since = "1.0.0")]
2752 pub fn into_mut(self) -> &'a mut V {
2753 self.handle.into_kv_mut().1
2756 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2757 /// and returns the entry's old value.
2762 /// use std::collections::BTreeMap;
2763 /// use std::collections::btree_map::Entry;
2765 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2766 /// map.entry("poneyland").or_insert(12);
2768 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2769 /// assert_eq!(o.insert(15), 12);
2771 /// assert_eq!(map["poneyland"], 15);
2773 #[stable(feature = "rust1", since = "1.0.0")]
2774 pub fn insert(&mut self, value: V) -> V {
2775 mem::replace(self.get_mut(), value)
2778 /// Takes the value of the entry out of the map, and returns it.
2783 /// use std::collections::BTreeMap;
2784 /// use std::collections::btree_map::Entry;
2786 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2787 /// map.entry("poneyland").or_insert(12);
2789 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2790 /// assert_eq!(o.remove(), 12);
2792 /// // If we try to get "poneyland"'s value, it'll panic:
2793 /// // println!("{}", map["poneyland"]);
2795 #[stable(feature = "rust1", since = "1.0.0")]
2796 pub fn remove(self) -> V {
2800 // Body of `remove_entry`, separate to keep the above implementations short.
2801 fn remove_kv(self) -> (K, V) {
2804 let RemoveResult { old_kv, pos, emptied_internal_root } = self.handle.remove_kv_tracking();
2805 let root = pos.into_node().into_root_mut();
2806 if emptied_internal_root {
2807 root.pop_internal_level();
2813 struct RemoveResult<'a, K, V> {
2814 // Key and value removed.
2816 // Unique location at the leaf level that the removed KV lopgically collapsed into.
2817 pos: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
2818 // Whether the remove left behind and empty internal root node, that should be removed
2819 // using `pop_internal_level`.
2820 emptied_internal_root: bool,
2823 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
2824 /// Removes a key/value-pair from the tree, and returns that pair, as well as
2825 /// the leaf edge corresponding to that former pair. It's possible this leaves
2826 /// an empty internal root node, which the caller should subsequently pop from
2827 /// the map holding the tree. The caller should also decrement the map's length.
2828 fn remove_kv_tracking(self) -> RemoveResult<'a, K, V> {
2829 let (mut pos, old_key, old_val, was_internal) = match self.force() {
2831 let (hole, old_key, old_val) = leaf.remove();
2832 (hole, old_key, old_val, false)
2834 Internal(mut internal) => {
2835 // Replace the location freed in the internal node with the next KV,
2836 // and remove that next KV from its leaf.
2838 let key_loc = internal.kv_mut().0 as *mut K;
2839 let val_loc = internal.kv_mut().1 as *mut V;
2841 // Deleting from the left side is typically faster since we can
2842 // just pop an element from the end of the KV array without
2843 // needing to shift the other values.
2844 let to_remove = internal.left_edge().descend().last_leaf_edge().left_kv().ok();
2845 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2847 let (hole, key, val) = to_remove.remove();
2849 let old_key = unsafe { mem::replace(&mut *key_loc, key) };
2850 let old_val = unsafe { mem::replace(&mut *val_loc, val) };
2852 (hole, old_key, old_val, true)
2857 let mut emptied_internal_root = false;
2858 let mut cur_node = unsafe { ptr::read(&pos).into_node().forget_type() };
2859 let mut at_leaf = true;
2860 while cur_node.len() < node::MIN_LEN {
2861 match handle_underfull_node(cur_node) {
2863 Merged(edge, merged_with_left, offset) => {
2864 // If we merged with our right sibling then our tracked
2865 // position has not changed. However if we merged with our
2866 // left sibling then our tracked position is now dangling.
2867 if at_leaf && merged_with_left {
2868 let idx = pos.idx() + offset;
2869 let node = match unsafe { ptr::read(&edge).descend().force() } {
2871 Internal(_) => unreachable!(),
2873 pos = unsafe { Handle::new_edge(node, idx) };
2876 let parent = edge.into_node();
2877 if parent.len() == 0 {
2878 // This empty parent must be the root, and should be popped off the tree.
2879 emptied_internal_root = true;
2882 cur_node = parent.forget_type();
2886 Stole(stole_from_left) => {
2887 // Adjust the tracked position if we stole from a left sibling
2888 if stole_from_left && at_leaf {
2889 // SAFETY: This is safe since we just added an element to our node.
2891 pos.next_unchecked();
2899 // If we deleted from an internal node then we need to compensate for
2900 // the earlier swap and adjust the tracked position to point to the
2903 pos = unsafe { unwrap_unchecked(pos.next_kv().ok()).next_leaf_edge() };
2906 RemoveResult { old_kv: (old_key, old_val), pos, emptied_internal_root }
2910 impl<K, V> node::Root<K, V> {
2911 /// Removes empty levels on the top, but keep an empty leaf if the entire tree is empty.
2912 fn fix_top(&mut self) {
2913 while self.height() > 0 && self.as_ref().len() == 0 {
2914 self.pop_internal_level();
2918 fn fix_right_border(&mut self) {
2922 let mut cur_node = self.as_mut();
2924 while let Internal(node) = cur_node.force() {
2925 let mut last_kv = node.last_kv();
2927 if last_kv.can_merge() {
2928 cur_node = last_kv.merge().descend();
2930 let right_len = last_kv.reborrow().right_edge().descend().len();
2931 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
2932 if right_len < node::MIN_LEN + 1 {
2933 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
2935 cur_node = last_kv.right_edge().descend();
2943 /// The symmetric clone of `fix_right_border`.
2944 fn fix_left_border(&mut self) {
2948 let mut cur_node = self.as_mut();
2950 while let Internal(node) = cur_node.force() {
2951 let mut first_kv = node.first_kv();
2953 if first_kv.can_merge() {
2954 cur_node = first_kv.merge().descend();
2956 let left_len = first_kv.reborrow().left_edge().descend().len();
2957 if left_len < node::MIN_LEN + 1 {
2958 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
2960 cur_node = first_kv.left_edge().descend();
2969 enum UnderflowResult<'a, K, V> {
2971 Merged(Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge>, bool, usize),
2975 fn handle_underfull_node<K, V>(
2976 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2977 ) -> UnderflowResult<'_, K, V> {
2978 let parent = match node.ascend() {
2979 Ok(parent) => parent,
2980 Err(_) => return AtRoot,
2983 let (is_left, mut handle) = match parent.left_kv() {
2984 Ok(left) => (true, left),
2986 match parent.right_kv() {
2987 Ok(right) => (false, right),
2989 // The underfull node has an empty parent, so it is the only child
2990 // of an empty root. It is destined to become the new root, thus
2991 // allowed to be underfull. The empty parent should be removed later
2992 // by `pop_internal_level`.
2999 if handle.can_merge() {
3000 let offset = if is_left { handle.reborrow().left_edge().descend().len() + 1 } else { 0 };
3001 Merged(handle.merge(), is_left, offset)
3004 handle.steal_left();
3006 handle.steal_right();
3012 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
3015 fn next(&mut self) -> Option<(K, V)> {
3016 let res = match (self.left.peek(), self.right.peek()) {
3017 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
3018 (Some(_), None) => Ordering::Less,
3019 (None, Some(_)) => Ordering::Greater,
3020 (None, None) => return None,
3023 // Check which elements comes first and only advance the corresponding iterator.
3024 // If two keys are equal, take the value from `right`.
3026 Ordering::Less => self.left.next(),
3027 Ordering::Greater => self.right.next(),
3028 Ordering::Equal => {