1 use core::borrow::Borrow;
2 use core::cmp::Ordering;
3 use core::fmt::{self, Debug};
4 use core::hash::{Hash, Hasher};
5 use core::iter::{FromIterator, FusedIterator};
6 use core::marker::PhantomData;
7 use core::mem::{self, ManuallyDrop};
8 use core::ops::{Index, RangeBounds};
11 use super::borrow::DormantMutRef;
12 use super::navigate::LeafRange;
13 use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root};
14 use super::search::SearchResult::*;
17 pub use entry::{Entry, OccupiedEntry, OccupiedError, 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 additional 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 absence 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 /// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
67 /// [`Cell`]: core::cell::Cell
68 /// [`RefCell`]: core::cell::RefCell
73 /// use std::collections::BTreeMap;
75 /// // type inference lets us omit an explicit type signature (which
76 /// // would be `BTreeMap<&str, &str>` in this example).
77 /// let mut movie_reviews = BTreeMap::new();
79 /// // review some movies.
80 /// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
81 /// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
82 /// movie_reviews.insert("The Godfather", "Very enjoyable.");
83 /// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
85 /// // check for a specific one.
86 /// if !movie_reviews.contains_key("Les Misérables") {
87 /// println!("We've got {} reviews, but Les Misérables ain't one.",
88 /// movie_reviews.len());
91 /// // oops, this review has a lot of spelling mistakes, let's delete it.
92 /// movie_reviews.remove("The Blues Brothers");
94 /// // look up the values associated with some keys.
95 /// let to_find = ["Up!", "Office Space"];
96 /// for movie in &to_find {
97 /// match movie_reviews.get(movie) {
98 /// Some(review) => println!("{}: {}", movie, review),
99 /// None => println!("{} is unreviewed.", movie)
103 /// // Look up the value for a key (will panic if the key is not found).
104 /// println!("Movie review: {}", movie_reviews["Office Space"]);
106 /// // iterate over everything.
107 /// for (movie, review) in &movie_reviews {
108 /// println!("{}: \"{}\"", movie, review);
112 /// `BTreeMap` also implements an [`Entry API`], which allows for more complex
113 /// methods of getting, setting, updating and removing keys and their values:
115 /// [`Entry API`]: BTreeMap::entry
118 /// use std::collections::BTreeMap;
120 /// // type inference lets us omit an explicit type signature (which
121 /// // would be `BTreeMap<&str, u8>` in this example).
122 /// let mut player_stats = BTreeMap::new();
124 /// fn random_stat_buff() -> u8 {
125 /// // could actually return some random value here - let's just return
126 /// // some fixed value for now
130 /// // insert a key only if it doesn't already exist
131 /// player_stats.entry("health").or_insert(100);
133 /// // insert a key using a function that provides a new value only if it
134 /// // doesn't already exist
135 /// player_stats.entry("defence").or_insert_with(random_stat_buff);
137 /// // update a key, guarding against the key possibly not being set
138 /// let stat = player_stats.entry("attack").or_insert(100);
139 /// *stat += random_stat_buff();
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
143 pub struct BTreeMap<K, V> {
144 root: Option<Root<K, V>>,
148 #[stable(feature = "btree_drop", since = "1.7.0")]
149 unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap<K, V> {
151 if let Some(root) = self.root.take() {
152 Dropper { front: root.into_dying().first_leaf_edge(), remaining_length: self.length };
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
159 fn clone(&self) -> BTreeMap<K, V> {
160 fn clone_subtree<'a, K: Clone, V: Clone>(
161 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
169 let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 };
172 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
173 let mut out_node = match root.borrow_mut().force() {
175 Internal(_) => unreachable!(),
178 let mut in_edge = leaf.first_edge();
179 while let Ok(kv) = in_edge.right_kv() {
180 let (k, v) = kv.into_kv();
181 in_edge = kv.right_edge();
183 out_node.push(k.clone(), v.clone());
184 out_tree.length += 1;
190 Internal(internal) => {
191 let mut out_tree = clone_subtree(internal.first_edge().descend());
194 let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root);
195 let mut out_node = out_root.push_internal_level();
196 let mut in_edge = internal.first_edge();
197 while let Ok(kv) = in_edge.right_kv() {
198 let (k, v) = kv.into_kv();
199 in_edge = kv.right_edge();
201 let k = (*k).clone();
202 let v = (*v).clone();
203 let subtree = clone_subtree(in_edge.descend());
205 // We can't destructure subtree directly
206 // because BTreeMap implements Drop
207 let (subroot, sublength) = unsafe {
208 let subtree = ManuallyDrop::new(subtree);
209 let root = ptr::read(&subtree.root);
210 let length = subtree.length;
214 out_node.push(k, v, subroot.unwrap_or_else(Root::new));
215 out_tree.length += 1 + sublength;
225 // Ideally we'd call `BTreeMap::new` here, but that has the `K:
226 // Ord` constraint, which this method lacks.
227 BTreeMap { root: None, length: 0 }
229 clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty
234 impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
241 fn get(&self, key: &Q) -> Option<&K> {
242 let root_node = self.root.as_ref()?.reborrow();
243 match root_node.search_tree(key) {
244 Found(handle) => Some(handle.into_kv().0),
249 fn take(&mut self, key: &Q) -> Option<K> {
250 let (map, dormant_map) = DormantMutRef::new(self);
251 let root_node = map.root.as_mut()?.borrow_mut();
252 match root_node.search_tree(key) {
254 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_kv().0)
260 fn replace(&mut self, key: K) -> Option<K> {
261 let (map, dormant_map) = DormantMutRef::new(self);
262 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
263 match root_node.search_tree::<K>(&key) {
264 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
266 VacantEntry { key, handle, dormant_map, _marker: PhantomData }.insert(());
273 /// An iterator over the entries of a `BTreeMap`.
275 /// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
276 /// documentation for more.
278 /// [`iter`]: BTreeMap::iter
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub struct Iter<'a, K: 'a, V: 'a> {
281 range: Range<'a, K, V>,
285 #[stable(feature = "collection_debug", since = "1.17.0")]
286 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 f.debug_list().entries(self.clone()).finish()
292 /// A mutable iterator over the entries of a `BTreeMap`.
294 /// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
295 /// documentation for more.
297 /// [`iter_mut`]: BTreeMap::iter_mut
298 #[stable(feature = "rust1", since = "1.0.0")]
300 pub struct IterMut<'a, K: 'a, V: 'a> {
301 range: RangeMut<'a, K, V>,
305 /// An owning iterator over the entries of a `BTreeMap`.
307 /// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
308 /// (provided by the `IntoIterator` trait). See its documentation for more.
310 /// [`into_iter`]: IntoIterator::into_iter
311 #[stable(feature = "rust1", since = "1.0.0")]
312 pub struct IntoIter<K, V> {
313 range: LeafRange<marker::Dying, K, V>,
317 impl<K, V> IntoIter<K, V> {
318 /// Returns an iterator of references over the remaining items.
320 pub(super) fn iter(&self) -> Iter<'_, K, V> {
321 let range = Range { inner: self.range.reborrow() };
322 Iter { range: range, length: self.length }
326 #[stable(feature = "collection_debug", since = "1.17.0")]
327 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IntoIter<K, V> {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 f.debug_list().entries(self.iter()).finish()
333 /// A simplified version of `IntoIter` that is not double-ended and has only one
334 /// purpose: to drop the remainder of an `IntoIter`. Therefore it also serves to
335 /// drop an entire tree without the need to first look up a `back` leaf edge.
336 struct Dropper<K, V> {
337 front: Handle<NodeRef<marker::Dying, K, V, marker::Leaf>, marker::Edge>,
338 remaining_length: usize,
341 /// An iterator over the keys of a `BTreeMap`.
343 /// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
344 /// documentation for more.
346 /// [`keys`]: BTreeMap::keys
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub struct Keys<'a, K: 'a, V: 'a> {
349 inner: Iter<'a, K, V>,
352 #[stable(feature = "collection_debug", since = "1.17.0")]
353 impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 f.debug_list().entries(self.clone()).finish()
359 /// An iterator over the values of a `BTreeMap`.
361 /// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
362 /// documentation for more.
364 /// [`values`]: BTreeMap::values
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub struct Values<'a, K: 'a, V: 'a> {
367 inner: Iter<'a, K, V>,
370 #[stable(feature = "collection_debug", since = "1.17.0")]
371 impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 f.debug_list().entries(self.clone()).finish()
377 /// A mutable iterator over the values of a `BTreeMap`.
379 /// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
380 /// documentation for more.
382 /// [`values_mut`]: BTreeMap::values_mut
383 #[stable(feature = "map_values_mut", since = "1.10.0")]
384 pub struct ValuesMut<'a, K: 'a, V: 'a> {
385 inner: IterMut<'a, K, V>,
388 #[stable(feature = "map_values_mut", since = "1.10.0")]
389 impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
395 /// An owning iterator over the keys of a `BTreeMap`.
397 /// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
398 /// See its documentation for more.
400 /// [`into_keys`]: BTreeMap::into_keys
401 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
402 pub struct IntoKeys<K, V> {
403 inner: IntoIter<K, V>,
406 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
407 impl<K: fmt::Debug, V> fmt::Debug for IntoKeys<K, V> {
408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
413 /// An owning iterator over the values of a `BTreeMap`.
415 /// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
416 /// See its documentation for more.
418 /// [`into_values`]: BTreeMap::into_values
419 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
420 pub struct IntoValues<K, V> {
421 inner: IntoIter<K, V>,
424 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
425 impl<K, V: fmt::Debug> fmt::Debug for IntoValues<K, V> {
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
431 /// An iterator over a sub-range of entries in a `BTreeMap`.
433 /// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
434 /// documentation for more.
436 /// [`range`]: BTreeMap::range
437 #[stable(feature = "btree_range", since = "1.17.0")]
438 pub struct Range<'a, K: 'a, V: 'a> {
439 inner: LeafRange<marker::Immut<'a>, K, V>,
442 #[stable(feature = "collection_debug", since = "1.17.0")]
443 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 f.debug_list().entries(self.clone()).finish()
449 /// A mutable iterator over a sub-range of entries in a `BTreeMap`.
451 /// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
452 /// documentation for more.
454 /// [`range_mut`]: BTreeMap::range_mut
455 #[stable(feature = "btree_range", since = "1.17.0")]
456 pub struct RangeMut<'a, K: 'a, V: 'a> {
457 inner: LeafRange<marker::ValMut<'a>, K, V>,
459 // Be invariant in `K` and `V`
460 _marker: PhantomData<&'a mut (K, V)>,
463 #[stable(feature = "collection_debug", since = "1.17.0")]
464 impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 let range = Range { inner: self.inner.reborrow() };
467 f.debug_list().entries(range).finish()
471 impl<K, 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>
494 BTreeMap { root: None, length: 0 }
497 /// Clears the map, removing all elements.
504 /// use std::collections::BTreeMap;
506 /// let mut a = BTreeMap::new();
507 /// a.insert(1, "a");
509 /// assert!(a.is_empty());
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn clear(&mut self) {
513 *self = BTreeMap { root: None, length: 0 };
516 /// Returns a reference to the value corresponding to the key.
518 /// The key may be any borrowed form of the map's key type, but the ordering
519 /// on the borrowed form *must* match the ordering on the key type.
526 /// use std::collections::BTreeMap;
528 /// let mut map = BTreeMap::new();
529 /// map.insert(1, "a");
530 /// assert_eq!(map.get(&1), Some(&"a"));
531 /// assert_eq!(map.get(&2), None);
533 #[stable(feature = "rust1", since = "1.0.0")]
534 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
539 let root_node = self.root.as_ref()?.reborrow();
540 match root_node.search_tree(key) {
541 Found(handle) => Some(handle.into_kv().1),
546 /// Returns the key-value pair corresponding to the supplied key.
548 /// The supplied key may be any borrowed form of the map's key type, but the ordering
549 /// on the borrowed form *must* match the ordering on the key type.
554 /// use std::collections::BTreeMap;
556 /// let mut map = BTreeMap::new();
557 /// map.insert(1, "a");
558 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
559 /// assert_eq!(map.get_key_value(&2), None);
561 #[stable(feature = "map_get_key_value", since = "1.40.0")]
562 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
567 let root_node = self.root.as_ref()?.reborrow();
568 match root_node.search_tree(k) {
569 Found(handle) => Some(handle.into_kv()),
574 /// Returns the first key-value pair in the map.
575 /// The key in this pair is the minimum key in the map.
582 /// #![feature(map_first_last)]
583 /// use std::collections::BTreeMap;
585 /// let mut map = BTreeMap::new();
586 /// assert_eq!(map.first_key_value(), None);
587 /// map.insert(1, "b");
588 /// map.insert(2, "a");
589 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
591 #[unstable(feature = "map_first_last", issue = "62924")]
592 pub fn first_key_value(&self) -> Option<(&K, &V)>
596 let root_node = self.root.as_ref()?.reborrow();
597 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
600 /// Returns the first entry in the map for in-place manipulation.
601 /// The key of this entry is the minimum key in the map.
606 /// #![feature(map_first_last)]
607 /// use std::collections::BTreeMap;
609 /// let mut map = BTreeMap::new();
610 /// map.insert(1, "a");
611 /// map.insert(2, "b");
612 /// if let Some(mut entry) = map.first_entry() {
613 /// if *entry.key() > 0 {
614 /// entry.insert("first");
617 /// assert_eq!(*map.get(&1).unwrap(), "first");
618 /// assert_eq!(*map.get(&2).unwrap(), "b");
620 #[unstable(feature = "map_first_last", issue = "62924")]
621 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
625 let (map, dormant_map) = DormantMutRef::new(self);
626 let root_node = map.root.as_mut()?.borrow_mut();
627 let kv = root_node.first_leaf_edge().right_kv().ok()?;
628 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
631 /// Removes and returns the first element in the map.
632 /// The key of this element is the minimum key that was in the map.
636 /// Draining elements in ascending order, while keeping a usable map each iteration.
639 /// #![feature(map_first_last)]
640 /// use std::collections::BTreeMap;
642 /// let mut map = BTreeMap::new();
643 /// map.insert(1, "a");
644 /// map.insert(2, "b");
645 /// while let Some((key, _val)) = map.pop_first() {
646 /// assert!(map.iter().all(|(k, _v)| *k > key));
648 /// assert!(map.is_empty());
650 #[unstable(feature = "map_first_last", issue = "62924")]
651 pub fn pop_first(&mut self) -> Option<(K, V)>
655 self.first_entry().map(|entry| entry.remove_entry())
658 /// Returns the last key-value pair in the map.
659 /// The key in this pair is the maximum key in the map.
666 /// #![feature(map_first_last)]
667 /// use std::collections::BTreeMap;
669 /// let mut map = BTreeMap::new();
670 /// map.insert(1, "b");
671 /// map.insert(2, "a");
672 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
674 #[unstable(feature = "map_first_last", issue = "62924")]
675 pub fn last_key_value(&self) -> Option<(&K, &V)>
679 let root_node = self.root.as_ref()?.reborrow();
680 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
683 /// Returns the last entry in the map for in-place manipulation.
684 /// The key of this entry is the maximum key in the map.
689 /// #![feature(map_first_last)]
690 /// use std::collections::BTreeMap;
692 /// let mut map = BTreeMap::new();
693 /// map.insert(1, "a");
694 /// map.insert(2, "b");
695 /// if let Some(mut entry) = map.last_entry() {
696 /// if *entry.key() > 0 {
697 /// entry.insert("last");
700 /// assert_eq!(*map.get(&1).unwrap(), "a");
701 /// assert_eq!(*map.get(&2).unwrap(), "last");
703 #[unstable(feature = "map_first_last", issue = "62924")]
704 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>>
708 let (map, dormant_map) = DormantMutRef::new(self);
709 let root_node = map.root.as_mut()?.borrow_mut();
710 let kv = root_node.last_leaf_edge().left_kv().ok()?;
711 Some(OccupiedEntry { handle: kv.forget_node_type(), dormant_map, _marker: PhantomData })
714 /// Removes and returns the last element in the map.
715 /// The key of this element is the maximum key that was in the map.
719 /// Draining elements in descending order, while keeping a usable map each iteration.
722 /// #![feature(map_first_last)]
723 /// use std::collections::BTreeMap;
725 /// let mut map = BTreeMap::new();
726 /// map.insert(1, "a");
727 /// map.insert(2, "b");
728 /// while let Some((key, _val)) = map.pop_last() {
729 /// assert!(map.iter().all(|(k, _v)| *k < key));
731 /// assert!(map.is_empty());
733 #[unstable(feature = "map_first_last", issue = "62924")]
734 pub fn pop_last(&mut self) -> Option<(K, V)>
738 self.last_entry().map(|entry| entry.remove_entry())
741 /// Returns `true` if the map contains a value for the specified key.
743 /// The key may be any borrowed form of the map's key type, but the ordering
744 /// on the borrowed form *must* match the ordering on the key type.
751 /// use std::collections::BTreeMap;
753 /// let mut map = BTreeMap::new();
754 /// map.insert(1, "a");
755 /// assert_eq!(map.contains_key(&1), true);
756 /// assert_eq!(map.contains_key(&2), false);
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
764 self.get(key).is_some()
767 /// Returns a mutable reference to the value corresponding to the key.
769 /// The key may be any borrowed form of the map's key type, but the ordering
770 /// on the borrowed form *must* match the ordering on the key type.
777 /// use std::collections::BTreeMap;
779 /// let mut map = BTreeMap::new();
780 /// map.insert(1, "a");
781 /// if let Some(x) = map.get_mut(&1) {
784 /// assert_eq!(map[&1], "b");
786 // See `get` for implementation notes, this is basically a copy-paste with mut's added
787 #[stable(feature = "rust1", since = "1.0.0")]
788 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
793 let root_node = self.root.as_mut()?.borrow_mut();
794 match root_node.search_tree(key) {
795 Found(handle) => Some(handle.into_val_mut()),
800 /// Inserts a key-value pair into the map.
802 /// If the map did not have this key present, `None` is returned.
804 /// If the map did have this key present, the value is updated, and the old
805 /// value is returned. The key is not updated, though; this matters for
806 /// types that can be `==` without being identical. See the [module-level
807 /// documentation] for more.
809 /// [module-level documentation]: index.html#insert-and-complex-keys
816 /// use std::collections::BTreeMap;
818 /// let mut map = BTreeMap::new();
819 /// assert_eq!(map.insert(37, "a"), None);
820 /// assert_eq!(map.is_empty(), false);
822 /// map.insert(37, "b");
823 /// assert_eq!(map.insert(37, "c"), Some("b"));
824 /// assert_eq!(map[&37], "c");
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn insert(&mut self, key: K, value: V) -> Option<V>
831 match self.entry(key) {
832 Occupied(mut entry) => Some(entry.insert(value)),
840 /// Tries to insert a key-value pair into the map, and returns
841 /// a mutable reference to the value in the entry.
843 /// If the map already had this key present, nothing is updated, and
844 /// an error containing the occupied entry and the value is returned.
851 /// #![feature(map_try_insert)]
853 /// use std::collections::BTreeMap;
855 /// let mut map = BTreeMap::new();
856 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
858 /// let err = map.try_insert(37, "b").unwrap_err();
859 /// assert_eq!(err.entry.key(), &37);
860 /// assert_eq!(err.entry.get(), &"a");
861 /// assert_eq!(err.value, "b");
863 #[unstable(feature = "map_try_insert", issue = "82766")]
864 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V>>
868 match self.entry(key) {
869 Occupied(entry) => Err(OccupiedError { entry, value }),
870 Vacant(entry) => Ok(entry.insert(value)),
874 /// Removes a key from the map, returning the value at the key if the key
875 /// was previously in the map.
877 /// The key may be any borrowed form of the map's key type, but the ordering
878 /// on the borrowed form *must* match the ordering on the key type.
885 /// use std::collections::BTreeMap;
887 /// let mut map = BTreeMap::new();
888 /// map.insert(1, "a");
889 /// assert_eq!(map.remove(&1), Some("a"));
890 /// assert_eq!(map.remove(&1), None);
892 #[stable(feature = "rust1", since = "1.0.0")]
893 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
898 self.remove_entry(key).map(|(_, v)| v)
901 /// Removes a key from the map, returning the stored key and value if the key
902 /// was previously in the map.
904 /// The key may be any borrowed form of the map's key type, but the ordering
905 /// on the borrowed form *must* match the ordering on the key type.
912 /// use std::collections::BTreeMap;
914 /// let mut map = BTreeMap::new();
915 /// map.insert(1, "a");
916 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
917 /// assert_eq!(map.remove_entry(&1), None);
919 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
920 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
925 let (map, dormant_map) = DormantMutRef::new(self);
926 let root_node = map.root.as_mut()?.borrow_mut();
927 match root_node.search_tree(key) {
929 Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry())
935 /// Retains only the elements specified by the predicate.
937 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
942 /// use std::collections::BTreeMap;
944 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
945 /// // Keep only the elements with even-numbered keys.
946 /// map.retain(|&k, _| k % 2 == 0);
947 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
950 #[stable(feature = "btree_retain", since = "1.53.0")]
951 pub fn retain<F>(&mut self, mut f: F)
954 F: FnMut(&K, &mut V) -> bool,
956 self.drain_filter(|k, v| !f(k, v));
959 /// Moves all elements from `other` into `Self`, leaving `other` empty.
964 /// use std::collections::BTreeMap;
966 /// let mut a = BTreeMap::new();
967 /// a.insert(1, "a");
968 /// a.insert(2, "b");
969 /// a.insert(3, "c");
971 /// let mut b = BTreeMap::new();
972 /// b.insert(3, "d");
973 /// b.insert(4, "e");
974 /// b.insert(5, "f");
976 /// a.append(&mut b);
978 /// assert_eq!(a.len(), 5);
979 /// assert_eq!(b.len(), 0);
981 /// assert_eq!(a[&1], "a");
982 /// assert_eq!(a[&2], "b");
983 /// assert_eq!(a[&3], "d");
984 /// assert_eq!(a[&4], "e");
985 /// assert_eq!(a[&5], "f");
987 #[stable(feature = "btree_append", since = "1.11.0")]
988 pub fn append(&mut self, other: &mut Self)
992 // Do we have to append anything at all?
993 if other.is_empty() {
997 // We can just swap `self` and `other` if `self` is empty.
999 mem::swap(self, other);
1003 let self_iter = mem::take(self).into_iter();
1004 let other_iter = mem::take(other).into_iter();
1005 let root = BTreeMap::ensure_is_owned(&mut self.root);
1006 root.append_from_sorted_iters(self_iter, other_iter, &mut self.length)
1009 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1010 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1011 /// yield elements from min (inclusive) to max (exclusive).
1012 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1013 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1014 /// range from 4 to 10.
1018 /// Panics if range `start > end`.
1019 /// Panics if range `start == end` and both bounds are `Excluded`.
1026 /// use std::collections::BTreeMap;
1027 /// use std::ops::Bound::Included;
1029 /// let mut map = BTreeMap::new();
1030 /// map.insert(3, "a");
1031 /// map.insert(5, "b");
1032 /// map.insert(8, "c");
1033 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1034 /// println!("{}: {}", key, value);
1036 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1038 #[stable(feature = "btree_range", since = "1.17.0")]
1039 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1045 if let Some(root) = &self.root {
1046 Range { inner: root.reborrow().range_search(range) }
1048 Range { inner: LeafRange::none() }
1052 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1053 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1054 /// yield elements from min (inclusive) to max (exclusive).
1055 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1056 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1057 /// range from 4 to 10.
1061 /// Panics if range `start > end`.
1062 /// Panics if range `start == end` and both bounds are `Excluded`.
1069 /// use std::collections::BTreeMap;
1071 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1073 /// .map(|&s| (s, 0))
1075 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1076 /// *balance += 100;
1078 /// for (name, balance) in &map {
1079 /// println!("{} => {}", name, balance);
1082 #[stable(feature = "btree_range", since = "1.17.0")]
1083 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1089 if let Some(root) = &mut self.root {
1090 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1092 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1096 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1103 /// use std::collections::BTreeMap;
1105 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1107 /// // count the number of occurrences of letters in the vec
1108 /// for x in vec!["a", "b", "a", "c", "a", "b"] {
1109 /// *count.entry(x).or_insert(0) += 1;
1112 /// assert_eq!(count["a"], 3);
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
1119 // FIXME(@porglezomp) Avoid allocating if we don't insert
1120 let (map, dormant_map) = DormantMutRef::new(self);
1121 let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut();
1122 match root_node.search_tree(&key) {
1123 Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }),
1125 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData })
1130 /// Splits the collection into two at the given key. Returns everything after the given key,
1131 /// including the key.
1138 /// use std::collections::BTreeMap;
1140 /// let mut a = BTreeMap::new();
1141 /// a.insert(1, "a");
1142 /// a.insert(2, "b");
1143 /// a.insert(3, "c");
1144 /// a.insert(17, "d");
1145 /// a.insert(41, "e");
1147 /// let b = a.split_off(&3);
1149 /// assert_eq!(a.len(), 2);
1150 /// assert_eq!(b.len(), 3);
1152 /// assert_eq!(a[&1], "a");
1153 /// assert_eq!(a[&2], "b");
1155 /// assert_eq!(b[&3], "c");
1156 /// assert_eq!(b[&17], "d");
1157 /// assert_eq!(b[&41], "e");
1159 #[stable(feature = "btree_split_off", since = "1.11.0")]
1160 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1164 if self.is_empty() {
1168 let total_num = self.len();
1169 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1171 let right_root = left_root.split_off(key);
1173 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1174 self.length = new_left_len;
1176 BTreeMap { root: Some(right_root), length: right_len }
1179 /// Creates an iterator that visits all elements (key-value pairs) in
1180 /// ascending key order and uses a closure to determine if an element should
1181 /// be removed. If the closure returns `true`, the element is removed from
1182 /// the map and yielded. If the closure returns `false`, or panics, the
1183 /// element remains in the map and will not be yielded.
1185 /// The iterator also lets you mutate the value of each element in the
1186 /// closure, regardless of whether you choose to keep or remove it.
1188 /// If the iterator is only partially consumed or not consumed at all, each
1189 /// of the remaining elements is still subjected to the closure, which may
1190 /// change its value and, by returning `true`, have the element removed and
1193 /// It is unspecified how many more elements will be subjected to the
1194 /// closure if a panic occurs in the closure, or a panic occurs while
1195 /// dropping an element, or if the `DrainFilter` value is leaked.
1199 /// Splitting a map into even and odd keys, reusing the original map:
1202 /// #![feature(btree_drain_filter)]
1203 /// use std::collections::BTreeMap;
1205 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1206 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1208 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1209 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1211 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1212 pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>
1215 F: FnMut(&K, &mut V) -> bool,
1217 DrainFilter { pred, inner: self.drain_filter_inner() }
1220 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V>
1224 if let Some(root) = self.root.as_mut() {
1225 let (root, dormant_root) = DormantMutRef::new(root);
1226 let front = root.borrow_mut().first_leaf_edge();
1228 length: &mut self.length,
1229 dormant_root: Some(dormant_root),
1230 cur_leaf_edge: Some(front),
1233 DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1237 /// Creates a consuming iterator visiting all the keys, in sorted order.
1238 /// The map cannot be used after calling this.
1239 /// The iterator element type is `K`.
1244 /// use std::collections::BTreeMap;
1246 /// let mut a = BTreeMap::new();
1247 /// a.insert(2, "b");
1248 /// a.insert(1, "a");
1250 /// let keys: Vec<i32> = a.into_keys().collect();
1251 /// assert_eq!(keys, [1, 2]);
1254 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1255 pub fn into_keys(self) -> IntoKeys<K, V> {
1256 IntoKeys { inner: self.into_iter() }
1259 /// Creates a consuming iterator visiting all the values, in order by key.
1260 /// The map cannot be used after calling this.
1261 /// The iterator element type is `V`.
1266 /// use std::collections::BTreeMap;
1268 /// let mut a = BTreeMap::new();
1269 /// a.insert(1, "hello");
1270 /// a.insert(2, "goodbye");
1272 /// let values: Vec<&str> = a.into_values().collect();
1273 /// assert_eq!(values, ["hello", "goodbye"]);
1276 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1277 pub fn into_values(self) -> IntoValues<K, V> {
1278 IntoValues { inner: self.into_iter() }
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
1284 type Item = (&'a K, &'a V);
1285 type IntoIter = Iter<'a, K, V>;
1287 fn into_iter(self) -> Iter<'a, K, V> {
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1294 type Item = (&'a K, &'a V);
1296 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1297 if self.length == 0 {
1301 Some(unsafe { self.range.inner.next_unchecked() })
1305 fn size_hint(&self) -> (usize, Option<usize>) {
1306 (self.length, Some(self.length))
1309 fn last(mut self) -> Option<(&'a K, &'a V)> {
1313 fn min(mut self) -> Option<(&'a K, &'a V)> {
1317 fn max(mut self) -> Option<(&'a K, &'a V)> {
1322 #[stable(feature = "fused", since = "1.26.0")]
1323 impl<K, V> FusedIterator for Iter<'_, K, V> {}
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1327 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1328 if self.length == 0 {
1332 Some(unsafe { self.range.inner.next_back_unchecked() })
1337 #[stable(feature = "rust1", since = "1.0.0")]
1338 impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1339 fn len(&self) -> usize {
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl<K, V> Clone for Iter<'_, K, V> {
1346 fn clone(&self) -> Self {
1347 Iter { range: self.range.clone(), length: self.length }
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
1353 type Item = (&'a K, &'a mut V);
1354 type IntoIter = IterMut<'a, K, V>;
1356 fn into_iter(self) -> IterMut<'a, K, V> {
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
1363 type Item = (&'a K, &'a mut V);
1365 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1366 if self.length == 0 {
1370 Some(unsafe { self.range.inner.next_unchecked() })
1374 fn size_hint(&self) -> (usize, Option<usize>) {
1375 (self.length, Some(self.length))
1378 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1382 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1386 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<'a, K: 'a, V: 'a> DoubleEndedIterator for IterMut<'a, K, V> {
1393 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1394 if self.length == 0 {
1398 Some(unsafe { self.range.inner.next_back_unchecked() })
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1405 fn len(&self) -> usize {
1410 #[stable(feature = "fused", since = "1.26.0")]
1411 impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1413 impl<'a, K, V> IterMut<'a, K, V> {
1414 /// Returns an iterator of references over the remaining items.
1416 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1417 Iter { range: self.range.iter(), length: self.length }
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 impl<K, V> IntoIterator for BTreeMap<K, V> {
1424 type IntoIter = IntoIter<K, V>;
1426 fn into_iter(self) -> IntoIter<K, V> {
1427 let mut me = ManuallyDrop::new(self);
1428 if let Some(root) = me.root.take() {
1429 let full_range = root.into_dying().full_range();
1431 IntoIter { range: full_range, length: me.length }
1433 IntoIter { range: LeafRange::none(), length: 0 }
1438 impl<K, V> Drop for Dropper<K, V> {
1439 fn drop(&mut self) {
1440 // Similar to advancing a non-fusing iterator.
1441 fn next_or_end<K, V>(
1442 this: &mut Dropper<K, V>,
1443 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>>
1445 if this.remaining_length == 0 {
1446 unsafe { ptr::read(&this.front).deallocating_end() }
1449 this.remaining_length -= 1;
1450 Some(unsafe { this.front.deallocating_next_unchecked() })
1454 struct DropGuard<'a, K, V>(&'a mut Dropper<K, V>);
1456 impl<'a, K, V> Drop for DropGuard<'a, K, V> {
1457 fn drop(&mut self) {
1458 // Continue the same loop we perform below. This only runs when unwinding, so we
1459 // don't have to care about panics this time (they'll abort).
1460 while let Some(kv) = next_or_end(&mut self.0) {
1466 while let Some(kv) = next_or_end(self) {
1467 let guard = DropGuard(self);
1474 #[stable(feature = "btree_drop", since = "1.7.0")]
1475 impl<K, V> Drop for IntoIter<K, V> {
1476 fn drop(&mut self) {
1477 if let Some(front) = self.range.take_front() {
1478 Dropper { front, remaining_length: self.length };
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<K, V> Iterator for IntoIter<K, V> {
1487 fn next(&mut self) -> Option<(K, V)> {
1488 if self.length == 0 {
1492 let kv = unsafe { self.range.deallocating_next_unchecked() };
1493 Some(kv.into_key_val())
1497 fn size_hint(&self) -> (usize, Option<usize>) {
1498 (self.length, Some(self.length))
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1504 fn next_back(&mut self) -> Option<(K, V)> {
1505 if self.length == 0 {
1509 let kv = unsafe { self.range.deallocating_next_back_unchecked() };
1510 Some(kv.into_key_val())
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1517 fn len(&self) -> usize {
1522 #[stable(feature = "fused", since = "1.26.0")]
1523 impl<K, V> FusedIterator for IntoIter<K, V> {}
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 impl<'a, K, V> Iterator for Keys<'a, K, V> {
1529 fn next(&mut self) -> Option<&'a K> {
1530 self.inner.next().map(|(k, _)| k)
1533 fn size_hint(&self) -> (usize, Option<usize>) {
1534 self.inner.size_hint()
1537 fn last(mut self) -> Option<&'a K> {
1541 fn min(mut self) -> Option<&'a K> {
1545 fn max(mut self) -> Option<&'a K> {
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1552 fn next_back(&mut self) -> Option<&'a K> {
1553 self.inner.next_back().map(|(k, _)| k)
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1559 fn len(&self) -> usize {
1564 #[stable(feature = "fused", since = "1.26.0")]
1565 impl<K, V> FusedIterator for Keys<'_, K, V> {}
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl<K, V> Clone for Keys<'_, K, V> {
1569 fn clone(&self) -> Self {
1570 Keys { inner: self.inner.clone() }
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 impl<'a, K, V> Iterator for Values<'a, K, V> {
1578 fn next(&mut self) -> Option<&'a V> {
1579 self.inner.next().map(|(_, v)| v)
1582 fn size_hint(&self) -> (usize, Option<usize>) {
1583 self.inner.size_hint()
1586 fn last(mut self) -> Option<&'a V> {
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1593 fn next_back(&mut self) -> Option<&'a V> {
1594 self.inner.next_back().map(|(_, v)| v)
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1600 fn len(&self) -> usize {
1605 #[stable(feature = "fused", since = "1.26.0")]
1606 impl<K, V> FusedIterator for Values<'_, K, V> {}
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl<K, V> Clone for Values<'_, K, V> {
1610 fn clone(&self) -> Self {
1611 Values { inner: self.inner.clone() }
1615 /// An iterator produced by calling `drain_filter` on BTreeMap.
1616 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1617 pub struct DrainFilter<'a, K, V, F>
1621 F: 'a + FnMut(&K, &mut V) -> bool,
1624 inner: DrainFilterInner<'a, K, V>,
1626 /// Most of the implementation of DrainFilter are generic over the type
1627 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1628 pub(super) struct DrainFilterInner<'a, K: 'a, V: 'a> {
1629 /// Reference to the length field in the borrowed map, updated live.
1630 length: &'a mut usize,
1631 /// Buried reference to the root field in the borrowed map.
1632 /// Wrapped in `Option` to allow drop handler to `take` it.
1633 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1634 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1635 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1636 /// or if a panic occurred in the predicate.
1637 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1640 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1641 impl<K, V, F> Drop for DrainFilter<'_, K, V, F>
1643 F: FnMut(&K, &mut V) -> bool,
1645 fn drop(&mut self) {
1646 self.for_each(drop);
1650 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1651 impl<K, V, F> fmt::Debug for DrainFilter<'_, K, V, F>
1655 F: FnMut(&K, &mut V) -> bool,
1657 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1658 f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish()
1662 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1663 impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
1665 F: FnMut(&K, &mut V) -> bool,
1669 fn next(&mut self) -> Option<(K, V)> {
1670 self.inner.next(&mut self.pred)
1673 fn size_hint(&self) -> (usize, Option<usize>) {
1674 self.inner.size_hint()
1678 impl<'a, K: 'a, V: 'a> DrainFilterInner<'a, K, V> {
1679 /// Allow Debug implementations to predict the next element.
1680 pub(super) fn peek(&self) -> Option<(&K, &V)> {
1681 let edge = self.cur_leaf_edge.as_ref()?;
1682 edge.reborrow().next_kv().ok().map(Handle::into_kv)
1685 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1686 pub(super) fn next<F>(&mut self, pred: &mut F) -> Option<(K, V)>
1688 F: FnMut(&K, &mut V) -> bool,
1690 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
1691 let (k, v) = kv.kv_mut();
1694 let (kv, pos) = kv.remove_kv_tracking(|| {
1695 // SAFETY: we will touch the root in a way that will not
1696 // invalidate the position returned.
1697 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
1698 root.pop_internal_level();
1699 self.dormant_root = Some(DormantMutRef::new(root).1);
1701 self.cur_leaf_edge = Some(pos);
1704 self.cur_leaf_edge = Some(kv.next_leaf_edge());
1709 /// Implementation of a typical `DrainFilter::size_hint` method.
1710 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
1711 // In most of the btree iterators, `self.length` is the number of elements
1712 // yet to be visited. Here, it includes elements that were visited and that
1713 // the predicate decided not to drain. Making this upper bound more accurate
1714 // requires maintaining an extra field and is not worth while.
1715 (0, Some(*self.length))
1719 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1720 impl<K, V, F> FusedIterator for DrainFilter<'_, K, V, F> where F: FnMut(&K, &mut V) -> bool {}
1722 #[stable(feature = "btree_range", since = "1.17.0")]
1723 impl<'a, K, V> Iterator for Range<'a, K, V> {
1724 type Item = (&'a K, &'a V);
1726 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1727 self.inner.next_checked()
1730 fn last(mut self) -> Option<(&'a K, &'a V)> {
1734 fn min(mut self) -> Option<(&'a K, &'a V)> {
1738 fn max(mut self) -> Option<(&'a K, &'a V)> {
1743 #[stable(feature = "map_values_mut", since = "1.10.0")]
1744 impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1745 type Item = &'a mut V;
1747 fn next(&mut self) -> Option<&'a mut V> {
1748 self.inner.next().map(|(_, v)| v)
1751 fn size_hint(&self) -> (usize, Option<usize>) {
1752 self.inner.size_hint()
1755 fn last(mut self) -> Option<&'a mut V> {
1760 #[stable(feature = "map_values_mut", since = "1.10.0")]
1761 impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1762 fn next_back(&mut self) -> Option<&'a mut V> {
1763 self.inner.next_back().map(|(_, v)| v)
1767 #[stable(feature = "map_values_mut", since = "1.10.0")]
1768 impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
1769 fn len(&self) -> usize {
1774 #[stable(feature = "fused", since = "1.26.0")]
1775 impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
1777 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1778 impl<K, V> Iterator for IntoKeys<K, V> {
1781 fn next(&mut self) -> Option<K> {
1782 self.inner.next().map(|(k, _)| k)
1785 fn size_hint(&self) -> (usize, Option<usize>) {
1786 self.inner.size_hint()
1789 fn last(mut self) -> Option<K> {
1793 fn min(mut self) -> Option<K> {
1797 fn max(mut self) -> Option<K> {
1802 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1803 impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
1804 fn next_back(&mut self) -> Option<K> {
1805 self.inner.next_back().map(|(k, _)| k)
1809 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1810 impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
1811 fn len(&self) -> usize {
1816 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1817 impl<K, V> FusedIterator for IntoKeys<K, V> {}
1819 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1820 impl<K, V> Iterator for IntoValues<K, V> {
1823 fn next(&mut self) -> Option<V> {
1824 self.inner.next().map(|(_, v)| v)
1827 fn size_hint(&self) -> (usize, Option<usize>) {
1828 self.inner.size_hint()
1831 fn last(mut self) -> Option<V> {
1836 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1837 impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
1838 fn next_back(&mut self) -> Option<V> {
1839 self.inner.next_back().map(|(_, v)| v)
1843 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1844 impl<K, V> ExactSizeIterator for IntoValues<K, V> {
1845 fn len(&self) -> usize {
1850 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1851 impl<K, V> FusedIterator for IntoValues<K, V> {}
1853 #[stable(feature = "btree_range", since = "1.17.0")]
1854 impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1855 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1856 self.inner.next_back_checked()
1860 #[stable(feature = "fused", since = "1.26.0")]
1861 impl<K, V> FusedIterator for Range<'_, K, V> {}
1863 #[stable(feature = "btree_range", since = "1.17.0")]
1864 impl<K, V> Clone for Range<'_, K, V> {
1865 fn clone(&self) -> Self {
1866 Range { inner: self.inner.clone() }
1870 #[stable(feature = "btree_range", since = "1.17.0")]
1871 impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1872 type Item = (&'a K, &'a mut V);
1874 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1875 self.inner.next_checked()
1878 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1882 fn min(mut self) -> Option<(&'a K, &'a mut V)> {
1886 fn max(mut self) -> Option<(&'a K, &'a mut V)> {
1891 impl<'a, K, V> RangeMut<'a, K, V> {
1892 /// Returns an iterator of references over the remaining items.
1894 pub(super) fn iter(&self) -> Range<'_, K, V> {
1895 Range { inner: self.inner.reborrow() }
1899 #[stable(feature = "btree_range", since = "1.17.0")]
1900 impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1901 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1902 self.inner.next_back_checked()
1906 #[stable(feature = "fused", since = "1.26.0")]
1907 impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
1911 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
1912 let mut map = BTreeMap::new();
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
1921 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1922 iter.into_iter().for_each(move |(k, v)| {
1928 fn extend_one(&mut self, (k, v): (K, V)) {
1933 #[stable(feature = "extend_ref", since = "1.2.0")]
1934 impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
1935 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1936 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1940 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
1947 fn hash<H: Hasher>(&self, state: &mut H) {
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<K: Ord, V> Default for BTreeMap<K, V> {
1956 /// Creates an empty `BTreeMap`.
1957 fn default() -> BTreeMap<K, V> {
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
1964 fn eq(&self, other: &BTreeMap<K, V>) -> bool {
1965 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
1975 fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
1976 self.iter().partial_cmp(other.iter())
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
1983 fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
1984 self.iter().cmp(other.iter())
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
1990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1991 f.debug_map().entries(self.iter()).finish()
1995 #[stable(feature = "rust1", since = "1.0.0")]
1996 impl<K, Q: ?Sized, V> Index<&Q> for BTreeMap<K, V>
2003 /// Returns a reference to the value corresponding to the supplied key.
2007 /// Panics if the key is not present in the `BTreeMap`.
2009 fn index(&self, key: &Q) -> &V {
2010 self.get(key).expect("no entry found for key")
2014 impl<K, V> BTreeMap<K, V> {
2015 /// Gets an iterator over the entries of the map, sorted by key.
2022 /// use std::collections::BTreeMap;
2024 /// let mut map = BTreeMap::new();
2025 /// map.insert(3, "c");
2026 /// map.insert(2, "b");
2027 /// map.insert(1, "a");
2029 /// for (key, value) in map.iter() {
2030 /// println!("{}: {}", key, value);
2033 /// let (first_key, first_value) = map.iter().next().unwrap();
2034 /// assert_eq!((*first_key, *first_value), (1, "a"));
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 pub fn iter(&self) -> Iter<'_, K, V> {
2038 if let Some(root) = &self.root {
2039 let full_range = root.reborrow().full_range();
2041 Iter { range: Range { inner: full_range }, length: self.length }
2043 Iter { range: Range { inner: LeafRange::none() }, length: 0 }
2047 /// Gets a mutable iterator over the entries of the map, sorted by key.
2054 /// use std::collections::BTreeMap;
2056 /// let mut map = BTreeMap::new();
2057 /// map.insert("a", 1);
2058 /// map.insert("b", 2);
2059 /// map.insert("c", 3);
2061 /// // add 10 to the value if the key isn't "a"
2062 /// for (key, value) in map.iter_mut() {
2063 /// if key != &"a" {
2068 #[stable(feature = "rust1", since = "1.0.0")]
2069 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2070 if let Some(root) = &mut self.root {
2071 let full_range = root.borrow_valmut().full_range();
2074 range: RangeMut { inner: full_range, _marker: PhantomData },
2075 length: self.length,
2079 range: RangeMut { inner: LeafRange::none(), _marker: PhantomData },
2085 /// Gets an iterator over the keys of the map, in sorted order.
2092 /// use std::collections::BTreeMap;
2094 /// let mut a = BTreeMap::new();
2095 /// a.insert(2, "b");
2096 /// a.insert(1, "a");
2098 /// let keys: Vec<_> = a.keys().cloned().collect();
2099 /// assert_eq!(keys, [1, 2]);
2101 #[stable(feature = "rust1", since = "1.0.0")]
2102 pub fn keys(&self) -> Keys<'_, K, V> {
2103 Keys { inner: self.iter() }
2106 /// Gets an iterator over the values of the map, in order by key.
2113 /// use std::collections::BTreeMap;
2115 /// let mut a = BTreeMap::new();
2116 /// a.insert(1, "hello");
2117 /// a.insert(2, "goodbye");
2119 /// let values: Vec<&str> = a.values().cloned().collect();
2120 /// assert_eq!(values, ["hello", "goodbye"]);
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 pub fn values(&self) -> Values<'_, K, V> {
2124 Values { inner: self.iter() }
2127 /// Gets a mutable iterator over the values of the map, in order by key.
2134 /// use std::collections::BTreeMap;
2136 /// let mut a = BTreeMap::new();
2137 /// a.insert(1, String::from("hello"));
2138 /// a.insert(2, String::from("goodbye"));
2140 /// for value in a.values_mut() {
2141 /// value.push_str("!");
2144 /// let values: Vec<String> = a.values().cloned().collect();
2145 /// assert_eq!(values, [String::from("hello!"),
2146 /// String::from("goodbye!")]);
2148 #[stable(feature = "map_values_mut", since = "1.10.0")]
2149 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2150 ValuesMut { inner: self.iter_mut() }
2153 /// Returns the number of elements in the map.
2160 /// use std::collections::BTreeMap;
2162 /// let mut a = BTreeMap::new();
2163 /// assert_eq!(a.len(), 0);
2164 /// a.insert(1, "a");
2165 /// assert_eq!(a.len(), 1);
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2169 pub const fn len(&self) -> usize {
2173 /// Returns `true` if the map contains no elements.
2180 /// use std::collections::BTreeMap;
2182 /// let mut a = BTreeMap::new();
2183 /// assert!(a.is_empty());
2184 /// a.insert(1, "a");
2185 /// assert!(!a.is_empty());
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2189 pub const fn is_empty(&self) -> bool {
2193 /// If the root node is the empty (non-allocated) root node, allocate our
2194 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2195 fn ensure_is_owned(root: &mut Option<Root<K, V>>) -> &mut Root<K, V> {
2196 root.get_or_insert_with(Root::new)