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::node::{self, marker, ForceResult::*, Handle, NodeRef};
13 use super::search::{self, SearchResult::*};
14 use super::unwrap_unchecked;
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 map based on a B-Tree.
26 /// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
27 /// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
28 /// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of
29 /// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
30 /// is done is *very* inefficient for modern computer architectures. In particular, every element
31 /// is stored in its own individually heap-allocated node. This means that every single insertion
32 /// triggers a heap-allocation, and every single comparison should be a cache-miss. Since these
33 /// are both notably expensive things to do in practice, we are forced to at very least reconsider
36 /// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
37 /// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
38 /// searches. However, this does mean that searches will have to do *more* comparisons on average.
39 /// The precise number of comparisons depends on the node search strategy used. For optimal cache
40 /// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
41 /// the node using binary search. As a compromise, one could also perform a linear search
42 /// that initially only checks every i<sup>th</sup> element for some choice of i.
44 /// Currently, our implementation simply performs naive linear search. This provides excellent
45 /// performance on *small* nodes of elements which are cheap to compare. However in the future we
46 /// would like to further explore choosing the optimal search strategy based on the choice of B,
47 /// and possibly other factors. Using linear search, searching for a random element is expected
48 /// to take O(B * log(n)) comparisons, which is generally worse than a BST. In practice,
49 /// however, performance is excellent.
51 /// It is a logic error for a key to be modified in such a way that the key's ordering relative to
52 /// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
53 /// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
55 /// [`Cell`]: core::cell::Cell
56 /// [`RefCell`]: core::cell::RefCell
61 /// use std::collections::BTreeMap;
63 /// // type inference lets us omit an explicit type signature (which
64 /// // would be `BTreeMap<&str, &str>` in this example).
65 /// let mut movie_reviews = BTreeMap::new();
67 /// // review some movies.
68 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
69 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
70 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
71 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
73 /// // check for a specific one.
74 /// if !movie_reviews.contains_key("Les Misérables") {
75 /// println!("We've got {} reviews, but Les Misérables ain't one.",
76 /// movie_reviews.len());
79 /// // oops, this review has a lot of spelling mistakes, let's delete it.
80 /// movie_reviews.remove("The Blues Brothers");
82 /// // look up the values associated with some keys.
83 /// let to_find = ["Up!", "Office Space"];
84 /// for movie in &to_find {
85 /// match movie_reviews.get(movie) {
86 /// Some(review) => println!("{}: {}", movie, review),
87 /// None => println!("{} is unreviewed.", movie)
91 /// // Look up the value for a key (will panic if the key is not found).
92 /// println!("Movie review: {}", movie_reviews["Office Space"]);
94 /// // iterate over everything.
95 /// for (movie, review) in &movie_reviews {
96 /// println!("{}: \"{}\"", movie, review);
100 /// `BTreeMap` also implements an [`Entry API`], which allows for more complex
101 /// methods of getting, setting, updating and removing keys and their values:
103 /// [`Entry API`]: BTreeMap::entry
106 /// use std::collections::BTreeMap;
108 /// // type inference lets us omit an explicit type signature (which
109 /// // would be `BTreeMap<&str, u8>` in this example).
110 /// let mut player_stats = BTreeMap::new();
112 /// fn random_stat_buff() -> u8 {
113 /// // could actually return some random value here - let's just return
114 /// // some fixed value for now
118 /// // insert a key only if it doesn't already exist
119 /// player_stats.entry("health").or_insert(100);
121 /// // insert a key using a function that provides a new value only if it
122 /// // doesn't already exist
123 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
125 /// // update a key, guarding against the key possibly not being set
126 /// let stat = player_stats.entry("attack").or_insert(100);
127 /// *stat += random_stat_buff();
129 #[stable(feature = "rust1", since = "1.0.0")]
130 pub struct BTreeMap<K, V> {
131 root: Option<node::Root<K, V>>,
135 #[stable(feature = "btree_drop", since = "1.7.0")]
136 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
139 drop(ptr::read(self).into_iter());
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
146 fn clone(&self) -> BTreeMap<K, V> {
147 fn clone_subtree<'a, K: Clone, V: Clone>(
148 node: node::NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
156 let mut out_tree = BTreeMap { root: Some(node::Root::new_leaf()), length: 0 };
159 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
160 let mut out_node = match root.borrow_mut().force() {
162 Internal(_) => unreachable!(),
165 let mut in_edge = leaf.first_edge();
166 while let Ok(kv) = in_edge.right_kv() {
167 let (k, v) = kv.into_kv();
168 in_edge = kv.right_edge();
170 out_node.push(k.clone(), v.clone());
171 out_tree.length += 1;
177 Internal(internal) => {
178 let mut out_tree = clone_subtree(internal.first_edge().descend());
181 let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
182 let mut out_node = out_root.push_internal_level();
183 let mut in_edge = internal.first_edge();
184 while let Ok(kv) = in_edge.right_kv() {
185 let (k, v) = kv.into_kv();
186 in_edge = kv.right_edge();
188 let k = (*k).clone();
189 let v = (*v).clone();
190 let subtree = clone_subtree(in_edge.descend());
192 // We can't destructure subtree directly
193 // because BTreeMap implements Drop
194 let (subroot, sublength) = unsafe {
195 let subtree = ManuallyDrop::new(subtree);
196 let root = ptr::read(&subtree.root);
197 let length = subtree.length;
201 out_node.push(k, v, subroot.unwrap_or_else(node::Root::new_leaf));
202 out_tree.length += 1 + sublength;
212 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
213 // Ord` constraint, which this method lacks.
214 BTreeMap { root: None, length: 0 }
216 clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
221 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
228 fn get(&self, key: &Q) -> Option<&K> {
229 let root_node = self.root.as_ref()?.reborrow();
230 match search::search_tree(root_node, key) {
231 Found(handle) => Some(handle.into_kv().0),
236 fn take(&mut self, key: &Q) -> Option<K> {
237 let (map, dormant_map) = DormantMutRef::new(self);
238 let root_node = map.root.as_mut()?.borrow_mut();
239 match search::search_tree(root_node, key) {
241 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
247 fn replace(&mut self, key: K) -> Option<K> {
248 let (map, dormant_map) = DormantMutRef::new(self);
249 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
250 match search::search_tree::<marker::Mut<'_>, K, (), K>(root_node, &key) {
251 Found(handle) => Some(mem::replace(handle.into_key_mut(), key)),
253 VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
260 /// An iterator over the entries of a `BTreeMap`.
262 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
263 /// documentation for more.
265 /// [`iter`]: BTreeMap::iter
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub struct Iter<'a, K: 'a, V: 'a> {
268 range: Range<'a, K, V>,
272 #[stable(feature = "collection_debug", since = "1.17.0")]
273 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.debug_list().entries(self.clone()).finish()
279 /// A mutable iterator over the entries of a `BTreeMap`.
281 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
282 /// documentation for more.
284 /// [`iter_mut`]: BTreeMap::iter_mut
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub struct IterMut<'a, K: 'a, V: 'a> {
288 range: RangeMut<'a, K, V>,
292 /// An owning iterator over the entries of a `BTreeMap`.
294 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
295 /// (provided by the `IntoIterator` trait). See its documentation for more.
297 /// [`into_iter`]: IntoIterator::into_iter
298 #[stable(feature = "rust1", since = "1.0.0")]
299 pub struct IntoIter<K, V> {
300 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
301 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
305 impl<K, V> IntoIter<K, V> {
306 /// Returns an iterator of references over the remaining items.
308 pub(super) fn iter(&self) -> Iter<'_, K, V> {
310 front: self.front.as_ref().map(|f| f.reborrow()),
311 back: self.back.as_ref().map(|b| b.reborrow()),
314 Iter { range: range, length: self.length }
318 #[stable(feature = "collection_debug", since = "1.17.0")]
319 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 f.debug_list().entries(self.iter()).finish()
325 /// An iterator over the keys of a `BTreeMap`.
327 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
328 /// documentation for more.
330 /// [`keys`]: BTreeMap::keys
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub struct Keys<'a, K: 'a, V: 'a> {
333 inner: Iter<'a, K, V>,
336 #[stable(feature = "collection_debug", since = "1.17.0")]
337 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 f.debug_list().entries(self.clone()).finish()
343 /// An iterator over the values of a `BTreeMap`.
345 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
346 /// documentation for more.
348 /// [`values`]: BTreeMap::values
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub struct Values<'a, K: 'a, V: 'a> {
351 inner: Iter<'a, K, V>,
354 #[stable(feature = "collection_debug", since = "1.17.0")]
355 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 f.debug_list().entries(self.clone()).finish()
361 /// A mutable iterator over the values of a `BTreeMap`.
363 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
364 /// documentation for more.
366 /// [`values_mut`]: BTreeMap::values_mut
367 #[stable(feature = "map_values_mut", since = "1.10.0")]
368 pub struct ValuesMut<'a, K: 'a, V: 'a> {
369 inner: IterMut<'a, K, V>,
372 #[stable(feature = "map_values_mut", since = "1.10.0")]
373 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
379 /// An owning iterator over the keys of a `BTreeMap`.
381 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
382 /// See its documentation for more.
384 /// [`into_keys`]: BTreeMap::into_keys
385 #[unstable(feature = "map_into_keys_values", issue = "75294")]
386 pub struct IntoKeys<K, V> {
387 inner: IntoIter<K, V>,
390 #[unstable(feature = "map_into_keys_values", issue = "75294")]
391 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
397 /// An owning iterator over the values of a `BTreeMap`.
399 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
400 /// See its documentation for more.
402 /// [`into_values`]: BTreeMap::into_values
403 #[unstable(feature = "map_into_keys_values", issue = "75294")]
404 pub struct IntoValues<K, V> {
405 inner: IntoIter<K, V>,
408 #[unstable(feature = "map_into_keys_values", issue = "75294")]
409 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
415 /// An iterator over a sub-range of entries in a `BTreeMap`.
417 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
418 /// documentation for more.
420 /// [`range`]: BTreeMap::range
421 #[stable(feature = "btree_range", since = "1.17.0")]
422 pub struct Range<'a, K: 'a, V: 'a> {
423 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
424 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
427 #[stable(feature = "collection_debug", since = "1.17.0")]
428 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 f.debug_list().entries(self.clone()).finish()
434 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
436 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
437 /// documentation for more.
439 /// [`range_mut`]: BTreeMap::range_mut
440 #[stable(feature = "btree_range", since = "1.17.0")]
441 pub struct RangeMut<'a, K: 'a, V: 'a> {
442 front: Option<Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>>,
443 back: Option<Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>>,
445 // Be invariant in `K` and `V`
446 _marker: PhantomData<&'a mut (K, V)>,
449 #[stable(feature = "collection_debug", since = "1.17.0")]
450 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 front: self.front.as_ref().map(|f| f.reborrow()),
454 back: self.back.as_ref().map(|b| b.reborrow()),
456 f.debug_list().entries(range).finish()
460 impl<K: Ord, V> BTreeMap<K, V> {
461 /// Makes a new empty BTreeMap.
463 /// Does not allocate anything on its own.
470 /// use std::collections::BTreeMap;
472 /// let mut map = BTreeMap::new();
474 /// // entries can now be inserted into the empty map
475 /// map.insert(1, "a");
477 #[stable(feature = "rust1", since = "1.0.0")]
478 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
479 pub const fn new() -> BTreeMap<K, V> {
480 BTreeMap { root: None, length: 0 }
483 /// Clears the map, removing all elements.
490 /// use std::collections::BTreeMap;
492 /// let mut a = BTreeMap::new();
493 /// a.insert(1, "a");
495 /// assert!(a.is_empty());
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn clear(&mut self) {
499 *self = BTreeMap::new();
502 /// Returns a reference to the value corresponding to the key.
504 /// The key may be any borrowed form of the map's key type, but the ordering
505 /// on the borrowed form *must* match the ordering on the key type.
512 /// use std::collections::BTreeMap;
514 /// let mut map = BTreeMap::new();
515 /// map.insert(1, "a");
516 /// assert_eq!(map.get(&1), Some(&"a"));
517 /// assert_eq!(map.get(&2), None);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
525 let root_node = self.root.as_ref()?.reborrow();
526 match search::search_tree(root_node, key) {
527 Found(handle) => Some(handle.into_kv().1),
532 /// Returns the key-value pair corresponding to the supplied key.
534 /// The supplied key may be any borrowed form of the map's key type, but the ordering
535 /// on the borrowed form *must* match the ordering on the key type.
540 /// use std::collections::BTreeMap;
542 /// let mut map = BTreeMap::new();
543 /// map.insert(1, "a");
544 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
545 /// assert_eq!(map.get_key_value(&2), None);
547 #[stable(feature = "map_get_key_value", since = "1.40.0")]
548 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
553 let root_node = self.root.as_ref()?.reborrow();
554 match search::search_tree(root_node, k) {
555 Found(handle) => Some(handle.into_kv()),
560 /// Returns the first key-value pair in the map.
561 /// The key in this pair is the minimum key in the map.
568 /// #![feature(map_first_last)]
569 /// use std::collections::BTreeMap;
571 /// let mut map = BTreeMap::new();
572 /// assert_eq!(map.first_key_value(), None);
573 /// map.insert(1, "b");
574 /// map.insert(2, "a");
575 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
577 #[unstable(feature = "map_first_last", issue = "62924")]
578 pub fn first_key_value(&self) -> Option<(&K, &V)> {
579 let root_node = self.root.as_ref()?.reborrow();
580 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
583 /// Returns the first entry in the map for in-place manipulation.
584 /// The key of this entry is the minimum key in the map.
589 /// #![feature(map_first_last)]
590 /// use std::collections::BTreeMap;
592 /// let mut map = BTreeMap::new();
593 /// map.insert(1, "a");
594 /// map.insert(2, "b");
595 /// if let Some(mut entry) = map.first_entry() {
596 /// if *entry.key() > 0 {
597 /// entry.insert("first");
600 /// assert_eq!(*map.get(&1).unwrap(), "first");
601 /// assert_eq!(*map.get(&2).unwrap(), "b");
603 #[unstable(feature = "map_first_last", issue = "62924")]
604 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
605 let (map, dormant_map) = DormantMutRef::new(self);
606 let root_node = map.root.as_mut()?.borrow_mut();
607 let kv = root_node.first_leaf_edge().right_kv().ok()?;
608 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
611 /// Removes and returns the first element in the map.
612 /// The key of this element is the minimum key that was in the map.
616 /// Draining elements in ascending order, while keeping a usable map each iteration.
619 /// #![feature(map_first_last)]
620 /// use std::collections::BTreeMap;
622 /// let mut map = BTreeMap::new();
623 /// map.insert(1, "a");
624 /// map.insert(2, "b");
625 /// while let Some((key, _val)) = map.pop_first() {
626 /// assert!(map.iter().all(|(k, _v)| *k > key));
628 /// assert!(map.is_empty());
630 #[unstable(feature = "map_first_last", issue = "62924")]
631 pub fn pop_first(&mut self) -> Option<(K, V)> {
632 self.first_entry().map(|entry| entry.remove_entry())
635 /// Returns the last key-value pair in the map.
636 /// The key in this pair is the maximum key in the map.
643 /// #![feature(map_first_last)]
644 /// use std::collections::BTreeMap;
646 /// let mut map = BTreeMap::new();
647 /// map.insert(1, "b");
648 /// map.insert(2, "a");
649 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
651 #[unstable(feature = "map_first_last", issue = "62924")]
652 pub fn last_key_value(&self) -> Option<(&K, &V)> {
653 let root_node = self.root.as_ref()?.reborrow();
654 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
657 /// Returns the last entry in the map for in-place manipulation.
658 /// The key of this entry is the maximum key in the map.
663 /// #![feature(map_first_last)]
664 /// use std::collections::BTreeMap;
666 /// let mut map = BTreeMap::new();
667 /// map.insert(1, "a");
668 /// map.insert(2, "b");
669 /// if let Some(mut entry) = map.last_entry() {
670 /// if *entry.key() > 0 {
671 /// entry.insert("last");
674 /// assert_eq!(*map.get(&1).unwrap(), "a");
675 /// assert_eq!(*map.get(&2).unwrap(), "last");
677 #[unstable(feature = "map_first_last", issue = "62924")]
678 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
679 let (map, dormant_map) = DormantMutRef::new(self);
680 let root_node = map.root.as_mut()?.borrow_mut();
681 let kv = root_node.last_leaf_edge().left_kv().ok()?;
682 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
685 /// Removes and returns the last element in the map.
686 /// The key of this element is the maximum key that was in the map.
690 /// Draining elements in descending order, while keeping a usable map each iteration.
693 /// #![feature(map_first_last)]
694 /// use std::collections::BTreeMap;
696 /// let mut map = BTreeMap::new();
697 /// map.insert(1, "a");
698 /// map.insert(2, "b");
699 /// while let Some((key, _val)) = map.pop_last() {
700 /// assert!(map.iter().all(|(k, _v)| *k < key));
702 /// assert!(map.is_empty());
704 #[unstable(feature = "map_first_last", issue = "62924")]
705 pub fn pop_last(&mut self) -> Option<(K, V)> {
706 self.last_entry().map(|entry| entry.remove_entry())
709 /// Returns `true` if the map contains a value for the specified key.
711 /// The key may be any borrowed form of the map's key type, but the ordering
712 /// on the borrowed form *must* match the ordering on the key type.
719 /// use std::collections::BTreeMap;
721 /// let mut map = BTreeMap::new();
722 /// map.insert(1, "a");
723 /// assert_eq!(map.contains_key(&1), true);
724 /// assert_eq!(map.contains_key(&2), false);
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
732 self.get(key).is_some()
735 /// Returns a mutable reference to the value corresponding to the key.
737 /// The key may be any borrowed form of the map's key type, but the ordering
738 /// on the borrowed form *must* match the ordering on the key type.
745 /// use std::collections::BTreeMap;
747 /// let mut map = BTreeMap::new();
748 /// map.insert(1, "a");
749 /// if let Some(x) = map.get_mut(&1) {
752 /// assert_eq!(map[&1], "b");
754 // See `get` for implementation notes, this is basically a copy-paste with mut's added
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
761 let root_node = self.root.as_mut()?.borrow_mut();
762 match search::search_tree(root_node, key) {
763 Found(handle) => Some(handle.into_val_mut()),
768 /// Inserts a key-value pair into the map.
770 /// If the map did not have this key present, `None` is returned.
772 /// If the map did have this key present, the value is updated, and the old
773 /// value is returned. The key is not updated, though; this matters for
774 /// types that can be `==` without being identical. See the [module-level
775 /// documentation] for more.
777 /// [module-level documentation]: index.html#insert-and-complex-keys
784 /// use std::collections::BTreeMap;
786 /// let mut map = BTreeMap::new();
787 /// assert_eq!(map.insert(37, "a"), None);
788 /// assert_eq!(map.is_empty(), false);
790 /// map.insert(37, "b");
791 /// assert_eq!(map.insert(37, "c"), Some("b"));
792 /// assert_eq!(map[&37], "c");
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
796 match self.entry(key) {
797 Occupied(mut entry) => Some(entry.insert(value)),
805 /// Removes a key from the map, returning the value at the key if the key
806 /// was previously in the map.
808 /// The key may be any borrowed form of the map's key type, but the ordering
809 /// on the borrowed form *must* match the ordering on the key type.
816 /// use std::collections::BTreeMap;
818 /// let mut map = BTreeMap::new();
819 /// map.insert(1, "a");
820 /// assert_eq!(map.remove(&1), Some("a"));
821 /// assert_eq!(map.remove(&1), None);
823 #[stable(feature = "rust1", since = "1.0.0")]
824 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
829 self.remove_entry(key).map(|(_, v)| v)
832 /// Removes a key from the map, returning the stored key and value if the key
833 /// was previously in the map.
835 /// The key may be any borrowed form of the map's key type, but the ordering
836 /// on the borrowed form *must* match the ordering on the key type.
843 /// use std::collections::BTreeMap;
845 /// let mut map = BTreeMap::new();
846 /// map.insert(1, "a");
847 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
848 /// assert_eq!(map.remove_entry(&1), None);
850 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
851 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
856 let (map, dormant_map) = DormantMutRef::new(self);
857 let root_node = map.root.as_mut()?.borrow_mut();
858 match search::search_tree(root_node, key) {
860 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
866 /// Retains only the elements specified by the predicate.
868 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
873 /// #![feature(btree_retain)]
874 /// use std::collections::BTreeMap;
876 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
877 /// // Keep only the elements with even-numbered keys.
878 /// map.retain(|&k, _| k % 2 == 0);
879 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
882 #[unstable(feature = "btree_retain", issue = "79025")]
883 pub fn retain<F>(&mut self, mut f: F)
885 F: FnMut(&K, &mut V) -> bool,
887 self.drain_filter(|k, v| !f(k, v));
890 /// Moves all elements from `other` into `Self`, leaving `other` empty.
895 /// use std::collections::BTreeMap;
897 /// let mut a = BTreeMap::new();
898 /// a.insert(1, "a");
899 /// a.insert(2, "b");
900 /// a.insert(3, "c");
902 /// let mut b = BTreeMap::new();
903 /// b.insert(3, "d");
904 /// b.insert(4, "e");
905 /// b.insert(5, "f");
907 /// a.append(&mut b);
909 /// assert_eq!(a.len(), 5);
910 /// assert_eq!(b.len(), 0);
912 /// assert_eq!(a[&1], "a");
913 /// assert_eq!(a[&2], "b");
914 /// assert_eq!(a[&3], "d");
915 /// assert_eq!(a[&4], "e");
916 /// assert_eq!(a[&5], "f");
918 #[stable(feature = "btree_append", since = "1.11.0")]
919 pub fn append(&mut self, other: &mut Self) {
920 // Do we have to append anything at all?
921 if other.is_empty() {
925 // We can just swap `self` and `other` if `self` is empty.
927 mem::swap(self, other);
931 let self_iter = mem::take(self).into_iter();
932 let other_iter = mem::take(other).into_iter();
933 let root = BTreeMap::ensure_is_owned(&mut self.root);
934 root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
937 /// Constructs a double-ended iterator over a sub-range of elements in the map.
938 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
939 /// yield elements from min (inclusive) to max (exclusive).
940 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
941 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
942 /// range from 4 to 10.
946 /// Panics if range `start > end`.
947 /// Panics if range `start == end` and both bounds are `Excluded`.
954 /// use std::collections::BTreeMap;
955 /// use std::ops::Bound::Included;
957 /// let mut map = BTreeMap::new();
958 /// map.insert(3, "a");
959 /// map.insert(5, "b");
960 /// map.insert(8, "c");
961 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
962 /// println!("{}: {}", key, value);
964 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
966 #[stable(feature = "btree_range", since = "1.17.0")]
967 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
973 if let Some(root) = &self.root {
974 let (f, b) = root.reborrow().range_search(range);
976 Range { front: Some(f), back: Some(b) }
978 Range { front: None, back: None }
982 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
983 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
984 /// yield elements from min (inclusive) to max (exclusive).
985 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
986 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
987 /// range from 4 to 10.
991 /// Panics if range `start > end`.
992 /// Panics if range `start == end` and both bounds are `Excluded`.
999 /// use std::collections::BTreeMap;
1001 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1003 /// .map(|&s| (s, 0))
1005 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1006 /// *balance += 100;
1008 /// for (name, balance) in &map {
1009 /// println!("{} => {}", name, balance);
1012 #[stable(feature = "btree_range", since = "1.17.0")]
1013 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1019 if let Some(root) = &mut self.root {
1020 let (f, b) = root.borrow_valmut().range_search(range);
1022 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1024 RangeMut { front: None, back: None, _marker: PhantomData }
1028 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1035 /// use std::collections::BTreeMap;
1037 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1039 /// // count the number of occurrences of letters in the vec
1040 /// for x in vec!["a","b","a","c","a","b"] {
1041 /// *count.entry(x).or_insert(0) += 1;
1044 /// assert_eq!(count["a"], 3);
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1048 // FIXME(@porglezomp) Avoid allocating if we don't insert
1049 let (map, dormant_map) = DormantMutRef::new(self);
1050 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
1051 match search::search_tree(root_node, &key) {
1052 Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
1054 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })
1059 /// Splits the collection into two at the given key. Returns everything after the given key,
1060 /// including the key.
1067 /// use std::collections::BTreeMap;
1069 /// let mut a = BTreeMap::new();
1070 /// a.insert(1, "a");
1071 /// a.insert(2, "b");
1072 /// a.insert(3, "c");
1073 /// a.insert(17, "d");
1074 /// a.insert(41, "e");
1076 /// let b = a.split_off(&3);
1078 /// assert_eq!(a.len(), 2);
1079 /// assert_eq!(b.len(), 3);
1081 /// assert_eq!(a[&1], "a");
1082 /// assert_eq!(a[&2], "b");
1084 /// assert_eq!(b[&3], "c");
1085 /// assert_eq!(b[&17], "d");
1086 /// assert_eq!(b[&41], "e");
1088 #[stable(feature = "btree_split_off", since = "1.11.0")]
1089 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1093 if self.is_empty() {
1097 let total_num = self.len();
1098 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1100 let mut right = Self::new();
1101 let right_root = Self::ensure_is_owned(&mut right.root);
1103 left_root.split_off(right_root, key);
1105 if left_root.height() < right_root.height() {
1106 self.length = left_root.reborrow().calc_length();
1107 right.length = total_num - self.len();
1109 right.length = right_root.reborrow().calc_length();
1110 self.length = total_num - right.len();
1116 /// Creates an iterator which uses a closure to determine if an element should be removed.
1118 /// If the closure returns true, the element is removed from the map and yielded.
1119 /// If the closure returns false, or panics, the element remains in the map and will not be
1122 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1123 /// whether you choose to keep or remove it.
1125 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1126 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1128 /// It is unspecified how many more elements will be subjected to the closure
1129 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1130 /// or if the `DrainFilter` value is leaked.
1134 /// Splitting a map into even and odd keys, reusing the original map:
1137 /// #![feature(btree_drain_filter)]
1138 /// use std::collections::BTreeMap;
1140 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1141 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1143 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1144 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1146 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1147 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1149 F: FnMut(&K, &mut V) -> bool,
1151 DrainFilter { pred, inner: self.drain_filter_inner() }
1154 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1155 if let Some(root) = self.root.as_mut() {
1156 let (root, dormant_root) = DormantMutRef::new(root);
1157 let front = root.borrow_mut().first_leaf_edge();
1159 length: &mut self.length,
1160 dormant_root: Some(dormant_root),
1161 cur_leaf_edge: Some(front),
1164 DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1168 /// Creates a consuming iterator visiting all the keys, in sorted order.
1169 /// The map cannot be used after calling this.
1170 /// The iterator element type is `K`.
1175 /// #![feature(map_into_keys_values)]
1176 /// use std::collections::BTreeMap;
1178 /// let mut a = BTreeMap::new();
1179 /// a.insert(2, "b");
1180 /// a.insert(1, "a");
1182 /// let keys: Vec<i32> = a.into_keys().collect();
1183 /// assert_eq!(keys, [1, 2]);
1186 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1187 pub fn into_keys(self) -> IntoKeys<K, V> {
1188 IntoKeys { inner: self.into_iter() }
1191 /// Creates a consuming iterator visiting all the values, in order by key.
1192 /// The map cannot be used after calling this.
1193 /// The iterator element type is `V`.
1198 /// #![feature(map_into_keys_values)]
1199 /// use std::collections::BTreeMap;
1201 /// let mut a = BTreeMap::new();
1202 /// a.insert(1, "hello");
1203 /// a.insert(2, "goodbye");
1205 /// let values: Vec<&str> = a.into_values().collect();
1206 /// assert_eq!(values, ["hello", "goodbye"]);
1209 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1210 pub fn into_values(self) -> IntoValues<K, V> {
1211 IntoValues { inner: self.into_iter() }
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1217 type Item = (&'a K, &'a V);
1218 type IntoIter = Iter<'a, K, V>;
1220 fn into_iter(self) -> Iter<'a, K, V> {
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1227 type Item = (&'a K, &'a V);
1229 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1230 if self.length == 0 {
1234 unsafe { Some(self.range.next_unchecked()) }
1238 fn size_hint(&self) -> (usize, Option<usize>) {
1239 (self.length, Some(self.length))
1242 fn last(mut self) -> Option<(&'a K, &'a V)> {
1246 fn min(mut self) -> Option<(&'a K, &'a V)> {
1250 fn max(mut self) -> Option<(&'a K, &'a V)> {
1255 #[stable(feature = "fused", since = "1.26.0")]
1256 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1260 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1261 if self.length == 0 {
1265 unsafe { Some(self.range.next_back_unchecked()) }
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1272 fn len(&self) -> usize {
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<K, V> Clone for Iter<'_, K, V> {
1279 fn clone(&self) -> Self {
1280 Iter { range: self.range.clone(), length: self.length }
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1286 type Item = (&'a K, &'a mut V);
1287 type IntoIter = IterMut<'a, K, V>;
1289 fn into_iter(self) -> IterMut<'a, K, V> {
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1296 type Item = (&'a K, &'a mut V);
1298 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1299 if self.length == 0 {
1303 let (k, v) = unsafe { self.range.next_unchecked() };
1304 Some((k, v)) // coerce k from `&mut K` to `&K`
1308 fn size_hint(&self) -> (usize, Option<usize>) {
1309 (self.length, Some(self.length))
1312 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1316 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1320 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1327 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1328 if self.length == 0 {
1332 let (k, v) = unsafe { self.range.next_back_unchecked() };
1333 Some((k, v)) // coerce k from `&mut K` to `&K`
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1340 fn len(&self) -> usize {
1345 #[stable(feature = "fused", since = "1.26.0")]
1346 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1348 impl<'a, K, V> IterMut<'a, K, V> {
1349 /// Returns an iterator of references over the remaining items.
1351 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1352 Iter { range: self.range.iter(), length: self.length }
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<K, V> IntoIterator for BTreeMap<K, V> {
1359 type IntoIter = IntoIter<K, V>;
1361 fn into_iter(self) -> IntoIter<K, V> {
1362 let mut me = ManuallyDrop::new(self);
1363 if let Some(root) = me.root.take() {
1364 let (f, b) = root.full_range();
1366 IntoIter { front: Some(f), back: Some(b), length: me.length }
1368 IntoIter { front: None, back: None, length: 0 }
1373 #[stable(feature = "btree_drop", since = "1.7.0")]
1374 impl<K, V> Drop for IntoIter<K, V> {
1375 fn drop(&mut self) {
1376 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1378 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1379 fn drop(&mut self) {
1380 // Continue the same loop we perform below. This only runs when unwinding, so we
1381 // don't have to care about panics this time (they'll abort).
1382 while let Some(_) = self.0.next() {}
1386 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1387 while let Some(parent) = node.deallocate_and_ascend() {
1388 node = parent.into_node().forget_type();
1394 while let Some(pair) = self.next() {
1395 let guard = DropGuard(self);
1401 if let Some(front) = ptr::read(&self.front) {
1402 let mut node = front.into_node().forget_type();
1403 // Most of the nodes have been deallocated while traversing
1404 // but one pile from a leaf up to the root is left standing.
1405 while let Some(parent) = node.deallocate_and_ascend() {
1406 node = parent.into_node().forget_type();
1413 #[stable(feature = "rust1", since = "1.0.0")]
1414 impl<K, V> Iterator for IntoIter<K, V> {
1417 fn next(&mut self) -> Option<(K, V)> {
1418 if self.length == 0 {
1422 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1426 fn size_hint(&self) -> (usize, Option<usize>) {
1427 (self.length, Some(self.length))
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1433 fn next_back(&mut self) -> Option<(K, V)> {
1434 if self.length == 0 {
1438 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1445 fn len(&self) -> usize {
1450 #[stable(feature = "fused", since = "1.26.0")]
1451 impl<K, V> FusedIterator for IntoIter<K, V> {}
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1457 fn next(&mut self) -> Option<&'a K> {
1458 self.inner.next().map(|(k, _)| k)
1461 fn size_hint(&self) -> (usize, Option<usize>) {
1462 self.inner.size_hint()
1465 fn last(mut self) -> Option<&'a K> {
1469 fn min(mut self) -> Option<&'a K> {
1473 fn max(mut self) -> Option<&'a K> {
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1480 fn next_back(&mut self) -> Option<&'a K> {
1481 self.inner.next_back().map(|(k, _)| k)
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1487 fn len(&self) -> usize {
1492 #[stable(feature = "fused", since = "1.26.0")]
1493 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl<K, V> Clone for Keys<'_, K, V> {
1497 fn clone(&self) -> Self {
1498 Keys { inner: self.inner.clone() }
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl<'a, K, V> Iterator for Values<'a, K, V> {
1506 fn next(&mut self) -> Option<&'a V> {
1507 self.inner.next().map(|(_, v)| v)
1510 fn size_hint(&self) -> (usize, Option<usize>) {
1511 self.inner.size_hint()
1514 fn last(mut self) -> Option<&'a V> {
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1521 fn next_back(&mut self) -> Option<&'a V> {
1522 self.inner.next_back().map(|(_, v)| v)
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1528 fn len(&self) -> usize {
1533 #[stable(feature = "fused", since = "1.26.0")]
1534 impl<K, V> FusedIterator for Values<'_, K, V> {}
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 impl<K, V> Clone for Values<'_, K, V> {
1538 fn clone(&self) -> Self {
1539 Values { inner: self.inner.clone() }
1543 /// An iterator produced by calling `drain_filter` on BTreeMap.
1544 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1545 pub struct DrainFilter<'a, K, V, F>
1549 F: 'a + FnMut(&K, &mut V) -> bool,
1552 inner: DrainFilterInner<'a, K, V>,
1554 /// Most of the implementation of DrainFilter, independent of the type
1555 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1556 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1557 /// Reference to the length field in the borrowed map, updated live.
1558 length: &'a mut usize,
1559 /// Burried reference to the root field in the borrowed map.
1560 /// Wrapped in `Option` to allow drop handler to `take` it.
1561 dormant_root: Option<DormantMutRef<'a, node::Root<K, V>>>,
1562 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1563 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1564 /// or if a panic occurred in the predicate.
1565 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1568 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1569 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1571 F: FnMut(&K, &mut V) -> bool,
1573 fn drop(&mut self) {
1574 self.for_each(drop);
1578 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1579 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1583 F: FnMut(&K, &mut V) -> bool,
1585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1586 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1590 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1591 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1593 F: FnMut(&K, &mut V) -> bool,
1597 fn next(&mut self) -> Option<(K, V)> {
1598 self.inner.next(&mut self.pred)
1601 fn size_hint(&self) -> (usize, Option<usize>) {
1602 self.inner.size_hint()
1606 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1607 /// Allow Debug implementations to predict the next element.
1608 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1609 let edge = self.cur_leaf_edge.as_ref()?;
1610 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1613 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1614 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1616 F: FnMut(&K, &mut V) -> bool,
1618 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1619 let (k, v) = kv.kv_mut();
1622 let (kv, pos) = kv.remove_kv_tracking(|| {
1623 // SAFETY: we will touch the root in a way that will not
1624 // invalidate the position returned.
1625 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1626 root.pop_internal_level();
1627 self.dormant_root = Some(DormantMutRef::new(root).1);
1629 self.cur_leaf_edge = Some(pos);
1632 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1637 /// Implementation of a typical `DrainFilter::size_hint` method.
1638 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1639 // In most of the btree iterators, `self.length` is the number of elements
1640 // yet to be visited. Here, it includes elements that were visited and that
1641 // the predicate decided not to drain. Making this upper bound more accurate
1642 // requires maintaining an extra field and is not worth while.
1643 (0, Some(*self.length))
1647 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1648 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1650 #[stable(feature = "btree_range", since = "1.17.0")]
1651 impl<'a, K, V> Iterator for Range<'a, K, V> {
1652 type Item = (&'a K, &'a V);
1654 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1655 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1658 fn last(mut self) -> Option<(&'a K, &'a V)> {
1662 fn min(mut self) -> Option<(&'a K, &'a V)> {
1666 fn max(mut self) -> Option<(&'a K, &'a V)> {
1671 #[stable(feature = "map_values_mut", since = "1.10.0")]
1672 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1673 type Item = &'a mut V;
1675 fn next(&mut self) -> Option<&'a mut V> {
1676 self.inner.next().map(|(_, v)| v)
1679 fn size_hint(&self) -> (usize, Option<usize>) {
1680 self.inner.size_hint()
1683 fn last(mut self) -> Option<&'a mut V> {
1688 #[stable(feature = "map_values_mut", since = "1.10.0")]
1689 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1690 fn next_back(&mut self) -> Option<&'a mut V> {
1691 self.inner.next_back().map(|(_, v)| v)
1695 #[stable(feature = "map_values_mut", since = "1.10.0")]
1696 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1697 fn len(&self) -> usize {
1702 #[stable(feature = "fused", since = "1.26.0")]
1703 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1705 impl<'a, K, V> Range<'a, K, V> {
1706 fn is_empty(&self) -> bool {
1707 self.front == self.back
1710 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1711 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1715 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1716 impl<K, V> Iterator for IntoKeys<K, V> {
1719 fn next(&mut self) -> Option<K> {
1720 self.inner.next().map(|(k, _)| k)
1723 fn size_hint(&self) -> (usize, Option<usize>) {
1724 self.inner.size_hint()
1727 fn last(mut self) -> Option<K> {
1731 fn min(mut self) -> Option<K> {
1735 fn max(mut self) -> Option<K> {
1740 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1741 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1742 fn next_back(&mut self) -> Option<K> {
1743 self.inner.next_back().map(|(k, _)| k)
1747 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1748 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1749 fn len(&self) -> usize {
1754 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1755 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1757 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1758 impl<K, V> Iterator for IntoValues<K, V> {
1761 fn next(&mut self) -> Option<V> {
1762 self.inner.next().map(|(_, v)| v)
1765 fn size_hint(&self) -> (usize, Option<usize>) {
1766 self.inner.size_hint()
1769 fn last(mut self) -> Option<V> {
1774 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1775 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1776 fn next_back(&mut self) -> Option<V> {
1777 self.inner.next_back().map(|(_, v)| v)
1781 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1782 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1783 fn len(&self) -> usize {
1788 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1789 impl<K, V> FusedIterator for IntoValues<K, V> {}
1791 #[stable(feature = "btree_range", since = "1.17.0")]
1792 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1793 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1794 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1798 impl<'a, K, V> Range<'a, K, V> {
1799 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1800 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1804 #[stable(feature = "fused", since = "1.26.0")]
1805 impl<K, V> FusedIterator for Range<'_, K, V> {}
1807 #[stable(feature = "btree_range", since = "1.17.0")]
1808 impl<K, V> Clone for Range<'_, K, V> {
1809 fn clone(&self) -> Self {
1810 Range { front: self.front, back: self.back }
1814 #[stable(feature = "btree_range", since = "1.17.0")]
1815 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1816 type Item = (&'a K, &'a mut V);
1818 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1819 if self.is_empty() {
1822 let (k, v) = unsafe { self.next_unchecked() };
1823 Some((k, v)) // coerce k from `&mut K` to `&K`
1827 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1831 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1835 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1840 impl<'a, K, V> RangeMut<'a, K, V> {
1841 fn is_empty(&self) -> bool {
1842 self.front == self.back
1845 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1846 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1849 /// Returns an iterator of references over the remaining items.
1851 pub(super) fn iter(&self) -> Range<'_, K, V> {
1853 front: self.front.as_ref().map(|f| f.reborrow()),
1854 back: self.back.as_ref().map(|b| b.reborrow()),
1859 #[stable(feature = "btree_range", since = "1.17.0")]
1860 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1861 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1862 if self.is_empty() {
1865 let (k, v) = unsafe { self.next_back_unchecked() };
1866 Some((k, v)) // coerce k from `&mut K` to `&K`
1871 #[stable(feature = "fused", since = "1.26.0")]
1872 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1874 impl<'a, K, V> RangeMut<'a, K, V> {
1875 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1876 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1882 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1883 let mut map = BTreeMap::new();
1889 #[stable(feature = "rust1", since = "1.0.0")]
1890 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1892 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1893 iter.into_iter().for_each(move |(k, v)| {
1899 fn extend_one(&mut self, (k, v): (K, V)) {
1904 #[stable(feature = "extend_ref", since = "1.2.0")]
1905 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1906 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1907 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1911 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1916 #[stable(feature = "rust1", since = "1.0.0")]
1917 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1918 fn hash<H: Hasher>(&self, state: &mut H) {
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 impl<K: Ord, V> Default for BTreeMap<K, V> {
1927 /// Creates an empty `BTreeMap<K, V>`.
1928 fn default() -> BTreeMap<K, V> {
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1935 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1936 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1946 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1947 self.iter().partial_cmp(other.iter())
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1954 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1955 self.iter().cmp(other.iter())
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1962 f.debug_map().entries(self.iter()).finish()
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1974 /// Returns a reference to the value corresponding to the supplied key.
1978 /// Panics if the key is not present in the `BTreeMap`.
1980 fn index(&self, key: &Q) -> &V {
1981 self.get(key).expect("no entry found for key")
1985 impl<K, V> BTreeMap<K, V> {
1986 /// Gets an iterator over the entries of the map, sorted by key.
1993 /// use std::collections::BTreeMap;
1995 /// let mut map = BTreeMap::new();
1996 /// map.insert(3, "c");
1997 /// map.insert(2, "b");
1998 /// map.insert(1, "a");
2000 /// for (key, value) in map.iter() {
2001 /// println!("{}: {}", key, value);
2004 /// let (first_key, first_value) = map.iter().next().unwrap();
2005 /// assert_eq!((*first_key, *first_value), (1, "a"));
2007 #[stable(feature = "rust1", since = "1.0.0")]
2008 pub fn iter(&self) -> Iter<'_, K, V> {
2009 if let Some(root) = &self.root {
2010 let (f, b) = root.reborrow().full_range();
2012 Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2014 Iter { range: Range { front: None, back: None }, length: 0 }
2018 /// Gets a mutable iterator over the entries of the map, sorted by key.
2025 /// use std::collections::BTreeMap;
2027 /// let mut map = BTreeMap::new();
2028 /// map.insert("a", 1);
2029 /// map.insert("b", 2);
2030 /// map.insert("c", 3);
2032 /// // add 10 to the value if the key isn't "a"
2033 /// for (key, value) in map.iter_mut() {
2034 /// if key != &"a" {
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2041 if let Some(root) = &mut self.root {
2042 let (f, b) = root.borrow_valmut().full_range();
2045 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2046 length: self.length,
2049 IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2053 /// Gets an iterator over the keys of the map, in sorted order.
2060 /// use std::collections::BTreeMap;
2062 /// let mut a = BTreeMap::new();
2063 /// a.insert(2, "b");
2064 /// a.insert(1, "a");
2066 /// let keys: Vec<_> = a.keys().cloned().collect();
2067 /// assert_eq!(keys, [1, 2]);
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 pub fn keys(&self) -> Keys<'_, K, V> {
2071 Keys { inner: self.iter() }
2074 /// Gets an iterator over the values of the map, in order by key.
2081 /// use std::collections::BTreeMap;
2083 /// let mut a = BTreeMap::new();
2084 /// a.insert(1, "hello");
2085 /// a.insert(2, "goodbye");
2087 /// let values: Vec<&str> = a.values().cloned().collect();
2088 /// assert_eq!(values, ["hello", "goodbye"]);
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub fn values(&self) -> Values<'_, K, V> {
2092 Values { inner: self.iter() }
2095 /// Gets a mutable iterator over the values of the map, in order by key.
2102 /// use std::collections::BTreeMap;
2104 /// let mut a = BTreeMap::new();
2105 /// a.insert(1, String::from("hello"));
2106 /// a.insert(2, String::from("goodbye"));
2108 /// for value in a.values_mut() {
2109 /// value.push_str("!");
2112 /// let values: Vec<String> = a.values().cloned().collect();
2113 /// assert_eq!(values, [String::from("hello!"),
2114 /// String::from("goodbye!")]);
2116 #[stable(feature = "map_values_mut", since = "1.10.0")]
2117 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2118 ValuesMut { inner: self.iter_mut() }
2121 /// Returns the number of elements in the map.
2128 /// use std::collections::BTreeMap;
2130 /// let mut a = BTreeMap::new();
2131 /// assert_eq!(a.len(), 0);
2132 /// a.insert(1, "a");
2133 /// assert_eq!(a.len(), 1);
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2137 pub const fn len(&self) -> usize {
2141 /// Returns `true` if the map contains no elements.
2148 /// use std::collections::BTreeMap;
2150 /// let mut a = BTreeMap::new();
2151 /// assert!(a.is_empty());
2152 /// a.insert(1, "a");
2153 /// assert!(!a.is_empty());
2155 #[stable(feature = "rust1", since = "1.0.0")]
2156 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2157 pub const fn is_empty(&self) -> bool {
2161 /// If the root node is the empty (non-allocated) root node, allocate our
2162 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2163 fn ensure_is_owned(root: &mut Option<node::Root<K, V>>) -> &mut node::Root<K, V> {
2164 root.get_or_insert_with(node::Root::new_leaf)