1 // ignore-tidy-filelength
3 use core::borrow::Borrow;
4 use core::cmp::Ordering;
5 use core::fmt::{self, Debug};
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.node_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().node_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 let root_node = self.root.as_ref()?.node_as_ref();
227 match search::search_tree(root_node, key) {
228 Found(handle) => Some(handle.into_kv().0),
233 fn take(&mut self, key: &Q) -> Option<K> {
234 let root_node = self.root.as_mut()?.node_as_mut();
235 match search::search_tree(root_node, key) {
236 Found(handle) => Some(
237 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
245 fn replace(&mut self, key: K) -> Option<K> {
246 let root = Self::ensure_is_owned(&mut self.root);
247 match search::search_tree::<marker::Mut<'_>, K, (), K>(root.node_as_mut(), &key) {
248 Found(handle) => Some(mem::replace(handle.into_kv_mut().0, key)),
250 VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData }
258 /// An iterator over the entries of a `BTreeMap`.
260 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
261 /// documentation for more.
263 /// [`iter`]: BTreeMap::iter
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub struct Iter<'a, K: 'a, V: 'a> {
266 range: Range<'a, K, V>,
270 #[stable(feature = "collection_debug", since = "1.17.0")]
271 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 f.debug_list().entries(self.clone()).finish()
277 /// A mutable iterator over the entries of a `BTreeMap`.
279 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
280 /// documentation for more.
282 /// [`iter_mut`]: BTreeMap::iter_mut
283 #[stable(feature = "rust1", since = "1.0.0")]
285 pub struct IterMut<'a, K: 'a, V: 'a> {
286 range: RangeMut<'a, K, V>,
290 /// An owning iterator over the entries of a `BTreeMap`.
292 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
293 /// (provided by the `IntoIterator` trait). See its documentation for more.
295 /// [`into_iter`]: IntoIterator::into_iter
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub struct IntoIter<K, V> {
298 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
299 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
303 #[stable(feature = "collection_debug", since = "1.17.0")]
304 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 front: self.front.as_ref().map(|f| f.reborrow()),
308 back: self.back.as_ref().map(|b| b.reborrow()),
310 f.debug_list().entries(range).finish()
314 /// An iterator over the keys of a `BTreeMap`.
316 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
317 /// documentation for more.
319 /// [`keys`]: BTreeMap::keys
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub struct Keys<'a, K: 'a, V: 'a> {
322 inner: Iter<'a, K, V>,
325 #[stable(feature = "collection_debug", since = "1.17.0")]
326 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 f.debug_list().entries(self.clone()).finish()
332 /// An iterator over the values of a `BTreeMap`.
334 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
335 /// documentation for more.
337 /// [`values`]: BTreeMap::values
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct Values<'a, K: 'a, V: 'a> {
340 inner: Iter<'a, K, V>,
343 #[stable(feature = "collection_debug", since = "1.17.0")]
344 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 f.debug_list().entries(self.clone()).finish()
350 /// A mutable iterator over the values of a `BTreeMap`.
352 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
353 /// documentation for more.
355 /// [`values_mut`]: BTreeMap::values_mut
356 #[stable(feature = "map_values_mut", since = "1.10.0")]
358 pub struct ValuesMut<'a, K: 'a, V: 'a> {
359 inner: IterMut<'a, K, V>,
362 /// An owning iterator over the keys of a `BTreeMap`.
364 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
365 /// See its documentation for more.
367 /// [`into_keys`]: BTreeMap::into_keys
368 #[unstable(feature = "map_into_keys_values", issue = "75294")]
370 pub struct IntoKeys<K, V> {
371 inner: IntoIter<K, V>,
374 /// An owning iterator over the values of a `BTreeMap`.
376 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
377 /// See its documentation for more.
379 /// [`into_values`]: BTreeMap::into_values
380 #[unstable(feature = "map_into_keys_values", issue = "75294")]
382 pub struct IntoValues<K, V> {
383 inner: IntoIter<K, V>,
386 /// An iterator over a sub-range of entries in a `BTreeMap`.
388 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
389 /// documentation for more.
391 /// [`range`]: BTreeMap::range
392 #[stable(feature = "btree_range", since = "1.17.0")]
393 pub struct Range<'a, K: 'a, V: 'a> {
394 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
395 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
398 #[stable(feature = "collection_debug", since = "1.17.0")]
399 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
400 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401 f.debug_list().entries(self.clone()).finish()
405 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
407 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
408 /// documentation for more.
410 /// [`range_mut`]: BTreeMap::range_mut
411 #[stable(feature = "btree_range", since = "1.17.0")]
412 pub struct RangeMut<'a, K: 'a, V: 'a> {
413 front: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
414 back: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
416 // Be invariant in `K` and `V`
417 _marker: PhantomData<&'a mut (K, V)>,
420 #[stable(feature = "collection_debug", since = "1.17.0")]
421 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424 front: self.front.as_ref().map(|f| f.reborrow()),
425 back: self.back.as_ref().map(|b| b.reborrow()),
427 f.debug_list().entries(range).finish()
431 /// A view into a single entry in a map, which may either be vacant or occupied.
433 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
435 /// [`entry`]: BTreeMap::entry
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub enum Entry<'a, K: 'a, V: 'a> {
439 #[stable(feature = "rust1", since = "1.0.0")]
440 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V>),
442 /// An occupied entry.
443 #[stable(feature = "rust1", since = "1.0.0")]
444 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V>),
447 #[stable(feature = "debug_btree_map", since = "1.12.0")]
448 impl<K: Debug + Ord, V: Debug> Debug for Entry<'_, K, V> {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
452 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
457 /// A view into a vacant entry in a `BTreeMap`.
458 /// It is part of the [`Entry`] enum.
460 /// [`Entry`]: enum.Entry.html
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub struct VacantEntry<'a, K: 'a, V: 'a> {
464 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>,
465 length: &'a mut usize,
467 // Be invariant in `K` and `V`
468 _marker: PhantomData<&'a mut (K, V)>,
471 #[stable(feature = "debug_btree_map", since = "1.12.0")]
472 impl<K: Debug + Ord, V> Debug for VacantEntry<'_, K, V> {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 f.debug_tuple("VacantEntry").field(self.key()).finish()
478 /// A view into an occupied entry in a `BTreeMap`.
479 /// It is part of the [`Entry`] enum.
481 /// [`Entry`]: enum.Entry.html
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
484 handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
486 length: &'a mut usize,
488 // Be invariant in `K` and `V`
489 _marker: PhantomData<&'a mut (K, V)>,
492 #[stable(feature = "debug_btree_map", since = "1.12.0")]
493 impl<K: Debug + Ord, V: Debug> Debug for OccupiedEntry<'_, K, V> {
494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
499 // An iterator for merging two sorted sequences into one
500 struct MergeIter<K, V, I: Iterator<Item = (K, V)>> {
505 impl<K: Ord, V> BTreeMap<K, V> {
506 /// Makes a new empty BTreeMap.
508 /// Does not allocate anything on its own.
515 /// use std::collections::BTreeMap;
517 /// let mut map = BTreeMap::new();
519 /// // entries can now be inserted into the empty map
520 /// map.insert(1, "a");
522 #[stable(feature = "rust1", since = "1.0.0")]
523 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
524 pub const fn new() -> BTreeMap<K, V> {
525 BTreeMap { root: None, length: 0 }
528 /// Clears the map, removing all elements.
535 /// use std::collections::BTreeMap;
537 /// let mut a = BTreeMap::new();
538 /// a.insert(1, "a");
540 /// assert!(a.is_empty());
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn clear(&mut self) {
544 *self = BTreeMap::new();
547 /// Returns a reference to the value corresponding to the key.
549 /// The key may be any borrowed form of the map's key type, but the ordering
550 /// on the borrowed form *must* match the ordering on the key type.
557 /// use std::collections::BTreeMap;
559 /// let mut map = BTreeMap::new();
560 /// map.insert(1, "a");
561 /// assert_eq!(map.get(&1), Some(&"a"));
562 /// assert_eq!(map.get(&2), None);
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
570 let root_node = self.root.as_ref()?.node_as_ref();
571 match search::search_tree(root_node, key) {
572 Found(handle) => Some(handle.into_kv().1),
577 /// Returns the key-value pair corresponding to the supplied key.
579 /// The supplied key may be any borrowed form of the map's key type, but the ordering
580 /// on the borrowed form *must* match the ordering on the key type.
585 /// use std::collections::BTreeMap;
587 /// let mut map = BTreeMap::new();
588 /// map.insert(1, "a");
589 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
590 /// assert_eq!(map.get_key_value(&2), None);
592 #[stable(feature = "map_get_key_value", since = "1.40.0")]
593 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
598 let root_node = self.root.as_ref()?.node_as_ref();
599 match search::search_tree(root_node, k) {
600 Found(handle) => Some(handle.into_kv()),
605 /// Returns the first key-value pair in the map.
606 /// The key in this pair is the minimum key in the map.
613 /// #![feature(map_first_last)]
614 /// use std::collections::BTreeMap;
616 /// let mut map = BTreeMap::new();
617 /// assert_eq!(map.first_key_value(), None);
618 /// map.insert(1, "b");
619 /// map.insert(2, "a");
620 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
622 #[unstable(feature = "map_first_last", issue = "62924")]
623 pub fn first_key_value(&self) -> Option<(&K, &V)> {
624 let root_node = self.root.as_ref()?.node_as_ref();
625 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
628 /// Returns the first entry in the map for in-place manipulation.
629 /// The key of this entry is the minimum key in the map.
634 /// #![feature(map_first_last)]
635 /// use std::collections::BTreeMap;
637 /// let mut map = BTreeMap::new();
638 /// map.insert(1, "a");
639 /// map.insert(2, "b");
640 /// if let Some(mut entry) = map.first_entry() {
641 /// if *entry.key() > 0 {
642 /// entry.insert("first");
645 /// assert_eq!(*map.get(&1).unwrap(), "first");
646 /// assert_eq!(*map.get(&2).unwrap(), "b");
648 #[unstable(feature = "map_first_last", issue = "62924")]
649 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
650 let root_node = self.root.as_mut()?.node_as_mut();
651 let kv = root_node.first_leaf_edge().right_kv().ok()?;
653 handle: kv.forget_node_type(),
654 length: &mut self.length,
655 _marker: PhantomData,
659 /// Removes and returns the first element in the map.
660 /// The key of this element is the minimum key that was in the map.
664 /// Draining elements in ascending order, while keeping a usable map each iteration.
667 /// #![feature(map_first_last)]
668 /// use std::collections::BTreeMap;
670 /// let mut map = BTreeMap::new();
671 /// map.insert(1, "a");
672 /// map.insert(2, "b");
673 /// while let Some((key, _val)) = map.pop_first() {
674 /// assert!(map.iter().all(|(k, _v)| *k > key));
676 /// assert!(map.is_empty());
678 #[unstable(feature = "map_first_last", issue = "62924")]
679 pub fn pop_first(&mut self) -> Option<(K, V)> {
680 self.first_entry().map(|entry| entry.remove_entry())
683 /// Returns the last key-value pair in the map.
684 /// The key in this pair is the maximum key in the map.
691 /// #![feature(map_first_last)]
692 /// use std::collections::BTreeMap;
694 /// let mut map = BTreeMap::new();
695 /// map.insert(1, "b");
696 /// map.insert(2, "a");
697 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
699 #[unstable(feature = "map_first_last", issue = "62924")]
700 pub fn last_key_value(&self) -> Option<(&K, &V)> {
701 let root_node = self.root.as_ref()?.node_as_ref();
702 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
705 /// Returns the last entry in the map for in-place manipulation.
706 /// The key of this entry is the maximum key in the map.
711 /// #![feature(map_first_last)]
712 /// use std::collections::BTreeMap;
714 /// let mut map = BTreeMap::new();
715 /// map.insert(1, "a");
716 /// map.insert(2, "b");
717 /// if let Some(mut entry) = map.last_entry() {
718 /// if *entry.key() > 0 {
719 /// entry.insert("last");
722 /// assert_eq!(*map.get(&1).unwrap(), "a");
723 /// assert_eq!(*map.get(&2).unwrap(), "last");
725 #[unstable(feature = "map_first_last", issue = "62924")]
726 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
727 let root_node = self.root.as_mut()?.node_as_mut();
728 let kv = root_node.last_leaf_edge().left_kv().ok()?;
730 handle: kv.forget_node_type(),
731 length: &mut self.length,
732 _marker: PhantomData,
736 /// Removes and returns the last element in the map.
737 /// The key of this element is the maximum key that was in the map.
741 /// Draining elements in descending order, while keeping a usable map each iteration.
744 /// #![feature(map_first_last)]
745 /// use std::collections::BTreeMap;
747 /// let mut map = BTreeMap::new();
748 /// map.insert(1, "a");
749 /// map.insert(2, "b");
750 /// while let Some((key, _val)) = map.pop_last() {
751 /// assert!(map.iter().all(|(k, _v)| *k < key));
753 /// assert!(map.is_empty());
755 #[unstable(feature = "map_first_last", issue = "62924")]
756 pub fn pop_last(&mut self) -> Option<(K, V)> {
757 self.last_entry().map(|entry| entry.remove_entry())
760 /// Returns `true` if the map contains a value for the specified key.
762 /// The key may be any borrowed form of the map's key type, but the ordering
763 /// on the borrowed form *must* match the ordering on the key type.
770 /// use std::collections::BTreeMap;
772 /// let mut map = BTreeMap::new();
773 /// map.insert(1, "a");
774 /// assert_eq!(map.contains_key(&1), true);
775 /// assert_eq!(map.contains_key(&2), false);
777 #[stable(feature = "rust1", since = "1.0.0")]
778 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
783 self.get(key).is_some()
786 /// Returns a mutable reference to the value corresponding to the key.
788 /// The key may be any borrowed form of the map's key type, but the ordering
789 /// on the borrowed form *must* match the ordering on the key type.
796 /// use std::collections::BTreeMap;
798 /// let mut map = BTreeMap::new();
799 /// map.insert(1, "a");
800 /// if let Some(x) = map.get_mut(&1) {
803 /// assert_eq!(map[&1], "b");
805 // See `get` for implementation notes, this is basically a copy-paste with mut's added
806 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
812 let root_node = self.root.as_mut()?.node_as_mut();
813 match search::search_tree(root_node, key) {
814 Found(handle) => Some(handle.into_kv_mut().1),
819 /// Inserts a key-value pair into the map.
821 /// If the map did not have this key present, `None` is returned.
823 /// If the map did have this key present, the value is updated, and the old
824 /// value is returned. The key is not updated, though; this matters for
825 /// types that can be `==` without being identical. See the [module-level
826 /// documentation] for more.
828 /// [module-level documentation]: index.html#insert-and-complex-keys
835 /// use std::collections::BTreeMap;
837 /// let mut map = BTreeMap::new();
838 /// assert_eq!(map.insert(37, "a"), None);
839 /// assert_eq!(map.is_empty(), false);
841 /// map.insert(37, "b");
842 /// assert_eq!(map.insert(37, "c"), Some("b"));
843 /// assert_eq!(map[&37], "c");
845 #[stable(feature = "rust1", since = "1.0.0")]
846 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
847 match self.entry(key) {
848 Occupied(mut entry) => Some(entry.insert(value)),
856 /// Removes a key from the map, returning the value at the key if the key
857 /// was previously in the map.
859 /// The key may be any borrowed form of the map's key type, but the ordering
860 /// on the borrowed form *must* match the ordering on the key type.
867 /// use std::collections::BTreeMap;
869 /// let mut map = BTreeMap::new();
870 /// map.insert(1, "a");
871 /// assert_eq!(map.remove(&1), Some("a"));
872 /// assert_eq!(map.remove(&1), None);
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
880 self.remove_entry(key).map(|(_, v)| v)
883 /// Removes a key from the map, returning the stored key and value if the key
884 /// was previously in the map.
886 /// The key may be any borrowed form of the map's key type, but the ordering
887 /// on the borrowed form *must* match the ordering on the key type.
894 /// use std::collections::BTreeMap;
896 /// let mut map = BTreeMap::new();
897 /// map.insert(1, "a");
898 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
899 /// assert_eq!(map.remove_entry(&1), None);
901 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
902 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
907 let root_node = self.root.as_mut()?.node_as_mut();
908 match search::search_tree(root_node, key) {
909 Found(handle) => Some(
910 OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData }
917 /// Moves all elements from `other` into `Self`, leaving `other` empty.
922 /// use std::collections::BTreeMap;
924 /// let mut a = BTreeMap::new();
925 /// a.insert(1, "a");
926 /// a.insert(2, "b");
927 /// a.insert(3, "c");
929 /// let mut b = BTreeMap::new();
930 /// b.insert(3, "d");
931 /// b.insert(4, "e");
932 /// b.insert(5, "f");
934 /// a.append(&mut b);
936 /// assert_eq!(a.len(), 5);
937 /// assert_eq!(b.len(), 0);
939 /// assert_eq!(a[&1], "a");
940 /// assert_eq!(a[&2], "b");
941 /// assert_eq!(a[&3], "d");
942 /// assert_eq!(a[&4], "e");
943 /// assert_eq!(a[&5], "f");
945 #[stable(feature = "btree_append", since = "1.11.0")]
946 pub fn append(&mut self, other: &mut Self) {
947 // Do we have to append anything at all?
948 if other.is_empty() {
952 // We can just swap `self` and `other` if `self` is empty.
954 mem::swap(self, other);
958 // First, we merge `self` and `other` into a sorted sequence in linear time.
959 let self_iter = mem::take(self).into_iter();
960 let other_iter = mem::take(other).into_iter();
961 let iter = MergeIter { left: self_iter.peekable(), right: other_iter.peekable() };
963 // Second, we build a tree from the sorted sequence in linear time.
964 self.from_sorted_iter(iter);
967 /// Constructs a double-ended iterator over a sub-range of elements in the map.
968 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
969 /// yield elements from min (inclusive) to max (exclusive).
970 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
971 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
972 /// range from 4 to 10.
976 /// Panics if range `start > end`.
977 /// Panics if range `start == end` and both bounds are `Excluded`.
984 /// use std::collections::BTreeMap;
985 /// use std::ops::Bound::Included;
987 /// let mut map = BTreeMap::new();
988 /// map.insert(3, "a");
989 /// map.insert(5, "b");
990 /// map.insert(8, "c");
991 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
992 /// println!("{}: {}", key, value);
994 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
996 #[stable(feature = "btree_range", since = "1.17.0")]
997 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1003 if let Some(root) = &self.root {
1004 let (f, b) = range_search(root.node_as_ref(), range);
1006 Range { front: Some(f), back: Some(b) }
1008 Range { front: None, back: None }
1012 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1013 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1014 /// yield elements from min (inclusive) to max (exclusive).
1015 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1016 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1017 /// range from 4 to 10.
1021 /// Panics if range `start > end`.
1022 /// Panics if range `start == end` and both bounds are `Excluded`.
1029 /// use std::collections::BTreeMap;
1031 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1033 /// .map(|&s| (s, 0))
1035 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1036 /// *balance += 100;
1038 /// for (name, balance) in &map {
1039 /// println!("{} => {}", name, balance);
1042 #[stable(feature = "btree_range", since = "1.17.0")]
1043 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1049 if let Some(root) = &mut self.root {
1050 let (f, b) = range_search(root.node_as_mut(), range);
1052 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1054 RangeMut { front: None, back: None, _marker: PhantomData }
1058 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1065 /// use std::collections::BTreeMap;
1067 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1069 /// // count the number of occurrences of letters in the vec
1070 /// for x in vec!["a","b","a","c","a","b"] {
1071 /// *count.entry(x).or_insert(0) += 1;
1074 /// assert_eq!(count["a"], 3);
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1078 // FIXME(@porglezomp) Avoid allocating if we don't insert
1079 let root = Self::ensure_is_owned(&mut self.root);
1080 match search::search_tree(root.node_as_mut(), &key) {
1082 Occupied(OccupiedEntry { handle, length: &mut self.length, _marker: PhantomData })
1085 Vacant(VacantEntry { key, handle, length: &mut self.length, _marker: PhantomData })
1090 fn from_sorted_iter<I: Iterator<Item = (K, V)>>(&mut self, iter: I) {
1091 let root = Self::ensure_is_owned(&mut self.root);
1092 let mut cur_node = root.node_as_mut().last_leaf_edge().into_node();
1093 // Iterate through all key-value pairs, pushing them into nodes at the right level.
1094 for (key, value) in iter {
1095 // Try to push key-value pair into the current leaf node.
1096 if cur_node.len() < node::CAPACITY {
1097 cur_node.push(key, value);
1099 // No space left, go up and push there.
1101 let mut test_node = cur_node.forget_type();
1103 match test_node.ascend() {
1105 let parent = parent.into_node();
1106 if parent.len() < node::CAPACITY {
1107 // Found a node with space left, push here.
1112 test_node = parent.forget_type();
1116 // We are at the top, create a new root node and push there.
1117 open_node = root.push_internal_level();
1123 // Push key-value pair and new right subtree.
1124 let tree_height = open_node.height() - 1;
1125 let mut right_tree = node::Root::new_leaf();
1126 for _ in 0..tree_height {
1127 right_tree.push_internal_level();
1129 open_node.push(key, value, right_tree);
1131 // Go down to the right-most leaf again.
1132 cur_node = open_node.forget_type().last_leaf_edge().into_node();
1137 Self::fix_right_edge(root)
1140 fn fix_right_edge(root: &mut node::Root<K, V>) {
1141 // Handle underfull nodes, start from the top.
1142 let mut cur_node = root.node_as_mut();
1143 while let Internal(internal) = cur_node.force() {
1144 // Check if right-most child is underfull.
1145 let mut last_edge = internal.last_edge();
1146 let right_child_len = last_edge.reborrow().descend().len();
1147 if right_child_len < node::MIN_LEN {
1148 // We need to steal.
1149 let mut last_kv = match last_edge.left_kv() {
1151 Err(_) => unreachable!(),
1153 last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
1154 last_edge = last_kv.right_edge();
1158 cur_node = last_edge.descend();
1162 /// Splits the collection into two at the given key. Returns everything after the given key,
1163 /// including the key.
1170 /// use std::collections::BTreeMap;
1172 /// let mut a = BTreeMap::new();
1173 /// a.insert(1, "a");
1174 /// a.insert(2, "b");
1175 /// a.insert(3, "c");
1176 /// a.insert(17, "d");
1177 /// a.insert(41, "e");
1179 /// let b = a.split_off(&3);
1181 /// assert_eq!(a.len(), 2);
1182 /// assert_eq!(b.len(), 3);
1184 /// assert_eq!(a[&1], "a");
1185 /// assert_eq!(a[&2], "b");
1187 /// assert_eq!(b[&3], "c");
1188 /// assert_eq!(b[&17], "d");
1189 /// assert_eq!(b[&41], "e");
1191 #[stable(feature = "btree_split_off", since = "1.11.0")]
1192 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1196 if self.is_empty() {
1200 let total_num = self.len();
1201 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1203 let mut right = Self::new();
1204 let right_root = Self::ensure_is_owned(&mut right.root);
1205 for _ in 0..left_root.height() {
1206 right_root.push_internal_level();
1210 let mut left_node = left_root.node_as_mut();
1211 let mut right_node = right_root.node_as_mut();
1214 let mut split_edge = match search::search_node(left_node, key) {
1215 // key is going to the right tree
1216 Found(handle) => handle.left_edge(),
1217 GoDown(handle) => handle,
1220 split_edge.move_suffix(&mut right_node);
1222 match (split_edge.force(), right_node.force()) {
1223 (Internal(edge), Internal(node)) => {
1224 left_node = edge.descend();
1225 right_node = node.first_edge().descend();
1227 (Leaf(_), Leaf(_)) => {
1237 left_root.fix_right_border();
1238 right_root.fix_left_border();
1240 if left_root.height() < right_root.height() {
1241 self.recalc_length();
1242 right.length = total_num - self.len();
1244 right.recalc_length();
1245 self.length = total_num - right.len();
1251 /// Creates an iterator which uses a closure to determine if an element should be removed.
1253 /// If the closure returns true, the element is removed from the map and yielded.
1254 /// If the closure returns false, or panics, the element remains in the map and will not be
1257 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1258 /// whether you choose to keep or remove it.
1260 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1261 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1263 /// It is unspecified how many more elements will be subjected to the closure
1264 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1265 /// or if the `DrainFilter` value is leaked.
1269 /// Splitting a map into even and odd keys, reusing the original map:
1272 /// #![feature(btree_drain_filter)]
1273 /// use std::collections::BTreeMap;
1275 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1276 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1278 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1279 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1281 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1282 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1284 F: FnMut(&K, &mut V) -> bool,
1286 DrainFilter { pred, inner: self.drain_filter_inner() }
1288 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1289 let root_node = self.root.as_mut().map(|r| r.node_as_mut());
1290 let front = root_node.map(|rn| rn.first_leaf_edge());
1292 length: &mut self.length,
1293 cur_leaf_edge: front,
1294 emptied_internal_root: false,
1298 /// Calculates the number of elements if it is incorrect.
1299 fn recalc_length(&mut self) {
1300 fn dfs<'a, K, V>(node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>) -> usize
1305 let mut res = node.len();
1307 if let Internal(node) = node.force() {
1308 let mut edge = node.first_edge();
1310 res += dfs(edge.reborrow().descend());
1311 match edge.right_kv() {
1313 edge = right_kv.right_edge();
1325 self.length = dfs(self.root.as_ref().unwrap().node_as_ref());
1328 /// Creates a consuming iterator visiting all the keys, in sorted order.
1329 /// The map cannot be used after calling this.
1330 /// The iterator element type is `K`.
1335 /// #![feature(map_into_keys_values)]
1336 /// use std::collections::BTreeMap;
1338 /// let mut a = BTreeMap::new();
1339 /// a.insert(2, "b");
1340 /// a.insert(1, "a");
1342 /// let keys: Vec<i32> = a.into_keys().collect();
1343 /// assert_eq!(keys, [1, 2]);
1346 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1347 pub fn into_keys(self) -> IntoKeys<K, V> {
1348 IntoKeys { inner: self.into_iter() }
1351 /// Creates a consuming iterator visiting all the values, in order by key.
1352 /// The map cannot be used after calling this.
1353 /// The iterator element type is `V`.
1358 /// #![feature(map_into_keys_values)]
1359 /// use std::collections::BTreeMap;
1361 /// let mut a = BTreeMap::new();
1362 /// a.insert(1, "hello");
1363 /// a.insert(2, "goodbye");
1365 /// let values: Vec<&str> = a.into_values().collect();
1366 /// assert_eq!(values, ["hello", "goodbye"]);
1369 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1370 pub fn into_values(self) -> IntoValues<K, V> {
1371 IntoValues { inner: self.into_iter() }
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1377 type Item = (&'a K, &'a V);
1378 type IntoIter = Iter<'a, K, V>;
1380 fn into_iter(self) -> Iter<'a, K, V> {
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1387 type Item = (&'a K, &'a V);
1389 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1390 if self.length == 0 {
1394 unsafe { Some(self.range.next_unchecked()) }
1398 fn size_hint(&self) -> (usize, Option<usize>) {
1399 (self.length, Some(self.length))
1402 fn last(mut self) -> Option<(&'a K, &'a V)> {
1406 fn min(mut self) -> Option<(&'a K, &'a V)> {
1410 fn max(mut self) -> Option<(&'a K, &'a V)> {
1415 #[stable(feature = "fused", since = "1.26.0")]
1416 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1418 #[stable(feature = "rust1", since = "1.0.0")]
1419 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1420 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1421 if self.length == 0 {
1425 unsafe { Some(self.range.next_back_unchecked()) }
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1432 fn len(&self) -> usize {
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<K, V> Clone for Iter<'_, K, V> {
1439 fn clone(&self) -> Self {
1440 Iter { range: self.range.clone(), length: self.length }
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1446 type Item = (&'a K, &'a mut V);
1447 type IntoIter = IterMut<'a, K, V>;
1449 fn into_iter(self) -> IterMut<'a, K, V> {
1454 #[stable(feature = "rust1", since = "1.0.0")]
1455 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1456 type Item = (&'a K, &'a mut V);
1458 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1459 if self.length == 0 {
1463 let (k, v) = unsafe { self.range.next_unchecked() };
1464 Some((k, v)) // coerce k from `&mut K` to `&K`
1468 fn size_hint(&self) -> (usize, Option<usize>) {
1469 (self.length, Some(self.length))
1472 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1476 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1480 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1487 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1488 if self.length == 0 {
1492 let (k, v) = unsafe { self.range.next_back_unchecked() };
1493 Some((k, v)) // coerce k from `&mut K` to `&K`
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1500 fn len(&self) -> usize {
1505 #[stable(feature = "fused", since = "1.26.0")]
1506 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 impl<K, V> IntoIterator for BTreeMap<K, V> {
1511 type IntoIter = IntoIter<K, V>;
1513 fn into_iter(self) -> IntoIter<K, V> {
1514 let mut me = ManuallyDrop::new(self);
1515 if let Some(root) = me.root.take() {
1516 let (f, b) = full_range_search(root.into_ref());
1518 IntoIter { front: Some(f), back: Some(b), length: me.length }
1520 IntoIter { front: None, back: None, length: 0 }
1525 #[stable(feature = "btree_drop", since = "1.7.0")]
1526 impl<K, V> Drop for IntoIter<K, V> {
1527 fn drop(&mut self) {
1528 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1530 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1531 fn drop(&mut self) {
1532 // Continue the same loop we perform below. This only runs when unwinding, so we
1533 // don't have to care about panics this time (they'll abort).
1534 while let Some(_) = self.0.next() {}
1538 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1539 while let Some(parent) = node.deallocate_and_ascend() {
1540 node = parent.into_node().forget_type();
1546 while let Some(pair) = self.next() {
1547 let guard = DropGuard(self);
1553 if let Some(front) = ptr::read(&self.front) {
1554 let mut node = front.into_node().forget_type();
1555 // Most of the nodes have been deallocated while traversing
1556 // but one pile from a leaf up to the root is left standing.
1557 while let Some(parent) = node.deallocate_and_ascend() {
1558 node = parent.into_node().forget_type();
1565 #[stable(feature = "rust1", since = "1.0.0")]
1566 impl<K, V> Iterator for IntoIter<K, V> {
1569 fn next(&mut self) -> Option<(K, V)> {
1570 if self.length == 0 {
1574 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1578 fn size_hint(&self) -> (usize, Option<usize>) {
1579 (self.length, Some(self.length))
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1585 fn next_back(&mut self) -> Option<(K, V)> {
1586 if self.length == 0 {
1590 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1597 fn len(&self) -> usize {
1602 #[stable(feature = "fused", since = "1.26.0")]
1603 impl<K, V> FusedIterator for IntoIter<K, V> {}
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1609 fn next(&mut self) -> Option<&'a K> {
1610 self.inner.next().map(|(k, _)| k)
1613 fn size_hint(&self) -> (usize, Option<usize>) {
1614 self.inner.size_hint()
1617 fn last(mut self) -> Option<&'a K> {
1621 fn min(mut self) -> Option<&'a K> {
1625 fn max(mut self) -> Option<&'a K> {
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1632 fn next_back(&mut self) -> Option<&'a K> {
1633 self.inner.next_back().map(|(k, _)| k)
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1639 fn len(&self) -> usize {
1644 #[stable(feature = "fused", since = "1.26.0")]
1645 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 impl<K, V> Clone for Keys<'_, K, V> {
1649 fn clone(&self) -> Self {
1650 Keys { inner: self.inner.clone() }
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl<'a, K, V> Iterator for Values<'a, K, V> {
1658 fn next(&mut self) -> Option<&'a V> {
1659 self.inner.next().map(|(_, v)| v)
1662 fn size_hint(&self) -> (usize, Option<usize>) {
1663 self.inner.size_hint()
1666 fn last(mut self) -> Option<&'a V> {
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1673 fn next_back(&mut self) -> Option<&'a V> {
1674 self.inner.next_back().map(|(_, v)| v)
1678 #[stable(feature = "rust1", since = "1.0.0")]
1679 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1680 fn len(&self) -> usize {
1685 #[stable(feature = "fused", since = "1.26.0")]
1686 impl<K, V> FusedIterator for Values<'_, K, V> {}
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<K, V> Clone for Values<'_, K, V> {
1690 fn clone(&self) -> Self {
1691 Values { inner: self.inner.clone() }
1695 /// An iterator produced by calling `drain_filter` on BTreeMap.
1696 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1697 pub struct DrainFilter<'a, K, V, F>
1701 F: 'a + FnMut(&K, &mut V) -> bool,
1704 inner: DrainFilterInner<'a, K, V>,
1706 /// Most of the implementation of DrainFilter, independent of the type
1707 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1708 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1709 length: &'a mut usize,
1710 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1711 emptied_internal_root: bool,
1714 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1715 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1717 F: FnMut(&K, &mut V) -> bool,
1719 fn drop(&mut self) {
1720 self.for_each(drop);
1724 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1725 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1729 F: FnMut(&K, &mut V) -> bool,
1731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1732 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1736 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1737 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1739 F: FnMut(&K, &mut V) -> bool,
1743 fn next(&mut self) -> Option<(K, V)> {
1744 self.inner.next(&mut self.pred)
1747 fn size_hint(&self) -> (usize, Option<usize>) {
1748 self.inner.size_hint()
1752 impl<K, V> Drop for DrainFilterInner<'_, K, V> {
1753 fn drop(&mut self) {
1754 if self.emptied_internal_root {
1755 if let Some(handle) = self.cur_leaf_edge.take() {
1756 let root = handle.into_node().into_root_mut();
1757 root.pop_internal_level();
1763 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1764 /// Allow Debug implementations to predict the next element.
1765 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1766 let edge = self.cur_leaf_edge.as_ref()?;
1767 edge.reborrow().next_kv().ok().map(|kv| kv.into_kv())
1770 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1771 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1773 F: FnMut(&K, &mut V) -> bool,
1775 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1776 let (k, v) = kv.kv_mut();
1779 let (kv, pos) = kv.remove_kv_tracking(|_| self.emptied_internal_root = true);
1780 self.cur_leaf_edge = Some(pos);
1783 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1788 /// Implementation of a typical `DrainFilter::size_hint` method.
1789 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1790 (0, Some(*self.length))
1794 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1795 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1797 #[stable(feature = "btree_range", since = "1.17.0")]
1798 impl<'a, K, V> Iterator for Range<'a, K, V> {
1799 type Item = (&'a K, &'a V);
1801 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1802 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1805 fn last(mut self) -> Option<(&'a K, &'a V)> {
1809 fn min(mut self) -> Option<(&'a K, &'a V)> {
1813 fn max(mut self) -> Option<(&'a K, &'a V)> {
1818 #[stable(feature = "map_values_mut", since = "1.10.0")]
1819 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1820 type Item = &'a mut V;
1822 fn next(&mut self) -> Option<&'a mut V> {
1823 self.inner.next().map(|(_, v)| v)
1826 fn size_hint(&self) -> (usize, Option<usize>) {
1827 self.inner.size_hint()
1830 fn last(mut self) -> Option<&'a mut V> {
1835 #[stable(feature = "map_values_mut", since = "1.10.0")]
1836 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1837 fn next_back(&mut self) -> Option<&'a mut V> {
1838 self.inner.next_back().map(|(_, v)| v)
1842 #[stable(feature = "map_values_mut", since = "1.10.0")]
1843 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1844 fn len(&self) -> usize {
1849 #[stable(feature = "fused", since = "1.26.0")]
1850 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1852 impl<'a, K, V> Range<'a, K, V> {
1853 fn is_empty(&self) -> bool {
1854 self.front == self.back
1857 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1858 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1862 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1863 impl<K, V> Iterator for IntoKeys<K, V> {
1866 fn next(&mut self) -> Option<K> {
1867 self.inner.next().map(|(k, _)| k)
1870 fn size_hint(&self) -> (usize, Option<usize>) {
1871 self.inner.size_hint()
1874 fn last(mut self) -> Option<K> {
1878 fn min(mut self) -> Option<K> {
1882 fn max(mut self) -> Option<K> {
1887 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1888 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1889 fn next_back(&mut self) -> Option<K> {
1890 self.inner.next_back().map(|(k, _)| k)
1894 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1895 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1896 fn len(&self) -> usize {
1901 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1902 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1904 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1905 impl<K, V> Iterator for IntoValues<K, V> {
1908 fn next(&mut self) -> Option<V> {
1909 self.inner.next().map(|(_, v)| v)
1912 fn size_hint(&self) -> (usize, Option<usize>) {
1913 self.inner.size_hint()
1916 fn last(mut self) -> Option<V> {
1921 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1922 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1923 fn next_back(&mut self) -> Option<V> {
1924 self.inner.next_back().map(|(_, v)| v)
1928 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1929 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1930 fn len(&self) -> usize {
1935 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1936 impl<K, V> FusedIterator for IntoValues<K, V> {}
1938 #[stable(feature = "btree_range", since = "1.17.0")]
1939 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1940 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1941 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1945 impl<'a, K, V> Range<'a, K, V> {
1946 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1947 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1951 #[stable(feature = "fused", since = "1.26.0")]
1952 impl<K, V> FusedIterator for Range<'_, K, V> {}
1954 #[stable(feature = "btree_range", since = "1.17.0")]
1955 impl<K, V> Clone for Range<'_, K, V> {
1956 fn clone(&self) -> Self {
1957 Range { front: self.front, back: self.back }
1961 #[stable(feature = "btree_range", since = "1.17.0")]
1962 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1963 type Item = (&'a K, &'a mut V);
1965 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1966 if self.is_empty() {
1969 let (k, v) = unsafe { self.next_unchecked() };
1970 Some((k, v)) // coerce k from `&mut K` to `&K`
1974 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1978 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1982 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1987 impl<'a, K, V> RangeMut<'a, K, V> {
1988 fn is_empty(&self) -> bool {
1989 self.front == self.back
1992 unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
1993 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1997 #[stable(feature = "btree_range", since = "1.17.0")]
1998 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1999 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2000 if self.is_empty() {
2003 let (k, v) = unsafe { self.next_back_unchecked() };
2004 Some((k, v)) // coerce k from `&mut K` to `&K`
2009 #[stable(feature = "fused", since = "1.26.0")]
2010 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2012 impl<'a, K, V> RangeMut<'a, K, V> {
2013 unsafe fn next_back_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
2014 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
2018 #[stable(feature = "rust1", since = "1.0.0")]
2019 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2020 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2021 let mut map = BTreeMap::new();
2027 #[stable(feature = "rust1", since = "1.0.0")]
2028 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
2030 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2031 iter.into_iter().for_each(move |(k, v)| {
2037 fn extend_one(&mut self, (k, v): (K, V)) {
2042 #[stable(feature = "extend_ref", since = "1.2.0")]
2043 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
2044 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2045 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2049 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2054 #[stable(feature = "rust1", since = "1.0.0")]
2055 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
2056 fn hash<H: Hasher>(&self, state: &mut H) {
2063 #[stable(feature = "rust1", since = "1.0.0")]
2064 impl<K: Ord, V> Default for BTreeMap<K, V> {
2065 /// Creates an empty `BTreeMap<K, V>`.
2066 fn default() -> BTreeMap<K, V> {
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
2073 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
2074 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2078 #[stable(feature = "rust1", since = "1.0.0")]
2079 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
2081 #[stable(feature = "rust1", since = "1.0.0")]
2082 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
2084 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
2085 self.iter().partial_cmp(other.iter())
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
2092 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
2093 self.iter().cmp(other.iter())
2097 #[stable(feature = "rust1", since = "1.0.0")]
2098 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
2099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2100 f.debug_map().entries(self.iter()).finish()
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
2112 /// Returns a reference to the value corresponding to the supplied key.
2116 /// Panics if the key is not present in the `BTreeMap`.
2118 fn index(&self, key: &Q) -> &V {
2119 self.get(key).expect("no entry found for key")
2123 /// Finds the leaf edges delimiting a specified range in or underneath a node.
2124 fn range_search<BorrowType, K, V, Q: ?Sized, R: RangeBounds<Q>>(
2125 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2128 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2129 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2135 match (range.start_bound(), range.end_bound()) {
2136 (Excluded(s), Excluded(e)) if s == e => {
2137 panic!("range start and end are equal and excluded in BTreeMap")
2139 (Included(s) | Excluded(s), Included(e) | Excluded(e)) if s > e => {
2140 panic!("range start is greater than range end in BTreeMap")
2145 // We duplicate the root NodeRef here -- we will never access it in a way
2146 // that overlaps references obtained from the root.
2147 let mut min_node = unsafe { ptr::read(&root) };
2148 let mut max_node = root;
2149 let mut min_found = false;
2150 let mut max_found = false;
2153 let front = match (min_found, range.start_bound()) {
2154 (false, Included(key)) => match search::search_node(min_node, key) {
2159 GoDown(edge) => edge,
2161 (false, Excluded(key)) => match search::search_node(min_node, key) {
2166 GoDown(edge) => edge,
2168 (true, Included(_)) => min_node.last_edge(),
2169 (true, Excluded(_)) => min_node.first_edge(),
2170 (_, Unbounded) => min_node.first_edge(),
2173 let back = match (max_found, range.end_bound()) {
2174 (false, Included(key)) => match search::search_node(max_node, key) {
2179 GoDown(edge) => edge,
2181 (false, Excluded(key)) => match search::search_node(max_node, key) {
2186 GoDown(edge) => edge,
2188 (true, Included(_)) => max_node.first_edge(),
2189 (true, Excluded(_)) => max_node.last_edge(),
2190 (_, Unbounded) => max_node.last_edge(),
2193 if front.partial_cmp(&back) == Some(Ordering::Greater) {
2194 panic!("Ord is ill-defined in BTreeMap range");
2196 match (front.force(), back.force()) {
2197 (Leaf(f), Leaf(b)) => {
2200 (Internal(min_int), Internal(max_int)) => {
2201 min_node = min_int.descend();
2202 max_node = max_int.descend();
2204 _ => unreachable!("BTreeMap has different depths"),
2209 /// Equivalent to `range_search(k, v, ..)` without the `Ord` bound.
2210 fn full_range_search<BorrowType, K, V>(
2211 root: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
2213 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2214 Handle<NodeRef<BorrowType, K, V, marker::Leaf>, marker::Edge>,
2216 // We duplicate the root NodeRef here -- we will never access it in a way
2217 // that overlaps references obtained from the root.
2218 let mut min_node = unsafe { ptr::read(&root) };
2219 let mut max_node = root;
2221 let front = min_node.first_edge();
2222 let back = max_node.last_edge();
2223 match (front.force(), back.force()) {
2224 (Leaf(f), Leaf(b)) => {
2227 (Internal(min_int), Internal(max_int)) => {
2228 min_node = min_int.descend();
2229 max_node = max_int.descend();
2231 _ => unreachable!("BTreeMap has different depths"),
2236 impl<K, V> BTreeMap<K, V> {
2237 /// Gets an iterator over the entries of the map, sorted by key.
2244 /// use std::collections::BTreeMap;
2246 /// let mut map = BTreeMap::new();
2247 /// map.insert(3, "c");
2248 /// map.insert(2, "b");
2249 /// map.insert(1, "a");
2251 /// for (key, value) in map.iter() {
2252 /// println!("{}: {}", key, value);
2255 /// let (first_key, first_value) = map.iter().next().unwrap();
2256 /// assert_eq!((*first_key, *first_value), (1, "a"));
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 pub fn iter(&self) -> Iter<'_, K, V> {
2260 if let Some(root) = &self.root {
2261 let (f, b) = full_range_search(root.node_as_ref());
2263 Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2265 Iter { range: Range { front: None, back: None }, length: 0 }
2269 /// Gets a mutable iterator over the entries of the map, sorted by key.
2276 /// use std::collections::BTreeMap;
2278 /// let mut map = BTreeMap::new();
2279 /// map.insert("a", 1);
2280 /// map.insert("b", 2);
2281 /// map.insert("c", 3);
2283 /// // add 10 to the value if the key isn't "a"
2284 /// for (key, value) in map.iter_mut() {
2285 /// if key != &"a" {
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2292 if let Some(root) = &mut self.root {
2293 let (f, b) = full_range_search(root.node_as_mut());
2296 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2297 length: self.length,
2300 IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2304 /// Gets an iterator over the keys of the map, in sorted order.
2311 /// use std::collections::BTreeMap;
2313 /// let mut a = BTreeMap::new();
2314 /// a.insert(2, "b");
2315 /// a.insert(1, "a");
2317 /// let keys: Vec<_> = a.keys().cloned().collect();
2318 /// assert_eq!(keys, [1, 2]);
2320 #[stable(feature = "rust1", since = "1.0.0")]
2321 pub fn keys(&self) -> Keys<'_, K, V> {
2322 Keys { inner: self.iter() }
2325 /// Gets an iterator over the values of the map, in order by key.
2332 /// use std::collections::BTreeMap;
2334 /// let mut a = BTreeMap::new();
2335 /// a.insert(1, "hello");
2336 /// a.insert(2, "goodbye");
2338 /// let values: Vec<&str> = a.values().cloned().collect();
2339 /// assert_eq!(values, ["hello", "goodbye"]);
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 pub fn values(&self) -> Values<'_, K, V> {
2343 Values { inner: self.iter() }
2346 /// Gets a mutable iterator over the values of the map, in order by key.
2353 /// use std::collections::BTreeMap;
2355 /// let mut a = BTreeMap::new();
2356 /// a.insert(1, String::from("hello"));
2357 /// a.insert(2, String::from("goodbye"));
2359 /// for value in a.values_mut() {
2360 /// value.push_str("!");
2363 /// let values: Vec<String> = a.values().cloned().collect();
2364 /// assert_eq!(values, [String::from("hello!"),
2365 /// String::from("goodbye!")]);
2367 #[stable(feature = "map_values_mut", since = "1.10.0")]
2368 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2369 ValuesMut { inner: self.iter_mut() }
2372 /// Returns the number of elements in the map.
2379 /// use std::collections::BTreeMap;
2381 /// let mut a = BTreeMap::new();
2382 /// assert_eq!(a.len(), 0);
2383 /// a.insert(1, "a");
2384 /// assert_eq!(a.len(), 1);
2386 #[stable(feature = "rust1", since = "1.0.0")]
2387 pub fn len(&self) -> usize {
2391 /// Returns `true` if the map contains no elements.
2398 /// use std::collections::BTreeMap;
2400 /// let mut a = BTreeMap::new();
2401 /// assert!(a.is_empty());
2402 /// a.insert(1, "a");
2403 /// assert!(!a.is_empty());
2405 #[stable(feature = "rust1", since = "1.0.0")]
2406 pub fn is_empty(&self) -> bool {
2410 /// If the root node is the empty (non-allocated) root node, allocate our
2411 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2412 fn ensure_is_owned(root: &mut Option<node::Root<K, V>>) -> &mut node::Root<K, V> {
2413 root.get_or_insert_with(node::Root::new_leaf)
2417 impl<'a, K: Ord, V> Entry<'a, K, V> {
2418 /// Ensures a value is in the entry by inserting the default if empty, and returns
2419 /// a mutable reference to the value in the entry.
2424 /// use std::collections::BTreeMap;
2426 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2427 /// map.entry("poneyland").or_insert(12);
2429 /// assert_eq!(map["poneyland"], 12);
2431 #[stable(feature = "rust1", since = "1.0.0")]
2432 pub fn or_insert(self, default: V) -> &'a mut V {
2434 Occupied(entry) => entry.into_mut(),
2435 Vacant(entry) => entry.insert(default),
2439 /// Ensures a value is in the entry by inserting the result of the default function if empty,
2440 /// and returns a mutable reference to the value in the entry.
2445 /// use std::collections::BTreeMap;
2447 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
2448 /// let s = "hoho".to_string();
2450 /// map.entry("poneyland").or_insert_with(|| s);
2452 /// assert_eq!(map["poneyland"], "hoho".to_string());
2454 #[stable(feature = "rust1", since = "1.0.0")]
2455 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
2457 Occupied(entry) => entry.into_mut(),
2458 Vacant(entry) => entry.insert(default()),
2462 #[unstable(feature = "or_insert_with_key", issue = "71024")]
2463 /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2464 /// which takes the key as its argument, and returns a mutable reference to the value in the
2470 /// #![feature(or_insert_with_key)]
2471 /// use std::collections::BTreeMap;
2473 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2475 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2477 /// assert_eq!(map["poneyland"], 9);
2480 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
2482 Occupied(entry) => entry.into_mut(),
2484 let value = default(entry.key());
2490 /// Returns a reference to this entry's key.
2495 /// use std::collections::BTreeMap;
2497 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2498 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2500 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2501 pub fn key(&self) -> &K {
2503 Occupied(ref entry) => entry.key(),
2504 Vacant(ref entry) => entry.key(),
2508 /// Provides in-place mutable access to an occupied entry before any
2509 /// potential inserts into the map.
2514 /// use std::collections::BTreeMap;
2516 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2518 /// map.entry("poneyland")
2519 /// .and_modify(|e| { *e += 1 })
2521 /// assert_eq!(map["poneyland"], 42);
2523 /// map.entry("poneyland")
2524 /// .and_modify(|e| { *e += 1 })
2526 /// assert_eq!(map["poneyland"], 43);
2528 #[stable(feature = "entry_and_modify", since = "1.26.0")]
2529 pub fn and_modify<F>(self, f: F) -> Self
2534 Occupied(mut entry) => {
2538 Vacant(entry) => Vacant(entry),
2543 impl<'a, K: Ord, V: Default> Entry<'a, K, V> {
2544 #[stable(feature = "entry_or_default", since = "1.28.0")]
2545 /// Ensures a value is in the entry by inserting the default value if empty,
2546 /// and returns a mutable reference to the value in the entry.
2551 /// use std::collections::BTreeMap;
2553 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
2554 /// map.entry("poneyland").or_default();
2556 /// assert_eq!(map["poneyland"], None);
2558 pub fn or_default(self) -> &'a mut V {
2560 Occupied(entry) => entry.into_mut(),
2561 Vacant(entry) => entry.insert(Default::default()),
2566 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
2567 /// Gets a reference to the key that would be used when inserting a value
2568 /// through the VacantEntry.
2573 /// use std::collections::BTreeMap;
2575 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2576 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2578 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2579 pub fn key(&self) -> &K {
2583 /// Take ownership of the key.
2588 /// use std::collections::BTreeMap;
2589 /// use std::collections::btree_map::Entry;
2591 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2593 /// if let Entry::Vacant(v) = map.entry("poneyland") {
2597 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2598 pub fn into_key(self) -> K {
2602 /// Sets the value of the entry with the `VacantEntry`'s key,
2603 /// and returns a mutable reference to it.
2608 /// use std::collections::BTreeMap;
2609 /// use std::collections::btree_map::Entry;
2611 /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
2613 /// if let Entry::Vacant(o) = map.entry("poneyland") {
2616 /// assert_eq!(map["poneyland"], 37);
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 pub fn insert(self, value: V) -> &'a mut V {
2622 let out_ptr = match self.handle.insert_recursing(self.key, value) {
2623 (Fit(_), val_ptr) => val_ptr,
2624 (Split(ins), val_ptr) => {
2625 let root = ins.left.into_root_mut();
2626 root.push_internal_level().push(ins.k, ins.v, ins.right);
2630 // Now that we have finished growing the tree using borrowed references,
2631 // dereference the pointer to a part of it, that we picked up along the way.
2632 unsafe { &mut *out_ptr }
2636 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
2637 /// Gets a reference to the key in the entry.
2642 /// use std::collections::BTreeMap;
2644 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2645 /// map.entry("poneyland").or_insert(12);
2646 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
2648 #[stable(feature = "map_entry_keys", since = "1.10.0")]
2649 pub fn key(&self) -> &K {
2650 self.handle.reborrow().into_kv().0
2653 /// Take ownership of the key and value from the map.
2658 /// use std::collections::BTreeMap;
2659 /// use std::collections::btree_map::Entry;
2661 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2662 /// map.entry("poneyland").or_insert(12);
2664 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2665 /// // We delete the entry from the map.
2666 /// o.remove_entry();
2669 /// // If now try to get the value, it will panic:
2670 /// // println!("{}", map["poneyland"]);
2672 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
2673 pub fn remove_entry(self) -> (K, V) {
2677 /// Gets a reference to the value in the entry.
2682 /// use std::collections::BTreeMap;
2683 /// use std::collections::btree_map::Entry;
2685 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2686 /// map.entry("poneyland").or_insert(12);
2688 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2689 /// assert_eq!(o.get(), &12);
2692 #[stable(feature = "rust1", since = "1.0.0")]
2693 pub fn get(&self) -> &V {
2694 self.handle.reborrow().into_kv().1
2697 /// Gets a mutable reference to the value in the entry.
2699 /// If you need a reference to the `OccupiedEntry` that may outlive the
2700 /// destruction of the `Entry` value, see [`into_mut`].
2702 /// [`into_mut`]: #method.into_mut
2707 /// use std::collections::BTreeMap;
2708 /// use std::collections::btree_map::Entry;
2710 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2711 /// map.entry("poneyland").or_insert(12);
2713 /// assert_eq!(map["poneyland"], 12);
2714 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2715 /// *o.get_mut() += 10;
2716 /// assert_eq!(*o.get(), 22);
2718 /// // We can use the same Entry multiple times.
2719 /// *o.get_mut() += 2;
2721 /// assert_eq!(map["poneyland"], 24);
2723 #[stable(feature = "rust1", since = "1.0.0")]
2724 pub fn get_mut(&mut self) -> &mut V {
2725 self.handle.kv_mut().1
2728 /// Converts the entry into a mutable reference to its value.
2730 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
2732 /// [`get_mut`]: #method.get_mut
2737 /// use std::collections::BTreeMap;
2738 /// use std::collections::btree_map::Entry;
2740 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2741 /// map.entry("poneyland").or_insert(12);
2743 /// assert_eq!(map["poneyland"], 12);
2744 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2745 /// *o.into_mut() += 10;
2747 /// assert_eq!(map["poneyland"], 22);
2749 #[stable(feature = "rust1", since = "1.0.0")]
2750 pub fn into_mut(self) -> &'a mut V {
2751 self.handle.into_kv_mut().1
2754 /// Sets the value of the entry with the `OccupiedEntry`'s key,
2755 /// and returns the entry's old value.
2760 /// use std::collections::BTreeMap;
2761 /// use std::collections::btree_map::Entry;
2763 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2764 /// map.entry("poneyland").or_insert(12);
2766 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
2767 /// assert_eq!(o.insert(15), 12);
2769 /// assert_eq!(map["poneyland"], 15);
2771 #[stable(feature = "rust1", since = "1.0.0")]
2772 pub fn insert(&mut self, value: V) -> V {
2773 mem::replace(self.get_mut(), value)
2776 /// Takes the value of the entry out of the map, and returns it.
2781 /// use std::collections::BTreeMap;
2782 /// use std::collections::btree_map::Entry;
2784 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
2785 /// map.entry("poneyland").or_insert(12);
2787 /// if let Entry::Occupied(o) = map.entry("poneyland") {
2788 /// assert_eq!(o.remove(), 12);
2790 /// // If we try to get "poneyland"'s value, it'll panic:
2791 /// // println!("{}", map["poneyland"]);
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 pub fn remove(self) -> V {
2798 // Body of `remove_entry`, separate to keep the above implementations short.
2799 fn remove_kv(self) -> (K, V) {
2803 self.handle.remove_kv_tracking(|root| root.into_root_mut().pop_internal_level());
2808 impl<'a, K: 'a, V: 'a> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV> {
2809 /// Removes a key/value-pair from the tree, and returns that pair, as well as
2810 /// the leaf edge corresponding to that former pair. It's possible this leaves
2811 /// an empty internal root node, which the caller should subsequently pop from
2812 /// the map holding the tree. The caller should also decrement the map's length.
2813 fn remove_kv_tracking<F>(
2815 handle_emptied_internal_root: F,
2816 ) -> ((K, V), Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>)
2818 F: FnOnce(NodeRef<marker::Mut<'a>, K, V, marker::Internal>),
2820 let (old_kv, mut pos, was_internal) = match self.force() {
2822 let (old_kv, pos) = leaf.remove();
2823 (old_kv, pos, false)
2825 Internal(mut internal) => {
2826 // Replace the location freed in the internal node with the next KV,
2827 // and remove that next KV from its leaf.
2829 let key_loc = internal.kv_mut().0 as *mut K;
2830 let val_loc = internal.kv_mut().1 as *mut V;
2832 // Deleting from the left side is typically faster since we can
2833 // just pop an element from the end of the KV array without
2834 // needing to shift the other values.
2835 let to_remove = internal.left_edge().descend().last_leaf_edge().left_kv().ok();
2836 let to_remove = unsafe { unwrap_unchecked(to_remove) };
2838 let (kv, pos) = to_remove.remove();
2840 let old_key = unsafe { mem::replace(&mut *key_loc, kv.0) };
2841 let old_val = unsafe { mem::replace(&mut *val_loc, kv.1) };
2843 ((old_key, old_val), pos, true)
2848 let mut cur_node = unsafe { ptr::read(&pos).into_node().forget_type() };
2849 let mut at_leaf = true;
2850 while cur_node.len() < node::MIN_LEN {
2851 match handle_underfull_node(cur_node) {
2853 Merged(edge, merged_with_left, offset) => {
2854 // If we merged with our right sibling then our tracked
2855 // position has not changed. However if we merged with our
2856 // left sibling then our tracked position is now dangling.
2857 if at_leaf && merged_with_left {
2858 let idx = pos.idx() + offset;
2859 let node = match unsafe { ptr::read(&edge).descend().force() } {
2861 Internal(_) => unreachable!(),
2863 pos = unsafe { Handle::new_edge(node, idx) };
2866 let parent = edge.into_node();
2867 if parent.len() == 0 {
2868 // The parent that was just emptied must be the root,
2869 // because nodes on a lower level would not have been
2870 // left underfull. It has to be popped off the tree soon.
2871 handle_emptied_internal_root(parent);
2874 cur_node = parent.forget_type();
2878 Stole(stole_from_left) => {
2879 // Adjust the tracked position if we stole from a left sibling
2880 if stole_from_left && at_leaf {
2881 // SAFETY: This is safe since we just added an element to our node.
2883 pos.next_unchecked();
2891 // If we deleted from an internal node then we need to compensate for
2892 // the earlier swap and adjust the tracked position to point to the
2895 pos = unsafe { unwrap_unchecked(pos.next_kv().ok()).next_leaf_edge() };
2902 impl<K, V> node::Root<K, V> {
2903 /// Removes empty levels on the top, but keep an empty leaf if the entire tree is empty.
2904 fn fix_top(&mut self) {
2905 while self.height() > 0 && self.node_as_ref().len() == 0 {
2906 self.pop_internal_level();
2910 fn fix_right_border(&mut self) {
2914 let mut cur_node = self.node_as_mut();
2916 while let Internal(node) = cur_node.force() {
2917 let mut last_kv = node.last_kv();
2919 if last_kv.can_merge() {
2920 cur_node = last_kv.merge().descend();
2922 let right_len = last_kv.reborrow().right_edge().descend().len();
2923 // `MINLEN + 1` to avoid readjust if merge happens on the next level.
2924 if right_len < node::MIN_LEN + 1 {
2925 last_kv.bulk_steal_left(node::MIN_LEN + 1 - right_len);
2927 cur_node = last_kv.right_edge().descend();
2935 /// The symmetric clone of `fix_right_border`.
2936 fn fix_left_border(&mut self) {
2940 let mut cur_node = self.node_as_mut();
2942 while let Internal(node) = cur_node.force() {
2943 let mut first_kv = node.first_kv();
2945 if first_kv.can_merge() {
2946 cur_node = first_kv.merge().descend();
2948 let left_len = first_kv.reborrow().left_edge().descend().len();
2949 if left_len < node::MIN_LEN + 1 {
2950 first_kv.bulk_steal_right(node::MIN_LEN + 1 - left_len);
2952 cur_node = first_kv.left_edge().descend();
2961 enum UnderflowResult<'a, K, V> {
2963 Merged(Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge>, bool, usize),
2967 fn handle_underfull_node<K, V>(
2968 node: NodeRef<marker::Mut<'_>, K, V, marker::LeafOrInternal>,
2969 ) -> UnderflowResult<'_, K, V> {
2970 let parent = match node.ascend() {
2971 Ok(parent) => parent,
2972 Err(_) => return AtRoot,
2975 let (is_left, mut handle) = match parent.left_kv() {
2976 Ok(left) => (true, left),
2978 match parent.right_kv() {
2979 Ok(right) => (false, right),
2981 // The underfull node has an empty parent, so it is the only child
2982 // of an empty root. It is destined to become the new root, thus
2983 // allowed to be underfull. The empty parent should be removed later
2984 // by `pop_internal_level`.
2991 if handle.can_merge() {
2992 let offset = if is_left { handle.reborrow().left_edge().descend().len() + 1 } else { 0 };
2993 Merged(handle.merge(), is_left, offset)
2996 handle.steal_left();
2998 handle.steal_right();
3004 impl<K: Ord, V, I: Iterator<Item = (K, V)>> Iterator for MergeIter<K, V, I> {
3007 fn next(&mut self) -> Option<(K, V)> {
3008 let res = match (self.left.peek(), self.right.peek()) {
3009 (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
3010 (Some(_), None) => Ordering::Less,
3011 (None, Some(_)) => Ordering::Greater,
3012 (None, None) => return None,
3015 // Check which elements comes first and only advance the corresponding iterator.
3016 // If two keys are equal, take the value from `right`.
3018 Ordering::Less => self.left.next(),
3019 Ordering::Greater => self.right.next(),
3020 Ordering::Equal => {