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, Root};
13 use super::search::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 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 pub struct BTreeMap<K, V> {
142 root: Option<Root<K, V>>,
146 #[stable(feature = "btree_drop", since = "1.7.0")]
147 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
150 drop(ptr::read(self).into_iter());
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
157 fn clone(&self) -> BTreeMap<K, V> {
158 fn clone_subtree<'a, K: Clone, V: Clone>(
159 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
167 let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 };
170 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
171 let mut out_node = match root.borrow_mut().force() {
173 Internal(_) => unreachable!(),
176 let mut in_edge = leaf.first_edge();
177 while let Ok(kv) = in_edge.right_kv() {
178 let (k, v) = kv.into_kv();
179 in_edge = kv.right_edge();
181 out_node.push(k.clone(), v.clone());
182 out_tree.length += 1;
188 Internal(internal) => {
189 let mut out_tree = clone_subtree(internal.first_edge().descend());
192 let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
193 let mut out_node = out_root.push_internal_level();
194 let mut in_edge = internal.first_edge();
195 while let Ok(kv) = in_edge.right_kv() {
196 let (k, v) = kv.into_kv();
197 in_edge = kv.right_edge();
199 let k = (*k).clone();
200 let v = (*v).clone();
201 let subtree = clone_subtree(in_edge.descend());
203 // We can't destructure subtree directly
204 // because BTreeMap implements Drop
205 let (subroot, sublength) = unsafe {
206 let subtree = ManuallyDrop::new(subtree);
207 let root = ptr::read(&subtree.root);
208 let length = subtree.length;
212 out_node.push(k, v, subroot.unwrap_or_else(Root::new));
213 out_tree.length += 1 + sublength;
223 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
224 // Ord` constraint, which this method lacks.
225 BTreeMap { root: None, length: 0 }
227 clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
232 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
239 fn get(&self, key: &Q) -> Option<&K> {
240 let root_node = self.root.as_ref()?.reborrow();
241 match root_node.search_tree(key) {
242 Found(handle) => Some(handle.into_kv().0),
247 fn take(&mut self, key: &Q) -> Option<K> {
248 let (map, dormant_map) = DormantMutRef::new(self);
249 let root_node = map.root.as_mut()?.borrow_mut();
250 match root_node.search_tree(key) {
252 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
258 fn replace(&mut self, key: K) -> Option<K> {
259 let (map, dormant_map) = DormantMutRef::new(self);
260 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
261 match root_node.search_tree::<K>(&key) {
262 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
264 VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
271 /// An iterator over the entries of a `BTreeMap`.
273 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
274 /// documentation for more.
276 /// [`iter`]: BTreeMap::iter
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub struct Iter<'a, K: 'a, V: 'a> {
279 range: Range<'a, K, V>,
283 #[stable(feature = "collection_debug", since = "1.17.0")]
284 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 f.debug_list().entries(self.clone()).finish()
290 /// A mutable iterator over the entries of a `BTreeMap`.
292 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
293 /// documentation for more.
295 /// [`iter_mut`]: BTreeMap::iter_mut
296 #[stable(feature = "rust1", since = "1.0.0")]
298 pub struct IterMut<'a, K: 'a, V: 'a> {
299 range: RangeMut<'a, K, V>,
303 /// An owning iterator over the entries of a `BTreeMap`.
305 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
306 /// (provided by the `IntoIterator` trait). See its documentation for more.
308 /// [`into_iter`]: IntoIterator::into_iter
309 #[stable(feature = "rust1", since = "1.0.0")]
310 pub struct IntoIter<K, V> {
311 front: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
312 back: Option<Handle<NodeRef<marker::Owned, K, V, marker::Leaf>, marker::Edge>>,
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> {
321 front: self.front.as_ref().map(|f| f.reborrow()),
322 back: self.back.as_ref().map(|b| b.reborrow()),
325 Iter { range: range, length: self.length }
329 #[stable(feature = "collection_debug", since = "1.17.0")]
330 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332 f.debug_list().entries(self.iter()).finish()
336 /// An iterator over the keys of a `BTreeMap`.
338 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
339 /// documentation for more.
341 /// [`keys`]: BTreeMap::keys
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub struct Keys<'a, K: 'a, V: 'a> {
344 inner: Iter<'a, K, V>,
347 #[stable(feature = "collection_debug", since = "1.17.0")]
348 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 f.debug_list().entries(self.clone()).finish()
354 /// An iterator over the values of a `BTreeMap`.
356 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
357 /// documentation for more.
359 /// [`values`]: BTreeMap::values
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub struct Values<'a, K: 'a, V: 'a> {
362 inner: Iter<'a, K, V>,
365 #[stable(feature = "collection_debug", since = "1.17.0")]
366 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 f.debug_list().entries(self.clone()).finish()
372 /// A mutable iterator over the values of a `BTreeMap`.
374 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
375 /// documentation for more.
377 /// [`values_mut`]: BTreeMap::values_mut
378 #[stable(feature = "map_values_mut", since = "1.10.0")]
379 pub struct ValuesMut<'a, K: 'a, V: 'a> {
380 inner: IterMut<'a, K, V>,
383 #[stable(feature = "map_values_mut", since = "1.10.0")]
384 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
390 /// An owning iterator over the keys of a `BTreeMap`.
392 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
393 /// See its documentation for more.
395 /// [`into_keys`]: BTreeMap::into_keys
396 #[unstable(feature = "map_into_keys_values", issue = "75294")]
397 pub struct IntoKeys<K, V> {
398 inner: IntoIter<K, V>,
401 #[unstable(feature = "map_into_keys_values", issue = "75294")]
402 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
408 /// An owning iterator over the values of a `BTreeMap`.
410 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
411 /// See its documentation for more.
413 /// [`into_values`]: BTreeMap::into_values
414 #[unstable(feature = "map_into_keys_values", issue = "75294")]
415 pub struct IntoValues<K, V> {
416 inner: IntoIter<K, V>,
419 #[unstable(feature = "map_into_keys_values", issue = "75294")]
420 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
426 /// An iterator over a sub-range of entries in a `BTreeMap`.
428 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
429 /// documentation for more.
431 /// [`range`]: BTreeMap::range
432 #[stable(feature = "btree_range", since = "1.17.0")]
433 pub struct Range<'a, K: 'a, V: 'a> {
434 front: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
435 back: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
438 #[stable(feature = "collection_debug", since = "1.17.0")]
439 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 f.debug_list().entries(self.clone()).finish()
445 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
447 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
448 /// documentation for more.
450 /// [`range_mut`]: BTreeMap::range_mut
451 #[stable(feature = "btree_range", since = "1.17.0")]
452 pub struct RangeMut<'a, K: 'a, V: 'a> {
453 front: Option<Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>>,
454 back: Option<Handle<NodeRef<marker::ValMut<'a>, K, V, marker::Leaf>, marker::Edge>>,
456 // Be invariant in `K` and `V`
457 _marker: PhantomData<&'a mut (K, V)>,
460 #[stable(feature = "collection_debug", since = "1.17.0")]
461 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464 front: self.front.as_ref().map(|f| f.reborrow()),
465 back: self.back.as_ref().map(|b| b.reborrow()),
467 f.debug_list().entries(range).finish()
471 impl<K: Ord, V> BTreeMap<K, V> {
472 /// Makes a new, empty `BTreeMap`.
474 /// Does not allocate anything on its own.
481 /// use std::collections::BTreeMap;
483 /// let mut map = BTreeMap::new();
485 /// // entries can now be inserted into the empty map
486 /// map.insert(1, "a");
488 #[stable(feature = "rust1", since = "1.0.0")]
489 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
490 pub const fn new() -> BTreeMap<K, V> {
491 BTreeMap { root: None, length: 0 }
494 /// Clears the map, removing all elements.
501 /// use std::collections::BTreeMap;
503 /// let mut a = BTreeMap::new();
504 /// a.insert(1, "a");
506 /// assert!(a.is_empty());
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn clear(&mut self) {
510 *self = BTreeMap::new();
513 /// Returns a reference to the value corresponding to the key.
515 /// The key may be any borrowed form of the map's key type, but the ordering
516 /// on the borrowed form *must* match the ordering on the key type.
523 /// use std::collections::BTreeMap;
525 /// let mut map = BTreeMap::new();
526 /// map.insert(1, "a");
527 /// assert_eq!(map.get(&1), Some(&"a"));
528 /// assert_eq!(map.get(&2), None);
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
536 let root_node = self.root.as_ref()?.reborrow();
537 match root_node.search_tree(key) {
538 Found(handle) => Some(handle.into_kv().1),
543 /// Returns the key-value pair corresponding to the supplied key.
545 /// The supplied key may be any borrowed form of the map's key type, but the ordering
546 /// on the borrowed form *must* match the ordering on the key type.
551 /// use std::collections::BTreeMap;
553 /// let mut map = BTreeMap::new();
554 /// map.insert(1, "a");
555 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
556 /// assert_eq!(map.get_key_value(&2), None);
558 #[stable(feature = "map_get_key_value", since = "1.40.0")]
559 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
564 let root_node = self.root.as_ref()?.reborrow();
565 match root_node.search_tree(k) {
566 Found(handle) => Some(handle.into_kv()),
571 /// Returns the first key-value pair in the map.
572 /// The key in this pair is the minimum key in the map.
579 /// #![feature(map_first_last)]
580 /// use std::collections::BTreeMap;
582 /// let mut map = BTreeMap::new();
583 /// assert_eq!(map.first_key_value(), None);
584 /// map.insert(1, "b");
585 /// map.insert(2, "a");
586 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
588 #[unstable(feature = "map_first_last", issue = "62924")]
589 pub fn first_key_value(&self) -> Option<(&K, &V)> {
590 let root_node = self.root.as_ref()?.reborrow();
591 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
594 /// Returns the first entry in the map for in-place manipulation.
595 /// The key of this entry is the minimum key in the map.
600 /// #![feature(map_first_last)]
601 /// use std::collections::BTreeMap;
603 /// let mut map = BTreeMap::new();
604 /// map.insert(1, "a");
605 /// map.insert(2, "b");
606 /// if let Some(mut entry) = map.first_entry() {
607 /// if *entry.key() > 0 {
608 /// entry.insert("first");
611 /// assert_eq!(*map.get(&1).unwrap(), "first");
612 /// assert_eq!(*map.get(&2).unwrap(), "b");
614 #[unstable(feature = "map_first_last", issue = "62924")]
615 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
616 let (map, dormant_map) = DormantMutRef::new(self);
617 let root_node = map.root.as_mut()?.borrow_mut();
618 let kv = root_node.first_leaf_edge().right_kv().ok()?;
619 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
622 /// Removes and returns the first element in the map.
623 /// The key of this element is the minimum key that was in the map.
627 /// Draining elements in ascending order, while keeping a usable map each iteration.
630 /// #![feature(map_first_last)]
631 /// use std::collections::BTreeMap;
633 /// let mut map = BTreeMap::new();
634 /// map.insert(1, "a");
635 /// map.insert(2, "b");
636 /// while let Some((key, _val)) = map.pop_first() {
637 /// assert!(map.iter().all(|(k, _v)| *k > key));
639 /// assert!(map.is_empty());
641 #[unstable(feature = "map_first_last", issue = "62924")]
642 pub fn pop_first(&mut self) -> Option<(K, V)> {
643 self.first_entry().map(|entry| entry.remove_entry())
646 /// Returns the last key-value pair in the map.
647 /// The key in this pair is the maximum key in the map.
654 /// #![feature(map_first_last)]
655 /// use std::collections::BTreeMap;
657 /// let mut map = BTreeMap::new();
658 /// map.insert(1, "b");
659 /// map.insert(2, "a");
660 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
662 #[unstable(feature = "map_first_last", issue = "62924")]
663 pub fn last_key_value(&self) -> Option<(&K, &V)> {
664 let root_node = self.root.as_ref()?.reborrow();
665 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
668 /// Returns the last entry in the map for in-place manipulation.
669 /// The key of this entry is the maximum key in the map.
674 /// #![feature(map_first_last)]
675 /// use std::collections::BTreeMap;
677 /// let mut map = BTreeMap::new();
678 /// map.insert(1, "a");
679 /// map.insert(2, "b");
680 /// if let Some(mut entry) = map.last_entry() {
681 /// if *entry.key() > 0 {
682 /// entry.insert("last");
685 /// assert_eq!(*map.get(&1).unwrap(), "a");
686 /// assert_eq!(*map.get(&2).unwrap(), "last");
688 #[unstable(feature = "map_first_last", issue = "62924")]
689 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> {
690 let (map, dormant_map) = DormantMutRef::new(self);
691 let root_node = map.root.as_mut()?.borrow_mut();
692 let kv = root_node.last_leaf_edge().left_kv().ok()?;
693 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
696 /// Removes and returns the last element in the map.
697 /// The key of this element is the maximum key that was in the map.
701 /// Draining elements in descending order, while keeping a usable map each iteration.
704 /// #![feature(map_first_last)]
705 /// use std::collections::BTreeMap;
707 /// let mut map = BTreeMap::new();
708 /// map.insert(1, "a");
709 /// map.insert(2, "b");
710 /// while let Some((key, _val)) = map.pop_last() {
711 /// assert!(map.iter().all(|(k, _v)| *k < key));
713 /// assert!(map.is_empty());
715 #[unstable(feature = "map_first_last", issue = "62924")]
716 pub fn pop_last(&mut self) -> Option<(K, V)> {
717 self.last_entry().map(|entry| entry.remove_entry())
720 /// Returns `true` if the map contains a value for the specified key.
722 /// The key may be any borrowed form of the map's key type, but the ordering
723 /// on the borrowed form *must* match the ordering on the key type.
730 /// use std::collections::BTreeMap;
732 /// let mut map = BTreeMap::new();
733 /// map.insert(1, "a");
734 /// assert_eq!(map.contains_key(&1), true);
735 /// assert_eq!(map.contains_key(&2), false);
737 #[stable(feature = "rust1", since = "1.0.0")]
738 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
743 self.get(key).is_some()
746 /// Returns a mutable reference to the value corresponding to the key.
748 /// The key may be any borrowed form of the map's key type, but the ordering
749 /// on the borrowed form *must* match the ordering on the key type.
756 /// use std::collections::BTreeMap;
758 /// let mut map = BTreeMap::new();
759 /// map.insert(1, "a");
760 /// if let Some(x) = map.get_mut(&1) {
763 /// assert_eq!(map[&1], "b");
765 // See `get` for implementation notes, this is basically a copy-paste with mut's added
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
772 let root_node = self.root.as_mut()?.borrow_mut();
773 match root_node.search_tree(key) {
774 Found(handle) => Some(handle.into_val_mut()),
779 /// Inserts a key-value pair into the map.
781 /// If the map did not have this key present, `None` is returned.
783 /// If the map did have this key present, the value is updated, and the old
784 /// value is returned. The key is not updated, though; this matters for
785 /// types that can be `==` without being identical. See the [module-level
786 /// documentation] for more.
788 /// [module-level documentation]: index.html#insert-and-complex-keys
795 /// use std::collections::BTreeMap;
797 /// let mut map = BTreeMap::new();
798 /// assert_eq!(map.insert(37, "a"), None);
799 /// assert_eq!(map.is_empty(), false);
801 /// map.insert(37, "b");
802 /// assert_eq!(map.insert(37, "c"), Some("b"));
803 /// assert_eq!(map[&37], "c");
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
807 match self.entry(key) {
808 Occupied(mut entry) => Some(entry.insert(value)),
816 /// Removes a key from the map, returning the value at the key if the key
817 /// was previously in the map.
819 /// The key may be any borrowed form of the map's key type, but the ordering
820 /// on the borrowed form *must* match the ordering on the key type.
827 /// use std::collections::BTreeMap;
829 /// let mut map = BTreeMap::new();
830 /// map.insert(1, "a");
831 /// assert_eq!(map.remove(&1), Some("a"));
832 /// assert_eq!(map.remove(&1), None);
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
840 self.remove_entry(key).map(|(_, v)| v)
843 /// Removes a key from the map, returning the stored key and value if the key
844 /// was previously in the map.
846 /// The key may be any borrowed form of the map's key type, but the ordering
847 /// on the borrowed form *must* match the ordering on the key type.
854 /// use std::collections::BTreeMap;
856 /// let mut map = BTreeMap::new();
857 /// map.insert(1, "a");
858 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
859 /// assert_eq!(map.remove_entry(&1), None);
861 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
862 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
867 let (map, dormant_map) = DormantMutRef::new(self);
868 let root_node = map.root.as_mut()?.borrow_mut();
869 match root_node.search_tree(key) {
871 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
877 /// Retains only the elements specified by the predicate.
879 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
884 /// #![feature(btree_retain)]
885 /// use std::collections::BTreeMap;
887 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
888 /// // Keep only the elements with even-numbered keys.
889 /// map.retain(|&k, _| k % 2 == 0);
890 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
893 #[unstable(feature = "btree_retain", issue = "79025")]
894 pub fn retain<F>(&mut self, mut f: F)
896 F: FnMut(&K, &mut V) -> bool,
898 self.drain_filter(|k, v| !f(k, v));
901 /// Moves all elements from `other` into `Self`, leaving `other` empty.
906 /// use std::collections::BTreeMap;
908 /// let mut a = BTreeMap::new();
909 /// a.insert(1, "a");
910 /// a.insert(2, "b");
911 /// a.insert(3, "c");
913 /// let mut b = BTreeMap::new();
914 /// b.insert(3, "d");
915 /// b.insert(4, "e");
916 /// b.insert(5, "f");
918 /// a.append(&mut b);
920 /// assert_eq!(a.len(), 5);
921 /// assert_eq!(b.len(), 0);
923 /// assert_eq!(a[&1], "a");
924 /// assert_eq!(a[&2], "b");
925 /// assert_eq!(a[&3], "d");
926 /// assert_eq!(a[&4], "e");
927 /// assert_eq!(a[&5], "f");
929 #[stable(feature = "btree_append", since = "1.11.0")]
930 pub fn append(&mut self, other: &mut Self) {
931 // Do we have to append anything at all?
932 if other.is_empty() {
936 // We can just swap `self` and `other` if `self` is empty.
938 mem::swap(self, other);
942 let self_iter = mem::take(self).into_iter();
943 let other_iter = mem::take(other).into_iter();
944 let root = BTreeMap::ensure_is_owned(&mut self.root);
945 root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
948 /// Constructs a double-ended iterator over a sub-range of elements in the map.
949 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
950 /// yield elements from min (inclusive) to max (exclusive).
951 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
952 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
953 /// range from 4 to 10.
957 /// Panics if range `start > end`.
958 /// Panics if range `start == end` and both bounds are `Excluded`.
965 /// use std::collections::BTreeMap;
966 /// use std::ops::Bound::Included;
968 /// let mut map = BTreeMap::new();
969 /// map.insert(3, "a");
970 /// map.insert(5, "b");
971 /// map.insert(8, "c");
972 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
973 /// println!("{}: {}", key, value);
975 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
977 #[stable(feature = "btree_range", since = "1.17.0")]
978 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
984 if let Some(root) = &self.root {
985 let (f, b) = root.reborrow().range_search(range);
987 Range { front: Some(f), back: Some(b) }
989 Range { front: None, back: None }
993 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
994 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
995 /// yield elements from min (inclusive) to max (exclusive).
996 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
997 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
998 /// range from 4 to 10.
1002 /// Panics if range `start > end`.
1003 /// Panics if range `start == end` and both bounds are `Excluded`.
1010 /// use std::collections::BTreeMap;
1012 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1014 /// .map(|&s| (s, 0))
1016 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1017 /// *balance += 100;
1019 /// for (name, balance) in &map {
1020 /// println!("{} => {}", name, balance);
1023 #[stable(feature = "btree_range", since = "1.17.0")]
1024 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1030 if let Some(root) = &mut self.root {
1031 let (f, b) = root.borrow_valmut().range_search(range);
1033 RangeMut { front: Some(f), back: Some(b), _marker: PhantomData }
1035 RangeMut { front: None, back: None, _marker: PhantomData }
1039 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1046 /// use std::collections::BTreeMap;
1048 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1050 /// // count the number of occurrences of letters in the vec
1051 /// for x in vec!["a", "b", "a", "c", "a", "b"] {
1052 /// *count.entry(x).or_insert(0) += 1;
1055 /// assert_eq!(count["a"], 3);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
1059 // FIXME(@porglezomp) Avoid allocating if we don't insert
1060 let (map, dormant_map) = DormantMutRef::new(self);
1061 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
1062 match root_node.search_tree(&key) {
1063 Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
1065 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })
1070 /// Splits the collection into two at the given key. Returns everything after the given key,
1071 /// including the key.
1078 /// use std::collections::BTreeMap;
1080 /// let mut a = BTreeMap::new();
1081 /// a.insert(1, "a");
1082 /// a.insert(2, "b");
1083 /// a.insert(3, "c");
1084 /// a.insert(17, "d");
1085 /// a.insert(41, "e");
1087 /// let b = a.split_off(&3);
1089 /// assert_eq!(a.len(), 2);
1090 /// assert_eq!(b.len(), 3);
1092 /// assert_eq!(a[&1], "a");
1093 /// assert_eq!(a[&2], "b");
1095 /// assert_eq!(b[&3], "c");
1096 /// assert_eq!(b[&17], "d");
1097 /// assert_eq!(b[&41], "e");
1099 #[stable(feature = "btree_split_off", since = "1.11.0")]
1100 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1104 if self.is_empty() {
1108 let total_num = self.len();
1109 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1111 let right_root = left_root.split_off(key);
1113 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1114 self.length = new_left_len;
1116 BTreeMap { root: Some(right_root), length: right_len }
1119 /// Creates an iterator which uses a closure to determine if an element should be removed.
1121 /// If the closure returns true, the element is removed from the map and yielded.
1122 /// If the closure returns false, or panics, the element remains in the map and will not be
1125 /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of
1126 /// whether you choose to keep or remove it.
1128 /// If the iterator is only partially consumed or not consumed at all, each of the remaining
1129 /// elements will still be subjected to the closure and removed and dropped if it returns true.
1131 /// It is unspecified how many more elements will be subjected to the closure
1132 /// if a panic occurs in the closure, or a panic occurs while dropping an element,
1133 /// or if the `DrainFilter` value is leaked.
1137 /// Splitting a map into even and odd keys, reusing the original map:
1140 /// #![feature(btree_drain_filter)]
1141 /// use std::collections::BTreeMap;
1143 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1144 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1146 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1147 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1149 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1150 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1152 F: FnMut(&K, &mut V) -> bool,
1154 DrainFilter { pred, inner: self.drain_filter_inner() }
1157 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> {
1158 if let Some(root) = self.root.as_mut() {
1159 let (root, dormant_root) = DormantMutRef::new(root);
1160 let front = root.borrow_mut().first_leaf_edge();
1162 length: &mut self.length,
1163 dormant_root: Some(dormant_root),
1164 cur_leaf_edge: Some(front),
1167 DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1171 /// Creates a consuming iterator visiting all the keys, in sorted order.
1172 /// The map cannot be used after calling this.
1173 /// The iterator element type is `K`.
1178 /// #![feature(map_into_keys_values)]
1179 /// use std::collections::BTreeMap;
1181 /// let mut a = BTreeMap::new();
1182 /// a.insert(2, "b");
1183 /// a.insert(1, "a");
1185 /// let keys: Vec<i32> = a.into_keys().collect();
1186 /// assert_eq!(keys, [1, 2]);
1189 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1190 pub fn into_keys(self) -> IntoKeys<K, V> {
1191 IntoKeys { inner: self.into_iter() }
1194 /// Creates a consuming iterator visiting all the values, in order by key.
1195 /// The map cannot be used after calling this.
1196 /// The iterator element type is `V`.
1201 /// #![feature(map_into_keys_values)]
1202 /// use std::collections::BTreeMap;
1204 /// let mut a = BTreeMap::new();
1205 /// a.insert(1, "hello");
1206 /// a.insert(2, "goodbye");
1208 /// let values: Vec<&str> = a.into_values().collect();
1209 /// assert_eq!(values, ["hello", "goodbye"]);
1212 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1213 pub fn into_values(self) -> IntoValues<K, V> {
1214 IntoValues { inner: self.into_iter() }
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1220 type Item = (&'a K, &'a V);
1221 type IntoIter = Iter<'a, K, V>;
1223 fn into_iter(self) -> Iter<'a, K, V> {
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1230 type Item = (&'a K, &'a V);
1232 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1233 if self.length == 0 {
1237 unsafe { Some(self.range.next_unchecked()) }
1241 fn size_hint(&self) -> (usize, Option<usize>) {
1242 (self.length, Some(self.length))
1245 fn last(mut self) -> Option<(&'a K, &'a V)> {
1249 fn min(mut self) -> Option<(&'a K, &'a V)> {
1253 fn max(mut self) -> Option<(&'a K, &'a V)> {
1258 #[stable(feature = "fused", since = "1.26.0")]
1259 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1263 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1264 if self.length == 0 {
1268 unsafe { Some(self.range.next_back_unchecked()) }
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1275 fn len(&self) -> usize {
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 impl<K, V> Clone for Iter<'_, K, V> {
1282 fn clone(&self) -> Self {
1283 Iter { range: self.range.clone(), length: self.length }
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1289 type Item = (&'a K, &'a mut V);
1290 type IntoIter = IterMut<'a, K, V>;
1292 fn into_iter(self) -> IterMut<'a, K, V> {
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1299 type Item = (&'a K, &'a mut V);
1301 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1302 if self.length == 0 {
1306 let (k, v) = unsafe { self.range.next_unchecked() };
1307 Some((k, v)) // coerce k from `&mut K` to `&K`
1311 fn size_hint(&self) -> (usize, Option<usize>) {
1312 (self.length, Some(self.length))
1315 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1319 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1323 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1330 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1331 if self.length == 0 {
1335 let (k, v) = unsafe { self.range.next_back_unchecked() };
1336 Some((k, v)) // coerce k from `&mut K` to `&K`
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1343 fn len(&self) -> usize {
1348 #[stable(feature = "fused", since = "1.26.0")]
1349 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1351 impl<'a, K, V> IterMut<'a, K, V> {
1352 /// Returns an iterator of references over the remaining items.
1354 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1355 Iter { range: self.range.iter(), length: self.length }
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<K, V> IntoIterator for BTreeMap<K, V> {
1362 type IntoIter = IntoIter<K, V>;
1364 fn into_iter(self) -> IntoIter<K, V> {
1365 let mut me = ManuallyDrop::new(self);
1366 if let Some(root) = me.root.take() {
1367 let (f, b) = root.full_range();
1369 IntoIter { front: Some(f), back: Some(b), length: me.length }
1371 IntoIter { front: None, back: None, length: 0 }
1376 #[stable(feature = "btree_drop", since = "1.7.0")]
1377 impl<K, V> Drop for IntoIter<K, V> {
1378 fn drop(&mut self) {
1379 struct DropGuard<'a, K, V>(&'a mut IntoIter<K, V>);
1381 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1382 fn drop(&mut self) {
1383 // Continue the same loop we perform below. This only runs when unwinding, so we
1384 // don't have to care about panics this time (they'll abort).
1385 while let Some(_) = self.0.next() {}
1389 unwrap_unchecked(ptr::read(&self.0.front)).into_node().forget_type();
1390 while let Some(parent) = node.deallocate_and_ascend() {
1391 node = parent.into_node().forget_type();
1397 while let Some(pair) = self.next() {
1398 let guard = DropGuard(self);
1404 if let Some(front) = ptr::read(&self.front) {
1405 let mut node = front.into_node().forget_type();
1406 // Most of the nodes have been deallocated while traversing
1407 // but one pile from a leaf up to the root is left standing.
1408 while let Some(parent) = node.deallocate_and_ascend() {
1409 node = parent.into_node().forget_type();
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<K, V> Iterator for IntoIter<K, V> {
1420 fn next(&mut self) -> Option<(K, V)> {
1421 if self.length == 0 {
1425 Some(unsafe { self.front.as_mut().unwrap().next_unchecked() })
1429 fn size_hint(&self) -> (usize, Option<usize>) {
1430 (self.length, Some(self.length))
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1436 fn next_back(&mut self) -> Option<(K, V)> {
1437 if self.length == 0 {
1441 Some(unsafe { self.back.as_mut().unwrap().next_back_unchecked() })
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1448 fn len(&self) -> usize {
1453 #[stable(feature = "fused", since = "1.26.0")]
1454 impl<K, V> FusedIterator for IntoIter<K, V> {}
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1460 fn next(&mut self) -> Option<&'a K> {
1461 self.inner.next().map(|(k, _)| k)
1464 fn size_hint(&self) -> (usize, Option<usize>) {
1465 self.inner.size_hint()
1468 fn last(mut self) -> Option<&'a K> {
1472 fn min(mut self) -> Option<&'a K> {
1476 fn max(mut self) -> Option<&'a K> {
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1483 fn next_back(&mut self) -> Option<&'a K> {
1484 self.inner.next_back().map(|(k, _)| k)
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1490 fn len(&self) -> usize {
1495 #[stable(feature = "fused", since = "1.26.0")]
1496 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<K, V> Clone for Keys<'_, K, V> {
1500 fn clone(&self) -> Self {
1501 Keys { inner: self.inner.clone() }
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<'a, K, V> Iterator for Values<'a, K, V> {
1509 fn next(&mut self) -> Option<&'a V> {
1510 self.inner.next().map(|(_, v)| v)
1513 fn size_hint(&self) -> (usize, Option<usize>) {
1514 self.inner.size_hint()
1517 fn last(mut self) -> Option<&'a V> {
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1524 fn next_back(&mut self) -> Option<&'a V> {
1525 self.inner.next_back().map(|(_, v)| v)
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1531 fn len(&self) -> usize {
1536 #[stable(feature = "fused", since = "1.26.0")]
1537 impl<K, V> FusedIterator for Values<'_, K, V> {}
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 impl<K, V> Clone for Values<'_, K, V> {
1541 fn clone(&self) -> Self {
1542 Values { inner: self.inner.clone() }
1546 /// An iterator produced by calling `drain_filter` on BTreeMap.
1547 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1548 pub struct DrainFilter<'a, K, V, F>
1552 F: 'a + FnMut(&K, &mut V) -> bool,
1555 inner: DrainFilterInner<'a, K, V>,
1557 /// Most of the implementation of DrainFilter are generic over the type
1558 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1559 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1560 /// Reference to the length field in the borrowed map, updated live.
1561 length: &'a mut usize,
1562 /// Buried reference to the root field in the borrowed map.
1563 /// Wrapped in `Option` to allow drop handler to `take` it.
1564 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1565 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1566 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1567 /// or if a panic occurred in the predicate.
1568 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1571 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1572 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1574 F: FnMut(&K, &mut V) -> bool,
1576 fn drop(&mut self) {
1577 self.for_each(drop);
1581 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1582 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1586 F: FnMut(&K, &mut V) -> bool,
1588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1589 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1593 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1594 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1596 F: FnMut(&K, &mut V) -> bool,
1600 fn next(&mut self) -> Option<(K, V)> {
1601 self.inner.next(&mut self.pred)
1604 fn size_hint(&self) -> (usize, Option<usize>) {
1605 self.inner.size_hint()
1609 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1610 /// Allow Debug implementations to predict the next element.
1611 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1612 let edge = self.cur_leaf_edge.as_ref()?;
1613 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1616 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1617 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1619 F: FnMut(&K, &mut V) -> bool,
1621 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1622 let (k, v) = kv.kv_mut();
1625 let (kv, pos) = kv.remove_kv_tracking(|| {
1626 // SAFETY: we will touch the root in a way that will not
1627 // invalidate the position returned.
1628 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1629 root.pop_internal_level();
1630 self.dormant_root = Some(DormantMutRef::new(root).1);
1632 self.cur_leaf_edge = Some(pos);
1635 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1640 /// Implementation of a typical `DrainFilter::size_hint` method.
1641 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1642 // In most of the btree iterators, `self.length` is the number of elements
1643 // yet to be visited. Here, it includes elements that were visited and that
1644 // the predicate decided not to drain. Making this upper bound more accurate
1645 // requires maintaining an extra field and is not worth while.
1646 (0, Some(*self.length))
1650 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1651 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1653 #[stable(feature = "btree_range", since = "1.17.0")]
1654 impl<'a, K, V> Iterator for Range<'a, K, V> {
1655 type Item = (&'a K, &'a V);
1657 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1658 if self.is_empty() { None } else { unsafe { Some(self.next_unchecked()) } }
1661 fn last(mut self) -> Option<(&'a K, &'a V)> {
1665 fn min(mut self) -> Option<(&'a K, &'a V)> {
1669 fn max(mut self) -> Option<(&'a K, &'a V)> {
1674 #[stable(feature = "map_values_mut", since = "1.10.0")]
1675 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1676 type Item = &'a mut V;
1678 fn next(&mut self) -> Option<&'a mut V> {
1679 self.inner.next().map(|(_, v)| v)
1682 fn size_hint(&self) -> (usize, Option<usize>) {
1683 self.inner.size_hint()
1686 fn last(mut self) -> Option<&'a mut V> {
1691 #[stable(feature = "map_values_mut", since = "1.10.0")]
1692 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1693 fn next_back(&mut self) -> Option<&'a mut V> {
1694 self.inner.next_back().map(|(_, v)| v)
1698 #[stable(feature = "map_values_mut", since = "1.10.0")]
1699 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1700 fn len(&self) -> usize {
1705 #[stable(feature = "fused", since = "1.26.0")]
1706 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1708 impl<'a, K, V> Range<'a, K, V> {
1709 fn is_empty(&self) -> bool {
1710 self.front == self.back
1713 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a V) {
1714 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1718 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1719 impl<K, V> Iterator for IntoKeys<K, V> {
1722 fn next(&mut self) -> Option<K> {
1723 self.inner.next().map(|(k, _)| k)
1726 fn size_hint(&self) -> (usize, Option<usize>) {
1727 self.inner.size_hint()
1730 fn last(mut self) -> Option<K> {
1734 fn min(mut self) -> Option<K> {
1738 fn max(mut self) -> Option<K> {
1743 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1744 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1745 fn next_back(&mut self) -> Option<K> {
1746 self.inner.next_back().map(|(k, _)| k)
1750 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1751 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1752 fn len(&self) -> usize {
1757 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1758 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1760 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1761 impl<K, V> Iterator for IntoValues<K, V> {
1764 fn next(&mut self) -> Option<V> {
1765 self.inner.next().map(|(_, v)| v)
1768 fn size_hint(&self) -> (usize, Option<usize>) {
1769 self.inner.size_hint()
1772 fn last(mut self) -> Option<V> {
1777 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1778 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1779 fn next_back(&mut self) -> Option<V> {
1780 self.inner.next_back().map(|(_, v)| v)
1784 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1785 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1786 fn len(&self) -> usize {
1791 #[unstable(feature = "map_into_keys_values", issue = "75294")]
1792 impl<K, V> FusedIterator for IntoValues<K, V> {}
1794 #[stable(feature = "btree_range", since = "1.17.0")]
1795 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1796 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1797 if self.is_empty() { None } else { Some(unsafe { self.next_back_unchecked() }) }
1801 impl<'a, K, V> Range<'a, K, V> {
1802 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a V) {
1803 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1807 #[stable(feature = "fused", since = "1.26.0")]
1808 impl<K, V> FusedIterator for Range<'_, K, V> {}
1810 #[stable(feature = "btree_range", since = "1.17.0")]
1811 impl<K, V> Clone for Range<'_, K, V> {
1812 fn clone(&self) -> Self {
1813 Range { front: self.front, back: self.back }
1817 #[stable(feature = "btree_range", since = "1.17.0")]
1818 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1819 type Item = (&'a K, &'a mut V);
1821 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1822 if self.is_empty() {
1825 let (k, v) = unsafe { self.next_unchecked() };
1826 Some((k, v)) // coerce k from `&mut K` to `&K`
1830 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1834 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1838 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1843 impl<'a, K, V> RangeMut<'a, K, V> {
1844 fn is_empty(&self) -> bool {
1845 self.front == self.back
1848 unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1849 unsafe { unwrap_unchecked(self.front.as_mut()).next_unchecked() }
1852 /// Returns an iterator of references over the remaining items.
1854 pub(super) fn iter(&self) -> Range<'_, K, V> {
1856 front: self.front.as_ref().map(|f| f.reborrow()),
1857 back: self.back.as_ref().map(|b| b.reborrow()),
1862 #[stable(feature = "btree_range", since = "1.17.0")]
1863 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1864 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1865 if self.is_empty() {
1868 let (k, v) = unsafe { self.next_back_unchecked() };
1869 Some((k, v)) // coerce k from `&mut K` to `&K`
1874 #[stable(feature = "fused", since = "1.26.0")]
1875 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1877 impl<'a, K, V> RangeMut<'a, K, V> {
1878 unsafe fn next_back_unchecked(&mut self) -> (&'a K, &'a mut V) {
1879 unsafe { unwrap_unchecked(self.back.as_mut()).next_back_unchecked() }
1883 #[stable(feature = "rust1", since = "1.0.0")]
1884 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1885 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1886 let mut map = BTreeMap::new();
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1895 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1896 iter.into_iter().for_each(move |(k, v)| {
1902 fn extend_one(&mut self, (k, v): (K, V)) {
1907 #[stable(feature = "extend_ref", since = "1.2.0")]
1908 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1909 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1910 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1914 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1921 fn hash<H: Hasher>(&self, state: &mut H) {
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 impl<K: Ord, V> Default for BTreeMap<K, V> {
1930 /// Creates an empty `BTreeMap`.
1931 fn default() -> BTreeMap<K, V> {
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1938 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1939 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1949 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1950 self.iter().partial_cmp(other.iter())
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1957 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1958 self.iter().cmp(other.iter())
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1964 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1965 f.debug_map().entries(self.iter()).finish()
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<K: Ord, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
1977 /// Returns a reference to the value corresponding to the supplied key.
1981 /// Panics if the key is not present in the `BTreeMap`.
1983 fn index(&self, key: &Q) -> &V {
1984 self.get(key).expect("no entry found for key")
1988 impl<K, V> BTreeMap<K, V> {
1989 /// Gets an iterator over the entries of the map, sorted by key.
1996 /// use std::collections::BTreeMap;
1998 /// let mut map = BTreeMap::new();
1999 /// map.insert(3, "c");
2000 /// map.insert(2, "b");
2001 /// map.insert(1, "a");
2003 /// for (key, value) in map.iter() {
2004 /// println!("{}: {}", key, value);
2007 /// let (first_key, first_value) = map.iter().next().unwrap();
2008 /// assert_eq!((*first_key, *first_value), (1, "a"));
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 pub fn iter(&self) -> Iter<'_, K, V> {
2012 if let Some(root) = &self.root {
2013 let (f, b) = root.reborrow().full_range();
2015 Iter { range: Range { front: Some(f), back: Some(b) }, length: self.length }
2017 Iter { range: Range { front: None, back: None }, length: 0 }
2021 /// Gets a mutable iterator over the entries of the map, sorted by key.
2028 /// use std::collections::BTreeMap;
2030 /// let mut map = BTreeMap::new();
2031 /// map.insert("a", 1);
2032 /// map.insert("b", 2);
2033 /// map.insert("c", 3);
2035 /// // add 10 to the value if the key isn't "a"
2036 /// for (key, value) in map.iter_mut() {
2037 /// if key != &"a" {
2042 #[stable(feature = "rust1", since = "1.0.0")]
2043 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2044 if let Some(root) = &mut self.root {
2045 let (f, b) = root.borrow_valmut().full_range();
2048 range: RangeMut { front: Some(f), back: Some(b), _marker: PhantomData },
2049 length: self.length,
2052 IterMut { range: RangeMut { front: None, back: None, _marker: PhantomData }, length: 0 }
2056 /// Gets an iterator over the keys of the map, in sorted order.
2063 /// use std::collections::BTreeMap;
2065 /// let mut a = BTreeMap::new();
2066 /// a.insert(2, "b");
2067 /// a.insert(1, "a");
2069 /// let keys: Vec<_> = a.keys().cloned().collect();
2070 /// assert_eq!(keys, [1, 2]);
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 pub fn keys(&self) -> Keys<'_, K, V> {
2074 Keys { inner: self.iter() }
2077 /// Gets an iterator over the values of the map, in order by key.
2084 /// use std::collections::BTreeMap;
2086 /// let mut a = BTreeMap::new();
2087 /// a.insert(1, "hello");
2088 /// a.insert(2, "goodbye");
2090 /// let values: Vec<&str> = a.values().cloned().collect();
2091 /// assert_eq!(values, ["hello", "goodbye"]);
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 pub fn values(&self) -> Values<'_, K, V> {
2095 Values { inner: self.iter() }
2098 /// Gets a mutable iterator over the values of the map, in order by key.
2105 /// use std::collections::BTreeMap;
2107 /// let mut a = BTreeMap::new();
2108 /// a.insert(1, String::from("hello"));
2109 /// a.insert(2, String::from("goodbye"));
2111 /// for value in a.values_mut() {
2112 /// value.push_str("!");
2115 /// let values: Vec<String> = a.values().cloned().collect();
2116 /// assert_eq!(values, [String::from("hello!"),
2117 /// String::from("goodbye!")]);
2119 #[stable(feature = "map_values_mut", since = "1.10.0")]
2120 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2121 ValuesMut { inner: self.iter_mut() }
2124 /// Returns the number of elements in the map.
2131 /// use std::collections::BTreeMap;
2133 /// let mut a = BTreeMap::new();
2134 /// assert_eq!(a.len(), 0);
2135 /// a.insert(1, "a");
2136 /// assert_eq!(a.len(), 1);
2138 #[doc(alias = "length")]
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2141 pub const fn len(&self) -> usize {
2145 /// Returns `true` if the map contains no elements.
2152 /// use std::collections::BTreeMap;
2154 /// let mut a = BTreeMap::new();
2155 /// assert!(a.is_empty());
2156 /// a.insert(1, "a");
2157 /// assert!(!a.is_empty());
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2161 pub const fn is_empty(&self) -> bool {
2165 /// If the root node is the empty (non-allocated) root node, allocate our
2166 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2167 fn ensure_is_owned(root: &mut Option<Root<K, V>>) -> &mut Root<K, V> {
2168 root.get_or_insert_with(Root::new)