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::*;
22 #[stable(feature = "rust1", since = "1.0.0")]
23 pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
27 /// Minimum number of elements in a node that is not a root.
28 /// We might temporarily have fewer elements during methods.
29 pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
31 // A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
32 // - Keys must appear in ascending order (according to the key's type).
33 // - Every non-leaf node contains at least 1 element (has at least 2 children).
34 // - Every non-root node contains at least MIN_LEN elements.
36 // An empty map is represented either by the absence of a root node or by a
37 // root node that is an empty leaf.
39 /// An ordered map based on a [B-Tree].
41 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
42 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
43 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
44 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
45 /// is done is *very* inefficient for modern computer architectures. In particular, every element
46 /// is stored in its own individually heap-allocated node. This means that every single insertion
47 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
48 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
51 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
52 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
53 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
54 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
55 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
56 /// the node using binary search. As a compromise, one could also perform a linear search
57 /// that initially only checks every i<sup>th</sup> element for some choice of i.
59 /// Currently, our implementation simply performs naive linear search. This provides excellent
60 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
61 /// would like to further explore choosing the optimal search strategy based on the choice of B,
62 /// and possibly other factors. Using linear search, searching for a random element is expected
63 /// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
64 /// however, performance is excellent.
66 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
67 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
68 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
69 /// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
70 /// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
71 /// include panics, incorrect results, aborts, memory leaks, and non-termination.
73 /// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::values`], or
74 /// [`BTreeMap::keys`] produce their items in order by key, and take worst-case logarithmic and
75 /// amortized constant time per item returned.
77 /// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
78 /// [`Cell`]: core::cell::Cell
79 /// [`RefCell`]: core::cell::RefCell
84 /// use std::collections::BTreeMap;
86 /// // type inference lets us omit an explicit type signature (which
87 /// // would be `BTreeMap<&str, &str>` in this example).
88 /// let mut movie_reviews = BTreeMap::new();
90 /// // review some movies.
91 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
92 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
93 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
94 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
96 /// // check for a specific one.
97 /// if !movie_reviews.contains_key("Les Misérables") {
98 /// println!("We've got {} reviews, but Les Misérables ain't one.",
99 /// movie_reviews.len());
102 /// // oops, this review has a lot of spelling mistakes, let's delete it.
103 /// movie_reviews.remove("The Blues Brothers");
105 /// // look up the values associated with some keys.
106 /// let to_find = ["Up!", "Office Space"];
107 /// for movie in &to_find {
108 /// match movie_reviews.get(movie) {
109 /// Some(review) => println!("{movie}: {review}"),
110 /// None => println!("{movie} is unreviewed.")
114 /// // Look up the value for a key (will panic if the key is not found).
115 /// println!("Movie review: {}", movie_reviews["Office Space"]);
117 /// // iterate over everything.
118 /// for (movie, review) in &movie_reviews {
119 /// println!("{movie}: \"{review}\"");
123 /// A `BTreeMap` with a known list of items can be initialized from an array:
126 /// use std::collections::BTreeMap;
128 /// let solar_distance = BTreeMap::from([
129 /// ("Mercury", 0.4),
136 /// `BTreeMap` implements an [`Entry API`], which allows for complex
137 /// methods of getting, setting, updating and removing keys and their values:
139 /// [`Entry API`]: BTreeMap::entry
142 /// use std::collections::BTreeMap;
144 /// // type inference lets us omit an explicit type signature (which
145 /// // would be `BTreeMap<&str, u8>` in this example).
146 /// let mut player_stats = BTreeMap::new();
148 /// fn random_stat_buff() -> u8 {
149 /// // could actually return some random value here - let's just return
150 /// // some fixed value for now
154 /// // insert a key only if it doesn't already exist
155 /// player_stats.entry("health").or_insert(100);
157 /// // insert a key using a function that provides a new value only if it
158 /// // doesn't already exist
159 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
161 /// // update a key, guarding against the key possibly not being set
162 /// let stat = player_stats.entry("attack").or_insert(100);
163 /// *stat += random_stat_buff();
165 #[stable(feature = "rust1", since = "1.0.0")]
166 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
167 #[rustc_insignificant_dtor]
171 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
173 root: Option<Root<K, V>>,
175 pub(super) alloc: ManuallyDrop<A>,
178 #[stable(feature = "btree_drop", since = "1.7.0")]
179 unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator> Drop for BTreeMap<K, V, A> {
181 drop(unsafe { ptr::read(self) }.into_iter())
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl<K: Clone, V: Clone, A: Clone + Allocator> Clone for BTreeMap<K, V, A> {
187 fn clone(&self) -> BTreeMap<K, V, A> {
188 fn clone_subtree<'a, K: Clone, V: Clone, A: Clone + Allocator>(
189 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
191 ) -> BTreeMap<K, V, A>
198 let mut out_tree = BTreeMap {
199 root: Some(Root::new(alloc)),
201 alloc: ManuallyDrop::new((*alloc).clone()),
205 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
206 let mut out_node = match root.borrow_mut().force() {
208 Internal(_) => unreachable!(),
211 let mut in_edge = leaf.first_edge();
212 while let Ok(kv) = in_edge.right_kv() {
213 let (k, v) = kv.into_kv();
214 in_edge = kv.right_edge();
216 out_node.push(k.clone(), v.clone());
217 out_tree.length += 1;
223 Internal(internal) => {
224 let mut out_tree = clone_subtree(internal.first_edge().descend(), alloc);
227 let out_root = out_tree.root.as_mut().unwrap();
228 let mut out_node = out_root.push_internal_level(alloc);
229 let mut in_edge = internal.first_edge();
230 while let Ok(kv) = in_edge.right_kv() {
231 let (k, v) = kv.into_kv();
232 in_edge = kv.right_edge();
234 let k = (*k).clone();
235 let v = (*v).clone();
236 let subtree = clone_subtree(in_edge.descend(), alloc);
238 // We can't destructure subtree directly
239 // because BTreeMap implements Drop
240 let (subroot, sublength) = unsafe {
241 let subtree = ManuallyDrop::new(subtree);
242 let root = ptr::read(&subtree.root);
243 let length = subtree.length;
247 out_node.push(k, v, subroot.unwrap_or_else(|| Root::new(alloc)));
248 out_tree.length += 1 + sublength;
258 BTreeMap::new_in(ManuallyDrop::into_inner(self.alloc.clone()))
260 clone_subtree(self.root.as_ref().unwrap().reborrow(), &*self.alloc) // unwrap succeeds because not empty
265 impl<K, Q: ?Sized, A: Allocator> super::Recover<Q> for BTreeMap<K, (), A>
272 fn get(&self, key: &Q) -> Option<&K> {
273 let root_node = self.root.as_ref()?.reborrow();
274 match root_node.search_tree(key) {
275 Found(handle) => Some(handle.into_kv().0),
280 fn take(&mut self, key: &Q) -> Option<K> {
281 let (map, dormant_map) = DormantMutRef::new(self);
282 let root_node = map.root.as_mut()?.borrow_mut();
283 match root_node.search_tree(key) {
284 Found(handle) => Some(
285 OccupiedEntry { handle, dormant_map, alloc: &*map.alloc, _marker: PhantomData }
293 fn replace(&mut self, key: K) -> Option<K> {
294 let (map, dormant_map) = DormantMutRef::new(self);
295 let root_node = map.root.get_or_insert_with(|| Root::new(&*map.alloc)).borrow_mut();
296 match root_node.search_tree::<K>(&key) {
297 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
301 handle: Some(handle),
304 _marker: PhantomData,
313 /// An iterator over the entries of a `BTreeMap`.
315 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
316 /// documentation for more.
318 /// [`iter`]: BTreeMap::iter
319 #[must_use = "iterators are lazy and do nothing unless consumed"]
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub struct Iter<'a, K: 'a, V: 'a> {
322 range: LazyLeafRange<marker::Immut<'a>, K, V>,
326 #[stable(feature = "collection_debug", since = "1.17.0")]
327 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 f.debug_list().entries(self.clone()).finish()
333 /// A mutable iterator over the entries of a `BTreeMap`.
335 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
336 /// documentation for more.
338 /// [`iter_mut`]: BTreeMap::iter_mut
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub struct IterMut<'a, K: 'a, V: 'a> {
341 range: LazyLeafRange<marker::ValMut<'a>, K, V>,
344 // Be invariant in `K` and `V`
345 _marker: PhantomData<&'a mut (K, V)>,
348 #[must_use = "iterators are lazy and do nothing unless consumed"]
349 #[stable(feature = "collection_debug", since = "1.17.0")]
350 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 let range = Iter { range: self.range.reborrow(), length: self.length };
353 f.debug_list().entries(range).finish()
357 /// An owning iterator over the entries of a `BTreeMap`.
359 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
360 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
362 /// [`into_iter`]: IntoIterator::into_iter
363 /// [`IntoIterator`]: core::iter::IntoIterator
364 #[stable(feature = "rust1", since = "1.0.0")]
365 #[rustc_insignificant_dtor]
369 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
371 range: LazyLeafRange<marker::Dying, K, V>,
376 impl<K, V, A: Allocator> IntoIter<K, V, A> {
377 /// Returns an iterator of references over the remaining items.
379 pub(super) fn iter(&self) -> Iter<'_, K, V> {
380 Iter { range: self.range.reborrow(), length: self.length }
384 #[stable(feature = "collection_debug", since = "1.17.0")]
385 impl<K: Debug, V: Debug, A: Allocator> Debug for IntoIter<K, V, A> {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 f.debug_list().entries(self.iter()).finish()
391 /// An iterator over the keys of a `BTreeMap`.
393 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
394 /// documentation for more.
396 /// [`keys`]: BTreeMap::keys
397 #[must_use = "iterators are lazy and do nothing unless consumed"]
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub struct Keys<'a, K, V> {
400 inner: Iter<'a, K, V>,
403 #[stable(feature = "collection_debug", since = "1.17.0")]
404 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 f.debug_list().entries(self.clone()).finish()
410 /// An iterator over the values of a `BTreeMap`.
412 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
413 /// documentation for more.
415 /// [`values`]: BTreeMap::values
416 #[must_use = "iterators are lazy and do nothing unless consumed"]
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub struct Values<'a, K, V> {
419 inner: Iter<'a, K, V>,
422 #[stable(feature = "collection_debug", since = "1.17.0")]
423 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 f.debug_list().entries(self.clone()).finish()
429 /// A mutable iterator over the values of a `BTreeMap`.
431 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
432 /// documentation for more.
434 /// [`values_mut`]: BTreeMap::values_mut
435 #[must_use = "iterators are lazy and do nothing unless consumed"]
436 #[stable(feature = "map_values_mut", since = "1.10.0")]
437 pub struct ValuesMut<'a, K, V> {
438 inner: IterMut<'a, K, V>,
441 #[stable(feature = "map_values_mut", since = "1.10.0")]
442 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
448 /// An owning iterator over the keys of a `BTreeMap`.
450 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
451 /// See its documentation for more.
453 /// [`into_keys`]: BTreeMap::into_keys
454 #[must_use = "iterators are lazy and do nothing unless consumed"]
455 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
456 pub struct IntoKeys<K, V, A: Allocator = Global> {
457 inner: IntoIter<K, V, A>,
460 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
461 impl<K: fmt::Debug, V, A: Allocator> fmt::Debug for IntoKeys<K, V, A> {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
467 /// An owning iterator over the values of a `BTreeMap`.
469 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
470 /// See its documentation for more.
472 /// [`into_values`]: BTreeMap::into_values
473 #[must_use = "iterators are lazy and do nothing unless consumed"]
474 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
475 pub struct IntoValues<
478 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
480 inner: IntoIter<K, V, A>,
483 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
484 impl<K, V: fmt::Debug, A: Allocator> fmt::Debug for IntoValues<K, V, A> {
485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
490 /// An iterator over a sub-range of entries in a `BTreeMap`.
492 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
493 /// documentation for more.
495 /// [`range`]: BTreeMap::range
496 #[must_use = "iterators are lazy and do nothing unless consumed"]
497 #[stable(feature = "btree_range", since = "1.17.0")]
498 pub struct Range<'a, K: 'a, V: 'a> {
499 inner: LeafRange<marker::Immut<'a>, K, V>,
502 #[stable(feature = "collection_debug", since = "1.17.0")]
503 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 f.debug_list().entries(self.clone()).finish()
509 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
511 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
512 /// documentation for more.
514 /// [`range_mut`]: BTreeMap::range_mut
515 #[must_use = "iterators are lazy and do nothing unless consumed"]
516 #[stable(feature = "btree_range", since = "1.17.0")]
517 pub struct RangeMut<'a, K: 'a, V: 'a> {
518 inner: LeafRange<marker::ValMut<'a>, K, V>,
520 // Be invariant in `K` and `V`
521 _marker: PhantomData<&'a mut (K, V)>,
524 #[stable(feature = "collection_debug", since = "1.17.0")]
525 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
527 let range = Range { inner: self.inner.reborrow() };
528 f.debug_list().entries(range).finish()
532 impl<K, V> BTreeMap<K, V> {
533 /// Makes a new, empty `BTreeMap`.
535 /// Does not allocate anything on its own.
542 /// use std::collections::BTreeMap;
544 /// let mut map = BTreeMap::new();
546 /// // entries can now be inserted into the empty map
547 /// map.insert(1, "a");
549 #[stable(feature = "rust1", since = "1.0.0")]
550 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
552 pub const fn new() -> BTreeMap<K, V> {
553 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global) }
557 impl<K, V, A: Allocator> BTreeMap<K, V, A> {
558 /// Clears the map, removing all elements.
565 /// use std::collections::BTreeMap;
567 /// let mut a = BTreeMap::new();
568 /// a.insert(1, "a");
570 /// assert!(a.is_empty());
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn clear(&mut self) {
575 // drop all elements and retrieve allocator
576 ptr::read(self).into_iter().into_alloc()
578 *self = BTreeMap::new_in(alloc);
581 /// Makes a new empty BTreeMap with a reasonable choice for B.
588 /// # #![feature(allocator_api)]
589 /// # #![feature(btreemap_alloc)]
590 /// use std::collections::BTreeMap;
591 /// use std::alloc::Global;
593 /// let mut map = BTreeMap::new_in(Global);
595 /// // entries can now be inserted into the empty map
596 /// map.insert(1, "a");
598 #[unstable(feature = "btreemap_alloc", issue = "32838")]
599 pub fn new_in(alloc: A) -> BTreeMap<K, V, A> {
600 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc) }
604 impl<K, V, A: Allocator> BTreeMap<K, V, A> {
605 /// Returns a reference to the value corresponding to the key.
607 /// The key may be any borrowed form of the map's key type, but the ordering
608 /// on the borrowed form *must* match the ordering on the key type.
615 /// use std::collections::BTreeMap;
617 /// let mut map = BTreeMap::new();
618 /// map.insert(1, "a");
619 /// assert_eq!(map.get(&1), Some(&"a"));
620 /// assert_eq!(map.get(&2), None);
622 #[stable(feature = "rust1", since = "1.0.0")]
623 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
628 let root_node = self.root.as_ref()?.reborrow();
629 match root_node.search_tree(key) {
630 Found(handle) => Some(handle.into_kv().1),
635 /// Returns the key-value pair corresponding to the supplied key.
637 /// The supplied key may be any borrowed form of the map's key type, but the ordering
638 /// on the borrowed form *must* match the ordering on the key type.
643 /// use std::collections::BTreeMap;
645 /// let mut map = BTreeMap::new();
646 /// map.insert(1, "a");
647 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
648 /// assert_eq!(map.get_key_value(&2), None);
650 #[stable(feature = "map_get_key_value", since = "1.40.0")]
651 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
656 let root_node = self.root.as_ref()?.reborrow();
657 match root_node.search_tree(k) {
658 Found(handle) => Some(handle.into_kv()),
663 /// Returns the first key-value pair in the map.
664 /// The key in this pair is the minimum key in the map.
671 /// #![feature(map_first_last)]
672 /// use std::collections::BTreeMap;
674 /// let mut map = BTreeMap::new();
675 /// assert_eq!(map.first_key_value(), None);
676 /// map.insert(1, "b");
677 /// map.insert(2, "a");
678 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
680 #[unstable(feature = "map_first_last", issue = "62924")]
681 pub fn first_key_value(&self) -> Option<(&K, &V)>
685 let root_node = self.root.as_ref()?.reborrow();
686 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
689 /// Returns the first entry in the map for in-place manipulation.
690 /// The key of this entry is the minimum key in the map.
695 /// #![feature(map_first_last)]
696 /// use std::collections::BTreeMap;
698 /// let mut map = BTreeMap::new();
699 /// map.insert(1, "a");
700 /// map.insert(2, "b");
701 /// if let Some(mut entry) = map.first_entry() {
702 /// if *entry.key() > 0 {
703 /// entry.insert("first");
706 /// assert_eq!(*map.get(&1).unwrap(), "first");
707 /// assert_eq!(*map.get(&2).unwrap(), "b");
709 #[unstable(feature = "map_first_last", issue = "62924")]
710 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
714 let (map, dormant_map) = DormantMutRef::new(self);
715 let root_node = map.root.as_mut()?.borrow_mut();
716 let kv = root_node.first_leaf_edge().right_kv().ok()?;
718 handle: kv.forget_node_type(),
721 _marker: PhantomData,
725 /// Removes and returns the first element in the map.
726 /// The key of this element is the minimum key that was in the map.
730 /// Draining elements in ascending order, while keeping a usable map each iteration.
733 /// #![feature(map_first_last)]
734 /// use std::collections::BTreeMap;
736 /// let mut map = BTreeMap::new();
737 /// map.insert(1, "a");
738 /// map.insert(2, "b");
739 /// while let Some((key, _val)) = map.pop_first() {
740 /// assert!(map.iter().all(|(k, _v)| *k > key));
742 /// assert!(map.is_empty());
744 #[unstable(feature = "map_first_last", issue = "62924")]
745 pub fn pop_first(&mut self) -> Option<(K, V)>
749 self.first_entry().map(|entry| entry.remove_entry())
752 /// Returns the last key-value pair in the map.
753 /// The key in this pair is the maximum key in the map.
760 /// #![feature(map_first_last)]
761 /// use std::collections::BTreeMap;
763 /// let mut map = BTreeMap::new();
764 /// map.insert(1, "b");
765 /// map.insert(2, "a");
766 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
768 #[unstable(feature = "map_first_last", issue = "62924")]
769 pub fn last_key_value(&self) -> Option<(&K, &V)>
773 let root_node = self.root.as_ref()?.reborrow();
774 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
777 /// Returns the last entry in the map for in-place manipulation.
778 /// The key of this entry is the maximum key in the map.
783 /// #![feature(map_first_last)]
784 /// use std::collections::BTreeMap;
786 /// let mut map = BTreeMap::new();
787 /// map.insert(1, "a");
788 /// map.insert(2, "b");
789 /// if let Some(mut entry) = map.last_entry() {
790 /// if *entry.key() > 0 {
791 /// entry.insert("last");
794 /// assert_eq!(*map.get(&1).unwrap(), "a");
795 /// assert_eq!(*map.get(&2).unwrap(), "last");
797 #[unstable(feature = "map_first_last", issue = "62924")]
798 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
802 let (map, dormant_map) = DormantMutRef::new(self);
803 let root_node = map.root.as_mut()?.borrow_mut();
804 let kv = root_node.last_leaf_edge().left_kv().ok()?;
806 handle: kv.forget_node_type(),
809 _marker: PhantomData,
813 /// Removes and returns the last element in the map.
814 /// The key of this element is the maximum key that was in the map.
818 /// Draining elements in descending order, while keeping a usable map each iteration.
821 /// #![feature(map_first_last)]
822 /// use std::collections::BTreeMap;
824 /// let mut map = BTreeMap::new();
825 /// map.insert(1, "a");
826 /// map.insert(2, "b");
827 /// while let Some((key, _val)) = map.pop_last() {
828 /// assert!(map.iter().all(|(k, _v)| *k < key));
830 /// assert!(map.is_empty());
832 #[unstable(feature = "map_first_last", issue = "62924")]
833 pub fn pop_last(&mut self) -> Option<(K, V)>
837 self.last_entry().map(|entry| entry.remove_entry())
840 /// Returns `true` if the map contains a value for the specified key.
842 /// The key may be any borrowed form of the map's key type, but the ordering
843 /// on the borrowed form *must* match the ordering on the key type.
850 /// use std::collections::BTreeMap;
852 /// let mut map = BTreeMap::new();
853 /// map.insert(1, "a");
854 /// assert_eq!(map.contains_key(&1), true);
855 /// assert_eq!(map.contains_key(&2), false);
857 #[stable(feature = "rust1", since = "1.0.0")]
858 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
863 self.get(key).is_some()
866 /// Returns a mutable reference to the value corresponding to the key.
868 /// The key may be any borrowed form of the map's key type, but the ordering
869 /// on the borrowed form *must* match the ordering on the key type.
876 /// use std::collections::BTreeMap;
878 /// let mut map = BTreeMap::new();
879 /// map.insert(1, "a");
880 /// if let Some(x) = map.get_mut(&1) {
883 /// assert_eq!(map[&1], "b");
885 // See `get` for implementation notes, this is basically a copy-paste with mut's added
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
892 let root_node = self.root.as_mut()?.borrow_mut();
893 match root_node.search_tree(key) {
894 Found(handle) => Some(handle.into_val_mut()),
899 /// Inserts a key-value pair into the map.
901 /// If the map did not have this key present, `None` is returned.
903 /// If the map did have this key present, the value is updated, and the old
904 /// value is returned. The key is not updated, though; this matters for
905 /// types that can be `==` without being identical. See the [module-level
906 /// documentation] for more.
908 /// [module-level documentation]: index.html#insert-and-complex-keys
915 /// use std::collections::BTreeMap;
917 /// let mut map = BTreeMap::new();
918 /// assert_eq!(map.insert(37, "a"), None);
919 /// assert_eq!(map.is_empty(), false);
921 /// map.insert(37, "b");
922 /// assert_eq!(map.insert(37, "c"), Some("b"));
923 /// assert_eq!(map[&37], "c");
925 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn insert(&mut self, key: K, value: V) -> Option<V>
930 match self.entry(key) {
931 Occupied(mut entry) => Some(entry.insert(value)),
939 /// Tries to insert a key-value pair into the map, and returns
940 /// a mutable reference to the value in the entry.
942 /// If the map already had this key present, nothing is updated, and
943 /// an error containing the occupied entry and the value is returned.
950 /// #![feature(map_try_insert)]
952 /// use std::collections::BTreeMap;
954 /// let mut map = BTreeMap::new();
955 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
957 /// let err = map.try_insert(37, "b").unwrap_err();
958 /// assert_eq!(err.entry.key(), &37);
959 /// assert_eq!(err.entry.get(), &"a");
960 /// assert_eq!(err.value, "b");
962 #[unstable(feature = "map_try_insert", issue = "82766")]
963 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
967 match self.entry(key) {
968 Occupied(entry) => Err(OccupiedError { entry, value }),
969 Vacant(entry) => Ok(entry.insert(value)),
973 /// Removes a key from the map, returning the value at the key if the key
974 /// was previously in the map.
976 /// The key may be any borrowed form of the map's key type, but the ordering
977 /// on the borrowed form *must* match the ordering on the key type.
984 /// use std::collections::BTreeMap;
986 /// let mut map = BTreeMap::new();
987 /// map.insert(1, "a");
988 /// assert_eq!(map.remove(&1), Some("a"));
989 /// assert_eq!(map.remove(&1), None);
991 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
997 self.remove_entry(key).map(|(_, v)| v)
1000 /// Removes a key from the map, returning the stored key and value if the key
1001 /// was previously in the map.
1003 /// The key may be any borrowed form of the map's key type, but the ordering
1004 /// on the borrowed form *must* match the ordering on the key type.
1011 /// use std::collections::BTreeMap;
1013 /// let mut map = BTreeMap::new();
1014 /// map.insert(1, "a");
1015 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1016 /// assert_eq!(map.remove_entry(&1), None);
1018 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1019 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1024 let (map, dormant_map) = DormantMutRef::new(self);
1025 let root_node = map.root.as_mut()?.borrow_mut();
1026 match root_node.search_tree(key) {
1027 Found(handle) => Some(
1028 OccupiedEntry { handle, dormant_map, alloc: &*map.alloc, _marker: PhantomData }
1035 /// Retains only the elements specified by the predicate.
1037 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1038 /// The elements are visited in ascending key order.
1043 /// use std::collections::BTreeMap;
1045 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1046 /// // Keep only the elements with even-numbered keys.
1047 /// map.retain(|&k, _| k % 2 == 0);
1048 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1051 #[stable(feature = "btree_retain", since = "1.53.0")]
1052 pub fn retain<F>(&mut self, mut f: F)
1055 F: FnMut(&K, &mut V) -> bool,
1057 self.drain_filter(|k, v| !f(k, v));
1060 /// Moves all elements from `other` into `self`, leaving `other` empty.
1065 /// use std::collections::BTreeMap;
1067 /// let mut a = BTreeMap::new();
1068 /// a.insert(1, "a");
1069 /// a.insert(2, "b");
1070 /// a.insert(3, "c");
1072 /// let mut b = BTreeMap::new();
1073 /// b.insert(3, "d");
1074 /// b.insert(4, "e");
1075 /// b.insert(5, "f");
1077 /// a.append(&mut b);
1079 /// assert_eq!(a.len(), 5);
1080 /// assert_eq!(b.len(), 0);
1082 /// assert_eq!(a[&1], "a");
1083 /// assert_eq!(a[&2], "b");
1084 /// assert_eq!(a[&3], "d");
1085 /// assert_eq!(a[&4], "e");
1086 /// assert_eq!(a[&5], "f");
1088 #[stable(feature = "btree_append", since = "1.11.0")]
1089 pub fn append(&mut self, other: &mut Self)
1094 // Do we have to append anything at all?
1095 if other.is_empty() {
1099 // We can just swap `self` and `other` if `self` is empty.
1100 if self.is_empty() {
1101 mem::swap(self, other);
1106 mem::replace(self, Self::new_in(ManuallyDrop::into_inner(self.alloc.clone())))
1109 mem::replace(other, Self::new_in(ManuallyDrop::into_inner(self.alloc.clone())))
1111 let root = self.root.get_or_insert_with(|| Root::new(&*self.alloc));
1112 root.append_from_sorted_iters(self_iter, other_iter, &mut self.length, &*self.alloc)
1115 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1116 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1117 /// yield elements from min (inclusive) to max (exclusive).
1118 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1119 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1120 /// range from 4 to 10.
1124 /// Panics if range `start > end`.
1125 /// Panics if range `start == end` and both bounds are `Excluded`.
1132 /// use std::collections::BTreeMap;
1133 /// use std::ops::Bound::Included;
1135 /// let mut map = BTreeMap::new();
1136 /// map.insert(3, "a");
1137 /// map.insert(5, "b");
1138 /// map.insert(8, "c");
1139 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1140 /// println!("{key}: {value}");
1142 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1144 #[stable(feature = "btree_range", since = "1.17.0")]
1145 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1151 if let Some(root) = &self.root {
1152 Range { inner: root.reborrow().range_search(range) }
1154 Range { inner: LeafRange::none() }
1158 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1159 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1160 /// yield elements from min (inclusive) to max (exclusive).
1161 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1162 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1163 /// range from 4 to 10.
1167 /// Panics if range `start > end`.
1168 /// Panics if range `start == end` and both bounds are `Excluded`.
1175 /// use std::collections::BTreeMap;
1177 /// let mut map: BTreeMap<&str, i32> =
1178 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1179 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1180 /// *balance += 100;
1182 /// for (name, balance) in &map {
1183 /// println!("{name} => {balance}");
1186 #[stable(feature = "btree_range", since = "1.17.0")]
1187 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1193 if let Some(root) = &mut self.root {
1194 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1196 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1200 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1207 /// use std::collections::BTreeMap;
1209 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1211 /// // count the number of occurrences of letters in the vec
1212 /// for x in ["a", "b", "a", "c", "a", "b"] {
1213 /// *count.entry(x).or_insert(0) += 1;
1216 /// assert_eq!(count["a"], 3);
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1223 let (map, dormant_map) = DormantMutRef::new(self);
1225 None => Vacant(VacantEntry {
1230 _marker: PhantomData,
1232 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1233 Found(handle) => Occupied(OccupiedEntry {
1237 _marker: PhantomData,
1239 GoDown(handle) => Vacant(VacantEntry {
1241 handle: Some(handle),
1244 _marker: PhantomData,
1250 /// Splits the collection into two at the given key. Returns everything after the given key,
1251 /// including the key.
1258 /// use std::collections::BTreeMap;
1260 /// let mut a = BTreeMap::new();
1261 /// a.insert(1, "a");
1262 /// a.insert(2, "b");
1263 /// a.insert(3, "c");
1264 /// a.insert(17, "d");
1265 /// a.insert(41, "e");
1267 /// let b = a.split_off(&3);
1269 /// assert_eq!(a.len(), 2);
1270 /// assert_eq!(b.len(), 3);
1272 /// assert_eq!(a[&1], "a");
1273 /// assert_eq!(a[&2], "b");
1275 /// assert_eq!(b[&3], "c");
1276 /// assert_eq!(b[&17], "d");
1277 /// assert_eq!(b[&41], "e");
1279 #[stable(feature = "btree_split_off", since = "1.11.0")]
1280 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1285 if self.is_empty() {
1286 return Self::new_in(ManuallyDrop::into_inner(self.alloc.clone()));
1289 let total_num = self.len();
1290 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1292 let right_root = left_root.split_off(key, &*self.alloc);
1294 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1295 self.length = new_left_len;
1298 root: Some(right_root),
1300 alloc: ManuallyDrop::new((*self.alloc).clone()),
1304 /// Creates an iterator that visits all elements (key-value pairs) in
1305 /// ascending key order and uses a closure to determine if an element should
1306 /// be removed. If the closure returns `true`, the element is removed from
1307 /// the map and yielded. If the closure returns `false`, or panics, the
1308 /// element remains in the map and will not be yielded.
1310 /// The iterator also lets you mutate the value of each element in the
1311 /// closure, regardless of whether you choose to keep or remove it.
1313 /// If the iterator is only partially consumed or not consumed at all, each
1314 /// of the remaining elements is still subjected to the closure, which may
1315 /// change its value and, by returning `true`, have the element removed and
1318 /// It is unspecified how many more elements will be subjected to the
1319 /// closure if a panic occurs in the closure, or a panic occurs while
1320 /// dropping an element, or if the `DrainFilter` value is leaked.
1324 /// Splitting a map into even and odd keys, reusing the original map:
1327 /// #![feature(btree_drain_filter)]
1328 /// use std::collections::BTreeMap;
1330 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1331 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1333 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1334 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1336 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1337 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F, &A>
1340 F: FnMut(&K, &mut V) -> bool,
1342 let (inner, alloc) = self.drain_filter_inner();
1343 DrainFilter { pred, inner, alloc }
1346 pub(super) fn drain_filter_inner(&mut self) -> (DrainFilterInner<'_, K, V>, &A)
1350 if let Some(root) = self.root.as_mut() {
1351 let (root, dormant_root) = DormantMutRef::new(root);
1352 let front = root.borrow_mut().first_leaf_edge();
1355 length: &mut self.length,
1356 dormant_root: Some(dormant_root),
1357 cur_leaf_edge: Some(front),
1364 length: &mut self.length,
1366 cur_leaf_edge: None,
1373 /// Creates a consuming iterator visiting all the keys, in sorted order.
1374 /// The map cannot be used after calling this.
1375 /// The iterator element type is `K`.
1380 /// use std::collections::BTreeMap;
1382 /// let mut a = BTreeMap::new();
1383 /// a.insert(2, "b");
1384 /// a.insert(1, "a");
1386 /// let keys: Vec<i32> = a.into_keys().collect();
1387 /// assert_eq!(keys, [1, 2]);
1390 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1391 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1392 IntoKeys { inner: self.into_iter() }
1395 /// Creates a consuming iterator visiting all the values, in order by key.
1396 /// The map cannot be used after calling this.
1397 /// The iterator element type is `V`.
1402 /// use std::collections::BTreeMap;
1404 /// let mut a = BTreeMap::new();
1405 /// a.insert(1, "hello");
1406 /// a.insert(2, "goodbye");
1408 /// let values: Vec<&str> = a.into_values().collect();
1409 /// assert_eq!(values, ["hello", "goodbye"]);
1412 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1413 pub fn into_values(self) -> IntoValues<K, V, A> {
1414 IntoValues { inner: self.into_iter() }
1417 /// Makes a `BTreeMap` from a sorted iterator.
1418 pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1421 I: IntoIterator<Item = (K, V)>,
1423 let mut root = Root::new(&alloc);
1425 root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, &alloc);
1426 BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc) }
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 impl<'a, K, V, A: Allocator> IntoIterator for &'a BTreeMap<K, V, A> {
1432 type Item = (&'a K, &'a V);
1433 type IntoIter = Iter<'a, K, V>;
1435 fn into_iter(self) -> Iter<'a, K, V> {
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1442 type Item = (&'a K, &'a V);
1444 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1445 if self.length == 0 {
1449 Some(unsafe { self.range.next_unchecked() })
1453 fn size_hint(&self) -> (usize, Option<usize>) {
1454 (self.length, Some(self.length))
1457 fn last(mut self) -> Option<(&'a K, &'a V)> {
1461 fn min(mut self) -> Option<(&'a K, &'a V)> {
1465 fn max(mut self) -> Option<(&'a K, &'a V)> {
1470 #[stable(feature = "fused", since = "1.26.0")]
1471 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1475 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1476 if self.length == 0 {
1480 Some(unsafe { self.range.next_back_unchecked() })
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1487 fn len(&self) -> usize {
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<K, V> Clone for Iter<'_, K, V> {
1494 fn clone(&self) -> Self {
1495 Iter { range: self.range.clone(), length: self.length }
1499 #[stable(feature = "rust1", since = "1.0.0")]
1500 impl<'a, K, V, A: Allocator> IntoIterator for &'a mut BTreeMap<K, V, A> {
1501 type Item = (&'a K, &'a mut V);
1502 type IntoIter = IterMut<'a, K, V>;
1504 fn into_iter(self) -> IterMut<'a, K, V> {
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1511 type Item = (&'a K, &'a mut V);
1513 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1514 if self.length == 0 {
1518 Some(unsafe { self.range.next_unchecked() })
1522 fn size_hint(&self) -> (usize, Option<usize>) {
1523 (self.length, Some(self.length))
1526 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1530 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1534 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1541 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1542 if self.length == 0 {
1546 Some(unsafe { self.range.next_back_unchecked() })
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1553 fn len(&self) -> usize {
1558 #[stable(feature = "fused", since = "1.26.0")]
1559 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1561 impl<'a, K, V> IterMut<'a, K, V> {
1562 /// Returns an iterator of references over the remaining items.
1564 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1565 Iter { range: self.range.reborrow(), length: self.length }
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<K, V, A: Allocator> IntoIterator for BTreeMap<K, V, A> {
1572 type IntoIter = IntoIter<K, V, A>;
1574 fn into_iter(self) -> IntoIter<K, V, A> {
1575 let mut me = ManuallyDrop::new(self);
1576 if let Some(root) = me.root.take() {
1577 let full_range = root.into_dying().full_range();
1582 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1586 range: LazyLeafRange::none(),
1588 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1594 #[stable(feature = "btree_drop", since = "1.7.0")]
1595 impl<K, V, A: Allocator> Drop for IntoIter<K, V, A> {
1596 fn drop(&mut self) {
1600 impl<K, V, A: Allocator> IntoIter<K, V, A> {
1601 fn dealloc(&mut self) {
1602 struct DropGuard<'a, K, V, A: Allocator>(&'a mut IntoIter<K, V, A>);
1604 impl<'a, K, V, A: Allocator> Drop for DropGuard<'a, K, V, A> {
1605 fn drop(&mut self) {
1606 // Continue the same loop we perform below. This only runs when unwinding, so we
1607 // don't have to care about panics this time (they'll abort).
1608 while let Some(kv) = self.0.dying_next() {
1609 // SAFETY: we consume the dying handle immediately.
1610 unsafe { kv.drop_key_val() };
1615 while let Some(kv) = self.dying_next() {
1616 let guard = DropGuard(self);
1617 // SAFETY: we don't touch the tree before consuming the dying handle.
1618 unsafe { kv.drop_key_val() };
1624 impl<K, V, A: Allocator> IntoIter<K, V, A> {
1625 /// Core of a `next` method returning a dying KV handle,
1626 /// invalidated by further calls to this function and some others.
1629 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1630 if self.length == 0 {
1631 self.range.deallocating_end(&self.alloc);
1635 Some(unsafe { self.range.deallocating_next_unchecked(&self.alloc) })
1639 /// Core of a `next_back` method returning a dying KV handle,
1640 /// invalidated by further calls to this function and some others.
1643 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1644 if self.length == 0 {
1645 self.range.deallocating_end(&self.alloc);
1649 Some(unsafe { self.range.deallocating_next_back_unchecked(&self.alloc) })
1652 fn into_alloc(mut self) -> A {
1653 self.dealloc(); // Deallocate, then don't drop as drop will also call dealloc
1654 let iter = ManuallyDrop::new(self);
1655 unsafe { ptr::read(&iter.alloc) }
1659 #[stable(feature = "rust1", since = "1.0.0")]
1660 impl<K, V, A: Allocator> Iterator for IntoIter<K, V, A> {
1663 fn next(&mut self) -> Option<(K, V)> {
1664 // SAFETY: we consume the dying handle immediately.
1665 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1668 fn size_hint(&self) -> (usize, Option<usize>) {
1669 (self.length, Some(self.length))
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl<K, V, A: Allocator> DoubleEndedIterator for IntoIter<K, V, A> {
1675 fn next_back(&mut self) -> Option<(K, V)> {
1676 // SAFETY: we consume the dying handle immediately.
1677 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<K, V, A: Allocator> ExactSizeIterator for IntoIter<K, V, A> {
1683 fn len(&self) -> usize {
1688 #[stable(feature = "fused", since = "1.26.0")]
1689 impl<K, V, A: Allocator> FusedIterator for IntoIter<K, V, A> {}
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1695 fn next(&mut self) -> Option<&'a K> {
1696 self.inner.next().map(|(k, _)| k)
1699 fn size_hint(&self) -> (usize, Option<usize>) {
1700 self.inner.size_hint()
1703 fn last(mut self) -> Option<&'a K> {
1707 fn min(mut self) -> Option<&'a K> {
1711 fn max(mut self) -> Option<&'a K> {
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1718 fn next_back(&mut self) -> Option<&'a K> {
1719 self.inner.next_back().map(|(k, _)| k)
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1725 fn len(&self) -> usize {
1730 #[stable(feature = "fused", since = "1.26.0")]
1731 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl<K, V> Clone for Keys<'_, K, V> {
1735 fn clone(&self) -> Self {
1736 Keys { inner: self.inner.clone() }
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl<'a, K, V> Iterator for Values<'a, K, V> {
1744 fn next(&mut self) -> Option<&'a V> {
1745 self.inner.next().map(|(_, v)| v)
1748 fn size_hint(&self) -> (usize, Option<usize>) {
1749 self.inner.size_hint()
1752 fn last(mut self) -> Option<&'a V> {
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1759 fn next_back(&mut self) -> Option<&'a V> {
1760 self.inner.next_back().map(|(_, v)| v)
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1766 fn len(&self) -> usize {
1771 #[stable(feature = "fused", since = "1.26.0")]
1772 impl<K, V> FusedIterator for Values<'_, K, V> {}
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 impl<K, V> Clone for Values<'_, K, V> {
1776 fn clone(&self) -> Self {
1777 Values { inner: self.inner.clone() }
1781 /// An iterator produced by calling `drain_filter` on BTreeMap.
1782 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1783 pub struct DrainFilter<
1788 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1790 F: 'a + FnMut(&K, &mut V) -> bool,
1793 inner: DrainFilterInner<'a, K, V>,
1796 /// Most of the implementation of DrainFilter are generic over the type
1797 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1798 pub(super) struct DrainFilterInner<'a, K, V> {
1799 /// Reference to the length field in the borrowed map, updated live.
1800 length: &'a mut usize,
1801 /// Buried reference to the root field in the borrowed map.
1802 /// Wrapped in `Option` to allow drop handler to `take` it.
1803 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1804 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1805 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1806 /// or if a panic occurred in the predicate.
1807 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1810 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1811 impl<K, V, F, A: Allocator> Drop for DrainFilter<'_, K, V, F, A>
1813 F: FnMut(&K, &mut V) -> bool,
1815 fn drop(&mut self) {
1816 self.for_each(drop);
1820 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1821 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1825 F: FnMut(&K, &mut V) -> bool,
1827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1828 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1832 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1833 impl<K, V, F, A: Allocator> Iterator for DrainFilter<'_, K, V, F, A>
1835 F: FnMut(&K, &mut V) -> bool,
1839 fn next(&mut self) -> Option<(K, V)> {
1840 self.inner.next(&mut self.pred, &self.alloc)
1843 fn size_hint(&self) -> (usize, Option<usize>) {
1844 self.inner.size_hint()
1848 impl<'a, K, V> DrainFilterInner<'a, K, V> {
1849 /// Allow Debug implementations to predict the next element.
1850 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1851 let edge = self.cur_leaf_edge.as_ref()?;
1852 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1855 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1856 pub(super) fn next<F, A: Allocator>(&mut self, pred: &mut F, alloc: &A) -> Option<(K, V)>
1858 F: FnMut(&K, &mut V) -> bool,
1860 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1861 let (k, v) = kv.kv_mut();
1864 let (kv, pos) = kv.remove_kv_tracking(
1866 // SAFETY: we will touch the root in a way that will not
1867 // invalidate the position returned.
1868 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1869 root.pop_internal_level(alloc);
1870 self.dormant_root = Some(DormantMutRef::new(root).1);
1874 self.cur_leaf_edge = Some(pos);
1877 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1882 /// Implementation of a typical `DrainFilter::size_hint` method.
1883 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1884 // In most of the btree iterators, `self.length` is the number of elements
1885 // yet to be visited. Here, it includes elements that were visited and that
1886 // the predicate decided not to drain. Making this upper bound more tight
1887 // during iteration would require an extra field.
1888 (0, Some(*self.length))
1892 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1893 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1895 #[stable(feature = "btree_range", since = "1.17.0")]
1896 impl<'a, K, V> Iterator for Range<'a, K, V> {
1897 type Item = (&'a K, &'a V);
1899 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1900 self.inner.next_checked()
1903 fn last(mut self) -> Option<(&'a K, &'a V)> {
1907 fn min(mut self) -> Option<(&'a K, &'a V)> {
1911 fn max(mut self) -> Option<(&'a K, &'a V)> {
1916 #[stable(feature = "map_values_mut", since = "1.10.0")]
1917 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1918 type Item = &'a mut V;
1920 fn next(&mut self) -> Option<&'a mut V> {
1921 self.inner.next().map(|(_, v)| v)
1924 fn size_hint(&self) -> (usize, Option<usize>) {
1925 self.inner.size_hint()
1928 fn last(mut self) -> Option<&'a mut V> {
1933 #[stable(feature = "map_values_mut", since = "1.10.0")]
1934 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1935 fn next_back(&mut self) -> Option<&'a mut V> {
1936 self.inner.next_back().map(|(_, v)| v)
1940 #[stable(feature = "map_values_mut", since = "1.10.0")]
1941 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1942 fn len(&self) -> usize {
1947 #[stable(feature = "fused", since = "1.26.0")]
1948 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1950 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1951 impl<K, V, A: Allocator> Iterator for IntoKeys<K, V, A> {
1954 fn next(&mut self) -> Option<K> {
1955 self.inner.next().map(|(k, _)| k)
1958 fn size_hint(&self) -> (usize, Option<usize>) {
1959 self.inner.size_hint()
1962 fn last(mut self) -> Option<K> {
1966 fn min(mut self) -> Option<K> {
1970 fn max(mut self) -> Option<K> {
1975 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1976 impl<K, V, A: Allocator> DoubleEndedIterator for IntoKeys<K, V, A> {
1977 fn next_back(&mut self) -> Option<K> {
1978 self.inner.next_back().map(|(k, _)| k)
1982 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1983 impl<K, V, A: Allocator> ExactSizeIterator for IntoKeys<K, V, A> {
1984 fn len(&self) -> usize {
1989 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1990 impl<K, V, A: Allocator> FusedIterator for IntoKeys<K, V, A> {}
1992 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1993 impl<K, V, A: Allocator> Iterator for IntoValues<K, V, A> {
1996 fn next(&mut self) -> Option<V> {
1997 self.inner.next().map(|(_, v)| v)
2000 fn size_hint(&self) -> (usize, Option<usize>) {
2001 self.inner.size_hint()
2004 fn last(mut self) -> Option<V> {
2009 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2010 impl<K, V, A: Allocator> DoubleEndedIterator for IntoValues<K, V, A> {
2011 fn next_back(&mut self) -> Option<V> {
2012 self.inner.next_back().map(|(_, v)| v)
2016 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2017 impl<K, V, A: Allocator> ExactSizeIterator for IntoValues<K, V, A> {
2018 fn len(&self) -> usize {
2023 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
2024 impl<K, V, A: Allocator> FusedIterator for IntoValues<K, V, A> {}
2026 #[stable(feature = "btree_range", since = "1.17.0")]
2027 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2028 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2029 self.inner.next_back_checked()
2033 #[stable(feature = "fused", since = "1.26.0")]
2034 impl<K, V> FusedIterator for Range<'_, K, V> {}
2036 #[stable(feature = "btree_range", since = "1.17.0")]
2037 impl<K, V> Clone for Range<'_, K, V> {
2038 fn clone(&self) -> Self {
2039 Range { inner: self.inner.clone() }
2043 #[stable(feature = "btree_range", since = "1.17.0")]
2044 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2045 type Item = (&'a K, &'a mut V);
2047 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2048 self.inner.next_checked()
2051 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2055 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
2059 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
2064 #[stable(feature = "btree_range", since = "1.17.0")]
2065 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2066 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2067 self.inner.next_back_checked()
2071 #[stable(feature = "fused", since = "1.26.0")]
2072 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2076 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2077 let mut inputs: Vec<_> = iter.into_iter().collect();
2079 if inputs.is_empty() {
2080 return BTreeMap::new();
2083 // use stable sort to preserve the insertion order.
2084 inputs.sort_by(|a, b| a.0.cmp(&b.0));
2085 BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2089 #[stable(feature = "rust1", since = "1.0.0")]
2090 impl<K: Ord, V, A: Allocator> Extend<(K, V)> for BTreeMap<K, V, A> {
2092 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2093 iter.into_iter().for_each(move |(k, v)| {
2099 fn extend_one(&mut self, (k, v): (K, V)) {
2104 #[stable(feature = "extend_ref", since = "1.2.0")]
2105 impl<'a, K: Ord + Copy, V: Copy, A: Allocator> Extend<(&'a K, &'a V)> for BTreeMap<K, V, A> {
2106 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2107 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2111 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2116 #[stable(feature = "rust1", since = "1.0.0")]
2117 impl<K: Hash, V: Hash, A: Allocator> Hash for BTreeMap<K, V, A> {
2118 fn hash<H: Hasher>(&self, state: &mut H) {
2119 state.write_length_prefix(self.len());
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<K, V> Default for BTreeMap<K, V> {
2128 /// Creates an empty `BTreeMap`.
2129 fn default() -> BTreeMap<K, V> {
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 impl<K: PartialEq, V: PartialEq, A: Allocator> PartialEq for BTreeMap<K, V, A> {
2136 fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2137 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2141 #[stable(feature = "rust1", since = "1.0.0")]
2142 impl<K: Eq, V: Eq, A: Allocator> Eq for BTreeMap<K, V, A> {}
2144 #[stable(feature = "rust1", since = "1.0.0")]
2145 impl<K: PartialOrd, V: PartialOrd, A: Allocator> PartialOrd for BTreeMap<K, V, A> {
2147 fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2148 self.iter().partial_cmp(other.iter())
2152 #[stable(feature = "rust1", since = "1.0.0")]
2153 impl<K: Ord, V: Ord, A: Allocator> Ord for BTreeMap<K, V, A> {
2155 fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2156 self.iter().cmp(other.iter())
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl<K: Debug, V: Debug, A: Allocator> Debug for BTreeMap<K, V, A> {
2162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2163 f.debug_map().entries(self.iter()).finish()
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 impl<K, Q: ?Sized, V, A: Allocator> Index<&Q> for BTreeMap<K, V, A>
2175 /// Returns a reference to the value corresponding to the supplied key.
2179 /// Panics if the key is not present in the `BTreeMap`.
2181 fn index(&self, key: &Q) -> &V {
2182 self.get(key).expect("no entry found for key")
2186 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
2187 impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2188 /// Converts a `[(K, V); N]` into a `BTreeMap<(K, V)>`.
2191 /// use std::collections::BTreeMap;
2193 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2194 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2195 /// assert_eq!(map1, map2);
2197 fn from(mut arr: [(K, V); N]) -> Self {
2199 return BTreeMap::new();
2202 // use stable sort to preserve the insertion order.
2203 arr.sort_by(|a, b| a.0.cmp(&b.0));
2204 BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2208 impl<K, V, A: Allocator> BTreeMap<K, V, A> {
2209 /// Gets an iterator over the entries of the map, sorted by key.
2216 /// use std::collections::BTreeMap;
2218 /// let mut map = BTreeMap::new();
2219 /// map.insert(3, "c");
2220 /// map.insert(2, "b");
2221 /// map.insert(1, "a");
2223 /// for (key, value) in map.iter() {
2224 /// println!("{key}: {value}");
2227 /// let (first_key, first_value) = map.iter().next().unwrap();
2228 /// assert_eq!((*first_key, *first_value), (1, "a"));
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 pub fn iter(&self) -> Iter<'_, K, V> {
2232 if let Some(root) = &self.root {
2233 let full_range = root.reborrow().full_range();
2235 Iter { range: full_range, length: self.length }
2237 Iter { range: LazyLeafRange::none(), length: 0 }
2241 /// Gets a mutable iterator over the entries of the map, sorted by key.
2248 /// use std::collections::BTreeMap;
2250 /// let mut map = BTreeMap::from([
2256 /// // add 10 to the value if the key isn't "a"
2257 /// for (key, value) in map.iter_mut() {
2258 /// if key != &"a" {
2263 #[stable(feature = "rust1", since = "1.0.0")]
2264 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2265 if let Some(root) = &mut self.root {
2266 let full_range = root.borrow_valmut().full_range();
2268 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2270 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2274 /// Gets an iterator over the keys of the map, in sorted order.
2281 /// use std::collections::BTreeMap;
2283 /// let mut a = BTreeMap::new();
2284 /// a.insert(2, "b");
2285 /// a.insert(1, "a");
2287 /// let keys: Vec<_> = a.keys().cloned().collect();
2288 /// assert_eq!(keys, [1, 2]);
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 pub fn keys(&self) -> Keys<'_, K, V> {
2292 Keys { inner: self.iter() }
2295 /// Gets an iterator over the values of the map, in order by key.
2302 /// use std::collections::BTreeMap;
2304 /// let mut a = BTreeMap::new();
2305 /// a.insert(1, "hello");
2306 /// a.insert(2, "goodbye");
2308 /// let values: Vec<&str> = a.values().cloned().collect();
2309 /// assert_eq!(values, ["hello", "goodbye"]);
2311 #[stable(feature = "rust1", since = "1.0.0")]
2312 pub fn values(&self) -> Values<'_, K, V> {
2313 Values { inner: self.iter() }
2316 /// Gets a mutable iterator over the values of the map, in order by key.
2323 /// use std::collections::BTreeMap;
2325 /// let mut a = BTreeMap::new();
2326 /// a.insert(1, String::from("hello"));
2327 /// a.insert(2, String::from("goodbye"));
2329 /// for value in a.values_mut() {
2330 /// value.push_str("!");
2333 /// let values: Vec<String> = a.values().cloned().collect();
2334 /// assert_eq!(values, [String::from("hello!"),
2335 /// String::from("goodbye!")]);
2337 #[stable(feature = "map_values_mut", since = "1.10.0")]
2338 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2339 ValuesMut { inner: self.iter_mut() }
2342 /// Returns the number of elements in the map.
2349 /// use std::collections::BTreeMap;
2351 /// let mut a = BTreeMap::new();
2352 /// assert_eq!(a.len(), 0);
2353 /// a.insert(1, "a");
2354 /// assert_eq!(a.len(), 1);
2357 #[stable(feature = "rust1", since = "1.0.0")]
2358 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2359 pub const fn len(&self) -> usize {
2363 /// Returns `true` if the map contains no elements.
2370 /// use std::collections::BTreeMap;
2372 /// let mut a = BTreeMap::new();
2373 /// assert!(a.is_empty());
2374 /// a.insert(1, "a");
2375 /// assert!(!a.is_empty());
2378 #[stable(feature = "rust1", since = "1.0.0")]
2379 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2380 pub const fn is_empty(&self) -> bool {