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 super::borrow::DormantMutRef;
13 use super::dedup_sorted_iter::DedupSortedIter;
14 use super::navigate::{LazyLeafRange, LeafRange};
15 use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
16 use super::search::SearchResult::*;
20 #[stable(feature = "rust1", since = "1.0.0")]
21 pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
25 /// Minimum number of elements in a node that is not a root.
26 /// We might temporarily have fewer elements during methods.
27 pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
29 // A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
30 // - Keys must appear in ascending order (according to the key's type).
31 // - Every non-leaf node contains at least 1 element (has at least 2 children).
32 // - Every non-root node contains at least MIN_LEN elements.
34 // An empty map is represented either by the absence of a root node or by a
35 // root node that is an empty leaf.
37 /// An ordered map based on a [B-Tree].
39 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
40 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
41 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
42 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
43 /// is done is *very* inefficient for modern computer architectures. In particular, every element
44 /// is stored in its own individually heap-allocated node. This means that every single insertion
45 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
46 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
49 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
50 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
51 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
52 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
53 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
54 /// the node using binary search. As a compromise, one could also perform a linear search
55 /// that initially only checks every i<sup>th</sup> element for some choice of i.
57 /// Currently, our implementation simply performs naive linear search. This provides excellent
58 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
59 /// would like to further explore choosing the optimal search strategy based on the choice of B,
60 /// and possibly other factors. Using linear search, searching for a random element is expected
61 /// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
62 /// however, performance is excellent.
64 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
65 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
66 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
67 /// The behavior resulting from such a logic error is not specified (it could include panics,
68 /// incorrect results, aborts, memory leaks, or non-termination) but will not be undefined
71 /// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::values`], or
72 /// [`BTreeMap::keys`] produce their items in order by key, and take worst-case logarithmic and
73 /// amortized constant time per item returned.
75 /// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
76 /// [`Cell`]: core::cell::Cell
77 /// [`RefCell`]: core::cell::RefCell
82 /// use std::collections::BTreeMap;
84 /// // type inference lets us omit an explicit type signature (which
85 /// // would be `BTreeMap<&str, &str>` in this example).
86 /// let mut movie_reviews = BTreeMap::new();
88 /// // review some movies.
89 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
90 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
91 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
92 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
94 /// // check for a specific one.
95 /// if !movie_reviews.contains_key("Les Misérables") {
96 /// println!("We've got {} reviews, but Les Misérables ain't one.",
97 /// movie_reviews.len());
100 /// // oops, this review has a lot of spelling mistakes, let's delete it.
101 /// movie_reviews.remove("The Blues Brothers");
103 /// // look up the values associated with some keys.
104 /// let to_find = ["Up!", "Office Space"];
105 /// for movie in &to_find {
106 /// match movie_reviews.get(movie) {
107 /// Some(review) => println!("{movie}: {review}"),
108 /// None => println!("{movie} is unreviewed.")
112 /// // Look up the value for a key (will panic if the key is not found).
113 /// println!("Movie review: {}", movie_reviews["Office Space"]);
115 /// // iterate over everything.
116 /// for (movie, review) in &movie_reviews {
117 /// println!("{movie}: \"{review}\"");
121 /// A `BTreeMap` with a known list of items can be initialized from an array:
124 /// use std::collections::BTreeMap;
126 /// let solar_distance = BTreeMap::from([
127 /// ("Mercury", 0.4),
134 /// `BTreeMap` implements an [`Entry API`], which allows for complex
135 /// methods of getting, setting, updating and removing keys and their values:
137 /// [`Entry API`]: BTreeMap::entry
140 /// use std::collections::BTreeMap;
142 /// // type inference lets us omit an explicit type signature (which
143 /// // would be `BTreeMap<&str, u8>` in this example).
144 /// let mut player_stats = BTreeMap::new();
146 /// fn random_stat_buff() -> u8 {
147 /// // could actually return some random value here - let's just return
148 /// // some fixed value for now
152 /// // insert a key only if it doesn't already exist
153 /// player_stats.entry("health").or_insert(100);
155 /// // insert a key using a function that provides a new value only if it
156 /// // doesn't already exist
157 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
159 /// // update a key, guarding against the key possibly not being set
160 /// let stat = player_stats.entry("attack").or_insert(100);
161 /// *stat += random_stat_buff();
163 #[stable(feature = "rust1", since = "1.0.0")]
164 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
165 #[rustc_insignificant_dtor]
166 pub struct BTreeMap<K, V> {
167 root: Option<Root<K, V>>,
171 #[stable(feature = "btree_drop", since = "1.7.0")]
172 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
174 drop(unsafe { ptr::read(self) }.into_iter())
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
180 fn clone(&self) -> BTreeMap<K, V> {
181 fn clone_subtree<'a, K: Clone, V: Clone>(
182 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
190 let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 };
193 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
194 let mut out_node = match root.borrow_mut().force() {
196 Internal(_) => unreachable!(),
199 let mut in_edge = leaf.first_edge();
200 while let Ok(kv) = in_edge.right_kv() {
201 let (k, v) = kv.into_kv();
202 in_edge = kv.right_edge();
204 out_node.push(k.clone(), v.clone());
205 out_tree.length += 1;
211 Internal(internal) => {
212 let mut out_tree = clone_subtree(internal.first_edge().descend());
215 let out_root = out_tree.root.as_mut().unwrap();
216 let mut out_node = out_root.push_internal_level();
217 let mut in_edge = internal.first_edge();
218 while let Ok(kv) = in_edge.right_kv() {
219 let (k, v) = kv.into_kv();
220 in_edge = kv.right_edge();
222 let k = (*k).clone();
223 let v = (*v).clone();
224 let subtree = clone_subtree(in_edge.descend());
226 // We can't destructure subtree directly
227 // because BTreeMap implements Drop
228 let (subroot, sublength) = unsafe {
229 let subtree = ManuallyDrop::new(subtree);
230 let root = ptr::read(&subtree.root);
231 let length = subtree.length;
235 out_node.push(k, v, subroot.unwrap_or_else(Root::new));
236 out_tree.length += 1 + sublength;
248 clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
253 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
260 fn get(&self, key: &Q) -> Option<&K> {
261 let root_node = self.root.as_ref()?.reborrow();
262 match root_node.search_tree(key) {
263 Found(handle) => Some(handle.into_kv().0),
268 fn take(&mut self, key: &Q) -> Option<K> {
269 let (map, dormant_map) = DormantMutRef::new(self);
270 let root_node = map.root.as_mut()?.borrow_mut();
271 match root_node.search_tree(key) {
273 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
279 fn replace(&mut self, key: K) -> Option<K> {
280 let (map, dormant_map) = DormantMutRef::new(self);
281 let root_node = map.root.get_or_insert_with(Root::new).borrow_mut();
282 match root_node.search_tree::<K>(&key) {
283 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
285 VacantEntry { key, handle: Some(handle), dormant_map, _marker: PhantomData }
293 /// An iterator over the entries of a `BTreeMap`.
295 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
296 /// documentation for more.
298 /// [`iter`]: BTreeMap::iter
299 #[must_use = "iterators are lazy and do nothing unless consumed"]
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub struct Iter<'a, K: 'a, V: 'a> {
302 range: LazyLeafRange<marker::Immut<'a>, K, V>,
306 #[stable(feature = "collection_debug", since = "1.17.0")]
307 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 f.debug_list().entries(self.clone()).finish()
313 /// A mutable iterator over the entries of a `BTreeMap`.
315 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
316 /// documentation for more.
318 /// [`iter_mut`]: BTreeMap::iter_mut
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub struct IterMut<'a, K: 'a, V: 'a> {
321 range: LazyLeafRange<marker::ValMut<'a>, K, V>,
324 // Be invariant in `K` and `V`
325 _marker: PhantomData<&'a mut (K, V)>,
328 #[must_use = "iterators are lazy and do nothing unless consumed"]
329 #[stable(feature = "collection_debug", since = "1.17.0")]
330 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 let range = Iter { range: self.range.reborrow(), length: self.length };
333 f.debug_list().entries(range).finish()
337 /// An owning iterator over the entries of a `BTreeMap`.
339 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
340 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
342 /// [`into_iter`]: IntoIterator::into_iter
343 /// [`IntoIterator`]: core::iter::IntoIterator
344 #[stable(feature = "rust1", since = "1.0.0")]
345 #[rustc_insignificant_dtor]
346 pub struct IntoIter<K, V> {
347 range: LazyLeafRange<marker::Dying, K, V>,
351 impl<K, V> IntoIter<K, V> {
352 /// Returns an iterator of references over the remaining items.
354 pub(super) fn iter(&self) -> Iter<'_, K, V> {
355 Iter { range: self.range.reborrow(), length: self.length }
359 #[stable(feature = "collection_debug", since = "1.17.0")]
360 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 f.debug_list().entries(self.iter()).finish()
366 /// An iterator over the keys of a `BTreeMap`.
368 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
369 /// documentation for more.
371 /// [`keys`]: BTreeMap::keys
372 #[must_use = "iterators are lazy and do nothing unless consumed"]
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub struct Keys<'a, K: 'a, V: 'a> {
375 inner: Iter<'a, K, V>,
378 #[stable(feature = "collection_debug", since = "1.17.0")]
379 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 f.debug_list().entries(self.clone()).finish()
385 /// An iterator over the values of a `BTreeMap`.
387 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
388 /// documentation for more.
390 /// [`values`]: BTreeMap::values
391 #[must_use = "iterators are lazy and do nothing unless consumed"]
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub struct Values<'a, K: 'a, V: 'a> {
394 inner: Iter<'a, K, V>,
397 #[stable(feature = "collection_debug", since = "1.17.0")]
398 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400 f.debug_list().entries(self.clone()).finish()
404 /// A mutable iterator over the values of a `BTreeMap`.
406 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
407 /// documentation for more.
409 /// [`values_mut`]: BTreeMap::values_mut
410 #[must_use = "iterators are lazy and do nothing unless consumed"]
411 #[stable(feature = "map_values_mut", since = "1.10.0")]
412 pub struct ValuesMut<'a, K: 'a, V: 'a> {
413 inner: IterMut<'a, K, V>,
416 #[stable(feature = "map_values_mut", since = "1.10.0")]
417 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
423 /// An owning iterator over the keys of a `BTreeMap`.
425 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
426 /// See its documentation for more.
428 /// [`into_keys`]: BTreeMap::into_keys
429 #[must_use = "iterators are lazy and do nothing unless consumed"]
430 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
431 pub struct IntoKeys<K, V> {
432 inner: IntoIter<K, V>,
435 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
436 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
442 /// An owning iterator over the values of a `BTreeMap`.
444 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
445 /// See its documentation for more.
447 /// [`into_values`]: BTreeMap::into_values
448 #[must_use = "iterators are lazy and do nothing unless consumed"]
449 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
450 pub struct IntoValues<K, V> {
451 inner: IntoIter<K, V>,
454 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
455 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
461 /// An iterator over a sub-range of entries in a `BTreeMap`.
463 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
464 /// documentation for more.
466 /// [`range`]: BTreeMap::range
467 #[must_use = "iterators are lazy and do nothing unless consumed"]
468 #[stable(feature = "btree_range", since = "1.17.0")]
469 pub struct Range<'a, K: 'a, V: 'a> {
470 inner: LeafRange<marker::Immut<'a>, K, V>,
473 #[stable(feature = "collection_debug", since = "1.17.0")]
474 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476 f.debug_list().entries(self.clone()).finish()
480 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
482 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
483 /// documentation for more.
485 /// [`range_mut`]: BTreeMap::range_mut
486 #[must_use = "iterators are lazy and do nothing unless consumed"]
487 #[stable(feature = "btree_range", since = "1.17.0")]
488 pub struct RangeMut<'a, K: 'a, V: 'a> {
489 inner: LeafRange<marker::ValMut<'a>, K, V>,
491 // Be invariant in `K` and `V`
492 _marker: PhantomData<&'a mut (K, V)>,
495 #[stable(feature = "collection_debug", since = "1.17.0")]
496 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 let range = Range { inner: self.inner.reborrow() };
499 f.debug_list().entries(range).finish()
503 impl<K, V> BTreeMap<K, V> {
504 /// Makes a new, empty `BTreeMap`.
506 /// Does not allocate anything on its own.
513 /// use std::collections::BTreeMap;
515 /// let mut map = BTreeMap::new();
517 /// // entries can now be inserted into the empty map
518 /// map.insert(1, "a");
520 #[stable(feature = "rust1", since = "1.0.0")]
521 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
523 pub const fn new() -> BTreeMap<K, V> {
524 BTreeMap { root: None, length: 0 }
527 /// Clears the map, removing all elements.
534 /// use std::collections::BTreeMap;
536 /// let mut a = BTreeMap::new();
537 /// a.insert(1, "a");
539 /// assert!(a.is_empty());
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn clear(&mut self) {
543 *self = BTreeMap::new();
546 /// Returns a reference to the value corresponding to the key.
548 /// The key may be any borrowed form of the map's key type, but the ordering
549 /// on the borrowed form *must* match the ordering on the key type.
556 /// use std::collections::BTreeMap;
558 /// let mut map = BTreeMap::new();
559 /// map.insert(1, "a");
560 /// assert_eq!(map.get(&1), Some(&"a"));
561 /// assert_eq!(map.get(&2), None);
563 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
569 let root_node = self.root.as_ref()?.reborrow();
570 match root_node.search_tree(key) {
571 Found(handle) => Some(handle.into_kv().1),
576 /// Returns the key-value pair corresponding to the supplied key.
578 /// The supplied key may be any borrowed form of the map's key type, but the ordering
579 /// on the borrowed form *must* match the ordering on the key type.
584 /// use std::collections::BTreeMap;
586 /// let mut map = BTreeMap::new();
587 /// map.insert(1, "a");
588 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
589 /// assert_eq!(map.get_key_value(&2), None);
591 #[stable(feature = "map_get_key_value", since = "1.40.0")]
592 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
597 let root_node = self.root.as_ref()?.reborrow();
598 match root_node.search_tree(k) {
599 Found(handle) => Some(handle.into_kv()),
604 /// Returns the first key-value pair in the map.
605 /// The key in this pair is the minimum key in the map.
612 /// #![feature(map_first_last)]
613 /// use std::collections::BTreeMap;
615 /// let mut map = BTreeMap::new();
616 /// assert_eq!(map.first_key_value(), None);
617 /// map.insert(1, "b");
618 /// map.insert(2, "a");
619 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
621 #[unstable(feature = "map_first_last", issue = "62924")]
622 pub fn first_key_value(&self) -> Option<(&K, &V)>
626 let root_node = self.root.as_ref()?.reborrow();
627 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
630 /// Returns the first entry in the map for in-place manipulation.
631 /// The key of this entry is the minimum key in the map.
636 /// #![feature(map_first_last)]
637 /// use std::collections::BTreeMap;
639 /// let mut map = BTreeMap::new();
640 /// map.insert(1, "a");
641 /// map.insert(2, "b");
642 /// if let Some(mut entry) = map.first_entry() {
643 /// if *entry.key() > 0 {
644 /// entry.insert("first");
647 /// assert_eq!(*map.get(&1).unwrap(), "first");
648 /// assert_eq!(*map.get(&2).unwrap(), "b");
650 #[unstable(feature = "map_first_last", issue = "62924")]
651 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
655 let (map, dormant_map) = DormantMutRef::new(self);
656 let root_node = map.root.as_mut()?.borrow_mut();
657 let kv = root_node.first_leaf_edge().right_kv().ok()?;
658 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
661 /// Removes and returns the first element in the map.
662 /// The key of this element is the minimum key that was in the map.
666 /// Draining elements in ascending order, while keeping a usable map each iteration.
669 /// #![feature(map_first_last)]
670 /// use std::collections::BTreeMap;
672 /// let mut map = BTreeMap::new();
673 /// map.insert(1, "a");
674 /// map.insert(2, "b");
675 /// while let Some((key, _val)) = map.pop_first() {
676 /// assert!(map.iter().all(|(k, _v)| *k > key));
678 /// assert!(map.is_empty());
680 #[unstable(feature = "map_first_last", issue = "62924")]
681 pub fn pop_first(&mut self) -> Option<(K, V)>
685 self.first_entry().map(|entry| entry.remove_entry())
688 /// Returns the last key-value pair in the map.
689 /// The key in this pair is the maximum key in the map.
696 /// #![feature(map_first_last)]
697 /// use std::collections::BTreeMap;
699 /// let mut map = BTreeMap::new();
700 /// map.insert(1, "b");
701 /// map.insert(2, "a");
702 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
704 #[unstable(feature = "map_first_last", issue = "62924")]
705 pub fn last_key_value(&self) -> Option<(&K, &V)>
709 let root_node = self.root.as_ref()?.reborrow();
710 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
713 /// Returns the last entry in the map for in-place manipulation.
714 /// The key of this entry is the maximum key in the map.
719 /// #![feature(map_first_last)]
720 /// use std::collections::BTreeMap;
722 /// let mut map = BTreeMap::new();
723 /// map.insert(1, "a");
724 /// map.insert(2, "b");
725 /// if let Some(mut entry) = map.last_entry() {
726 /// if *entry.key() > 0 {
727 /// entry.insert("last");
730 /// assert_eq!(*map.get(&1).unwrap(), "a");
731 /// assert_eq!(*map.get(&2).unwrap(), "last");
733 #[unstable(feature = "map_first_last", issue = "62924")]
734 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
738 let (map, dormant_map) = DormantMutRef::new(self);
739 let root_node = map.root.as_mut()?.borrow_mut();
740 let kv = root_node.last_leaf_edge().left_kv().ok()?;
741 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
744 /// Removes and returns the last element in the map.
745 /// The key of this element is the maximum key that was in the map.
749 /// Draining elements in descending order, while keeping a usable map each iteration.
752 /// #![feature(map_first_last)]
753 /// use std::collections::BTreeMap;
755 /// let mut map = BTreeMap::new();
756 /// map.insert(1, "a");
757 /// map.insert(2, "b");
758 /// while let Some((key, _val)) = map.pop_last() {
759 /// assert!(map.iter().all(|(k, _v)| *k < key));
761 /// assert!(map.is_empty());
763 #[unstable(feature = "map_first_last", issue = "62924")]
764 pub fn pop_last(&mut self) -> Option<(K, V)>
768 self.last_entry().map(|entry| entry.remove_entry())
771 /// Returns `true` if the map contains a value for the specified key.
773 /// The key may be any borrowed form of the map's key type, but the ordering
774 /// on the borrowed form *must* match the ordering on the key type.
781 /// use std::collections::BTreeMap;
783 /// let mut map = BTreeMap::new();
784 /// map.insert(1, "a");
785 /// assert_eq!(map.contains_key(&1), true);
786 /// assert_eq!(map.contains_key(&2), false);
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
794 self.get(key).is_some()
797 /// Returns a mutable reference to the value corresponding to the key.
799 /// The key may be any borrowed form of the map's key type, but the ordering
800 /// on the borrowed form *must* match the ordering on the key type.
807 /// use std::collections::BTreeMap;
809 /// let mut map = BTreeMap::new();
810 /// map.insert(1, "a");
811 /// if let Some(x) = map.get_mut(&1) {
814 /// assert_eq!(map[&1], "b");
816 // See `get` for implementation notes, this is basically a copy-paste with mut's added
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
823 let root_node = self.root.as_mut()?.borrow_mut();
824 match root_node.search_tree(key) {
825 Found(handle) => Some(handle.into_val_mut()),
830 /// Inserts a key-value pair into the map.
832 /// If the map did not have this key present, `None` is returned.
834 /// If the map did have this key present, the value is updated, and the old
835 /// value is returned. The key is not updated, though; this matters for
836 /// types that can be `==` without being identical. See the [module-level
837 /// documentation] for more.
839 /// [module-level documentation]: index.html#insert-and-complex-keys
846 /// use std::collections::BTreeMap;
848 /// let mut map = BTreeMap::new();
849 /// assert_eq!(map.insert(37, "a"), None);
850 /// assert_eq!(map.is_empty(), false);
852 /// map.insert(37, "b");
853 /// assert_eq!(map.insert(37, "c"), Some("b"));
854 /// assert_eq!(map[&37], "c");
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn insert(&mut self, key: K, value: V) -> Option<V>
861 match self.entry(key) {
862 Occupied(mut entry) => Some(entry.insert(value)),
870 /// Tries to insert a key-value pair into the map, and returns
871 /// a mutable reference to the value in the entry.
873 /// If the map already had this key present, nothing is updated, and
874 /// an error containing the occupied entry and the value is returned.
881 /// #![feature(map_try_insert)]
883 /// use std::collections::BTreeMap;
885 /// let mut map = BTreeMap::new();
886 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
888 /// let err = map.try_insert(37, "b").unwrap_err();
889 /// assert_eq!(err.entry.key(), &37);
890 /// assert_eq!(err.entry.get(), &"a");
891 /// assert_eq!(err.value, "b");
893 #[unstable(feature = "map_try_insert", issue = "82766")]
894 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>>
898 match self.entry(key) {
899 Occupied(entry) => Err(OccupiedError { entry, value }),
900 Vacant(entry) => Ok(entry.insert(value)),
904 /// Removes a key from the map, returning the value at the key if the key
905 /// was previously in the map.
907 /// The key may be any borrowed form of the map's key type, but the ordering
908 /// on the borrowed form *must* match the ordering on the key type.
915 /// use std::collections::BTreeMap;
917 /// let mut map = BTreeMap::new();
918 /// map.insert(1, "a");
919 /// assert_eq!(map.remove(&1), Some("a"));
920 /// assert_eq!(map.remove(&1), None);
922 #[stable(feature = "rust1", since = "1.0.0")]
923 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
928 self.remove_entry(key).map(|(_, v)| v)
931 /// Removes a key from the map, returning the stored key and value if the key
932 /// was previously in the map.
934 /// The key may be any borrowed form of the map's key type, but the ordering
935 /// on the borrowed form *must* match the ordering on the key type.
942 /// use std::collections::BTreeMap;
944 /// let mut map = BTreeMap::new();
945 /// map.insert(1, "a");
946 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
947 /// assert_eq!(map.remove_entry(&1), None);
949 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
950 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
955 let (map, dormant_map) = DormantMutRef::new(self);
956 let root_node = map.root.as_mut()?.borrow_mut();
957 match root_node.search_tree(key) {
959 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
965 /// Retains only the elements specified by the predicate.
967 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
968 /// The elements are visited in ascending key order.
973 /// use std::collections::BTreeMap;
975 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
976 /// // Keep only the elements with even-numbered keys.
977 /// map.retain(|&k, _| k % 2 == 0);
978 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
981 #[stable(feature = "btree_retain", since = "1.53.0")]
982 pub fn retain<F>(&mut self, mut f: F)
985 F: FnMut(&K, &mut V) -> bool,
987 self.drain_filter(|k, v| !f(k, v));
990 /// Moves all elements from `other` into `self`, leaving `other` empty.
995 /// use std::collections::BTreeMap;
997 /// let mut a = BTreeMap::new();
998 /// a.insert(1, "a");
999 /// a.insert(2, "b");
1000 /// a.insert(3, "c");
1002 /// let mut b = BTreeMap::new();
1003 /// b.insert(3, "d");
1004 /// b.insert(4, "e");
1005 /// b.insert(5, "f");
1007 /// a.append(&mut b);
1009 /// assert_eq!(a.len(), 5);
1010 /// assert_eq!(b.len(), 0);
1012 /// assert_eq!(a[&1], "a");
1013 /// assert_eq!(a[&2], "b");
1014 /// assert_eq!(a[&3], "d");
1015 /// assert_eq!(a[&4], "e");
1016 /// assert_eq!(a[&5], "f");
1018 #[stable(feature = "btree_append", since = "1.11.0")]
1019 pub fn append(&mut self, other: &mut Self)
1023 // Do we have to append anything at all?
1024 if other.is_empty() {
1028 // We can just swap `self` and `other` if `self` is empty.
1029 if self.is_empty() {
1030 mem::swap(self, other);
1034 let self_iter = mem::take(self).into_iter();
1035 let other_iter = mem::take(other).into_iter();
1036 let root = self.root.get_or_insert_with(Root::new);
1037 root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
1040 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1041 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1042 /// yield elements from min (inclusive) to max (exclusive).
1043 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1044 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1045 /// range from 4 to 10.
1049 /// Panics if range `start > end`.
1050 /// Panics if range `start == end` and both bounds are `Excluded`.
1057 /// use std::collections::BTreeMap;
1058 /// use std::ops::Bound::Included;
1060 /// let mut map = BTreeMap::new();
1061 /// map.insert(3, "a");
1062 /// map.insert(5, "b");
1063 /// map.insert(8, "c");
1064 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1065 /// println!("{key}: {value}");
1067 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1069 #[stable(feature = "btree_range", since = "1.17.0")]
1070 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1076 if let Some(root) = &self.root {
1077 Range { inner: root.reborrow().range_search(range) }
1079 Range { inner: LeafRange::none() }
1083 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1084 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1085 /// yield elements from min (inclusive) to max (exclusive).
1086 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1087 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1088 /// range from 4 to 10.
1092 /// Panics if range `start > end`.
1093 /// Panics if range `start == end` and both bounds are `Excluded`.
1100 /// use std::collections::BTreeMap;
1102 /// let mut map: BTreeMap<&str, i32> =
1103 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1104 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1105 /// *balance += 100;
1107 /// for (name, balance) in &map {
1108 /// println!("{name} => {balance}");
1111 #[stable(feature = "btree_range", since = "1.17.0")]
1112 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1118 if let Some(root) = &mut self.root {
1119 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1121 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1125 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1132 /// use std::collections::BTreeMap;
1134 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1136 /// // count the number of occurrences of letters in the vec
1137 /// for x in ["a", "b", "a", "c", "a", "b"] {
1138 /// *count.entry(x).or_insert(0) += 1;
1141 /// assert_eq!(count["a"], 3);
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
1148 let (map, dormant_map) = DormantMutRef::new(self);
1150 None => Vacant(VacantEntry { key, handle: None, dormant_map, _marker: PhantomData }),
1151 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1153 Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData })
1155 GoDown(handle) => Vacant(VacantEntry {
1157 handle: Some(handle),
1159 _marker: PhantomData,
1165 /// Splits the collection into two at the given key. Returns everything after the given key,
1166 /// including the key.
1173 /// use std::collections::BTreeMap;
1175 /// let mut a = BTreeMap::new();
1176 /// a.insert(1, "a");
1177 /// a.insert(2, "b");
1178 /// a.insert(3, "c");
1179 /// a.insert(17, "d");
1180 /// a.insert(41, "e");
1182 /// let b = a.split_off(&3);
1184 /// assert_eq!(a.len(), 2);
1185 /// assert_eq!(b.len(), 3);
1187 /// assert_eq!(a[&1], "a");
1188 /// assert_eq!(a[&2], "b");
1190 /// assert_eq!(b[&3], "c");
1191 /// assert_eq!(b[&17], "d");
1192 /// assert_eq!(b[&41], "e");
1194 #[stable(feature = "btree_split_off", since = "1.11.0")]
1195 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1199 if self.is_empty() {
1203 let total_num = self.len();
1204 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1206 let right_root = left_root.split_off(key);
1208 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1209 self.length = new_left_len;
1211 BTreeMap { root: Some(right_root), length: right_len }
1214 /// Creates an iterator that visits all elements (key-value pairs) in
1215 /// ascending key order and uses a closure to determine if an element should
1216 /// be removed. If the closure returns `true`, the element is removed from
1217 /// the map and yielded. If the closure returns `false`, or panics, the
1218 /// element remains in the map and will not be yielded.
1220 /// The iterator also lets you mutate the value of each element in the
1221 /// closure, regardless of whether you choose to keep or remove it.
1223 /// If the iterator is only partially consumed or not consumed at all, each
1224 /// of the remaining elements is still subjected to the closure, which may
1225 /// change its value and, by returning `true`, have the element removed and
1228 /// It is unspecified how many more elements will be subjected to the
1229 /// closure if a panic occurs in the closure, or a panic occurs while
1230 /// dropping an element, or if the `DrainFilter` value is leaked.
1234 /// Splitting a map into even and odd keys, reusing the original map:
1237 /// #![feature(btree_drain_filter)]
1238 /// use std::collections::BTreeMap;
1240 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1241 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1243 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1244 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1246 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1247 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1250 F: FnMut(&K, &mut V) -> bool,
1252 DrainFilter { pred, inner: self.drain_filter_inner() }
1255 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V>
1259 if let Some(root) = self.root.as_mut() {
1260 let (root, dormant_root) = DormantMutRef::new(root);
1261 let front = root.borrow_mut().first_leaf_edge();
1263 length: &mut self.length,
1264 dormant_root: Some(dormant_root),
1265 cur_leaf_edge: Some(front),
1268 DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1272 /// Creates a consuming iterator visiting all the keys, in sorted order.
1273 /// The map cannot be used after calling this.
1274 /// The iterator element type is `K`.
1279 /// use std::collections::BTreeMap;
1281 /// let mut a = BTreeMap::new();
1282 /// a.insert(2, "b");
1283 /// a.insert(1, "a");
1285 /// let keys: Vec<i32> = a.into_keys().collect();
1286 /// assert_eq!(keys, [1, 2]);
1289 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1290 pub fn into_keys(self) -> IntoKeys<K, V> {
1291 IntoKeys { inner: self.into_iter() }
1294 /// Creates a consuming iterator visiting all the values, in order by key.
1295 /// The map cannot be used after calling this.
1296 /// The iterator element type is `V`.
1301 /// use std::collections::BTreeMap;
1303 /// let mut a = BTreeMap::new();
1304 /// a.insert(1, "hello");
1305 /// a.insert(2, "goodbye");
1307 /// let values: Vec<&str> = a.into_values().collect();
1308 /// assert_eq!(values, ["hello", "goodbye"]);
1311 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1312 pub fn into_values(self) -> IntoValues<K, V> {
1313 IntoValues { inner: self.into_iter() }
1316 /// Makes a `BTreeMap` from a sorted iterator.
1317 pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I) -> Self
1320 I: IntoIterator<Item = (K, V)>,
1322 let mut root = Root::new();
1324 root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length);
1325 BTreeMap { root: Some(root), length }
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1331 type Item = (&'a K, &'a V);
1332 type IntoIter = Iter<'a, K, V>;
1334 fn into_iter(self) -> Iter<'a, K, V> {
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1341 type Item = (&'a K, &'a V);
1343 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1344 if self.length == 0 {
1348 Some(unsafe { self.range.next_unchecked() })
1352 fn size_hint(&self) -> (usize, Option<usize>) {
1353 (self.length, Some(self.length))
1356 fn last(mut self) -> Option<(&'a K, &'a V)> {
1360 fn min(mut self) -> Option<(&'a K, &'a V)> {
1364 fn max(mut self) -> Option<(&'a K, &'a V)> {
1369 #[stable(feature = "fused", since = "1.26.0")]
1370 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1374 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1375 if self.length == 0 {
1379 Some(unsafe { self.range.next_back_unchecked() })
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1386 fn len(&self) -> usize {
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<K, V> Clone for Iter<'_, K, V> {
1393 fn clone(&self) -> Self {
1394 Iter { range: self.range.clone(), length: self.length }
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1400 type Item = (&'a K, &'a mut V);
1401 type IntoIter = IterMut<'a, K, V>;
1403 fn into_iter(self) -> IterMut<'a, K, V> {
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1410 type Item = (&'a K, &'a mut V);
1412 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1413 if self.length == 0 {
1417 Some(unsafe { self.range.next_unchecked() })
1421 fn size_hint(&self) -> (usize, Option<usize>) {
1422 (self.length, Some(self.length))
1425 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1429 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1433 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1440 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1441 if self.length == 0 {
1445 Some(unsafe { self.range.next_back_unchecked() })
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1452 fn len(&self) -> usize {
1457 #[stable(feature = "fused", since = "1.26.0")]
1458 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1460 impl<'a, K, V> IterMut<'a, K, V> {
1461 /// Returns an iterator of references over the remaining items.
1463 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1464 Iter { range: self.range.reborrow(), length: self.length }
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl<K, V> IntoIterator for BTreeMap<K, V> {
1471 type IntoIter = IntoIter<K, V>;
1473 fn into_iter(self) -> IntoIter<K, V> {
1474 let mut me = ManuallyDrop::new(self);
1475 if let Some(root) = me.root.take() {
1476 let full_range = root.into_dying().full_range();
1478 IntoIter { range: full_range, length: me.length }
1480 IntoIter { range: LazyLeafRange::none(), length: 0 }
1485 #[stable(feature = "btree_drop", since = "1.7.0")]
1486 impl<K, V> Drop for IntoIter<K, V> {
1487 fn drop(&mut self) {
1488 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1490 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1491 fn drop(&mut self) {
1492 // Continue the same loop we perform below. This only runs when unwinding, so we
1493 // don't have to care about panics this time (they'll abort).
1494 while let Some(kv) = self.0.dying_next() {
1495 // SAFETY: we consume the dying handle immediately.
1496 unsafe { kv.drop_key_val() };
1501 while let Some(kv) = self.dying_next() {
1502 let guard = DropGuard(self);
1503 // SAFETY: we don't touch the tree before consuming the dying handle.
1504 unsafe { kv.drop_key_val() };
1510 impl<K, V> IntoIter<K, V> {
1511 /// Core of a `next` method returning a dying KV handle,
1512 /// invalidated by further calls to this function and some others.
1515 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1516 if self.length == 0 {
1517 self.range.deallocating_end();
1521 Some(unsafe { self.range.deallocating_next_unchecked() })
1525 /// Core of a `next_back` method returning a dying KV handle,
1526 /// invalidated by further calls to this function and some others.
1529 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1530 if self.length == 0 {
1531 self.range.deallocating_end();
1535 Some(unsafe { self.range.deallocating_next_back_unchecked() })
1540 #[stable(feature = "rust1", since = "1.0.0")]
1541 impl<K, V> Iterator for IntoIter<K, V> {
1544 fn next(&mut self) -> Option<(K, V)> {
1545 // SAFETY: we consume the dying handle immediately.
1546 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1549 fn size_hint(&self) -> (usize, Option<usize>) {
1550 (self.length, Some(self.length))
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1556 fn next_back(&mut self) -> Option<(K, V)> {
1557 // SAFETY: we consume the dying handle immediately.
1558 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1564 fn len(&self) -> usize {
1569 #[stable(feature = "fused", since = "1.26.0")]
1570 impl<K, V> FusedIterator for IntoIter<K, V> {}
1572 #[stable(feature = "rust1", since = "1.0.0")]
1573 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1576 fn next(&mut self) -> Option<&'a K> {
1577 self.inner.next().map(|(k, _)| k)
1580 fn size_hint(&self) -> (usize, Option<usize>) {
1581 self.inner.size_hint()
1584 fn last(mut self) -> Option<&'a K> {
1588 fn min(mut self) -> Option<&'a K> {
1592 fn max(mut self) -> Option<&'a K> {
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1599 fn next_back(&mut self) -> Option<&'a K> {
1600 self.inner.next_back().map(|(k, _)| k)
1604 #[stable(feature = "rust1", since = "1.0.0")]
1605 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1606 fn len(&self) -> usize {
1611 #[stable(feature = "fused", since = "1.26.0")]
1612 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 impl<K, V> Clone for Keys<'_, K, V> {
1616 fn clone(&self) -> Self {
1617 Keys { inner: self.inner.clone() }
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<'a, K, V> Iterator for Values<'a, K, V> {
1625 fn next(&mut self) -> Option<&'a V> {
1626 self.inner.next().map(|(_, v)| v)
1629 fn size_hint(&self) -> (usize, Option<usize>) {
1630 self.inner.size_hint()
1633 fn last(mut self) -> Option<&'a V> {
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1640 fn next_back(&mut self) -> Option<&'a V> {
1641 self.inner.next_back().map(|(_, v)| v)
1645 #[stable(feature = "rust1", since = "1.0.0")]
1646 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1647 fn len(&self) -> usize {
1652 #[stable(feature = "fused", since = "1.26.0")]
1653 impl<K, V> FusedIterator for Values<'_, K, V> {}
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<K, V> Clone for Values<'_, K, V> {
1657 fn clone(&self) -> Self {
1658 Values { inner: self.inner.clone() }
1662 /// An iterator produced by calling `drain_filter` on BTreeMap.
1663 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1664 pub struct DrainFilter<'a, K, V, F>
1668 F: 'a + FnMut(&K, &mut V) -> bool,
1671 inner: DrainFilterInner<'a, K, V>,
1673 /// Most of the implementation of DrainFilter are generic over the type
1674 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1675 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1676 /// Reference to the length field in the borrowed map, updated live.
1677 length: &'a mut usize,
1678 /// Buried reference to the root field in the borrowed map.
1679 /// Wrapped in `Option` to allow drop handler to `take` it.
1680 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1681 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1682 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1683 /// or if a panic occurred in the predicate.
1684 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1687 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1688 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1690 F: FnMut(&K, &mut V) -> bool,
1692 fn drop(&mut self) {
1693 self.for_each(drop);
1697 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1698 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1702 F: FnMut(&K, &mut V) -> bool,
1704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1709 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1710 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1712 F: FnMut(&K, &mut V) -> bool,
1716 fn next(&mut self) -> Option<(K, V)> {
1717 self.inner.next(&mut self.pred)
1720 fn size_hint(&self) -> (usize, Option<usize>) {
1721 self.inner.size_hint()
1725 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1726 /// Allow Debug implementations to predict the next element.
1727 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1728 let edge = self.cur_leaf_edge.as_ref()?;
1729 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1732 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1733 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1735 F: FnMut(&K, &mut V) -> bool,
1737 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1738 let (k, v) = kv.kv_mut();
1741 let (kv, pos) = kv.remove_kv_tracking(|| {
1742 // SAFETY: we will touch the root in a way that will not
1743 // invalidate the position returned.
1744 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1745 root.pop_internal_level();
1746 self.dormant_root = Some(DormantMutRef::new(root).1);
1748 self.cur_leaf_edge = Some(pos);
1751 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1756 /// Implementation of a typical `DrainFilter::size_hint` method.
1757 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1758 // In most of the btree iterators, `self.length` is the number of elements
1759 // yet to be visited. Here, it includes elements that were visited and that
1760 // the predicate decided not to drain. Making this upper bound more tight
1761 // during iteration would require an extra field.
1762 (0, Some(*self.length))
1766 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1767 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1769 #[stable(feature = "btree_range", since = "1.17.0")]
1770 impl<'a, K, V> Iterator for Range<'a, K, V> {
1771 type Item = (&'a K, &'a V);
1773 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1774 self.inner.next_checked()
1777 fn last(mut self) -> Option<(&'a K, &'a V)> {
1781 fn min(mut self) -> Option<(&'a K, &'a V)> {
1785 fn max(mut self) -> Option<(&'a K, &'a V)> {
1790 #[stable(feature = "map_values_mut", since = "1.10.0")]
1791 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1792 type Item = &'a mut V;
1794 fn next(&mut self) -> Option<&'a mut V> {
1795 self.inner.next().map(|(_, v)| v)
1798 fn size_hint(&self) -> (usize, Option<usize>) {
1799 self.inner.size_hint()
1802 fn last(mut self) -> Option<&'a mut V> {
1807 #[stable(feature = "map_values_mut", since = "1.10.0")]
1808 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1809 fn next_back(&mut self) -> Option<&'a mut V> {
1810 self.inner.next_back().map(|(_, v)| v)
1814 #[stable(feature = "map_values_mut", since = "1.10.0")]
1815 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1816 fn len(&self) -> usize {
1821 #[stable(feature = "fused", since = "1.26.0")]
1822 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1824 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1825 impl<K, V> Iterator for IntoKeys<K, V> {
1828 fn next(&mut self) -> Option<K> {
1829 self.inner.next().map(|(k, _)| k)
1832 fn size_hint(&self) -> (usize, Option<usize>) {
1833 self.inner.size_hint()
1836 fn last(mut self) -> Option<K> {
1840 fn min(mut self) -> Option<K> {
1844 fn max(mut self) -> Option<K> {
1849 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1850 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1851 fn next_back(&mut self) -> Option<K> {
1852 self.inner.next_back().map(|(k, _)| k)
1856 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1857 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1858 fn len(&self) -> usize {
1863 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1864 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1866 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1867 impl<K, V> Iterator for IntoValues<K, V> {
1870 fn next(&mut self) -> Option<V> {
1871 self.inner.next().map(|(_, v)| v)
1874 fn size_hint(&self) -> (usize, Option<usize>) {
1875 self.inner.size_hint()
1878 fn last(mut self) -> Option<V> {
1883 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1884 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1885 fn next_back(&mut self) -> Option<V> {
1886 self.inner.next_back().map(|(_, v)| v)
1890 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1891 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1892 fn len(&self) -> usize {
1897 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1898 impl<K, V> FusedIterator for IntoValues<K, V> {}
1900 #[stable(feature = "btree_range", since = "1.17.0")]
1901 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1902 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1903 self.inner.next_back_checked()
1907 #[stable(feature = "fused", since = "1.26.0")]
1908 impl<K, V> FusedIterator for Range<'_, K, V> {}
1910 #[stable(feature = "btree_range", since = "1.17.0")]
1911 impl<K, V> Clone for Range<'_, K, V> {
1912 fn clone(&self) -> Self {
1913 Range { inner: self.inner.clone() }
1917 #[stable(feature = "btree_range", since = "1.17.0")]
1918 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1919 type Item = (&'a K, &'a mut V);
1921 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1922 self.inner.next_checked()
1925 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1929 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1933 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1938 #[stable(feature = "btree_range", since = "1.17.0")]
1939 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1940 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1941 self.inner.next_back_checked()
1945 #[stable(feature = "fused", since = "1.26.0")]
1946 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1950 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1951 let mut inputs: Vec<_> = iter.into_iter().collect();
1953 if inputs.is_empty() {
1954 return BTreeMap::new();
1957 // use stable sort to preserve the insertion order.
1958 inputs.sort_by(|a, b| a.0.cmp(&b.0));
1959 BTreeMap::bulk_build_from_sorted_iter(inputs)
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1966 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1967 iter.into_iter().for_each(move |(k, v)| {
1973 fn extend_one(&mut self, (k, v): (K, V)) {
1978 #[stable(feature = "extend_ref", since = "1.2.0")]
1979 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1980 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1981 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1985 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1992 fn hash<H: Hasher>(&self, state: &mut H) {
1993 state.write_length_prefix(self.len());
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<K, V> Default for BTreeMap<K, V> {
2002 /// Creates an empty `BTreeMap`.
2003 fn default() -> BTreeMap<K, V> {
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
2010 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
2011 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
2018 #[stable(feature = "rust1", since = "1.0.0")]
2019 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
2021 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
2022 self.iter().partial_cmp(other.iter())
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
2029 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
2030 self.iter().cmp(other.iter())
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
2036 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2037 f.debug_map().entries(self.iter()).finish()
2041 #[stable(feature = "rust1", since = "1.0.0")]
2042 impl<K, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
2049 /// Returns a reference to the value corresponding to the supplied key.
2053 /// Panics if the key is not present in the `BTreeMap`.
2055 fn index(&self, key: &Q) -> &V {
2056 self.get(key).expect("no entry found for key")
2060 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
2061 impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2062 /// Converts a `[(K, V); N]` into a `BTreeMap<(K, V)>`.
2065 /// use std::collections::BTreeMap;
2067 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2068 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2069 /// assert_eq!(map1, map2);
2071 fn from(mut arr: [(K, V); N]) -> Self {
2073 return BTreeMap::new();
2076 // use stable sort to preserve the insertion order.
2077 arr.sort_by(|a, b| a.0.cmp(&b.0));
2078 BTreeMap::bulk_build_from_sorted_iter(arr)
2082 impl<K, V> BTreeMap<K, V> {
2083 /// Gets an iterator over the entries of the map, sorted by key.
2090 /// use std::collections::BTreeMap;
2092 /// let mut map = BTreeMap::new();
2093 /// map.insert(3, "c");
2094 /// map.insert(2, "b");
2095 /// map.insert(1, "a");
2097 /// for (key, value) in map.iter() {
2098 /// println!("{key}: {value}");
2101 /// let (first_key, first_value) = map.iter().next().unwrap();
2102 /// assert_eq!((*first_key, *first_value), (1, "a"));
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 pub fn iter(&self) -> Iter<'_, K, V> {
2106 if let Some(root) = &self.root {
2107 let full_range = root.reborrow().full_range();
2109 Iter { range: full_range, length: self.length }
2111 Iter { range: LazyLeafRange::none(), length: 0 }
2115 /// Gets a mutable iterator over the entries of the map, sorted by key.
2122 /// use std::collections::BTreeMap;
2124 /// let mut map = BTreeMap::from([
2130 /// // add 10 to the value if the key isn't "a"
2131 /// for (key, value) in map.iter_mut() {
2132 /// if key != &"a" {
2137 #[stable(feature = "rust1", since = "1.0.0")]
2138 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2139 if let Some(root) = &mut self.root {
2140 let full_range = root.borrow_valmut().full_range();
2142 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2144 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2148 /// Gets an iterator over the keys of the map, in sorted order.
2155 /// use std::collections::BTreeMap;
2157 /// let mut a = BTreeMap::new();
2158 /// a.insert(2, "b");
2159 /// a.insert(1, "a");
2161 /// let keys: Vec<_> = a.keys().cloned().collect();
2162 /// assert_eq!(keys, [1, 2]);
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 pub fn keys(&self) -> Keys<'_, K, V> {
2166 Keys { inner: self.iter() }
2169 /// Gets an iterator over the values of the map, in order by key.
2176 /// use std::collections::BTreeMap;
2178 /// let mut a = BTreeMap::new();
2179 /// a.insert(1, "hello");
2180 /// a.insert(2, "goodbye");
2182 /// let values: Vec<&str> = a.values().cloned().collect();
2183 /// assert_eq!(values, ["hello", "goodbye"]);
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 pub fn values(&self) -> Values<'_, K, V> {
2187 Values { inner: self.iter() }
2190 /// Gets a mutable iterator over the values of the map, in order by key.
2197 /// use std::collections::BTreeMap;
2199 /// let mut a = BTreeMap::new();
2200 /// a.insert(1, String::from("hello"));
2201 /// a.insert(2, String::from("goodbye"));
2203 /// for value in a.values_mut() {
2204 /// value.push_str("!");
2207 /// let values: Vec<String> = a.values().cloned().collect();
2208 /// assert_eq!(values, [String::from("hello!"),
2209 /// String::from("goodbye!")]);
2211 #[stable(feature = "map_values_mut", since = "1.10.0")]
2212 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2213 ValuesMut { inner: self.iter_mut() }
2216 /// Returns the number of elements in the map.
2223 /// use std::collections::BTreeMap;
2225 /// let mut a = BTreeMap::new();
2226 /// assert_eq!(a.len(), 0);
2227 /// a.insert(1, "a");
2228 /// assert_eq!(a.len(), 1);
2231 #[stable(feature = "rust1", since = "1.0.0")]
2232 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2233 pub const fn len(&self) -> usize {
2237 /// Returns `true` if the map contains no elements.
2244 /// use std::collections::BTreeMap;
2246 /// let mut a = BTreeMap::new();
2247 /// assert!(a.is_empty());
2248 /// a.insert(1, "a");
2249 /// assert!(!a.is_empty());
2252 #[stable(feature = "rust1", since = "1.0.0")]
2253 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2254 pub const fn is_empty(&self) -> bool {