1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
3 use core::fmt::{self, Debug};
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator};
6 use core::marker::PhantomData;
7 use core::mem::{self, ManuallyDrop};
8 use core::ops::{Index, RangeBounds};
11 use super::borrow::DormantMutRef;
12 use super::navigate::LeafRange;
13 use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
14 use super::search::SearchResult::*;
17 pub use entry::{Entry, OccupiedEntry, VacantEntry};
20 /// Minimum number of elements in nodes that are not a root.
21 /// We might temporarily have fewer elements during methods.
22 pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
24 // A tree in a `BTreeMap` is a tree in the `node` module with addtional invariants:
25 // - Keys must appear in ascending order (according to the key's type).
26 // - If the root node is internal, it must contain at least 1 element.
27 // - Every non-root node contains at least MIN_LEN elements.
29 // An empty map may be represented both by the absense of a root node or by a
30 // root node that is an empty leaf.
32 /// A map based on a B-Tree.
34 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
35 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
36 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
37 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
38 /// is done is *very* inefficient for modern computer architectures. In particular, every element
39 /// is stored in its own individually heap-allocated node. This means that every single insertion
40 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
41 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
44 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
45 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
46 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
47 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
48 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
49 /// the node using binary search. As a compromise, one could also perform a linear search
50 /// that initially only checks every i<sup>th</sup> element for some choice of i.
52 /// Currently, our implementation simply performs naive linear search. This provides excellent
53 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
54 /// would like to further explore choosing the optimal search strategy based on the choice of B,
55 /// and possibly other factors. Using linear search, searching for a random element is expected
56 /// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
57 /// however, performance is excellent.
59 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
60 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
61 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
62 /// The behavior resulting from such a logic error is not specified, but will not result in
63 /// undefined behavior. This could include panics, incorrect results, aborts, memory leaks, and
66 /// [`Cell`]: core::cell::Cell
67 /// [`RefCell`]: core::cell::RefCell
72 /// use std::collections::BTreeMap;
74 /// // type inference lets us omit an explicit type signature (which
75 /// // would be `BTreeMap<&str, &str>` in this example).
76 /// let mut movie_reviews = BTreeMap::new();
78 /// // review some movies.
79 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
80 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
81 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
82 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
84 /// // check for a specific one.
85 /// if !movie_reviews.contains_key("Les Misérables") {
86 /// println!("We've got {} reviews, but Les Misérables ain't one.",
87 /// movie_reviews.len());
90 /// // oops, this review has a lot of spelling mistakes, let's delete it.
91 /// movie_reviews.remove("The Blues Brothers");
93 /// // look up the values associated with some keys.
94 /// let to_find = ["Up!", "Office Space"];
95 /// for movie in &to_find {
96 /// match movie_reviews.get(movie) {
97 /// Some(review) => println!("{}: {}", movie, review),
98 /// None => println!("{} is unreviewed.", movie)
102 /// // Look up the value for a key (will panic if the key is not found).
103 /// println!("Movie review: {}", movie_reviews["Office Space"]);
105 /// // iterate over everything.
106 /// for (movie, review) in &movie_reviews {
107 /// println!("{}: \"{}\"", movie, review);
111 /// `BTreeMap` also implements an [`Entry API`], which allows for more complex
112 /// methods of getting, setting, updating and removing keys and their values:
114 /// [`Entry API`]: BTreeMap::entry
117 /// use std::collections::BTreeMap;
119 /// // type inference lets us omit an explicit type signature (which
120 /// // would be `BTreeMap<&str, u8>` in this example).
121 /// let mut player_stats = BTreeMap::new();
123 /// fn random_stat_buff() -> u8 {
124 /// // could actually return some random value here - let's just return
125 /// // some fixed value for now
129 /// // insert a key only if it doesn't already exist
130 /// player_stats.entry("health").or_insert(100);
132 /// // insert a key using a function that provides a new value only if it
133 /// // doesn't already exist
134 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
136 /// // update a key, guarding against the key possibly not being set
137 /// let stat = player_stats.entry("attack").or_insert(100);
138 /// *stat += random_stat_buff();
140 #[stable(feature = "rust1", since = "1.0.0")]
141 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
142 pub struct BTreeMap<K, V> {
143 root: Option<Root<K, V>>,
147 #[stable(feature = "btree_drop", since = "1.7.0")]
148 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
150 if let Some(root) = self.root.take() {
151 Dropper { front: root.into_dying().first_leaf_edge(), remaining_length: self.length };
156 #[stable(feature = "rust1", since = "1.0.0")]
157 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
158 fn clone(&self) -> BTreeMap<K, V> {
159 fn clone_subtree<'a, K: Clone, V: Clone>(
160 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
168 let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 };
171 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
172 let mut out_node = match root.borrow_mut().force() {
174 Internal(_) => unreachable!(),
177 let mut in_edge = leaf.first_edge();
178 while let Ok(kv) = in_edge.right_kv() {
179 let (k, v) = kv.into_kv();
180 in_edge = kv.right_edge();
182 out_node.push(k.clone(), v.clone());
183 out_tree.length += 1;
189 Internal(internal) => {
190 let mut out_tree = clone_subtree(internal.first_edge().descend());
193 let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
194 let mut out_node = out_root.push_internal_level();
195 let mut in_edge = internal.first_edge();
196 while let Ok(kv) = in_edge.right_kv() {
197 let (k, v) = kv.into_kv();
198 in_edge = kv.right_edge();
200 let k = (*k).clone();
201 let v = (*v).clone();
202 let subtree = clone_subtree(in_edge.descend());
204 // We can't destructure subtree directly
205 // because BTreeMap implements Drop
206 let (subroot, sublength) = unsafe {
207 let subtree = ManuallyDrop::new(subtree);
208 let root = ptr::read(&subtree.root);
209 let length = subtree.length;
213 out_node.push(k, v, subroot.unwrap_or_else(Root::new));
214 out_tree.length += 1 + sublength;
224 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
225 // Ord` constraint, which this method lacks.
226 BTreeMap { root: None, length: 0 }
228 clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
233 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
240 fn get(&self, key: &Q) -> Option<&K> {
241 let root_node = self.root.as_ref()?.reborrow();
242 match root_node.search_tree(key) {
243 Found(handle) => Some(handle.into_kv().0),
248 fn take(&mut self, key: &Q) -> Option<K> {
249 let (map, dormant_map) = DormantMutRef::new(self);
250 let root_node = map.root.as_mut()?.borrow_mut();
251 match root_node.search_tree(key) {
253 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
259 fn replace(&mut self, key: K) -> Option<K> {
260 let (map, dormant_map) = DormantMutRef::new(self);
261 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
262 match root_node.search_tree::<K>(&key) {
263 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
265 VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
272 /// An iterator over the entries of a `BTreeMap`.
274 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
275 /// documentation for more.
277 /// [`iter`]: BTreeMap::iter
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub struct Iter<'a, K: 'a, V: 'a> {
280 range: Range<'a, K, V>,
284 #[stable(feature = "collection_debug", since = "1.17.0")]
285 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 f.debug_list().entries(self.clone()).finish()
291 /// A mutable iterator over the entries of a `BTreeMap`.
293 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
294 /// documentation for more.
296 /// [`iter_mut`]: BTreeMap::iter_mut
297 #[stable(feature = "rust1", since = "1.0.0")]
299 pub struct IterMut<'a, K: 'a, V: 'a> {
300 range: RangeMut<'a, K, V>,
304 /// An owning iterator over the entries of a `BTreeMap`.
306 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
307 /// (provided by the `IntoIterator` trait). See its documentation for more.
309 /// [`into_iter`]: IntoIterator::into_iter
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub struct IntoIter<K, V> {
312 range: LeafRange<marker::Dying, K, V>,
316 impl<K, V> IntoIter<K, V> {
317 /// Returns an iterator of references over the remaining items.
319 pub(super) fn iter(&self) -> Iter<'_, K, V> {
320 let range = Range { inner: self.range.reborrow() };
321 Iter { range: range, length: self.length }
325 #[stable(feature = "collection_debug", since = "1.17.0")]
326 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 f.debug_list().entries(self.iter()).finish()
332 /// A simplified version of `IntoIter` that is not double-ended and has only one
333 /// purpose: to drop the remainder of an `IntoIter`. Therefore it also serves to
334 /// drop an entire tree without the need to first look up a `back` leaf edge.
335 struct Dropper<K, V> {
336 front: Handle<NodeRef<marker::Dying, K, V, marker::Leaf>, marker::Edge>,
337 remaining_length: usize,
340 /// An iterator over the keys of a `BTreeMap`.
342 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
343 /// documentation for more.
345 /// [`keys`]: BTreeMap::keys
346 #[stable(feature = "rust1", since = "1.0.0")]
347 pub struct Keys<'a, K: 'a, V: 'a> {
348 inner: Iter<'a, K, V>,
351 #[stable(feature = "collection_debug", since = "1.17.0")]
352 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 f.debug_list().entries(self.clone()).finish()
358 /// An iterator over the values of a `BTreeMap`.
360 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
361 /// documentation for more.
363 /// [`values`]: BTreeMap::values
364 #[stable(feature = "rust1", since = "1.0.0")]
365 pub struct Values<'a, K: 'a, V: 'a> {
366 inner: Iter<'a, K, V>,
369 #[stable(feature = "collection_debug", since = "1.17.0")]
370 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 f.debug_list().entries(self.clone()).finish()
376 /// A mutable iterator over the values of a `BTreeMap`.
378 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
379 /// documentation for more.
381 /// [`values_mut`]: BTreeMap::values_mut
382 #[stable(feature = "map_values_mut", since = "1.10.0")]
383 pub struct ValuesMut<'a, K: 'a, V: 'a> {
384 inner: IterMut<'a, K, V>,
387 #[stable(feature = "map_values_mut", since = "1.10.0")]
388 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
394 /// An owning iterator over the keys of a `BTreeMap`.
396 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
397 /// See its documentation for more.
399 /// [`into_keys`]: BTreeMap::into_keys
400 #[unstable(feature = "map_into_keys_values", issue = "75294")]
401 pub struct IntoKeys<K, V> {
402 inner: IntoIter<K, V>,
405 #[unstable(feature = "map_into_keys_values", issue = "75294")]
406 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
412 /// An owning iterator over the values of a `BTreeMap`.
414 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
415 /// See its documentation for more.
417 /// [`into_values`]: BTreeMap::into_values
418 #[unstable(feature = "map_into_keys_values", issue = "75294")]
419 pub struct IntoValues<K, V> {
420 inner: IntoIter<K, V>,
423 #[unstable(feature = "map_into_keys_values", issue = "75294")]
424 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
430 /// An iterator over a sub-range of entries in a `BTreeMap`.
432 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
433 /// documentation for more.
435 /// [`range`]: BTreeMap::range
436 #[stable(feature = "btree_range", since = "1.17.0")]
437 pub struct Range<'a, K: 'a, V: 'a> {
438 inner: LeafRange<marker::Immut<'a>, K, V>,
441 #[stable(feature = "collection_debug", since = "1.17.0")]
442 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444 f.debug_list().entries(self.clone()).finish()
448 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
450 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
451 /// documentation for more.
453 /// [`range_mut`]: BTreeMap::range_mut
454 #[stable(feature = "btree_range", since = "1.17.0")]
455 pub struct RangeMut<'a, K: 'a, V: 'a> {
456 inner: LeafRange<marker::ValMut<'a>, K, V>,
458 // Be invariant in `K` and `V`
459 _marker: PhantomData<&'a mut (K, V)>,
462 #[stable(feature = "collection_debug", since = "1.17.0")]
463 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465 let range = Range { inner: self.inner.reborrow() };
466 f.debug_list().entries(range).finish()
470 impl<K, V> BTreeMap<K, V> {
471 /// Makes a new, empty `BTreeMap`.
473 /// Does not allocate anything on its own.
480 /// use std::collections::BTreeMap;
482 /// let mut map = BTreeMap::new();
484 /// // entries can now be inserted into the empty map
485 /// map.insert(1, "a");
487 #[stable(feature = "rust1", since = "1.0.0")]
488 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
489 pub const fn new() -> BTreeMap<K, V>
493 BTreeMap { root: None, length: 0 }
496 /// Clears the map, removing all elements.
503 /// use std::collections::BTreeMap;
505 /// let mut a = BTreeMap::new();
506 /// a.insert(1, "a");
508 /// assert!(a.is_empty());
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn clear(&mut self) {
512 *self = BTreeMap { root: None, length: 0 };
515 /// Returns a reference to the value corresponding to the key.
517 /// The key may be any borrowed form of the map's key type, but the ordering
518 /// on the borrowed form *must* match the ordering on the key type.
525 /// use std::collections::BTreeMap;
527 /// let mut map = BTreeMap::new();
528 /// map.insert(1, "a");
529 /// assert_eq!(map.get(&1), Some(&"a"));
530 /// assert_eq!(map.get(&2), None);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
538 let root_node = self.root.as_ref()?.reborrow();
539 match root_node.search_tree(key) {
540 Found(handle) => Some(handle.into_kv().1),
545 /// Returns the key-value pair corresponding to the supplied key.
547 /// The supplied key may be any borrowed form of the map's key type, but the ordering
548 /// on the borrowed form *must* match the ordering on the key type.
553 /// use std::collections::BTreeMap;
555 /// let mut map = BTreeMap::new();
556 /// map.insert(1, "a");
557 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
558 /// assert_eq!(map.get_key_value(&2), None);
560 #[stable(feature = "map_get_key_value", since = "1.40.0")]
561 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
566 let root_node = self.root.as_ref()?.reborrow();
567 match root_node.search_tree(k) {
568 Found(handle) => Some(handle.into_kv()),
573 /// Returns the first key-value pair in the map.
574 /// The key in this pair is the minimum key in the map.
581 /// #![feature(map_first_last)]
582 /// use std::collections::BTreeMap;
584 /// let mut map = BTreeMap::new();
585 /// assert_eq!(map.first_key_value(), None);
586 /// map.insert(1, "b");
587 /// map.insert(2, "a");
588 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
590 #[unstable(feature = "map_first_last", issue = "62924")]
591 pub fn first_key_value(&self) -> Option<(&K, &V)>
595 let root_node = self.root.as_ref()?.reborrow();
596 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
599 /// Returns the first entry in the map for in-place manipulation.
600 /// The key of this entry is the minimum key in the map.
605 /// #![feature(map_first_last)]
606 /// use std::collections::BTreeMap;
608 /// let mut map = BTreeMap::new();
609 /// map.insert(1, "a");
610 /// map.insert(2, "b");
611 /// if let Some(mut entry) = map.first_entry() {
612 /// if *entry.key() > 0 {
613 /// entry.insert("first");
616 /// assert_eq!(*map.get(&1).unwrap(), "first");
617 /// assert_eq!(*map.get(&2).unwrap(), "b");
619 #[unstable(feature = "map_first_last", issue = "62924")]
620 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
624 let (map, dormant_map) = DormantMutRef::new(self);
625 let root_node = map.root.as_mut()?.borrow_mut();
626 let kv = root_node.first_leaf_edge().right_kv().ok()?;
627 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
630 /// Removes and returns the first element in the map.
631 /// The key of this element is the minimum key that was in the map.
635 /// Draining elements in ascending order, while keeping a usable map each iteration.
638 /// #![feature(map_first_last)]
639 /// use std::collections::BTreeMap;
641 /// let mut map = BTreeMap::new();
642 /// map.insert(1, "a");
643 /// map.insert(2, "b");
644 /// while let Some((key, _val)) = map.pop_first() {
645 /// assert!(map.iter().all(|(k, _v)| *k > key));
647 /// assert!(map.is_empty());
649 #[unstable(feature = "map_first_last", issue = "62924")]
650 pub fn pop_first(&mut self) -> Option<(K, V)>
654 self.first_entry().map(|entry| entry.remove_entry())
657 /// Returns the last key-value pair in the map.
658 /// The key in this pair is the maximum key in the map.
665 /// #![feature(map_first_last)]
666 /// use std::collections::BTreeMap;
668 /// let mut map = BTreeMap::new();
669 /// map.insert(1, "b");
670 /// map.insert(2, "a");
671 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
673 #[unstable(feature = "map_first_last", issue = "62924")]
674 pub fn last_key_value(&self) -> Option<(&K, &V)>
678 let root_node = self.root.as_ref()?.reborrow();
679 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
682 /// Returns the last entry in the map for in-place manipulation.
683 /// The key of this entry is the maximum key in the map.
688 /// #![feature(map_first_last)]
689 /// use std::collections::BTreeMap;
691 /// let mut map = BTreeMap::new();
692 /// map.insert(1, "a");
693 /// map.insert(2, "b");
694 /// if let Some(mut entry) = map.last_entry() {
695 /// if *entry.key() > 0 {
696 /// entry.insert("last");
699 /// assert_eq!(*map.get(&1).unwrap(), "a");
700 /// assert_eq!(*map.get(&2).unwrap(), "last");
702 #[unstable(feature = "map_first_last", issue = "62924")]
703 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
707 let (map, dormant_map) = DormantMutRef::new(self);
708 let root_node = map.root.as_mut()?.borrow_mut();
709 let kv = root_node.last_leaf_edge().left_kv().ok()?;
710 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
713 /// Removes and returns the last element in the map.
714 /// The key of this element is the maximum key that was in the map.
718 /// Draining elements in descending order, while keeping a usable map each iteration.
721 /// #![feature(map_first_last)]
722 /// use std::collections::BTreeMap;
724 /// let mut map = BTreeMap::new();
725 /// map.insert(1, "a");
726 /// map.insert(2, "b");
727 /// while let Some((key, _val)) = map.pop_last() {
728 /// assert!(map.iter().all(|(k, _v)| *k < key));
730 /// assert!(map.is_empty());
732 #[unstable(feature = "map_first_last", issue = "62924")]
733 pub fn pop_last(&mut self) -> Option<(K, V)>
737 self.last_entry().map(|entry| entry.remove_entry())
740 /// Returns `true` if the map contains a value for the specified key.
742 /// The key may be any borrowed form of the map's key type, but the ordering
743 /// on the borrowed form *must* match the ordering on the key type.
750 /// use std::collections::BTreeMap;
752 /// let mut map = BTreeMap::new();
753 /// map.insert(1, "a");
754 /// assert_eq!(map.contains_key(&1), true);
755 /// assert_eq!(map.contains_key(&2), false);
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
763 self.get(key).is_some()
766 /// Returns a mutable reference to the value corresponding to the key.
768 /// The key may be any borrowed form of the map's key type, but the ordering
769 /// on the borrowed form *must* match the ordering on the key type.
776 /// use std::collections::BTreeMap;
778 /// let mut map = BTreeMap::new();
779 /// map.insert(1, "a");
780 /// if let Some(x) = map.get_mut(&1) {
783 /// assert_eq!(map[&1], "b");
785 // See `get` for implementation notes, this is basically a copy-paste with mut's added
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
792 let root_node = self.root.as_mut()?.borrow_mut();
793 match root_node.search_tree(key) {
794 Found(handle) => Some(handle.into_val_mut()),
799 /// Inserts a key-value pair into the map.
801 /// If the map did not have this key present, `None` is returned.
803 /// If the map did have this key present, the value is updated, and the old
804 /// value is returned. The key is not updated, though; this matters for
805 /// types that can be `==` without being identical. See the [module-level
806 /// documentation] for more.
808 /// [module-level documentation]: index.html#insert-and-complex-keys
815 /// use std::collections::BTreeMap;
817 /// let mut map = BTreeMap::new();
818 /// assert_eq!(map.insert(37, "a"), None);
819 /// assert_eq!(map.is_empty(), false);
821 /// map.insert(37, "b");
822 /// assert_eq!(map.insert(37, "c"), Some("b"));
823 /// assert_eq!(map[&37], "c");
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub fn insert(&mut self, key: K, value: V) -> Option<V>
830 match self.entry(key) {
831 Occupied(mut entry) => Some(entry.insert(value)),
839 /// Removes a key from the map, returning the value at the key if the key
840 /// was previously in the map.
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.remove(&1), Some("a"));
855 /// assert_eq!(map.remove(&1), None);
857 #[doc(alias = "delete")]
858 #[stable(feature = "rust1", since = "1.0.0")]
859 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
864 self.remove_entry(key).map(|(_, v)| v)
867 /// Removes a key from the map, returning the stored key and value if the key
868 /// was previously in the map.
870 /// The key may be any borrowed form of the map's key type, but the ordering
871 /// on the borrowed form *must* match the ordering on the key type.
878 /// use std::collections::BTreeMap;
880 /// let mut map = BTreeMap::new();
881 /// map.insert(1, "a");
882 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
883 /// assert_eq!(map.remove_entry(&1), None);
885 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
886 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
891 let (map, dormant_map) = DormantMutRef::new(self);
892 let root_node = map.root.as_mut()?.borrow_mut();
893 match root_node.search_tree(key) {
895 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
901 /// Retains only the elements specified by the predicate.
903 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
908 /// #![feature(btree_retain)]
909 /// use std::collections::BTreeMap;
911 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
912 /// // Keep only the elements with even-numbered keys.
913 /// map.retain(|&k, _| k % 2 == 0);
914 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
917 #[unstable(feature = "btree_retain", issue = "79025")]
918 pub fn retain<F>(&mut self, mut f: F)
921 F: FnMut(&K, &mut V) -> bool,
923 self.drain_filter(|k, v| !f(k, v));
926 /// Moves all elements from `other` into `Self`, leaving `other` empty.
931 /// use std::collections::BTreeMap;
933 /// let mut a = BTreeMap::new();
934 /// a.insert(1, "a");
935 /// a.insert(2, "b");
936 /// a.insert(3, "c");
938 /// let mut b = BTreeMap::new();
939 /// b.insert(3, "d");
940 /// b.insert(4, "e");
941 /// b.insert(5, "f");
943 /// a.append(&mut b);
945 /// assert_eq!(a.len(), 5);
946 /// assert_eq!(b.len(), 0);
948 /// assert_eq!(a[&1], "a");
949 /// assert_eq!(a[&2], "b");
950 /// assert_eq!(a[&3], "d");
951 /// assert_eq!(a[&4], "e");
952 /// assert_eq!(a[&5], "f");
954 #[stable(feature = "btree_append", since = "1.11.0")]
955 pub fn append(&mut self, other: &mut Self)
959 // Do we have to append anything at all?
960 if other.is_empty() {
964 // We can just swap `self` and `other` if `self` is empty.
966 mem::swap(self, other);
970 let self_iter = mem::take(self).into_iter();
971 let other_iter = mem::take(other).into_iter();
972 let root = BTreeMap::ensure_is_owned(&mut self.root);
973 root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
976 /// Constructs a double-ended iterator over a sub-range of elements in the map.
977 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
978 /// yield elements from min (inclusive) to max (exclusive).
979 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
980 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
981 /// range from 4 to 10.
985 /// Panics if range `start > end`.
986 /// Panics if range `start == end` and both bounds are `Excluded`.
993 /// use std::collections::BTreeMap;
994 /// use std::ops::Bound::Included;
996 /// let mut map = BTreeMap::new();
997 /// map.insert(3, "a");
998 /// map.insert(5, "b");
999 /// map.insert(8, "c");
1000 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1001 /// println!("{}: {}", key, value);
1003 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1005 #[stable(feature = "btree_range", since = "1.17.0")]
1006 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1012 if let Some(root) = &self.root {
1013 Range { inner: root.reborrow().range_search(range) }
1015 Range { inner: LeafRange::none() }
1019 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1020 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1021 /// yield elements from min (inclusive) to max (exclusive).
1022 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1023 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1024 /// range from 4 to 10.
1028 /// Panics if range `start > end`.
1029 /// Panics if range `start == end` and both bounds are `Excluded`.
1036 /// use std::collections::BTreeMap;
1038 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1040 /// .map(|&s| (s, 0))
1042 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1043 /// *balance += 100;
1045 /// for (name, balance) in &map {
1046 /// println!("{} => {}", name, balance);
1049 #[stable(feature = "btree_range", since = "1.17.0")]
1050 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1056 if let Some(root) = &mut self.root {
1057 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1059 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1063 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1070 /// use std::collections::BTreeMap;
1072 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1074 /// // count the number of occurrences of letters in the vec
1075 /// for x in vec!["a", "b", "a", "c", "a", "b"] {
1076 /// *count.entry(x).or_insert(0) += 1;
1079 /// assert_eq!(count["a"], 3);
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
1086 // FIXME(@porglezomp) Avoid allocating if we don't insert
1087 let (map, dormant_map) = DormantMutRef::new(self);
1088 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
1089 match root_node.search_tree(&key) {
1090 Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
1092 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })
1097 /// Splits the collection into two at the given key. Returns everything after the given key,
1098 /// including the key.
1105 /// use std::collections::BTreeMap;
1107 /// let mut a = BTreeMap::new();
1108 /// a.insert(1, "a");
1109 /// a.insert(2, "b");
1110 /// a.insert(3, "c");
1111 /// a.insert(17, "d");
1112 /// a.insert(41, "e");
1114 /// let b = a.split_off(&3);
1116 /// assert_eq!(a.len(), 2);
1117 /// assert_eq!(b.len(), 3);
1119 /// assert_eq!(a[&1], "a");
1120 /// assert_eq!(a[&2], "b");
1122 /// assert_eq!(b[&3], "c");
1123 /// assert_eq!(b[&17], "d");
1124 /// assert_eq!(b[&41], "e");
1126 #[stable(feature = "btree_split_off", since = "1.11.0")]
1127 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1131 if self.is_empty() {
1135 let total_num = self.len();
1136 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1138 let right_root = left_root.split_off(key);
1140 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1141 self.length = new_left_len;
1143 BTreeMap { root: Some(right_root), length: right_len }
1146 /// Creates an iterator that visits all elements (key-value pairs) in
1147 /// ascending key order and uses a closure to determine if an element should
1148 /// be removed. If the closure returns `true`, the element is removed from
1149 /// the map and yielded. If the closure returns `false`, or panics, the
1150 /// element remains in the map and will not be yielded.
1152 /// The iterator also lets you mutate the value of each element in the
1153 /// closure, regardless of whether you choose to keep or remove it.
1155 /// If the iterator is only partially consumed or not consumed at all, each
1156 /// of the remaining elements is still subjected to the closure, which may
1157 /// change its value and, by returning `true`, have the element removed and
1160 /// It is unspecified how many more elements will be subjected to the
1161 /// closure if a panic occurs in the closure, or a panic occurs while
1162 /// dropping an element, or if the `DrainFilter` value is leaked.
1166 /// Splitting a map into even and odd keys, reusing the original map:
1169 /// #![feature(btree_drain_filter)]
1170 /// use std::collections::BTreeMap;
1172 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1173 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1175 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1176 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1178 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1179 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1182 F: FnMut(&K, &mut V) -> bool,
1184 DrainFilter { pred, inner: self.drain_filter_inner() }
1187 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V>
1191 if let Some(root) = self.root.as_mut() {
1192 let (root, dormant_root) = DormantMutRef::new(root);
1193 let front = root.borrow_mut().first_leaf_edge();
1195 length: &mut self.length,
1196 dormant_root: Some(dormant_root),
1197 cur_leaf_edge: Some(front),
1200 DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1204 /// Creates a consuming iterator visiting all the keys, in sorted order.
1205 /// The map cannot be used after calling this.
1206 /// The iterator element type is `K`.
1211 /// #![feature(map_into_keys_values)]
1212 /// use std::collections::BTreeMap;
1214 /// let mut a = BTreeMap::new();
1215 /// a.insert(2, "b");
1216 /// a.insert(1, "a");
1218 /// let keys: Vec<i32> = a.into_keys().collect();
1219 /// assert_eq!(keys, [1, 2]);
1222 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1223 pub fn into_keys(self) -> IntoKeys<K, V> {
1224 IntoKeys { inner: self.into_iter() }
1227 /// Creates a consuming iterator visiting all the values, in order by key.
1228 /// The map cannot be used after calling this.
1229 /// The iterator element type is `V`.
1234 /// #![feature(map_into_keys_values)]
1235 /// use std::collections::BTreeMap;
1237 /// let mut a = BTreeMap::new();
1238 /// a.insert(1, "hello");
1239 /// a.insert(2, "goodbye");
1241 /// let values: Vec<&str> = a.into_values().collect();
1242 /// assert_eq!(values, ["hello", "goodbye"]);
1245 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1246 pub fn into_values(self) -> IntoValues<K, V> {
1247 IntoValues { inner: self.into_iter() }
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1253 type Item = (&'a K, &'a V);
1254 type IntoIter = Iter<'a, K, V>;
1256 fn into_iter(self) -> Iter<'a, K, V> {
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1263 type Item = (&'a K, &'a V);
1265 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1266 if self.length == 0 {
1270 Some(unsafe { self.range.next_unchecked() })
1274 fn size_hint(&self) -> (usize, Option<usize>) {
1275 (self.length, Some(self.length))
1278 fn last(mut self) -> Option<(&'a K, &'a V)> {
1282 fn min(mut self) -> Option<(&'a K, &'a V)> {
1286 fn max(mut self) -> Option<(&'a K, &'a V)> {
1291 #[stable(feature = "fused", since = "1.26.0")]
1292 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1296 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1297 if self.length == 0 {
1301 Some(unsafe { self.range.next_back_unchecked() })
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1308 fn len(&self) -> usize {
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<K, V> Clone for Iter<'_, K, V> {
1315 fn clone(&self) -> Self {
1316 Iter { range: self.range.clone(), length: self.length }
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1322 type Item = (&'a K, &'a mut V);
1323 type IntoIter = IterMut<'a, K, V>;
1325 fn into_iter(self) -> IterMut<'a, K, V> {
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1332 type Item = (&'a K, &'a mut V);
1334 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1335 if self.length == 0 {
1339 Some(unsafe { self.range.next_unchecked() })
1343 fn size_hint(&self) -> (usize, Option<usize>) {
1344 (self.length, Some(self.length))
1347 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1351 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1355 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1362 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1363 if self.length == 0 {
1367 Some(unsafe { self.range.next_back_unchecked() })
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1374 fn len(&self) -> usize {
1379 #[stable(feature = "fused", since = "1.26.0")]
1380 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1382 impl<'a, K, V> IterMut<'a, K, V> {
1383 /// Returns an iterator of references over the remaining items.
1385 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1386 Iter { range: self.range.iter(), length: self.length }
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<K, V> IntoIterator for BTreeMap<K, V> {
1393 type IntoIter = IntoIter<K, V>;
1395 fn into_iter(self) -> IntoIter<K, V> {
1396 let mut me = ManuallyDrop::new(self);
1397 if let Some(root) = me.root.take() {
1398 let full_range = root.into_dying().full_range();
1400 IntoIter { range: full_range, length: me.length }
1402 IntoIter { range: LeafRange::none(), length: 0 }
1407 impl<K, V> Drop for Dropper<K, V> {
1408 fn drop(&mut self) {
1409 // Similar to advancing a non-fusing iterator.
1410 fn next_or_end<K, V>(this: &mut Dropper<K, V>) -> Option<(K, V)> {
1411 if this.remaining_length == 0 {
1412 unsafe { ptr::read(&this.front).deallocating_end() }
1415 this.remaining_length -= 1;
1416 Some(unsafe { this.front.deallocating_next_unchecked() })
1420 struct DropGuard<'a, K, V>(&'a mut Dropper<K, V>);
1422 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1423 fn drop(&mut self) {
1424 // Continue the same loop we perform below. This only runs when unwinding, so we
1425 // don't have to care about panics this time (they'll abort).
1426 while let Some(_pair) = next_or_end(&mut self.0) {}
1430 while let Some(pair) = next_or_end(self) {
1431 let guard = DropGuard(self);
1438 #[stable(feature = "btree_drop", since = "1.7.0")]
1439 impl<K, V> Drop for IntoIter<K, V> {
1440 fn drop(&mut self) {
1441 if let Some(front) = self.range.front.take() {
1442 Dropper { front, remaining_length: self.length };
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<K, V> Iterator for IntoIter<K, V> {
1451 fn next(&mut self) -> Option<(K, V)> {
1452 if self.length == 0 {
1456 Some(unsafe { self.range.front.as_mut().unwrap().deallocating_next_unchecked() })
1460 fn size_hint(&self) -> (usize, Option<usize>) {
1461 (self.length, Some(self.length))
1465 #[stable(feature = "rust1", since = "1.0.0")]
1466 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1467 fn next_back(&mut self) -> Option<(K, V)> {
1468 if self.length == 0 {
1472 Some(unsafe { self.range.back.as_mut().unwrap().deallocating_next_back_unchecked() })
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1479 fn len(&self) -> usize {
1484 #[stable(feature = "fused", since = "1.26.0")]
1485 impl<K, V> FusedIterator for IntoIter<K, V> {}
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1491 fn next(&mut self) -> Option<&'a K> {
1492 self.inner.next().map(|(k, _)| k)
1495 fn size_hint(&self) -> (usize, Option<usize>) {
1496 self.inner.size_hint()
1499 fn last(mut self) -> Option<&'a K> {
1503 fn min(mut self) -> Option<&'a K> {
1507 fn max(mut self) -> Option<&'a K> {
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1514 fn next_back(&mut self) -> Option<&'a K> {
1515 self.inner.next_back().map(|(k, _)| k)
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1521 fn len(&self) -> usize {
1526 #[stable(feature = "fused", since = "1.26.0")]
1527 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<K, V> Clone for Keys<'_, K, V> {
1531 fn clone(&self) -> Self {
1532 Keys { inner: self.inner.clone() }
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 impl<'a, K, V> Iterator for Values<'a, K, V> {
1540 fn next(&mut self) -> Option<&'a V> {
1541 self.inner.next().map(|(_, v)| v)
1544 fn size_hint(&self) -> (usize, Option<usize>) {
1545 self.inner.size_hint()
1548 fn last(mut self) -> Option<&'a V> {
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1555 fn next_back(&mut self) -> Option<&'a V> {
1556 self.inner.next_back().map(|(_, v)| v)
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1562 fn len(&self) -> usize {
1567 #[stable(feature = "fused", since = "1.26.0")]
1568 impl<K, V> FusedIterator for Values<'_, K, V> {}
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl<K, V> Clone for Values<'_, K, V> {
1572 fn clone(&self) -> Self {
1573 Values { inner: self.inner.clone() }
1577 /// An iterator produced by calling `drain_filter` on BTreeMap.
1578 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1579 pub struct DrainFilter<'a, K, V, F>
1583 F: 'a + FnMut(&K, &mut V) -> bool,
1586 inner: DrainFilterInner<'a, K, V>,
1588 /// Most of the implementation of DrainFilter are generic over the type
1589 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1590 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1591 /// Reference to the length field in the borrowed map, updated live.
1592 length: &'a mut usize,
1593 /// Buried reference to the root field in the borrowed map.
1594 /// Wrapped in `Option` to allow drop handler to `take` it.
1595 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1596 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1597 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1598 /// or if a panic occurred in the predicate.
1599 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1602 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1603 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1605 F: FnMut(&K, &mut V) -> bool,
1607 fn drop(&mut self) {
1608 self.for_each(drop);
1612 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1613 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1617 F: FnMut(&K, &mut V) -> bool,
1619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1620 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1624 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1625 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1627 F: FnMut(&K, &mut V) -> bool,
1631 fn next(&mut self) -> Option<(K, V)> {
1632 self.inner.next(&mut self.pred)
1635 fn size_hint(&self) -> (usize, Option<usize>) {
1636 self.inner.size_hint()
1640 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1641 /// Allow Debug implementations to predict the next element.
1642 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1643 let edge = self.cur_leaf_edge.as_ref()?;
1644 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1647 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1648 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1650 F: FnMut(&K, &mut V) -> bool,
1652 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1653 let (k, v) = kv.kv_mut();
1656 let (kv, pos) = kv.remove_kv_tracking(|| {
1657 // SAFETY: we will touch the root in a way that will not
1658 // invalidate the position returned.
1659 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1660 root.pop_internal_level();
1661 self.dormant_root = Some(DormantMutRef::new(root).1);
1663 self.cur_leaf_edge = Some(pos);
1666 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1671 /// Implementation of a typical `DrainFilter::size_hint` method.
1672 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1673 // In most of the btree iterators, `self.length` is the number of elements
1674 // yet to be visited. Here, it includes elements that were visited and that
1675 // the predicate decided not to drain. Making this upper bound more accurate
1676 // requires maintaining an extra field and is not worth while.
1677 (0, Some(*self.length))
1681 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1682 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1684 #[stable(feature = "btree_range", since = "1.17.0")]
1685 impl<'a, K, V> Iterator for Range<'a, K, V> {
1686 type Item = (&'a K, &'a V);
1688 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1689 if self.inner.is_empty() { None } else { Some(unsafe { self.next_unchecked() }) }
1692 fn last(mut self) -> Option<(&'a K, &'a V)> {
1696 fn min(mut self) -> Option<(&'a K, &'a V)> {
1700 fn max(mut self) -> Option<(&'a K, &'a V)> {
1705 #[stable(feature = "map_values_mut", since = "1.10.0")]
1706 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1707 type Item = &'a mut V;
1709 fn next(&mut self) -> Option<&'a mut V> {
1710 self.inner.next().map(|(_, v)| v)
1713 fn size_hint(&self) -> (usize, Option<usize>) {
1714 self.inner.size_hint()
1717 fn last(mut self) -> Option<&'a mut V> {
1722 #[stable(feature = "map_values_mut", since = "1.10.0")]
1723 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1724 fn next_back(&mut self) -> Option<&'a mut V> {
1725 self.inner.next_back().map(|(_, v)| v)
1729 #[stable(feature = "map_values_mut", since = "1.10.0")]
1730 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1731 fn len(&self) -> usize {
1736 #[stable(feature = "fused", since = "1.26.0")]
1737 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1739 impl<'a, K, V> Range<'a, K, V> {
1740 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1741 unsafe { self.inner.front.as_mut().unwrap_unchecked().next_unchecked() }
1745 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1746 impl<K, V> Iterator for IntoKeys<K, V> {
1749 fn next(&mut self) -> Option<K> {
1750 self.inner.next().map(|(k, _)| k)
1753 fn size_hint(&self) -> (usize, Option<usize>) {
1754 self.inner.size_hint()
1757 fn last(mut self) -> Option<K> {
1761 fn min(mut self) -> Option<K> {
1765 fn max(mut self) -> Option<K> {
1770 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1771 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1772 fn next_back(&mut self) -> Option<K> {
1773 self.inner.next_back().map(|(k, _)| k)
1777 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1778 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1779 fn len(&self) -> usize {
1784 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1785 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1787 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1788 impl<K, V> Iterator for IntoValues<K, V> {
1791 fn next(&mut self) -> Option<V> {
1792 self.inner.next().map(|(_, v)| v)
1795 fn size_hint(&self) -> (usize, Option<usize>) {
1796 self.inner.size_hint()
1799 fn last(mut self) -> Option<V> {
1804 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1805 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1806 fn next_back(&mut self) -> Option<V> {
1807 self.inner.next_back().map(|(_, v)| v)
1811 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1812 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1813 fn len(&self) -> usize {
1818 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1819 impl<K, V> FusedIterator for IntoValues<K, V> {}
1821 #[stable(feature = "btree_range", since = "1.17.0")]
1822 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1823 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1824 if self.inner.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1828 impl<'a, K, V> Range<'a, K, V> {
1829 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1830 unsafe { self.inner.back.as_mut().unwrap_unchecked().next_back_unchecked() }
1834 #[stable(feature = "fused", since = "1.26.0")]
1835 impl<K, V> FusedIterator for Range<'_, K, V> {}
1837 #[stable(feature = "btree_range", since = "1.17.0")]
1838 impl<K, V> Clone for Range<'_, K, V> {
1839 fn clone(&self) -> Self {
1840 Range { inner: LeafRange { front: self.inner.front, back: self.inner.back } }
1844 #[stable(feature = "btree_range", since = "1.17.0")]
1845 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1846 type Item = (&'a K, &'a mut V);
1848 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1849 if self.inner.is_empty() { None } else { Some(unsafe { self.next_unchecked() }) }
1852 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1856 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1860 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1865 impl<'a, K, V> RangeMut<'a, K, V> {
1866 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1867 unsafe { self.inner.front.as_mut().unwrap_unchecked().next_unchecked() }
1870 /// Returns an iterator of references over the remaining items.
1872 pub(super) fn iter(&self) -> Range<'_, K, V> {
1873 Range { inner: self.inner.reborrow() }
1877 #[stable(feature = "btree_range", since = "1.17.0")]
1878 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1879 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1880 if self.inner.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1884 #[stable(feature = "fused", since = "1.26.0")]
1885 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1887 impl<'a, K, V> RangeMut<'a, K, V> {
1888 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1889 unsafe { self.inner.back.as_mut().unwrap_unchecked().next_back_unchecked() }
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1895 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1896 let mut map = BTreeMap::new();
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1905 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1906 iter.into_iter().for_each(move |(k, v)| {
1912 fn extend_one(&mut self, (k, v): (K, V)) {
1917 #[stable(feature = "extend_ref", since = "1.2.0")]
1918 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1919 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1920 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1924 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1931 fn hash<H: Hasher>(&self, state: &mut H) {
1938 #[stable(feature = "rust1", since = "1.0.0")]
1939 impl<K: Ord, V> Default for BTreeMap<K, V> {
1940 /// Creates an empty `BTreeMap`.
1941 fn default() -> BTreeMap<K, V> {
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1948 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1949 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1959 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1960 self.iter().partial_cmp(other.iter())
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1967 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1968 self.iter().cmp(other.iter())
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1974 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1975 f.debug_map().entries(self.iter()).finish()
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl<K, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1987 /// Returns a reference to the value corresponding to the supplied key.
1991 /// Panics if the key is not present in the `BTreeMap`.
1993 fn index(&self, key: &Q) -> &V {
1994 self.get(key).expect("no entry found for key")
1998 impl<K, V> BTreeMap<K, V> {
1999 /// Gets an iterator over the entries of the map, sorted by key.
2006 /// use std::collections::BTreeMap;
2008 /// let mut map = BTreeMap::new();
2009 /// map.insert(3, "c");
2010 /// map.insert(2, "b");
2011 /// map.insert(1, "a");
2013 /// for (key, value) in map.iter() {
2014 /// println!("{}: {}", key, value);
2017 /// let (first_key, first_value) = map.iter().next().unwrap();
2018 /// assert_eq!((*first_key, *first_value), (1, "a"));
2020 #[stable(feature = "rust1", since = "1.0.0")]
2021 pub fn iter(&self) -> Iter<'_, K, V> {
2022 if let Some(root) = &self.root {
2023 let full_range = root.reborrow().full_range();
2025 Iter { range: Range { inner: full_range }, length: self.length }
2027 Iter { range: Range { inner: LeafRange::none() }, length: 0 }
2031 /// Gets a mutable iterator over the entries of the map, sorted by key.
2038 /// use std::collections::BTreeMap;
2040 /// let mut map = BTreeMap::new();
2041 /// map.insert("a", 1);
2042 /// map.insert("b", 2);
2043 /// map.insert("c", 3);
2045 /// // add 10 to the value if the key isn't "a"
2046 /// for (key, value) in map.iter_mut() {
2047 /// if key != &"a" {
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2054 if let Some(root) = &mut self.root {
2055 let full_range = root.borrow_valmut().full_range();
2058 range: RangeMut { inner: full_range, _marker: PhantomData },
2059 length: self.length,
2063 range: RangeMut { inner: LeafRange::none(), _marker: PhantomData },
2069 /// Gets an iterator over the keys of the map, in sorted order.
2076 /// use std::collections::BTreeMap;
2078 /// let mut a = BTreeMap::new();
2079 /// a.insert(2, "b");
2080 /// a.insert(1, "a");
2082 /// let keys: Vec<_> = a.keys().cloned().collect();
2083 /// assert_eq!(keys, [1, 2]);
2085 #[stable(feature = "rust1", since = "1.0.0")]
2086 pub fn keys(&self) -> Keys<'_, K, V> {
2087 Keys { inner: self.iter() }
2090 /// Gets an iterator over the values of the map, in order by key.
2097 /// use std::collections::BTreeMap;
2099 /// let mut a = BTreeMap::new();
2100 /// a.insert(1, "hello");
2101 /// a.insert(2, "goodbye");
2103 /// let values: Vec<&str> = a.values().cloned().collect();
2104 /// assert_eq!(values, ["hello", "goodbye"]);
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 pub fn values(&self) -> Values<'_, K, V> {
2108 Values { inner: self.iter() }
2111 /// Gets a mutable iterator over the values of the map, in order by key.
2118 /// use std::collections::BTreeMap;
2120 /// let mut a = BTreeMap::new();
2121 /// a.insert(1, String::from("hello"));
2122 /// a.insert(2, String::from("goodbye"));
2124 /// for value in a.values_mut() {
2125 /// value.push_str("!");
2128 /// let values: Vec<String> = a.values().cloned().collect();
2129 /// assert_eq!(values, [String::from("hello!"),
2130 /// String::from("goodbye!")]);
2132 #[stable(feature = "map_values_mut", since = "1.10.0")]
2133 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2134 ValuesMut { inner: self.iter_mut() }
2137 /// Returns the number of elements in the map.
2144 /// use std::collections::BTreeMap;
2146 /// let mut a = BTreeMap::new();
2147 /// assert_eq!(a.len(), 0);
2148 /// a.insert(1, "a");
2149 /// assert_eq!(a.len(), 1);
2151 #[doc(alias = "length")]
2152 #[stable(feature = "rust1", since = "1.0.0")]
2153 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2154 pub const fn len(&self) -> usize {
2158 /// Returns `true` if the map contains no elements.
2165 /// use std::collections::BTreeMap;
2167 /// let mut a = BTreeMap::new();
2168 /// assert!(a.is_empty());
2169 /// a.insert(1, "a");
2170 /// assert!(!a.is_empty());
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2174 pub const fn is_empty(&self) -> bool {
2178 /// If the root node is the empty (non-allocated) root node, allocate our
2179 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2180 fn ensure_is_owned(root: &mut Option<Root<K, V>>) -> &mut Root<K, V> {
2181 root.get_or_insert_with(Root::new)