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`.
938 /// The elements are visited in ascending key order.
943 /// use std::collections::BTreeMap;
945 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
946 /// // Keep only the elements with even-numbered keys.
947 /// map.retain(|&k, _| k % 2 == 0);
948 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
951 #[stable(feature = "btree_retain", since = "1.53.0")]
952 pub fn retain
<F
>(&mut self, mut f
: F
)
955 F
: FnMut(&K
, &mut V
) -> bool
,
957 self.drain_filter(|k
, v
| !f(k
, v
));
960 /// Moves all elements from `other` into `Self`, leaving `other` empty.
965 /// use std::collections::BTreeMap;
967 /// let mut a = BTreeMap::new();
968 /// a.insert(1, "a");
969 /// a.insert(2, "b");
970 /// a.insert(3, "c");
972 /// let mut b = BTreeMap::new();
973 /// b.insert(3, "d");
974 /// b.insert(4, "e");
975 /// b.insert(5, "f");
977 /// a.append(&mut b);
979 /// assert_eq!(a.len(), 5);
980 /// assert_eq!(b.len(), 0);
982 /// assert_eq!(a[&1], "a");
983 /// assert_eq!(a[&2], "b");
984 /// assert_eq!(a[&3], "d");
985 /// assert_eq!(a[&4], "e");
986 /// assert_eq!(a[&5], "f");
988 #[stable(feature = "btree_append", since = "1.11.0")]
989 pub fn append(&mut self, other
: &mut Self)
993 // Do we have to append anything at all?
994 if other
.is_empty() {
998 // We can just swap `self` and `other` if `self` is empty.
1000 mem
::swap(self, other
);
1004 let self_iter
= mem
::take(self).into_iter();
1005 let other_iter
= mem
::take(other
).into_iter();
1006 let root
= BTreeMap
::ensure_is_owned(&mut self.root
);
1007 root
.append_from_sorted_iters(self_iter
, other_iter
, &mut self.length
)
1010 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1011 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1012 /// yield elements from min (inclusive) to max (exclusive).
1013 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1014 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1015 /// range from 4 to 10.
1019 /// Panics if range `start > end`.
1020 /// Panics if range `start == end` and both bounds are `Excluded`.
1027 /// use std::collections::BTreeMap;
1028 /// use std::ops::Bound::Included;
1030 /// let mut map = BTreeMap::new();
1031 /// map.insert(3, "a");
1032 /// map.insert(5, "b");
1033 /// map.insert(8, "c");
1034 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1035 /// println!("{}: {}", key, value);
1037 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1039 #[stable(feature = "btree_range", since = "1.17.0")]
1040 pub fn range
<T
: ?Sized
, R
>(&self, range
: R
) -> Range
<'_
, K
, V
>
1046 if let Some(root
) = &self.root
{
1047 Range { inner: root.reborrow().range_search(range) }
1049 Range { inner: LeafRange::none() }
1053 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1054 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1055 /// yield elements from min (inclusive) to max (exclusive).
1056 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1057 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1058 /// range from 4 to 10.
1062 /// Panics if range `start > end`.
1063 /// Panics if range `start == end` and both bounds are `Excluded`.
1070 /// use std::collections::BTreeMap;
1072 /// let mut map: BTreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"]
1074 /// .map(|&s| (s, 0))
1076 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1077 /// *balance += 100;
1079 /// for (name, balance) in &map {
1080 /// println!("{} => {}", name, balance);
1083 #[stable(feature = "btree_range", since = "1.17.0")]
1084 pub fn range_mut
<T
: ?Sized
, R
>(&mut self, range
: R
) -> RangeMut
<'_
, K
, V
>
1090 if let Some(root
) = &mut self.root
{
1091 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1093 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1097 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1104 /// use std::collections::BTreeMap;
1106 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1108 /// // count the number of occurrences of letters in the vec
1109 /// for x in vec!["a", "b", "a", "c", "a", "b"] {
1110 /// *count.entry(x).or_insert(0) += 1;
1113 /// assert_eq!(count["a"], 3);
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 pub fn entry(&mut self, key
: K
) -> Entry
<'_
, K
, V
>
1120 // FIXME(@porglezomp) Avoid allocating if we don't insert
1121 let (map
, dormant_map
) = DormantMutRef
::new(self);
1122 let root_node
= Self::ensure_is_owned(&mut map
.root
).borrow_mut();
1123 match root_node
.search_tree(&key
) {
1124 Found(handle
) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }
),
1126 Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }
)
1131 /// Splits the collection into two at the given key. Returns everything after the given key,
1132 /// including the key.
1139 /// use std::collections::BTreeMap;
1141 /// let mut a = BTreeMap::new();
1142 /// a.insert(1, "a");
1143 /// a.insert(2, "b");
1144 /// a.insert(3, "c");
1145 /// a.insert(17, "d");
1146 /// a.insert(41, "e");
1148 /// let b = a.split_off(&3);
1150 /// assert_eq!(a.len(), 2);
1151 /// assert_eq!(b.len(), 3);
1153 /// assert_eq!(a[&1], "a");
1154 /// assert_eq!(a[&2], "b");
1156 /// assert_eq!(b[&3], "c");
1157 /// assert_eq!(b[&17], "d");
1158 /// assert_eq!(b[&41], "e");
1160 #[stable(feature = "btree_split_off", since = "1.11.0")]
1161 pub fn split_off
<Q
: ?Sized
+ Ord
>(&mut self, key
: &Q
) -> Self
1165 if self.is_empty() {
1169 let total_num
= self.len();
1170 let left_root
= self.root
.as_mut().unwrap(); // unwrap succeeds because not empty
1172 let right_root
= left_root
.split_off(key
);
1174 let (new_left_len
, right_len
) = Root
::calc_split_length(total_num
, &left_root
, &right_root
);
1175 self.length
= new_left_len
;
1177 BTreeMap { root: Some(right_root), length: right_len }
1180 /// Creates an iterator that visits all elements (key-value pairs) in
1181 /// ascending key order and uses a closure to determine if an element should
1182 /// be removed. If the closure returns `true`, the element is removed from
1183 /// the map and yielded. If the closure returns `false`, or panics, the
1184 /// element remains in the map and will not be yielded.
1186 /// The iterator also lets you mutate the value of each element in the
1187 /// closure, regardless of whether you choose to keep or remove it.
1189 /// If the iterator is only partially consumed or not consumed at all, each
1190 /// of the remaining elements is still subjected to the closure, which may
1191 /// change its value and, by returning `true`, have the element removed and
1194 /// It is unspecified how many more elements will be subjected to the
1195 /// closure if a panic occurs in the closure, or a panic occurs while
1196 /// dropping an element, or if the `DrainFilter` value is leaked.
1200 /// Splitting a map into even and odd keys, reusing the original map:
1203 /// #![feature(btree_drain_filter)]
1204 /// use std::collections::BTreeMap;
1206 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1207 /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect();
1209 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), vec![0, 2, 4, 6]);
1210 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), vec![1, 3, 5, 7]);
1212 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1213 pub fn drain_filter
<F
>(&mut self, pred
: F
) -> DrainFilter
<'_
, K
, V
, F
>
1216 F
: FnMut(&K
, &mut V
) -> bool
,
1218 DrainFilter { pred, inner: self.drain_filter_inner() }
1221 pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner
<'_
, K
, V
>
1225 if let Some(root
) = self.root
.as_mut() {
1226 let (root
, dormant_root
) = DormantMutRef
::new(root
);
1227 let front
= root
.borrow_mut().first_leaf_edge();
1229 length
: &mut self.length
,
1230 dormant_root
: Some(dormant_root
),
1231 cur_leaf_edge
: Some(front
),
1234 DrainFilterInner { length: &mut self.length, dormant_root: None, cur_leaf_edge: None }
1238 /// Creates a consuming iterator visiting all the keys, in sorted order.
1239 /// The map cannot be used after calling this.
1240 /// The iterator element type is `K`.
1245 /// use std::collections::BTreeMap;
1247 /// let mut a = BTreeMap::new();
1248 /// a.insert(2, "b");
1249 /// a.insert(1, "a");
1251 /// let keys: Vec<i32> = a.into_keys().collect();
1252 /// assert_eq!(keys, [1, 2]);
1255 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1256 pub fn into_keys(self) -> IntoKeys
<K
, V
> {
1257 IntoKeys { inner: self.into_iter() }
1260 /// Creates a consuming iterator visiting all the values, in order by key.
1261 /// The map cannot be used after calling this.
1262 /// The iterator element type is `V`.
1267 /// use std::collections::BTreeMap;
1269 /// let mut a = BTreeMap::new();
1270 /// a.insert(1, "hello");
1271 /// a.insert(2, "goodbye");
1273 /// let values: Vec<&str> = a.into_values().collect();
1274 /// assert_eq!(values, ["hello", "goodbye"]);
1277 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1278 pub fn into_values(self) -> IntoValues
<K
, V
> {
1279 IntoValues { inner: self.into_iter() }
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 impl<'a
, K
, V
> IntoIterator
for &'a BTreeMap
<K
, V
> {
1285 type Item
= (&'a K
, &'a V
);
1286 type IntoIter
= Iter
<'a
, K
, V
>;
1288 fn into_iter(self) -> Iter
<'a
, K
, V
> {
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<'a
, K
: 'a
, V
: 'a
> Iterator
for Iter
<'a
, K
, V
> {
1295 type Item
= (&'a K
, &'a V
);
1297 fn next(&mut self) -> Option
<(&'a K
, &'a V
)> {
1298 if self.length
== 0 {
1302 Some(unsafe { self.range.inner.next_unchecked() }
)
1306 fn size_hint(&self) -> (usize, Option
<usize>) {
1307 (self.length
, Some(self.length
))
1310 fn last(mut self) -> Option
<(&'a K
, &'a V
)> {
1314 fn min(mut self) -> Option
<(&'a K
, &'a V
)> {
1318 fn max(mut self) -> Option
<(&'a K
, &'a V
)> {
1323 #[stable(feature = "fused", since = "1.26.0")]
1324 impl<K
, V
> FusedIterator
for Iter
<'_
, K
, V
> {}
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<'a
, K
: 'a
, V
: 'a
> DoubleEndedIterator
for Iter
<'a
, K
, V
> {
1328 fn next_back(&mut self) -> Option
<(&'a K
, &'a V
)> {
1329 if self.length
== 0 {
1333 Some(unsafe { self.range.inner.next_back_unchecked() }
)
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 impl<K
, V
> ExactSizeIterator
for Iter
<'_
, K
, V
> {
1340 fn len(&self) -> usize {
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 impl<K
, V
> Clone
for Iter
<'_
, K
, V
> {
1347 fn clone(&self) -> Self {
1348 Iter { range: self.range.clone(), length: self.length }
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl<'a
, K
, V
> IntoIterator
for &'a
mut BTreeMap
<K
, V
> {
1354 type Item
= (&'a K
, &'a
mut V
);
1355 type IntoIter
= IterMut
<'a
, K
, V
>;
1357 fn into_iter(self) -> IterMut
<'a
, K
, V
> {
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 impl<'a
, K
: 'a
, V
: 'a
> Iterator
for IterMut
<'a
, K
, V
> {
1364 type Item
= (&'a K
, &'a
mut V
);
1366 fn next(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1367 if self.length
== 0 {
1371 Some(unsafe { self.range.inner.next_unchecked() }
)
1375 fn size_hint(&self) -> (usize, Option
<usize>) {
1376 (self.length
, Some(self.length
))
1379 fn last(mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1383 fn min(mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1387 fn max(mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<'a
, K
: 'a
, V
: 'a
> DoubleEndedIterator
for IterMut
<'a
, K
, V
> {
1394 fn next_back(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1395 if self.length
== 0 {
1399 Some(unsafe { self.range.inner.next_back_unchecked() }
)
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 impl<K
, V
> ExactSizeIterator
for IterMut
<'_
, K
, V
> {
1406 fn len(&self) -> usize {
1411 #[stable(feature = "fused", since = "1.26.0")]
1412 impl<K
, V
> FusedIterator
for IterMut
<'_
, K
, V
> {}
1414 impl<'a
, K
, V
> IterMut
<'a
, K
, V
> {
1415 /// Returns an iterator of references over the remaining items.
1417 pub(super) fn iter(&self) -> Iter
<'_
, K
, V
> {
1418 Iter { range: self.range.iter(), length: self.length }
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 impl<K
, V
> IntoIterator
for BTreeMap
<K
, V
> {
1425 type IntoIter
= IntoIter
<K
, V
>;
1427 fn into_iter(self) -> IntoIter
<K
, V
> {
1428 let mut me
= ManuallyDrop
::new(self);
1429 if let Some(root
) = me
.root
.take() {
1430 let full_range
= root
.into_dying().full_range();
1432 IntoIter { range: full_range, length: me.length }
1434 IntoIter { range: LeafRange::none(), length: 0 }
1439 impl<K
, V
> Drop
for Dropper
<K
, V
> {
1440 fn drop(&mut self) {
1441 // Similar to advancing a non-fusing iterator.
1442 fn next_or_end
<K
, V
>(
1443 this
: &mut Dropper
<K
, V
>,
1444 ) -> Option
<Handle
<NodeRef
<marker
::Dying
, K
, V
, marker
::LeafOrInternal
>, marker
::KV
>>
1446 if this
.remaining_length
== 0 {
1447 unsafe { ptr::read(&this.front).deallocating_end() }
1450 this
.remaining_length
-= 1;
1451 Some(unsafe { this.front.deallocating_next_unchecked() }
)
1455 struct DropGuard
<'a
, K
, V
>(&'a
mut Dropper
<K
, V
>);
1457 impl<'a
, K
, V
> Drop
for DropGuard
<'a
, K
, V
> {
1458 fn drop(&mut self) {
1459 // Continue the same loop we perform below. This only runs when unwinding, so we
1460 // don't have to care about panics this time (they'll abort).
1461 while let Some(kv
) = next_or_end(&mut self.0) {
1467 while let Some(kv
) = next_or_end(self) {
1468 let guard
= DropGuard(self);
1475 #[stable(feature = "btree_drop", since = "1.7.0")]
1476 impl<K
, V
> Drop
for IntoIter
<K
, V
> {
1477 fn drop(&mut self) {
1478 if let Some(front
) = self.range
.take_front() {
1479 Dropper { front, remaining_length: self.length }
;
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<K
, V
> Iterator
for IntoIter
<K
, V
> {
1488 fn next(&mut self) -> Option
<(K
, V
)> {
1489 if self.length
== 0 {
1493 let kv
= unsafe { self.range.deallocating_next_unchecked() }
;
1494 Some(kv
.into_key_val())
1498 fn size_hint(&self) -> (usize, Option
<usize>) {
1499 (self.length
, Some(self.length
))
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 impl<K
, V
> DoubleEndedIterator
for IntoIter
<K
, V
> {
1505 fn next_back(&mut self) -> Option
<(K
, V
)> {
1506 if self.length
== 0 {
1510 let kv
= unsafe { self.range.deallocating_next_back_unchecked() }
;
1511 Some(kv
.into_key_val())
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<K
, V
> ExactSizeIterator
for IntoIter
<K
, V
> {
1518 fn len(&self) -> usize {
1523 #[stable(feature = "fused", since = "1.26.0")]
1524 impl<K
, V
> FusedIterator
for IntoIter
<K
, V
> {}
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<'a
, K
, V
> Iterator
for Keys
<'a
, K
, V
> {
1530 fn next(&mut self) -> Option
<&'a K
> {
1531 self.inner
.next().map(|(k
, _
)| k
)
1534 fn size_hint(&self) -> (usize, Option
<usize>) {
1535 self.inner
.size_hint()
1538 fn last(mut self) -> Option
<&'a K
> {
1542 fn min(mut self) -> Option
<&'a K
> {
1546 fn max(mut self) -> Option
<&'a K
> {
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 impl<'a
, K
, V
> DoubleEndedIterator
for Keys
<'a
, K
, V
> {
1553 fn next_back(&mut self) -> Option
<&'a K
> {
1554 self.inner
.next_back().map(|(k
, _
)| k
)
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 impl<K
, V
> ExactSizeIterator
for Keys
<'_
, K
, V
> {
1560 fn len(&self) -> usize {
1565 #[stable(feature = "fused", since = "1.26.0")]
1566 impl<K
, V
> FusedIterator
for Keys
<'_
, K
, V
> {}
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<K
, V
> Clone
for Keys
<'_
, K
, V
> {
1570 fn clone(&self) -> Self {
1571 Keys { inner: self.inner.clone() }
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<'a
, K
, V
> Iterator
for Values
<'a
, K
, V
> {
1579 fn next(&mut self) -> Option
<&'a V
> {
1580 self.inner
.next().map(|(_
, v
)| v
)
1583 fn size_hint(&self) -> (usize, Option
<usize>) {
1584 self.inner
.size_hint()
1587 fn last(mut self) -> Option
<&'a V
> {
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<'a
, K
, V
> DoubleEndedIterator
for Values
<'a
, K
, V
> {
1594 fn next_back(&mut self) -> Option
<&'a V
> {
1595 self.inner
.next_back().map(|(_
, v
)| v
)
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<K
, V
> ExactSizeIterator
for Values
<'_
, K
, V
> {
1601 fn len(&self) -> usize {
1606 #[stable(feature = "fused", since = "1.26.0")]
1607 impl<K
, V
> FusedIterator
for Values
<'_
, K
, V
> {}
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 impl<K
, V
> Clone
for Values
<'_
, K
, V
> {
1611 fn clone(&self) -> Self {
1612 Values { inner: self.inner.clone() }
1616 /// An iterator produced by calling `drain_filter` on BTreeMap.
1617 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1618 pub struct DrainFilter
<'a
, K
, V
, F
>
1622 F
: 'a
+ FnMut(&K
, &mut V
) -> bool
,
1625 inner
: DrainFilterInner
<'a
, K
, V
>,
1627 /// Most of the implementation of DrainFilter are generic over the type
1628 /// of the predicate, thus also serving for BTreeSet::DrainFilter.
1629 pub(super) struct DrainFilterInner
<'a
, K
: 'a
, V
: 'a
> {
1630 /// Reference to the length field in the borrowed map, updated live.
1631 length
: &'a
mut usize,
1632 /// Buried reference to the root field in the borrowed map.
1633 /// Wrapped in `Option` to allow drop handler to `take` it.
1634 dormant_root
: Option
<DormantMutRef
<'a
, Root
<K
, V
>>>,
1635 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1636 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1637 /// or if a panic occurred in the predicate.
1638 cur_leaf_edge
: Option
<Handle
<NodeRef
<marker
::Mut
<'a
>, K
, V
, marker
::Leaf
>, marker
::Edge
>>,
1641 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1642 impl<K
, V
, F
> Drop
for DrainFilter
<'_
, K
, V
, F
>
1644 F
: FnMut(&K
, &mut V
) -> bool
,
1646 fn drop(&mut self) {
1647 self.for_each(drop
);
1651 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1652 impl<K
, V
, F
> fmt
::Debug
for DrainFilter
<'_
, K
, V
, F
>
1656 F
: FnMut(&K
, &mut V
) -> bool
,
1658 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1659 f
.debug_tuple("DrainFilter").field(&self.inner
.peek()).finish()
1663 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1664 impl<K
, V
, F
> Iterator
for DrainFilter
<'_
, K
, V
, F
>
1666 F
: FnMut(&K
, &mut V
) -> bool
,
1670 fn next(&mut self) -> Option
<(K
, V
)> {
1671 self.inner
.next(&mut self.pred
)
1674 fn size_hint(&self) -> (usize, Option
<usize>) {
1675 self.inner
.size_hint()
1679 impl<'a
, K
: 'a
, V
: 'a
> DrainFilterInner
<'a
, K
, V
> {
1680 /// Allow Debug implementations to predict the next element.
1681 pub(super) fn peek(&self) -> Option
<(&K
, &V
)> {
1682 let edge
= self.cur_leaf_edge
.as_ref()?
;
1683 edge
.reborrow().next_kv().ok().map(Handle
::into_kv
)
1686 /// Implementation of a typical `DrainFilter::next` method, given the predicate.
1687 pub(super) fn next
<F
>(&mut self, pred
: &mut F
) -> Option
<(K
, V
)>
1689 F
: FnMut(&K
, &mut V
) -> bool
,
1691 while let Ok(mut kv
) = self.cur_leaf_edge
.take()?
.next_kv() {
1692 let (k
, v
) = kv
.kv_mut();
1695 let (kv
, pos
) = kv
.remove_kv_tracking(|| {
1696 // SAFETY: we will touch the root in a way that will not
1697 // invalidate the position returned.
1698 let root
= unsafe { self.dormant_root.take().unwrap().awaken() }
;
1699 root
.pop_internal_level();
1700 self.dormant_root
= Some(DormantMutRef
::new(root
).1);
1702 self.cur_leaf_edge
= Some(pos
);
1705 self.cur_leaf_edge
= Some(kv
.next_leaf_edge());
1710 /// Implementation of a typical `DrainFilter::size_hint` method.
1711 pub(super) fn size_hint(&self) -> (usize, Option
<usize>) {
1712 // In most of the btree iterators, `self.length` is the number of elements
1713 // yet to be visited. Here, it includes elements that were visited and that
1714 // the predicate decided not to drain. Making this upper bound more accurate
1715 // requires maintaining an extra field and is not worth while.
1716 (0, Some(*self.length
))
1720 #[unstable(feature = "btree_drain_filter", issue = "70530")]
1721 impl<K
, V
, F
> FusedIterator
for DrainFilter
<'_
, K
, V
, F
> where F
: FnMut(&K
, &mut V
) -> bool {}
1723 #[stable(feature = "btree_range", since = "1.17.0")]
1724 impl<'a
, K
, V
> Iterator
for Range
<'a
, K
, V
> {
1725 type Item
= (&'a K
, &'a V
);
1727 fn next(&mut self) -> Option
<(&'a K
, &'a V
)> {
1728 self.inner
.next_checked()
1731 fn last(mut self) -> Option
<(&'a K
, &'a V
)> {
1735 fn min(mut self) -> Option
<(&'a K
, &'a V
)> {
1739 fn max(mut self) -> Option
<(&'a K
, &'a V
)> {
1744 #[stable(feature = "map_values_mut", since = "1.10.0")]
1745 impl<'a
, K
, V
> Iterator
for ValuesMut
<'a
, K
, V
> {
1746 type Item
= &'a
mut V
;
1748 fn next(&mut self) -> Option
<&'a
mut V
> {
1749 self.inner
.next().map(|(_
, v
)| v
)
1752 fn size_hint(&self) -> (usize, Option
<usize>) {
1753 self.inner
.size_hint()
1756 fn last(mut self) -> Option
<&'a
mut V
> {
1761 #[stable(feature = "map_values_mut", since = "1.10.0")]
1762 impl<'a
, K
, V
> DoubleEndedIterator
for ValuesMut
<'a
, K
, V
> {
1763 fn next_back(&mut self) -> Option
<&'a
mut V
> {
1764 self.inner
.next_back().map(|(_
, v
)| v
)
1768 #[stable(feature = "map_values_mut", since = "1.10.0")]
1769 impl<K
, V
> ExactSizeIterator
for ValuesMut
<'_
, K
, V
> {
1770 fn len(&self) -> usize {
1775 #[stable(feature = "fused", since = "1.26.0")]
1776 impl<K
, V
> FusedIterator
for ValuesMut
<'_
, K
, V
> {}
1778 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1779 impl<K
, V
> Iterator
for IntoKeys
<K
, V
> {
1782 fn next(&mut self) -> Option
<K
> {
1783 self.inner
.next().map(|(k
, _
)| k
)
1786 fn size_hint(&self) -> (usize, Option
<usize>) {
1787 self.inner
.size_hint()
1790 fn last(mut self) -> Option
<K
> {
1794 fn min(mut self) -> Option
<K
> {
1798 fn max(mut self) -> Option
<K
> {
1803 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1804 impl<K
, V
> DoubleEndedIterator
for IntoKeys
<K
, V
> {
1805 fn next_back(&mut self) -> Option
<K
> {
1806 self.inner
.next_back().map(|(k
, _
)| k
)
1810 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1811 impl<K
, V
> ExactSizeIterator
for IntoKeys
<K
, V
> {
1812 fn len(&self) -> usize {
1817 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1818 impl<K
, V
> FusedIterator
for IntoKeys
<K
, V
> {}
1820 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1821 impl<K
, V
> Iterator
for IntoValues
<K
, V
> {
1824 fn next(&mut self) -> Option
<V
> {
1825 self.inner
.next().map(|(_
, v
)| v
)
1828 fn size_hint(&self) -> (usize, Option
<usize>) {
1829 self.inner
.size_hint()
1832 fn last(mut self) -> Option
<V
> {
1837 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1838 impl<K
, V
> DoubleEndedIterator
for IntoValues
<K
, V
> {
1839 fn next_back(&mut self) -> Option
<V
> {
1840 self.inner
.next_back().map(|(_
, v
)| v
)
1844 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1845 impl<K
, V
> ExactSizeIterator
for IntoValues
<K
, V
> {
1846 fn len(&self) -> usize {
1851 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1852 impl<K
, V
> FusedIterator
for IntoValues
<K
, V
> {}
1854 #[stable(feature = "btree_range", since = "1.17.0")]
1855 impl<'a
, K
, V
> DoubleEndedIterator
for Range
<'a
, K
, V
> {
1856 fn next_back(&mut self) -> Option
<(&'a K
, &'a V
)> {
1857 self.inner
.next_back_checked()
1861 #[stable(feature = "fused", since = "1.26.0")]
1862 impl<K
, V
> FusedIterator
for Range
<'_
, K
, V
> {}
1864 #[stable(feature = "btree_range", since = "1.17.0")]
1865 impl<K
, V
> Clone
for Range
<'_
, K
, V
> {
1866 fn clone(&self) -> Self {
1867 Range { inner: self.inner.clone() }
1871 #[stable(feature = "btree_range", since = "1.17.0")]
1872 impl<'a
, K
, V
> Iterator
for RangeMut
<'a
, K
, V
> {
1873 type Item
= (&'a K
, &'a
mut V
);
1875 fn next(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1876 self.inner
.next_checked()
1879 fn last(mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1883 fn min(mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1887 fn max(mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1892 impl<'a
, K
, V
> RangeMut
<'a
, K
, V
> {
1893 /// Returns an iterator of references over the remaining items.
1895 pub(super) fn iter(&self) -> Range
<'_
, K
, V
> {
1896 Range { inner: self.inner.reborrow() }
1900 #[stable(feature = "btree_range", since = "1.17.0")]
1901 impl<'a
, K
, V
> DoubleEndedIterator
for RangeMut
<'a
, K
, V
> {
1902 fn next_back(&mut self) -> Option
<(&'a K
, &'a
mut V
)> {
1903 self.inner
.next_back_checked()
1907 #[stable(feature = "fused", since = "1.26.0")]
1908 impl<K
, V
> FusedIterator
for RangeMut
<'_
, K
, V
> {}
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl<K
: Ord
, V
> FromIterator
<(K
, V
)> for BTreeMap
<K
, V
> {
1912 fn from_iter
<T
: IntoIterator
<Item
= (K
, V
)>>(iter
: T
) -> BTreeMap
<K
, V
> {
1913 let mut map
= BTreeMap
::new();
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 impl<K
: Ord
, V
> Extend
<(K
, V
)> for BTreeMap
<K
, V
> {
1922 fn extend
<T
: IntoIterator
<Item
= (K
, V
)>>(&mut self, iter
: T
) {
1923 iter
.into_iter().for_each(move |(k
, v
)| {
1929 fn extend_one(&mut self, (k
, v
): (K
, V
)) {
1934 #[stable(feature = "extend_ref", since = "1.2.0")]
1935 impl<'a
, K
: Ord
+ Copy
, V
: Copy
> Extend
<(&'a K
, &'a V
)> for BTreeMap
<K
, V
> {
1936 fn extend
<I
: IntoIterator
<Item
= (&'a K
, &'a V
)>>(&mut self, iter
: I
) {
1937 self.extend(iter
.into_iter().map(|(&key
, &value
)| (key
, value
)));
1941 fn extend_one(&mut self, (&k
, &v
): (&'a K
, &'a V
)) {
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 impl<K
: Hash
, V
: Hash
> Hash
for BTreeMap
<K
, V
> {
1948 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<K
: Ord
, V
> Default
for BTreeMap
<K
, V
> {
1957 /// Creates an empty `BTreeMap`.
1958 fn default() -> BTreeMap
<K
, V
> {
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 impl<K
: PartialEq
, V
: PartialEq
> PartialEq
for BTreeMap
<K
, V
> {
1965 fn eq(&self, other
: &BTreeMap
<K
, V
>) -> bool
{
1966 self.len() == other
.len() && self.iter().zip(other
).all(|(a
, b
)| a
== b
)
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<K
: Eq
, V
: Eq
> Eq
for BTreeMap
<K
, V
> {}
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<K
: PartialOrd
, V
: PartialOrd
> PartialOrd
for BTreeMap
<K
, V
> {
1976 fn partial_cmp(&self, other
: &BTreeMap
<K
, V
>) -> Option
<Ordering
> {
1977 self.iter().partial_cmp(other
.iter())
1981 #[stable(feature = "rust1", since = "1.0.0")]
1982 impl<K
: Ord
, V
: Ord
> Ord
for BTreeMap
<K
, V
> {
1984 fn cmp(&self, other
: &BTreeMap
<K
, V
>) -> Ordering
{
1985 self.iter().cmp(other
.iter())
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 impl<K
: Debug
, V
: Debug
> Debug
for BTreeMap
<K
, V
> {
1991 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1992 f
.debug_map().entries(self.iter()).finish()
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 impl<K
, Q
: ?Sized
, V
> Index
<&Q
> for BTreeMap
<K
, V
>
2004 /// Returns a reference to the value corresponding to the supplied key.
2008 /// Panics if the key is not present in the `BTreeMap`.
2010 fn index(&self, key
: &Q
) -> &V
{
2011 self.get(key
).expect("no entry found for key")
2015 impl<K
, V
> BTreeMap
<K
, V
> {
2016 /// Gets an iterator over the entries of the map, sorted by key.
2023 /// use std::collections::BTreeMap;
2025 /// let mut map = BTreeMap::new();
2026 /// map.insert(3, "c");
2027 /// map.insert(2, "b");
2028 /// map.insert(1, "a");
2030 /// for (key, value) in map.iter() {
2031 /// println!("{}: {}", key, value);
2034 /// let (first_key, first_value) = map.iter().next().unwrap();
2035 /// assert_eq!((*first_key, *first_value), (1, "a"));
2037 #[stable(feature = "rust1", since = "1.0.0")]
2038 pub fn iter(&self) -> Iter
<'_
, K
, V
> {
2039 if let Some(root
) = &self.root
{
2040 let full_range
= root
.reborrow().full_range();
2042 Iter { range: Range { inner: full_range }
, length
: self.length
}
2044 Iter { range: Range { inner: LeafRange::none() }
, length
: 0 }
2048 /// Gets a mutable iterator over the entries of the map, sorted by key.
2055 /// use std::collections::BTreeMap;
2057 /// let mut map = BTreeMap::new();
2058 /// map.insert("a", 1);
2059 /// map.insert("b", 2);
2060 /// map.insert("c", 3);
2062 /// // add 10 to the value if the key isn't "a"
2063 /// for (key, value) in map.iter_mut() {
2064 /// if key != &"a" {
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 pub fn iter_mut(&mut self) -> IterMut
<'_
, K
, V
> {
2071 if let Some(root
) = &mut self.root
{
2072 let full_range
= root
.borrow_valmut().full_range();
2075 range
: RangeMut { inner: full_range, _marker: PhantomData }
,
2076 length
: self.length
,
2080 range
: RangeMut { inner: LeafRange::none(), _marker: PhantomData }
,
2086 /// Gets an iterator over the keys of the map, in sorted order.
2093 /// use std::collections::BTreeMap;
2095 /// let mut a = BTreeMap::new();
2096 /// a.insert(2, "b");
2097 /// a.insert(1, "a");
2099 /// let keys: Vec<_> = a.keys().cloned().collect();
2100 /// assert_eq!(keys, [1, 2]);
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 pub fn keys(&self) -> Keys
<'_
, K
, V
> {
2104 Keys { inner: self.iter() }
2107 /// Gets an iterator over the values of the map, in order by key.
2114 /// use std::collections::BTreeMap;
2116 /// let mut a = BTreeMap::new();
2117 /// a.insert(1, "hello");
2118 /// a.insert(2, "goodbye");
2120 /// let values: Vec<&str> = a.values().cloned().collect();
2121 /// assert_eq!(values, ["hello", "goodbye"]);
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 pub fn values(&self) -> Values
<'_
, K
, V
> {
2125 Values { inner: self.iter() }
2128 /// Gets a mutable iterator over the values of the map, in order by key.
2135 /// use std::collections::BTreeMap;
2137 /// let mut a = BTreeMap::new();
2138 /// a.insert(1, String::from("hello"));
2139 /// a.insert(2, String::from("goodbye"));
2141 /// for value in a.values_mut() {
2142 /// value.push_str("!");
2145 /// let values: Vec<String> = a.values().cloned().collect();
2146 /// assert_eq!(values, [String::from("hello!"),
2147 /// String::from("goodbye!")]);
2149 #[stable(feature = "map_values_mut", since = "1.10.0")]
2150 pub fn values_mut(&mut self) -> ValuesMut
<'_
, K
, V
> {
2151 ValuesMut { inner: self.iter_mut() }
2154 /// Returns the number of elements in the map.
2161 /// use std::collections::BTreeMap;
2163 /// let mut a = BTreeMap::new();
2164 /// assert_eq!(a.len(), 0);
2165 /// a.insert(1, "a");
2166 /// assert_eq!(a.len(), 1);
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2170 pub const fn len(&self) -> usize {
2174 /// Returns `true` if the map contains no elements.
2181 /// use std::collections::BTreeMap;
2183 /// let mut a = BTreeMap::new();
2184 /// assert!(a.is_empty());
2185 /// a.insert(1, "a");
2186 /// assert!(!a.is_empty());
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")]
2190 pub const fn is_empty(&self) -> bool
{
2194 /// If the root node is the empty (non-allocated) root node, allocate our
2195 /// own node. Is an associated function to avoid borrowing the entire BTreeMap.
2196 fn ensure_is_owned(root
: &mut Option
<Root
<K
, V
>>) -> &mut Root
<K
, V
> {
2197 root
.get_or_insert_with(Root
::new
)