2 use core::borrow::Borrow;
3 use core::cmp::Ordering;
4 use core::fmt::{self, Debug};
5 use core::hash::{Hash, Hasher};
6 use core::iter::{FromIterator, FusedIterator};
7 use core::marker::PhantomData;
8 use core::mem::{self, ManuallyDrop};
9 use core::ops::{Index, RangeBounds};
12 use crate::alloc::{Allocator, Global};
14 use super::borrow::DormantMutRef;
15 use super::dedup_sorted_iter::DedupSortedIter;
16 use super::navigate::{LazyLeafRange, LeafRange};
17 use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
18 use super::search::SearchResult::*;
19 use super::set_val::SetValZST;
23 #[stable(feature = "rust1", since = "1.0.0")]
24 pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
28 /// Minimum number of elements in a node that is not a root.
29 /// We might temporarily have fewer elements during methods.
30 pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
32 // A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
33 // - Keys must appear in ascending order (according to the key's type).
34 // - Every non-leaf node contains at least 1 element (has at least 2 children).
35 // - Every non-root node contains at least MIN_LEN elements.
37 // An empty map is represented either by the absence of a root node or by a
38 // root node that is an empty leaf.
40 /// An ordered map based on a [B-Tree].
42 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
43 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
44 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
45 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
46 /// is done is *very* inefficient for modern computer architectures. In particular, every element
47 /// is stored in its own individually heap-allocated node. This means that every single insertion
48 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
49 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
52 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
53 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
54 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
55 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
56 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
57 /// the node using binary search. As a compromise, one could also perform a linear search
58 /// that initially only checks every i<sup>th</sup> element for some choice of i.
60 /// Currently, our implementation simply performs naive linear search. This provides excellent
61 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
62 /// would like to further explore choosing the optimal search strategy based on the choice of B,
63 /// and possibly other factors. Using linear search, searching for a random element is expected
64 /// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
65 /// however, performance is excellent.
67 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
68 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
69 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
70 /// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
71 /// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
72 /// include panics, incorrect results, aborts, memory leaks, and non-termination.
74 /// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::values`], or
75 /// [`BTreeMap::keys`] produce their items in order by key, and take worst-case logarithmic and
76 /// amortized constant time per item returned.
78 /// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
79 /// [`Cell`]: core::cell::Cell
80 /// [`RefCell`]: core::cell::RefCell
85 /// use std::collections::BTreeMap;
87 /// // type inference lets us omit an explicit type signature (which
88 /// // would be `BTreeMap<&str, &str>` in this example).
89 /// let mut movie_reviews = BTreeMap::new();
91 /// // review some movies.
92 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
93 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
94 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
95 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
97 /// // check for a specific one.
98 /// if !movie_reviews.contains_key("Les Misérables") {
99 /// println!("We've got {} reviews, but Les Misérables ain't one.",
100 /// movie_reviews.len());
103 /// // oops, this review has a lot of spelling mistakes, let's delete it.
104 /// movie_reviews.remove("The Blues Brothers");
106 /// // look up the values associated with some keys.
107 /// let to_find = ["Up!", "Office Space"];
108 /// for movie in &to_find {
109 /// match movie_reviews.get(movie) {
110 /// Some(review) => println!("{movie}: {review}"),
111 /// None => println!("{movie} is unreviewed.")
115 /// // Look up the value for a key (will panic if the key is not found).
116 /// println!("Movie review: {}", movie_reviews["Office Space"]);
118 /// // iterate over everything.
119 /// for (movie, review) in &movie_reviews {
120 /// println!("{movie}: \"{review}\"");
124 /// A `BTreeMap` with a known list of items can be initialized from an array:
127 /// use std::collections::BTreeMap;
129 /// let solar_distance = BTreeMap::from([
130 /// ("Mercury", 0.4),
137 /// `BTreeMap` implements an [`Entry API`], which allows for complex
138 /// methods of getting, setting, updating and removing keys and their values:
140 /// [`Entry API`]: BTreeMap::entry
143 /// use std::collections::BTreeMap;
145 /// // type inference lets us omit an explicit type signature (which
146 /// // would be `BTreeMap<&str, u8>` in this example).
147 /// let mut player_stats = BTreeMap::new();
149 /// fn random_stat_buff() -> u8 {
150 /// // could actually return some random value here - let's just return
151 /// // some fixed value for now
155 /// // insert a key only if it doesn't already exist
156 /// player_stats.entry("health").or_insert(100);
158 /// // insert a key using a function that provides a new value only if it
159 /// // doesn't already exist
160 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
162 /// // update a key, guarding against the key possibly not being set
163 /// let stat = player_stats.entry("attack").or_insert(100);
164 /// *stat += random_stat_buff();
166 /// // modify an entry before an insert with in-place mutation
167 /// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
169 #[stable(feature = "rust1", since = "1.0.0")]
170 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
171 #[rustc_insignificant_dtor]
175 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
177 root: Option<Root<K, V>>,
179 /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
180 pub(super) alloc: ManuallyDrop<A>,
183 #[stable(feature = "btree_drop", since = "1.7.0")]
184 unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTreeMap<K, V, A> {
186 drop(unsafe { ptr::read(self) }.into_iter())
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl<K: Clone, V: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, A> {
192 fn clone(&self) -> BTreeMap<K, V, A> {
193 fn clone_subtree<'a, K: Clone, V: Clone, A: Allocator + Clone>(
194 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
196 ) -> BTreeMap<K, V, A>
203 let mut out_tree = BTreeMap {
204 root: Some(Root::new(alloc.clone())),
206 alloc: ManuallyDrop::new(alloc),
210 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
211 let mut out_node = match root.borrow_mut().force() {
213 Internal(_) => unreachable!(),
216 let mut in_edge = leaf.first_edge();
217 while let Ok(kv) = in_edge.right_kv() {
218 let (k, v) = kv.into_kv();
219 in_edge = kv.right_edge();
221 out_node.push(k.clone(), v.clone());
222 out_tree.length += 1;
228 Internal(internal) => {
230 clone_subtree(internal.first_edge().descend(), alloc.clone());
233 let out_root = out_tree.root.as_mut().unwrap();
234 let mut out_node = out_root.push_internal_level(alloc.clone());
235 let mut in_edge = internal.first_edge();
236 while let Ok(kv) = in_edge.right_kv() {
237 let (k, v) = kv.into_kv();
238 in_edge = kv.right_edge();
240 let k = (*k).clone();
241 let v = (*v).clone();
242 let subtree = clone_subtree(in_edge.descend(), alloc.clone());
244 // We can't destructure subtree directly
245 // because BTreeMap implements Drop
246 let (subroot, sublength) = unsafe {
247 let subtree = ManuallyDrop::new(subtree);
248 let root = ptr::read(&subtree.root);
249 let length = subtree.length;
256 subroot.unwrap_or_else(|| Root::new(alloc.clone())),
258 out_tree.length += 1 + sublength;
268 BTreeMap::new_in((*self.alloc).clone())
270 clone_subtree(self.root.as_ref().unwrap().reborrow(), (*self.alloc).clone()) // unwrap succeeds because not empty
275 impl<K, Q: ?Sized, A: Allocator + Clone> super::Recover<Q> for BTreeMap<K, SetValZST, A>
282 fn get(&self, key: &Q) -> Option<&K> {
283 let root_node = self.root.as_ref()?.reborrow();
284 match root_node.search_tree(key) {
285 Found(handle) => Some(handle.into_kv().0),
290 fn take(&mut self, key: &Q) -> Option<K> {
291 let (map, dormant_map) = DormantMutRef::new(self);
292 let root_node = map.root.as_mut()?.borrow_mut();
293 match root_node.search_tree(key) {
294 Found(handle) => Some(
298 alloc: (*map.alloc).clone(),
299 _marker: PhantomData,
308 fn replace(&mut self, key: K) -> Option<K> {
309 let (map, dormant_map) = DormantMutRef::new(self);
311 map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
312 match root_node.search_tree::<K>(&key) {
313 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
317 handle: Some(handle),
319 alloc: (*map.alloc).clone(),
320 _marker: PhantomData,
322 .insert(SetValZST::default());
329 /// An iterator over the entries of a `BTreeMap`.
331 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
332 /// documentation for more.
334 /// [`iter`]: BTreeMap::iter
335 #[must_use = "iterators are lazy and do nothing unless consumed"]
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub struct Iter<'a, K: 'a, V: 'a> {
338 range: LazyLeafRange<marker::Immut<'a>, K, V>,
342 #[stable(feature = "collection_debug", since = "1.17.0")]
343 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345 f.debug_list().entries(self.clone()).finish()
349 /// A mutable iterator over the entries of a `BTreeMap`.
351 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
352 /// documentation for more.
354 /// [`iter_mut`]: BTreeMap::iter_mut
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub struct IterMut<'a, K: 'a, V: 'a> {
357 range: LazyLeafRange<marker::ValMut<'a>, K, V>,
360 // Be invariant in `K` and `V`
361 _marker: PhantomData<&'a mut (K, V)>,
364 #[must_use = "iterators are lazy and do nothing unless consumed"]
365 #[stable(feature = "collection_debug", since = "1.17.0")]
366 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 let range = Iter { range: self.range.reborrow(), length: self.length };
369 f.debug_list().entries(range).finish()
373 /// An owning iterator over the entries of a `BTreeMap`.
375 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
376 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
378 /// [`into_iter`]: IntoIterator::into_iter
379 /// [`IntoIterator`]: core::iter::IntoIterator
380 #[stable(feature = "rust1", since = "1.0.0")]
381 #[rustc_insignificant_dtor]
385 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
387 range: LazyLeafRange<marker::Dying, K, V>,
389 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
393 impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
394 /// Returns an iterator of references over the remaining items.
396 pub(super) fn iter(&self) -> Iter<'_, K, V> {
397 Iter { range: self.range.reborrow(), length: self.length }
401 #[stable(feature = "collection_debug", since = "1.17.0")]
402 impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.debug_list().entries(self.iter()).finish()
408 /// An iterator over the keys of a `BTreeMap`.
410 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
411 /// documentation for more.
413 /// [`keys`]: BTreeMap::keys
414 #[must_use = "iterators are lazy and do nothing unless consumed"]
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub struct Keys<'a, K, V> {
417 inner: Iter<'a, K, V>,
420 #[stable(feature = "collection_debug", since = "1.17.0")]
421 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 f.debug_list().entries(self.clone()).finish()
427 /// An iterator over the values of a `BTreeMap`.
429 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
430 /// documentation for more.
432 /// [`values`]: BTreeMap::values
433 #[must_use = "iterators are lazy and do nothing unless consumed"]
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub struct Values<'a, K, V> {
436 inner: Iter<'a, K, V>,
439 #[stable(feature = "collection_debug", since = "1.17.0")]
440 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 f.debug_list().entries(self.clone()).finish()
446 /// A mutable iterator over the values of a `BTreeMap`.
448 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
449 /// documentation for more.
451 /// [`values_mut`]: BTreeMap::values_mut
452 #[must_use = "iterators are lazy and do nothing unless consumed"]
453 #[stable(feature = "map_values_mut", since = "1.10.0")]
454 pub struct ValuesMut<'a, K, V> {
455 inner: IterMut<'a, K, V>,
458 #[stable(feature = "map_values_mut", since = "1.10.0")]
459 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
465 /// An owning iterator over the keys of a `BTreeMap`.
467 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
468 /// See its documentation for more.
470 /// [`into_keys`]: BTreeMap::into_keys
471 #[must_use = "iterators are lazy and do nothing unless consumed"]
472 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
473 pub struct IntoKeys<K, V, A: Allocator + Clone = Global> {
474 inner: IntoIter<K, V, A>,
477 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
478 impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
484 /// An owning iterator over the values of a `BTreeMap`.
486 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
487 /// See its documentation for more.
489 /// [`into_values`]: BTreeMap::into_values
490 #[must_use = "iterators are lazy and do nothing unless consumed"]
491 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
492 pub struct IntoValues<
495 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
497 inner: IntoIter<K, V, A>,
500 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
501 impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
507 /// An iterator over a sub-range of entries in a `BTreeMap`.
509 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
510 /// documentation for more.
512 /// [`range`]: BTreeMap::range
513 #[must_use = "iterators are lazy and do nothing unless consumed"]
514 #[stable(feature = "btree_range", since = "1.17.0")]
515 pub struct Range<'a, K: 'a, V: 'a> {
516 inner: LeafRange<marker::Immut<'a>, K, V>,
519 #[stable(feature = "collection_debug", since = "1.17.0")]
520 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 f.debug_list().entries(self.clone()).finish()
526 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
528 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
529 /// documentation for more.
531 /// [`range_mut`]: BTreeMap::range_mut
532 #[must_use = "iterators are lazy and do nothing unless consumed"]
533 #[stable(feature = "btree_range", since = "1.17.0")]
534 pub struct RangeMut<'a, K: 'a, V: 'a> {
535 inner: LeafRange<marker::ValMut<'a>, K, V>,
537 // Be invariant in `K` and `V`
538 _marker: PhantomData<&'a mut (K, V)>,
541 #[stable(feature = "collection_debug", since = "1.17.0")]
542 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544 let range = Range { inner: self.inner.reborrow() };
545 f.debug_list().entries(range).finish()
549 impl<K, V> BTreeMap<K, V> {
550 /// Makes a new, empty `BTreeMap`.
552 /// Does not allocate anything on its own.
559 /// use std::collections::BTreeMap;
561 /// let mut map = BTreeMap::new();
563 /// // entries can now be inserted into the empty map
564 /// map.insert(1, "a");
566 #[stable(feature = "rust1", since = "1.0.0")]
567 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
569 pub const fn new() -> BTreeMap<K, V> {
570 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global) }
574 impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
575 /// Clears the map, removing all elements.
582 /// use std::collections::BTreeMap;
584 /// let mut a = BTreeMap::new();
585 /// a.insert(1, "a");
587 /// assert!(a.is_empty());
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn clear(&mut self) {
591 // avoid moving the allocator
593 root: mem::replace(&mut self.root, None),
594 length: mem::replace(&mut self.length, 0),
595 alloc: self.alloc.clone(),
599 /// Makes a new empty BTreeMap with a reasonable choice for B.
606 /// # #![feature(allocator_api)]
607 /// # #![feature(btreemap_alloc)]
608 /// use std::collections::BTreeMap;
609 /// use std::alloc::Global;
611 /// let mut map = BTreeMap::new_in(Global);
613 /// // entries can now be inserted into the empty map
614 /// map.insert(1, "a");
616 #[unstable(feature = "btreemap_alloc", issue = "32838")]
617 pub fn new_in(alloc: A) -> BTreeMap<K, V, A> {
618 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc) }
622 impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
623 /// Returns a reference to the value corresponding to the key.
625 /// The key may be any borrowed form of the map's key type, but the ordering
626 /// on the borrowed form *must* match the ordering on the key type.
633 /// use std::collections::BTreeMap;
635 /// let mut map = BTreeMap::new();
636 /// map.insert(1, "a");
637 /// assert_eq!(map.get(&1), Some(&"a"));
638 /// assert_eq!(map.get(&2), None);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
646 let root_node = self.root.as_ref()?.reborrow();
647 match root_node.search_tree(key) {
648 Found(handle) => Some(handle.into_kv().1),
653 /// Returns the key-value pair corresponding to the supplied key.
655 /// The supplied key may be any borrowed form of the map's key type, but the ordering
656 /// on the borrowed form *must* match the ordering on the key type.
661 /// use std::collections::BTreeMap;
663 /// let mut map = BTreeMap::new();
664 /// map.insert(1, "a");
665 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
666 /// assert_eq!(map.get_key_value(&2), None);
668 #[stable(feature = "map_get_key_value", since = "1.40.0")]
669 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
674 let root_node = self.root.as_ref()?.reborrow();
675 match root_node.search_tree(k) {
676 Found(handle) => Some(handle.into_kv()),
681 /// Returns the first key-value pair in the map.
682 /// The key in this pair is the minimum key in the map.
689 /// #![feature(map_first_last)]
690 /// use std::collections::BTreeMap;
692 /// let mut map = BTreeMap::new();
693 /// assert_eq!(map.first_key_value(), None);
694 /// map.insert(1, "b");
695 /// map.insert(2, "a");
696 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
698 #[unstable(feature = "map_first_last", issue = "62924")]
699 pub fn first_key_value(&self) -> Option<(&K, &V)>
703 let root_node = self.root.as_ref()?.reborrow();
704 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
707 /// Returns the first entry in the map for in-place manipulation.
708 /// The key of this entry is the minimum key in the map.
713 /// #![feature(map_first_last)]
714 /// use std::collections::BTreeMap;
716 /// let mut map = BTreeMap::new();
717 /// map.insert(1, "a");
718 /// map.insert(2, "b");
719 /// if let Some(mut entry) = map.first_entry() {
720 /// if *entry.key() > 0 {
721 /// entry.insert("first");
724 /// assert_eq!(*map.get(&1).unwrap(), "first");
725 /// assert_eq!(*map.get(&2).unwrap(), "b");
727 #[unstable(feature = "map_first_last", issue = "62924")]
728 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
732 let (map, dormant_map) = DormantMutRef::new(self);
733 let root_node = map.root.as_mut()?.borrow_mut();
734 let kv = root_node.first_leaf_edge().right_kv().ok()?;
736 handle: kv.forget_node_type(),
738 alloc: (*map.alloc).clone(),
739 _marker: PhantomData,
743 /// Removes and returns the first element in the map.
744 /// The key of this element is the minimum key that was in the map.
748 /// Draining elements in ascending order, while keeping a usable map each iteration.
751 /// #![feature(map_first_last)]
752 /// use std::collections::BTreeMap;
754 /// let mut map = BTreeMap::new();
755 /// map.insert(1, "a");
756 /// map.insert(2, "b");
757 /// while let Some((key, _val)) = map.pop_first() {
758 /// assert!(map.iter().all(|(k, _v)| *k > key));
760 /// assert!(map.is_empty());
762 #[unstable(feature = "map_first_last", issue = "62924")]
763 pub fn pop_first(&mut self) -> Option<(K, V)>
767 self.first_entry().map(|entry| entry.remove_entry())
770 /// Returns the last key-value pair in the map.
771 /// The key in this pair is the maximum key in the map.
778 /// #![feature(map_first_last)]
779 /// use std::collections::BTreeMap;
781 /// let mut map = BTreeMap::new();
782 /// map.insert(1, "b");
783 /// map.insert(2, "a");
784 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
786 #[unstable(feature = "map_first_last", issue = "62924")]
787 pub fn last_key_value(&self) -> Option<(&K, &V)>
791 let root_node = self.root.as_ref()?.reborrow();
792 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
795 /// Returns the last entry in the map for in-place manipulation.
796 /// The key of this entry is the maximum key in the map.
801 /// #![feature(map_first_last)]
802 /// use std::collections::BTreeMap;
804 /// let mut map = BTreeMap::new();
805 /// map.insert(1, "a");
806 /// map.insert(2, "b");
807 /// if let Some(mut entry) = map.last_entry() {
808 /// if *entry.key() > 0 {
809 /// entry.insert("last");
812 /// assert_eq!(*map.get(&1).unwrap(), "a");
813 /// assert_eq!(*map.get(&2).unwrap(), "last");
815 #[unstable(feature = "map_first_last", issue = "62924")]
816 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
820 let (map, dormant_map) = DormantMutRef::new(self);
821 let root_node = map.root.as_mut()?.borrow_mut();
822 let kv = root_node.last_leaf_edge().left_kv().ok()?;
824 handle: kv.forget_node_type(),
826 alloc: (*map.alloc).clone(),
827 _marker: PhantomData,
831 /// Removes and returns the last element in the map.
832 /// The key of this element is the maximum key that was in the map.
836 /// Draining elements in descending order, while keeping a usable map each iteration.
839 /// #![feature(map_first_last)]
840 /// use std::collections::BTreeMap;
842 /// let mut map = BTreeMap::new();
843 /// map.insert(1, "a");
844 /// map.insert(2, "b");
845 /// while let Some((key, _val)) = map.pop_last() {
846 /// assert!(map.iter().all(|(k, _v)| *k < key));
848 /// assert!(map.is_empty());
850 #[unstable(feature = "map_first_last", issue = "62924")]
851 pub fn pop_last(&mut self) -> Option<(K, V)>
855 self.last_entry().map(|entry| entry.remove_entry())
858 /// Returns `true` if the map contains a value for the specified key.
860 /// The key may be any borrowed form of the map's key type, but the ordering
861 /// on the borrowed form *must* match the ordering on the key type.
868 /// use std::collections::BTreeMap;
870 /// let mut map = BTreeMap::new();
871 /// map.insert(1, "a");
872 /// assert_eq!(map.contains_key(&1), true);
873 /// assert_eq!(map.contains_key(&2), false);
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
881 self.get(key).is_some()
884 /// Returns a mutable reference to the value corresponding to the key.
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 /// if let Some(x) = map.get_mut(&1) {
901 /// assert_eq!(map[&1], "b");
903 // See `get` for implementation notes, this is basically a copy-paste with mut's added
904 #[stable(feature = "rust1", since = "1.0.0")]
905 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
910 let root_node = self.root.as_mut()?.borrow_mut();
911 match root_node.search_tree(key) {
912 Found(handle) => Some(handle.into_val_mut()),
917 /// Inserts a key-value pair into the map.
919 /// If the map did not have this key present, `None` is returned.
921 /// If the map did have this key present, the value is updated, and the old
922 /// value is returned. The key is not updated, though; this matters for
923 /// types that can be `==` without being identical. See the [module-level
924 /// documentation] for more.
926 /// [module-level documentation]: index.html#insert-and-complex-keys
933 /// use std::collections::BTreeMap;
935 /// let mut map = BTreeMap::new();
936 /// assert_eq!(map.insert(37, "a"), None);
937 /// assert_eq!(map.is_empty(), false);
939 /// map.insert(37, "b");
940 /// assert_eq!(map.insert(37, "c"), Some("b"));
941 /// assert_eq!(map[&37], "c");
943 #[stable(feature = "rust1", since = "1.0.0")]
944 pub fn insert(&mut self, key: K, value: V) -> Option<V>
948 match self.entry(key) {
949 Occupied(mut entry) => Some(entry.insert(value)),
957 /// Tries to insert a key-value pair into the map, and returns
958 /// a mutable reference to the value in the entry.
960 /// If the map already had this key present, nothing is updated, and
961 /// an error containing the occupied entry and the value is returned.
968 /// #![feature(map_try_insert)]
970 /// use std::collections::BTreeMap;
972 /// let mut map = BTreeMap::new();
973 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
975 /// let err = map.try_insert(37, "b").unwrap_err();
976 /// assert_eq!(err.entry.key(), &37);
977 /// assert_eq!(err.entry.get(), &"a");
978 /// assert_eq!(err.value, "b");
980 #[unstable(feature = "map_try_insert", issue = "82766")]
981 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
985 match self.entry(key) {
986 Occupied(entry) => Err(OccupiedError { entry, value }),
987 Vacant(entry) => Ok(entry.insert(value)),
991 /// Removes a key from the map, returning the value at the key if the key
992 /// was previously in the map.
994 /// The key may be any borrowed form of the map's key type, but the ordering
995 /// on the borrowed form *must* match the ordering on the key type.
1002 /// use std::collections::BTreeMap;
1004 /// let mut map = BTreeMap::new();
1005 /// map.insert(1, "a");
1006 /// assert_eq!(map.remove(&1), Some("a"));
1007 /// assert_eq!(map.remove(&1), None);
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1015 self.remove_entry(key).map(|(_, v)| v)
1018 /// Removes a key from the map, returning the stored key and value if the key
1019 /// was previously in the map.
1021 /// The key may be any borrowed form of the map's key type, but the ordering
1022 /// on the borrowed form *must* match the ordering on the key type.
1029 /// use std::collections::BTreeMap;
1031 /// let mut map = BTreeMap::new();
1032 /// map.insert(1, "a");
1033 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1034 /// assert_eq!(map.remove_entry(&1), None);
1036 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1037 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1042 let (map, dormant_map) = DormantMutRef::new(self);
1043 let root_node = map.root.as_mut()?.borrow_mut();
1044 match root_node.search_tree(key) {
1045 Found(handle) => Some(
1049 alloc: (*map.alloc).clone(),
1050 _marker: PhantomData,
1058 /// Retains only the elements specified by the predicate.
1060 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1061 /// The elements are visited in ascending key order.
1066 /// use std::collections::BTreeMap;
1068 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1069 /// // Keep only the elements with even-numbered keys.
1070 /// map.retain(|&k, _| k % 2 == 0);
1071 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1074 #[stable(feature = "btree_retain", since = "1.53.0")]
1075 pub fn retain<F>(&mut self, mut f: F)
1078 F: FnMut(&K, &mut V) -> bool,
1080 self.drain_filter(|k, v| !f(k, v));
1083 /// Moves all elements from `other` into `self`, leaving `other` empty.
1088 /// use std::collections::BTreeMap;
1090 /// let mut a = BTreeMap::new();
1091 /// a.insert(1, "a");
1092 /// a.insert(2, "b");
1093 /// a.insert(3, "c");
1095 /// let mut b = BTreeMap::new();
1096 /// b.insert(3, "d");
1097 /// b.insert(4, "e");
1098 /// b.insert(5, "f");
1100 /// a.append(&mut b);
1102 /// assert_eq!(a.len(), 5);
1103 /// assert_eq!(b.len(), 0);
1105 /// assert_eq!(a[&1], "a");
1106 /// assert_eq!(a[&2], "b");
1107 /// assert_eq!(a[&3], "d");
1108 /// assert_eq!(a[&4], "e");
1109 /// assert_eq!(a[&5], "f");
1111 #[stable(feature = "btree_append", since = "1.11.0")]
1112 pub fn append(&mut self, other: &mut Self)
1117 // Do we have to append anything at all?
1118 if other.is_empty() {
1122 // We can just swap `self` and `other` if `self` is empty.
1123 if self.is_empty() {
1124 mem::swap(self, other);
1128 let self_iter = mem::replace(self, Self::new_in((*self.alloc).clone())).into_iter();
1129 let other_iter = mem::replace(other, Self::new_in((*self.alloc).clone())).into_iter();
1130 let root = self.root.get_or_insert_with(|| Root::new((*self.alloc).clone()));
1131 root.append_from_sorted_iters(
1135 (*self.alloc).clone(),
1139 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1140 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1141 /// yield elements from min (inclusive) to max (exclusive).
1142 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1143 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1144 /// range from 4 to 10.
1148 /// Panics if range `start > end`.
1149 /// Panics if range `start == end` and both bounds are `Excluded`.
1156 /// use std::collections::BTreeMap;
1157 /// use std::ops::Bound::Included;
1159 /// let mut map = BTreeMap::new();
1160 /// map.insert(3, "a");
1161 /// map.insert(5, "b");
1162 /// map.insert(8, "c");
1163 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1164 /// println!("{key}: {value}");
1166 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1168 #[stable(feature = "btree_range", since = "1.17.0")]
1169 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1175 if let Some(root) = &self.root {
1176 Range { inner: root.reborrow().range_search(range) }
1178 Range { inner: LeafRange::none() }
1182 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1183 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1184 /// yield elements from min (inclusive) to max (exclusive).
1185 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1186 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1187 /// range from 4 to 10.
1191 /// Panics if range `start > end`.
1192 /// Panics if range `start == end` and both bounds are `Excluded`.
1199 /// use std::collections::BTreeMap;
1201 /// let mut map: BTreeMap<&str, i32> =
1202 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1203 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1204 /// *balance += 100;
1206 /// for (name, balance) in &map {
1207 /// println!("{name} => {balance}");
1210 #[stable(feature = "btree_range", since = "1.17.0")]
1211 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1217 if let Some(root) = &mut self.root {
1218 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1220 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1224 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1231 /// use std::collections::BTreeMap;
1233 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1235 /// // count the number of occurrences of letters in the vec
1236 /// for x in ["a", "b", "a", "c", "a", "b"] {
1237 /// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1240 /// assert_eq!(count["a"], 3);
1241 /// assert_eq!(count["b"], 2);
1242 /// assert_eq!(count["c"], 1);
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1249 let (map, dormant_map) = DormantMutRef::new(self);
1251 None => Vacant(VacantEntry {
1255 alloc: (*map.alloc).clone(),
1256 _marker: PhantomData,
1258 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1259 Found(handle) => Occupied(OccupiedEntry {
1262 alloc: (*map.alloc).clone(),
1263 _marker: PhantomData,
1265 GoDown(handle) => Vacant(VacantEntry {
1267 handle: Some(handle),
1269 alloc: (*map.alloc).clone(),
1270 _marker: PhantomData,
1276 /// Splits the collection into two at the given key. Returns everything after the given key,
1277 /// including the key.
1284 /// use std::collections::BTreeMap;
1286 /// let mut a = BTreeMap::new();
1287 /// a.insert(1, "a");
1288 /// a.insert(2, "b");
1289 /// a.insert(3, "c");
1290 /// a.insert(17, "d");
1291 /// a.insert(41, "e");
1293 /// let b = a.split_off(&3);
1295 /// assert_eq!(a.len(), 2);
1296 /// assert_eq!(b.len(), 3);
1298 /// assert_eq!(a[&1], "a");
1299 /// assert_eq!(a[&2], "b");
1301 /// assert_eq!(b[&3], "c");
1302 /// assert_eq!(b[&17], "d");
1303 /// assert_eq!(b[&41], "e");
1305 #[stable(feature = "btree_split_off", since = "1.11.0")]
1306 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1311 if self.is_empty() {
1312 return Self::new_in((*self.alloc).clone());
1315 let total_num = self.len();
1316 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1318 let right_root = left_root.split_off(key, (*self.alloc).clone());
1320 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1321 self.length = new_left_len;
1323 BTreeMap { root: Some(right_root), length: right_len, alloc: self.alloc.clone() }
1326 /// Creates an iterator that visits all elements (key-value pairs) in
1327 /// ascending key order and uses a closure to determine if an element should
1328 /// be removed. If the closure returns `true`, the element is removed from
1329 /// the map and yielded. If the closure returns `false`, or panics, the
1330 /// element remains in the map and will not be yielded.
1332 /// The iterator also lets you mutate the value of each element in the
1333 /// closure, regardless of whether you choose to keep or remove it.
1335 /// If the iterator is only partially consumed or not consumed at all, each
1336 /// of the remaining elements is still subjected to the closure, which may
1337 /// change its value and, by returning `true`, have the element removed and
1340 /// It is unspecified how many more elements will be subjected to the
1341 /// closure if a panic occurs in the closure, or a panic occurs while
1342 /// dropping an element, or if the `DrainFilter` value is leaked.
1346 /// Splitting a map into even and odd keys, reusing the original map:
1349 /// #![feature(btree_drain_filter)]
1350 /// use std::collections::BTreeMap;
1352 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1353 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1355 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1356 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1358 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1359 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F, A>
1362 F: FnMut(&K, &mut V) -> bool,
1364 let (inner, alloc) = self.drain_filter_inner();
1365 DrainFilter { pred, inner, alloc }
1368 pub(super) fn drain_filter_inner(&mut self) -> (DrainFilterInner<'_, K, V>, A)
1372 if let Some(root) = self.root.as_mut() {
1373 let (root, dormant_root) = DormantMutRef::new(root);
1374 let front = root.borrow_mut().first_leaf_edge();
1377 length: &mut self.length,
1378 dormant_root: Some(dormant_root),
1379 cur_leaf_edge: Some(front),
1381 (*self.alloc).clone(),
1386 length: &mut self.length,
1388 cur_leaf_edge: None,
1390 (*self.alloc).clone(),
1395 /// Creates a consuming iterator visiting all the keys, in sorted order.
1396 /// The map cannot be used after calling this.
1397 /// The iterator element type is `K`.
1402 /// use std::collections::BTreeMap;
1404 /// let mut a = BTreeMap::new();
1405 /// a.insert(2, "b");
1406 /// a.insert(1, "a");
1408 /// let keys: Vec<i32> = a.into_keys().collect();
1409 /// assert_eq!(keys, [1, 2]);
1412 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1413 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1414 IntoKeys { inner: self.into_iter() }
1417 /// Creates a consuming iterator visiting all the values, in order by key.
1418 /// The map cannot be used after calling this.
1419 /// The iterator element type is `V`.
1424 /// use std::collections::BTreeMap;
1426 /// let mut a = BTreeMap::new();
1427 /// a.insert(1, "hello");
1428 /// a.insert(2, "goodbye");
1430 /// let values: Vec<&str> = a.into_values().collect();
1431 /// assert_eq!(values, ["hello", "goodbye"]);
1434 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1435 pub fn into_values(self) -> IntoValues<K, V, A> {
1436 IntoValues { inner: self.into_iter() }
1439 /// Makes a `BTreeMap` from a sorted iterator.
1440 pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1443 I: IntoIterator<Item = (K, V)>,
1445 let mut root = Root::new(alloc.clone());
1447 root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1448 BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc) }
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, A> {
1454 type Item = (&'a K, &'a V);
1455 type IntoIter = Iter<'a, K, V>;
1457 fn into_iter(self) -> Iter<'a, K, V> {
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1464 type Item = (&'a K, &'a V);
1466 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1467 if self.length == 0 {
1471 Some(unsafe { self.range.next_unchecked() })
1475 fn size_hint(&self) -> (usize, Option<usize>) {
1476 (self.length, Some(self.length))
1479 fn last(mut self) -> Option<(&'a K, &'a V)> {
1483 fn min(mut self) -> Option<(&'a K, &'a V)> {
1487 fn max(mut self) -> Option<(&'a K, &'a V)> {
1492 #[stable(feature = "fused", since = "1.26.0")]
1493 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1497 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1498 if self.length == 0 {
1502 Some(unsafe { self.range.next_back_unchecked() })
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1509 fn len(&self) -> usize {
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<K, V> Clone for Iter<'_, K, V> {
1516 fn clone(&self) -> Self {
1517 Iter { range: self.range.clone(), length: self.length }
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1523 type Item = (&'a K, &'a mut V);
1524 type IntoIter = IterMut<'a, K, V>;
1526 fn into_iter(self) -> IterMut<'a, K, V> {
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1533 type Item = (&'a K, &'a mut V);
1535 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1536 if self.length == 0 {
1540 Some(unsafe { self.range.next_unchecked() })
1544 fn size_hint(&self) -> (usize, Option<usize>) {
1545 (self.length, Some(self.length))
1548 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1552 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1556 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1563 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1564 if self.length == 0 {
1568 Some(unsafe { self.range.next_back_unchecked() })
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1575 fn len(&self) -> usize {
1580 #[stable(feature = "fused", since = "1.26.0")]
1581 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1583 impl<'a, K, V> IterMut<'a, K, V> {
1584 /// Returns an iterator of references over the remaining items.
1586 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1587 Iter { range: self.range.reborrow(), length: self.length }
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<K, V, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, A> {
1594 type IntoIter = IntoIter<K, V, A>;
1596 fn into_iter(self) -> IntoIter<K, V, A> {
1597 let mut me = ManuallyDrop::new(self);
1598 if let Some(root) = me.root.take() {
1599 let full_range = root.into_dying().full_range();
1604 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1608 range: LazyLeafRange::none(),
1610 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1616 #[stable(feature = "btree_drop", since = "1.7.0")]
1617 impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1618 fn drop(&mut self) {
1619 struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1621 impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1622 fn drop(&mut self) {
1623 // Continue the same loop we perform below. This only runs when unwinding, so we
1624 // don't have to care about panics this time (they'll abort).
1625 while let Some(kv) = self.0.dying_next() {
1626 // SAFETY: we consume the dying handle immediately.
1627 unsafe { kv.drop_key_val() };
1632 while let Some(kv) = self.dying_next() {
1633 let guard = DropGuard(self);
1634 // SAFETY: we don't touch the tree before consuming the dying handle.
1635 unsafe { kv.drop_key_val() };
1641 impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1642 /// Core of a `next` method returning a dying KV handle,
1643 /// invalidated by further calls to this function and some others.
1646 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1647 if self.length == 0 {
1648 self.range.deallocating_end(self.alloc.clone());
1652 Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1656 /// Core of a `next_back` method returning a dying KV handle,
1657 /// invalidated by further calls to this function and some others.
1660 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1661 if self.length == 0 {
1662 self.range.deallocating_end(self.alloc.clone());
1666 Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1675 fn next(&mut self) -> Option<(K, V)> {
1676 // SAFETY: we consume the dying handle immediately.
1677 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1680 fn size_hint(&self) -> (usize, Option<usize>) {
1681 (self.length, Some(self.length))
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1687 fn next_back(&mut self) -> Option<(K, V)> {
1688 // SAFETY: we consume the dying handle immediately.
1689 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1693 #[stable(feature = "rust1", since = "1.0.0")]
1694 impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1695 fn len(&self) -> usize {
1700 #[stable(feature = "fused", since = "1.26.0")]
1701 impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1707 fn next(&mut self) -> Option<&'a K> {
1708 self.inner.next().map(|(k, _)| k)
1711 fn size_hint(&self) -> (usize, Option<usize>) {
1712 self.inner.size_hint()
1715 fn last(mut self) -> Option<&'a K> {
1719 fn min(mut self) -> Option<&'a K> {
1723 fn max(mut self) -> Option<&'a K> {
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1730 fn next_back(&mut self) -> Option<&'a K> {
1731 self.inner.next_back().map(|(k, _)| k)
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1737 fn len(&self) -> usize {
1742 #[stable(feature = "fused", since = "1.26.0")]
1743 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1745 #[stable(feature = "rust1", since = "1.0.0")]
1746 impl<K, V> Clone for Keys<'_, K, V> {
1747 fn clone(&self) -> Self {
1748 Keys { inner: self.inner.clone() }
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl<'a, K, V> Iterator for Values<'a, K, V> {
1756 fn next(&mut self) -> Option<&'a V> {
1757 self.inner.next().map(|(_, v)| v)
1760 fn size_hint(&self) -> (usize, Option<usize>) {
1761 self.inner.size_hint()
1764 fn last(mut self) -> Option<&'a V> {
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1771 fn next_back(&mut self) -> Option<&'a V> {
1772 self.inner.next_back().map(|(_, v)| v)
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1778 fn len(&self) -> usize {
1783 #[stable(feature = "fused", since = "1.26.0")]
1784 impl<K, V> FusedIterator for Values<'_, K, V> {}
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 impl<K, V> Clone for Values<'_, K, V> {
1788 fn clone(&self) -> Self {
1789 Values { inner: self.inner.clone() }
1793 /// An iterator produced by calling `drain_filter` on BTreeMap.
1794 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1795 pub struct DrainFilter<
1800 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
1802 F: 'a + FnMut(&K, &mut V) -> bool,
1805 inner: DrainFilterInner<'a, K, V>,
1806 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1809 /// Most of the implementation of DrainFilter are generic over the type
1810 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1811 pub(super) struct DrainFilterInner<'a, K, V> {
1812 /// Reference to the length field in the borrowed map, updated live.
1813 length: &'a mut usize,
1814 /// Buried reference to the root field in the borrowed map.
1815 /// Wrapped in `Option` to allow drop handler to `take` it.
1816 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1817 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1818 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1819 /// or if a panic occurred in the predicate.
1820 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1823 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1824 impl<K, V, F, A: Allocator + Clone> Drop for DrainFilter<'_, K, V, F, A>
1826 F: FnMut(&K, &mut V) -> bool,
1828 fn drop(&mut self) {
1829 self.for_each(drop);
1833 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1834 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1838 F: FnMut(&K, &mut V) -> bool,
1840 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1841 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1845 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1846 impl<K, V, F, A: Allocator + Clone> Iterator for DrainFilter<'_, K, V, F, A>
1848 F: FnMut(&K, &mut V) -> bool,
1852 fn next(&mut self) -> Option<(K, V)> {
1853 self.inner.next(&mut self.pred, self.alloc.clone())
1856 fn size_hint(&self) -> (usize, Option<usize>) {
1857 self.inner.size_hint()
1861 impl<'a, K, V> DrainFilterInner<'a, K, V> {
1862 /// Allow Debug implementations to predict the next element.
1863 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1864 let edge = self.cur_leaf_edge.as_ref()?;
1865 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1868 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1869 pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
1871 F: FnMut(&K, &mut V) -> bool,
1873 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1874 let (k, v) = kv.kv_mut();
1877 let (kv, pos) = kv.remove_kv_tracking(
1879 // SAFETY: we will touch the root in a way that will not
1880 // invalidate the position returned.
1881 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1882 root.pop_internal_level(alloc.clone());
1883 self.dormant_root = Some(DormantMutRef::new(root).1);
1887 self.cur_leaf_edge = Some(pos);
1890 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1895 /// Implementation of a typical `DrainFilter::size_hint` method.
1896 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1897 // In most of the btree iterators, `self.length` is the number of elements
1898 // yet to be visited. Here, it includes elements that were visited and that
1899 // the predicate decided not to drain. Making this upper bound more tight
1900 // during iteration would require an extra field.
1901 (0, Some(*self.length))
1905 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1906 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1908 #[stable(feature = "btree_range", since = "1.17.0")]
1909 impl<'a, K, V> Iterator for Range<'a, K, V> {
1910 type Item = (&'a K, &'a V);
1912 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1913 self.inner.next_checked()
1916 fn last(mut self) -> Option<(&'a K, &'a V)> {
1920 fn min(mut self) -> Option<(&'a K, &'a V)> {
1924 fn max(mut self) -> Option<(&'a K, &'a V)> {
1929 #[stable(feature = "map_values_mut", since = "1.10.0")]
1930 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1931 type Item = &'a mut V;
1933 fn next(&mut self) -> Option<&'a mut V> {
1934 self.inner.next().map(|(_, v)| v)
1937 fn size_hint(&self) -> (usize, Option<usize>) {
1938 self.inner.size_hint()
1941 fn last(mut self) -> Option<&'a mut V> {
1946 #[stable(feature = "map_values_mut", since = "1.10.0")]
1947 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1948 fn next_back(&mut self) -> Option<&'a mut V> {
1949 self.inner.next_back().map(|(_, v)| v)
1953 #[stable(feature = "map_values_mut", since = "1.10.0")]
1954 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1955 fn len(&self) -> usize {
1960 #[stable(feature = "fused", since = "1.26.0")]
1961 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1963 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1964 impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
1967 fn next(&mut self) -> Option<K> {
1968 self.inner.next().map(|(k, _)| k)
1971 fn size_hint(&self) -> (usize, Option<usize>) {
1972 self.inner.size_hint()
1975 fn last(mut self) -> Option<K> {
1979 fn min(mut self) -> Option<K> {
1983 fn max(mut self) -> Option<K> {
1988 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1989 impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
1990 fn next_back(&mut self) -> Option<K> {
1991 self.inner.next_back().map(|(k, _)| k)
1995 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1996 impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
1997 fn len(&self) -> usize {
2002 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2003 impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2005 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2006 impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2009 fn next(&mut self) -> Option<V> {
2010 self.inner.next().map(|(_, v)| v)
2013 fn size_hint(&self) -> (usize, Option<usize>) {
2014 self.inner.size_hint()
2017 fn last(mut self) -> Option<V> {
2022 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2023 impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2024 fn next_back(&mut self) -> Option<V> {
2025 self.inner.next_back().map(|(_, v)| v)
2029 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2030 impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2031 fn len(&self) -> usize {
2036 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2037 impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2039 #[stable(feature = "btree_range", since = "1.17.0")]
2040 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2041 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2042 self.inner.next_back_checked()
2046 #[stable(feature = "fused", since = "1.26.0")]
2047 impl<K, V> FusedIterator for Range<'_, K, V> {}
2049 #[stable(feature = "btree_range", since = "1.17.0")]
2050 impl<K, V> Clone for Range<'_, K, V> {
2051 fn clone(&self) -> Self {
2052 Range { inner: self.inner.clone() }
2056 #[stable(feature = "btree_range", since = "1.17.0")]
2057 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2058 type Item = (&'a K, &'a mut V);
2060 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2061 self.inner.next_checked()
2064 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2068 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
2072 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
2077 #[stable(feature = "btree_range", since = "1.17.0")]
2078 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2079 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2080 self.inner.next_back_checked()
2084 #[stable(feature = "fused", since = "1.26.0")]
2085 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2089 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2090 let mut inputs: Vec<_> = iter.into_iter().collect();
2092 if inputs.is_empty() {
2093 return BTreeMap::new();
2096 // use stable sort to preserve the insertion order.
2097 inputs.sort_by(|a, b| a.0.cmp(&b.0));
2098 BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 impl<K: Ord, V, A: Allocator + Clone> Extend<(K, V)> for BTreeMap<K, V, A> {
2105 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2106 iter.into_iter().for_each(move |(k, v)| {
2112 fn extend_one(&mut self, (k, v): (K, V)) {
2117 #[stable(feature = "extend_ref", since = "1.2.0")]
2118 impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)>
2119 for BTreeMap<K, V, A>
2121 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2122 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2126 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 impl<K: Hash, V: Hash, A: Allocator + Clone> Hash for BTreeMap<K, V, A> {
2133 fn hash<H: Hasher>(&self, state: &mut H) {
2134 state.write_length_prefix(self.len());
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 impl<K, V> Default for BTreeMap<K, V> {
2143 /// Creates an empty `BTreeMap`.
2144 fn default() -> BTreeMap<K, V> {
2149 #[stable(feature = "rust1", since = "1.0.0")]
2150 impl<K: PartialEq, V: PartialEq, A: Allocator + Clone> PartialEq for BTreeMap<K, V, A> {
2151 fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2152 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<K: Eq, V: Eq, A: Allocator + Clone> Eq for BTreeMap<K, V, A> {}
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 impl<K: PartialOrd, V: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, A> {
2162 fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2163 self.iter().partial_cmp(other.iter())
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl<K: Ord, V: Ord, A: Allocator + Clone> Ord for BTreeMap<K, V, A> {
2170 fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2171 self.iter().cmp(other.iter())
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for BTreeMap<K, V, A> {
2177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2178 f.debug_map().entries(self.iter()).finish()
2182 #[stable(feature = "rust1", since = "1.0.0")]
2183 impl<K, Q: ?Sized, V, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, A>
2190 /// Returns a reference to the value corresponding to the supplied key.
2194 /// Panics if the key is not present in the `BTreeMap`.
2196 fn index(&self, key: &Q) -> &V {
2197 self.get(key).expect("no entry found for key")
2201 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
2202 impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2203 /// Converts a `[(K, V); N]` into a `BTreeMap<(K, V)>`.
2206 /// use std::collections::BTreeMap;
2208 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2209 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2210 /// assert_eq!(map1, map2);
2212 fn from(mut arr: [(K, V); N]) -> Self {
2214 return BTreeMap::new();
2217 // use stable sort to preserve the insertion order.
2218 arr.sort_by(|a, b| a.0.cmp(&b.0));
2219 BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2223 impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
2224 /// Gets an iterator over the entries of the map, sorted by key.
2231 /// use std::collections::BTreeMap;
2233 /// let mut map = BTreeMap::new();
2234 /// map.insert(3, "c");
2235 /// map.insert(2, "b");
2236 /// map.insert(1, "a");
2238 /// for (key, value) in map.iter() {
2239 /// println!("{key}: {value}");
2242 /// let (first_key, first_value) = map.iter().next().unwrap();
2243 /// assert_eq!((*first_key, *first_value), (1, "a"));
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 pub fn iter(&self) -> Iter<'_, K, V> {
2247 if let Some(root) = &self.root {
2248 let full_range = root.reborrow().full_range();
2250 Iter { range: full_range, length: self.length }
2252 Iter { range: LazyLeafRange::none(), length: 0 }
2256 /// Gets a mutable iterator over the entries of the map, sorted by key.
2263 /// use std::collections::BTreeMap;
2265 /// let mut map = BTreeMap::from([
2271 /// // add 10 to the value if the key isn't "a"
2272 /// for (key, value) in map.iter_mut() {
2273 /// if key != &"a" {
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2280 if let Some(root) = &mut self.root {
2281 let full_range = root.borrow_valmut().full_range();
2283 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2285 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2289 /// Gets an iterator over the keys of the map, in sorted order.
2296 /// use std::collections::BTreeMap;
2298 /// let mut a = BTreeMap::new();
2299 /// a.insert(2, "b");
2300 /// a.insert(1, "a");
2302 /// let keys: Vec<_> = a.keys().cloned().collect();
2303 /// assert_eq!(keys, [1, 2]);
2305 #[stable(feature = "rust1", since = "1.0.0")]
2306 pub fn keys(&self) -> Keys<'_, K, V> {
2307 Keys { inner: self.iter() }
2310 /// Gets an iterator over the values of the map, in order by key.
2317 /// use std::collections::BTreeMap;
2319 /// let mut a = BTreeMap::new();
2320 /// a.insert(1, "hello");
2321 /// a.insert(2, "goodbye");
2323 /// let values: Vec<&str> = a.values().cloned().collect();
2324 /// assert_eq!(values, ["hello", "goodbye"]);
2326 #[stable(feature = "rust1", since = "1.0.0")]
2327 pub fn values(&self) -> Values<'_, K, V> {
2328 Values { inner: self.iter() }
2331 /// Gets a mutable iterator over the values of the map, in order by key.
2338 /// use std::collections::BTreeMap;
2340 /// let mut a = BTreeMap::new();
2341 /// a.insert(1, String::from("hello"));
2342 /// a.insert(2, String::from("goodbye"));
2344 /// for value in a.values_mut() {
2345 /// value.push_str("!");
2348 /// let values: Vec<String> = a.values().cloned().collect();
2349 /// assert_eq!(values, [String::from("hello!"),
2350 /// String::from("goodbye!")]);
2352 #[stable(feature = "map_values_mut", since = "1.10.0")]
2353 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2354 ValuesMut { inner: self.iter_mut() }
2357 /// Returns the number of elements in the map.
2364 /// use std::collections::BTreeMap;
2366 /// let mut a = BTreeMap::new();
2367 /// assert_eq!(a.len(), 0);
2368 /// a.insert(1, "a");
2369 /// assert_eq!(a.len(), 1);
2372 #[stable(feature = "rust1", since = "1.0.0")]
2373 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2374 pub const fn len(&self) -> usize {
2378 /// Returns `true` if the map contains no elements.
2385 /// use std::collections::BTreeMap;
2387 /// let mut a = BTreeMap::new();
2388 /// assert!(a.is_empty());
2389 /// a.insert(1, "a");
2390 /// assert!(!a.is_empty());
2393 #[stable(feature = "rust1", since = "1.0.0")]
2394 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2395 pub const fn is_empty(&self) -> bool {