alloc/collections/btree/
map.rs

1use core::borrow::Borrow;
2use core::cmp::Ordering;
3use core::error::Error;
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::FusedIterator;
7use core::marker::PhantomData;
8use core::mem::{self, ManuallyDrop};
9use core::ops::{Bound, Index, RangeBounds};
10use core::ptr;
11
12use super::borrow::DormantMutRef;
13use super::dedup_sorted_iter::DedupSortedIter;
14use super::navigate::{LazyLeafRange, LeafRange};
15use super::node::ForceResult::*;
16use super::node::{self, Handle, NodeRef, Root, marker};
17use super::search::SearchBound;
18use super::search::SearchResult::*;
19use super::set_val::SetValZST;
20use crate::alloc::{Allocator, Global};
21use crate::vec::Vec;
22
23mod entry;
24
25use Entry::*;
26#[stable(feature = "rust1", since = "1.0.0")]
27pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
28
29/// Minimum number of elements in a node that is not a root.
30/// We might temporarily have fewer elements during methods.
31pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
32
33// A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
34// - Keys must appear in ascending order (according to the key's type).
35// - Every non-leaf node contains at least 1 element (has at least 2 children).
36// - Every non-root node contains at least MIN_LEN elements.
37//
38// An empty map is represented either by the absence of a root node or by a
39// root node that is an empty leaf.
40
41/// An ordered map based on a [B-Tree].
42///
43/// Given a key type with a [total order], an ordered map stores its entries in key order.
44/// That means that keys must be of a type that implements the [`Ord`] trait,
45/// such that two keys can always be compared to determine their [`Ordering`].
46/// Examples of keys with a total order are strings with lexicographical order,
47/// and numbers with their natural order.
48///
49/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::into_iter`], [`BTreeMap::values`], or
50/// [`BTreeMap::keys`] produce their items in key order, and take worst-case logarithmic and
51/// amortized constant time per item returned.
52///
53/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
54/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
55/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
57/// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
58/// include panics, incorrect results, aborts, memory leaks, and non-termination.
59///
60/// # Examples
61///
62/// ```
63/// use std::collections::BTreeMap;
64///
65/// // type inference lets us omit an explicit type signature (which
66/// // would be `BTreeMap<&str, &str>` in this example).
67/// let mut movie_reviews = BTreeMap::new();
68///
69/// // review some movies.
70/// movie_reviews.insert("Office Space",       "Deals with real issues in the workplace.");
71/// movie_reviews.insert("Pulp Fiction",       "Masterpiece.");
72/// movie_reviews.insert("The Godfather",      "Very enjoyable.");
73/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
74///
75/// // check for a specific one.
76/// if !movie_reviews.contains_key("Les Misérables") {
77///     println!("We've got {} reviews, but Les Misérables ain't one.",
78///              movie_reviews.len());
79/// }
80///
81/// // oops, this review has a lot of spelling mistakes, let's delete it.
82/// movie_reviews.remove("The Blues Brothers");
83///
84/// // look up the values associated with some keys.
85/// let to_find = ["Up!", "Office Space"];
86/// for movie in &to_find {
87///     match movie_reviews.get(movie) {
88///        Some(review) => println!("{movie}: {review}"),
89///        None => println!("{movie} is unreviewed.")
90///     }
91/// }
92///
93/// // Look up the value for a key (will panic if the key is not found).
94/// println!("Movie review: {}", movie_reviews["Office Space"]);
95///
96/// // iterate over everything.
97/// for (movie, review) in &movie_reviews {
98///     println!("{movie}: \"{review}\"");
99/// }
100/// ```
101///
102/// A `BTreeMap` with a known list of items can be initialized from an array:
103///
104/// ```
105/// use std::collections::BTreeMap;
106///
107/// let solar_distance = BTreeMap::from([
108///     ("Mercury", 0.4),
109///     ("Venus", 0.7),
110///     ("Earth", 1.0),
111///     ("Mars", 1.5),
112/// ]);
113/// ```
114///
115/// ## `Entry` API
116///
117/// `BTreeMap` implements an [`Entry API`], which allows for complex
118/// methods of getting, setting, updating and removing keys and their values:
119///
120/// [`Entry API`]: BTreeMap::entry
121///
122/// ```
123/// use std::collections::BTreeMap;
124///
125/// // type inference lets us omit an explicit type signature (which
126/// // would be `BTreeMap<&str, u8>` in this example).
127/// let mut player_stats = BTreeMap::new();
128///
129/// fn random_stat_buff() -> u8 {
130///     // could actually return some random value here - let's just return
131///     // some fixed value for now
132///     42
133/// }
134///
135/// // insert a key only if it doesn't already exist
136/// player_stats.entry("health").or_insert(100);
137///
138/// // insert a key using a function that provides a new value only if it
139/// // doesn't already exist
140/// player_stats.entry("defence").or_insert_with(random_stat_buff);
141///
142/// // update a key, guarding against the key possibly not being set
143/// let stat = player_stats.entry("attack").or_insert(100);
144/// *stat += random_stat_buff();
145///
146/// // modify an entry before an insert with in-place mutation
147/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
148/// ```
149///
150/// # Background
151///
152/// A B-tree is (like) a [binary search tree], but adapted to the natural granularity that modern
153/// machines like to consume data at. This means that each node contains an entire array of elements,
154/// instead of just a single element.
155///
156/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
157/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
158/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum number of
159/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
160/// is done is *very* inefficient for modern computer architectures. In particular, every element
161/// is stored in its own individually heap-allocated node. This means that every single insertion
162/// triggers a heap-allocation, and every comparison is a potential cache-miss due to the indirection.
163/// Since both heap-allocations and cache-misses are notably expensive in practice, we are forced to,
164/// at the very least, reconsider the BST strategy.
165///
166/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
167/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
168/// searches. However, this does mean that searches will have to do *more* comparisons on average.
169/// The precise number of comparisons depends on the node search strategy used. For optimal cache
170/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
171/// the node using binary search. As a compromise, one could also perform a linear search
172/// that initially only checks every i<sup>th</sup> element for some choice of i.
173///
174/// Currently, our implementation simply performs naive linear search. This provides excellent
175/// performance on *small* nodes of elements which are cheap to compare. However in the future we
176/// would like to further explore choosing the optimal search strategy based on the choice of B,
177/// and possibly other factors. Using linear search, searching for a random element is expected
178/// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
179/// however, performance is excellent.
180///
181/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
182/// [binary search tree]: https://en.wikipedia.org/wiki/Binary_search_tree
183/// [total order]: https://en.wikipedia.org/wiki/Total_order
184/// [`Cell`]: core::cell::Cell
185/// [`RefCell`]: core::cell::RefCell
186#[stable(feature = "rust1", since = "1.0.0")]
187#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
188#[rustc_insignificant_dtor]
189pub struct BTreeMap<
190    K,
191    V,
192    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
193> {
194    root: Option<Root<K, V>>,
195    length: usize,
196    /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
197    pub(super) alloc: ManuallyDrop<A>,
198    // For dropck; the `Box` avoids making the `Unpin` impl more strict than before
199    _marker: PhantomData<crate::boxed::Box<(K, V), A>>,
200}
201
202#[stable(feature = "btree_drop", since = "1.7.0")]
203unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTreeMap<K, V, A> {
204    fn drop(&mut self) {
205        drop(unsafe { ptr::read(self) }.into_iter())
206    }
207}
208
209// FIXME: This implementation is "wrong", but changing it would be a breaking change.
210// (The bounds of the automatic `UnwindSafe` implementation have been like this since Rust 1.50.)
211// Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe`
212// traits are deprecated, or disarmed (no longer causing hard errors) in the future.
213#[stable(feature = "btree_unwindsafe", since = "1.64.0")]
214impl<K, V, A: Allocator + Clone> core::panic::UnwindSafe for BTreeMap<K, V, A>
215where
216    A: core::panic::UnwindSafe,
217    K: core::panic::RefUnwindSafe,
218    V: core::panic::RefUnwindSafe,
219{
220}
221
222#[stable(feature = "rust1", since = "1.0.0")]
223impl<K: Clone, V: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, A> {
224    fn clone(&self) -> BTreeMap<K, V, A> {
225        fn clone_subtree<'a, K: Clone, V: Clone, A: Allocator + Clone>(
226            node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
227            alloc: A,
228        ) -> BTreeMap<K, V, A>
229        where
230            K: 'a,
231            V: 'a,
232        {
233            match node.force() {
234                Leaf(leaf) => {
235                    let mut out_tree = BTreeMap {
236                        root: Some(Root::new(alloc.clone())),
237                        length: 0,
238                        alloc: ManuallyDrop::new(alloc),
239                        _marker: PhantomData,
240                    };
241
242                    {
243                        let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
244                        let mut out_node = match root.borrow_mut().force() {
245                            Leaf(leaf) => leaf,
246                            Internal(_) => unreachable!(),
247                        };
248
249                        let mut in_edge = leaf.first_edge();
250                        while let Ok(kv) = in_edge.right_kv() {
251                            let (k, v) = kv.into_kv();
252                            in_edge = kv.right_edge();
253
254                            out_node.push(k.clone(), v.clone());
255                            out_tree.length += 1;
256                        }
257                    }
258
259                    out_tree
260                }
261                Internal(internal) => {
262                    let mut out_tree =
263                        clone_subtree(internal.first_edge().descend(), alloc.clone());
264
265                    {
266                        let out_root = out_tree.root.as_mut().unwrap();
267                        let mut out_node = out_root.push_internal_level(alloc.clone());
268                        let mut in_edge = internal.first_edge();
269                        while let Ok(kv) = in_edge.right_kv() {
270                            let (k, v) = kv.into_kv();
271                            in_edge = kv.right_edge();
272
273                            let k = (*k).clone();
274                            let v = (*v).clone();
275                            let subtree = clone_subtree(in_edge.descend(), alloc.clone());
276
277                            // We can't destructure subtree directly
278                            // because BTreeMap implements Drop
279                            let (subroot, sublength) = unsafe {
280                                let subtree = ManuallyDrop::new(subtree);
281                                let root = ptr::read(&subtree.root);
282                                let length = subtree.length;
283                                (root, length)
284                            };
285
286                            out_node.push(
287                                k,
288                                v,
289                                subroot.unwrap_or_else(|| Root::new(alloc.clone())),
290                            );
291                            out_tree.length += 1 + sublength;
292                        }
293                    }
294
295                    out_tree
296                }
297            }
298        }
299
300        if self.is_empty() {
301            BTreeMap::new_in((*self.alloc).clone())
302        } else {
303            clone_subtree(self.root.as_ref().unwrap().reborrow(), (*self.alloc).clone()) // unwrap succeeds because not empty
304        }
305    }
306}
307
308// Internal functionality for `BTreeSet`.
309impl<K, A: Allocator + Clone> BTreeMap<K, SetValZST, A> {
310    pub(super) fn replace(&mut self, key: K) -> Option<K>
311    where
312        K: Ord,
313    {
314        let (map, dormant_map) = DormantMutRef::new(self);
315        let root_node =
316            map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
317        match root_node.search_tree::<K>(&key) {
318            Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
319            GoDown(handle) => {
320                VacantEntry {
321                    key,
322                    handle: Some(handle),
323                    dormant_map,
324                    alloc: (*map.alloc).clone(),
325                    _marker: PhantomData,
326                }
327                .insert(SetValZST);
328                None
329            }
330        }
331    }
332
333    pub(super) fn get_or_insert_with<Q: ?Sized, F>(&mut self, q: &Q, f: F) -> &K
334    where
335        K: Borrow<Q> + Ord,
336        Q: Ord,
337        F: FnOnce(&Q) -> K,
338    {
339        let (map, dormant_map) = DormantMutRef::new(self);
340        let root_node =
341            map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
342        match root_node.search_tree(q) {
343            Found(handle) => handle.into_kv_mut().0,
344            GoDown(handle) => {
345                let key = f(q);
346                assert!(*key.borrow() == *q, "new value is not equal");
347                VacantEntry {
348                    key,
349                    handle: Some(handle),
350                    dormant_map,
351                    alloc: (*map.alloc).clone(),
352                    _marker: PhantomData,
353                }
354                .insert_entry(SetValZST)
355                .into_key()
356            }
357        }
358    }
359}
360
361/// An iterator over the entries of a `BTreeMap`.
362///
363/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
364/// documentation for more.
365///
366/// [`iter`]: BTreeMap::iter
367#[must_use = "iterators are lazy and do nothing unless consumed"]
368#[stable(feature = "rust1", since = "1.0.0")]
369pub struct Iter<'a, K: 'a, V: 'a> {
370    range: LazyLeafRange<marker::Immut<'a>, K, V>,
371    length: usize,
372}
373
374#[stable(feature = "collection_debug", since = "1.17.0")]
375impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        f.debug_list().entries(self.clone()).finish()
378    }
379}
380
381#[stable(feature = "default_iters", since = "1.70.0")]
382impl<'a, K: 'a, V: 'a> Default for Iter<'a, K, V> {
383    /// Creates an empty `btree_map::Iter`.
384    ///
385    /// ```
386    /// # use std::collections::btree_map;
387    /// let iter: btree_map::Iter<'_, u8, u8> = Default::default();
388    /// assert_eq!(iter.len(), 0);
389    /// ```
390    fn default() -> Self {
391        Iter { range: Default::default(), length: 0 }
392    }
393}
394
395/// A mutable iterator over the entries of a `BTreeMap`.
396///
397/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
398/// documentation for more.
399///
400/// [`iter_mut`]: BTreeMap::iter_mut
401#[must_use = "iterators are lazy and do nothing unless consumed"]
402#[stable(feature = "rust1", since = "1.0.0")]
403pub struct IterMut<'a, K: 'a, V: 'a> {
404    range: LazyLeafRange<marker::ValMut<'a>, K, V>,
405    length: usize,
406
407    // Be invariant in `K` and `V`
408    _marker: PhantomData<&'a mut (K, V)>,
409}
410
411#[stable(feature = "collection_debug", since = "1.17.0")]
412impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        let range = Iter { range: self.range.reborrow(), length: self.length };
415        f.debug_list().entries(range).finish()
416    }
417}
418
419#[stable(feature = "default_iters", since = "1.70.0")]
420impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> {
421    /// Creates an empty `btree_map::IterMut`.
422    ///
423    /// ```
424    /// # use std::collections::btree_map;
425    /// let iter: btree_map::IterMut<'_, u8, u8> = Default::default();
426    /// assert_eq!(iter.len(), 0);
427    /// ```
428    fn default() -> Self {
429        IterMut { range: Default::default(), length: 0, _marker: PhantomData {} }
430    }
431}
432
433/// An owning iterator over the entries of a `BTreeMap`, sorted by key.
434///
435/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
436/// (provided by the [`IntoIterator`] trait). See its documentation for more.
437///
438/// [`into_iter`]: IntoIterator::into_iter
439#[stable(feature = "rust1", since = "1.0.0")]
440#[rustc_insignificant_dtor]
441pub struct IntoIter<
442    K,
443    V,
444    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
445> {
446    range: LazyLeafRange<marker::Dying, K, V>,
447    length: usize,
448    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
449    alloc: A,
450}
451
452impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
453    /// Returns an iterator of references over the remaining items.
454    #[inline]
455    pub(super) fn iter(&self) -> Iter<'_, K, V> {
456        Iter { range: self.range.reborrow(), length: self.length }
457    }
458}
459
460#[stable(feature = "collection_debug", since = "1.17.0")]
461impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
462    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463        f.debug_list().entries(self.iter()).finish()
464    }
465}
466
467#[stable(feature = "default_iters", since = "1.70.0")]
468impl<K, V, A> Default for IntoIter<K, V, A>
469where
470    A: Allocator + Default + Clone,
471{
472    /// Creates an empty `btree_map::IntoIter`.
473    ///
474    /// ```
475    /// # use std::collections::btree_map;
476    /// let iter: btree_map::IntoIter<u8, u8> = Default::default();
477    /// assert_eq!(iter.len(), 0);
478    /// ```
479    fn default() -> Self {
480        IntoIter { range: Default::default(), length: 0, alloc: Default::default() }
481    }
482}
483
484/// An iterator over the keys of a `BTreeMap`.
485///
486/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
487/// documentation for more.
488///
489/// [`keys`]: BTreeMap::keys
490#[must_use = "iterators are lazy and do nothing unless consumed"]
491#[stable(feature = "rust1", since = "1.0.0")]
492pub struct Keys<'a, K, V> {
493    inner: Iter<'a, K, V>,
494}
495
496#[stable(feature = "collection_debug", since = "1.17.0")]
497impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499        f.debug_list().entries(self.clone()).finish()
500    }
501}
502
503/// An iterator over the values of a `BTreeMap`.
504///
505/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
506/// documentation for more.
507///
508/// [`values`]: BTreeMap::values
509#[must_use = "iterators are lazy and do nothing unless consumed"]
510#[stable(feature = "rust1", since = "1.0.0")]
511pub struct Values<'a, K, V> {
512    inner: Iter<'a, K, V>,
513}
514
515#[stable(feature = "collection_debug", since = "1.17.0")]
516impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518        f.debug_list().entries(self.clone()).finish()
519    }
520}
521
522/// A mutable iterator over the values of a `BTreeMap`.
523///
524/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
525/// documentation for more.
526///
527/// [`values_mut`]: BTreeMap::values_mut
528#[must_use = "iterators are lazy and do nothing unless consumed"]
529#[stable(feature = "map_values_mut", since = "1.10.0")]
530pub struct ValuesMut<'a, K, V> {
531    inner: IterMut<'a, K, V>,
532}
533
534#[stable(feature = "map_values_mut", since = "1.10.0")]
535impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
538    }
539}
540
541/// An owning iterator over the keys of a `BTreeMap`.
542///
543/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
544/// See its documentation for more.
545///
546/// [`into_keys`]: BTreeMap::into_keys
547#[must_use = "iterators are lazy and do nothing unless consumed"]
548#[stable(feature = "map_into_keys_values", since = "1.54.0")]
549pub struct IntoKeys<K, V, A: Allocator + Clone = Global> {
550    inner: IntoIter<K, V, A>,
551}
552
553#[stable(feature = "map_into_keys_values", since = "1.54.0")]
554impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
555    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556        f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
557    }
558}
559
560/// An owning iterator over the values of a `BTreeMap`.
561///
562/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
563/// See its documentation for more.
564///
565/// [`into_values`]: BTreeMap::into_values
566#[must_use = "iterators are lazy and do nothing unless consumed"]
567#[stable(feature = "map_into_keys_values", since = "1.54.0")]
568pub struct IntoValues<
569    K,
570    V,
571    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
572> {
573    inner: IntoIter<K, V, A>,
574}
575
576#[stable(feature = "map_into_keys_values", since = "1.54.0")]
577impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579        f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
580    }
581}
582
583/// An iterator over a sub-range of entries in a `BTreeMap`.
584///
585/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
586/// documentation for more.
587///
588/// [`range`]: BTreeMap::range
589#[must_use = "iterators are lazy and do nothing unless consumed"]
590#[stable(feature = "btree_range", since = "1.17.0")]
591pub struct Range<'a, K: 'a, V: 'a> {
592    inner: LeafRange<marker::Immut<'a>, K, V>,
593}
594
595#[stable(feature = "collection_debug", since = "1.17.0")]
596impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598        f.debug_list().entries(self.clone()).finish()
599    }
600}
601
602/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
603///
604/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
605/// documentation for more.
606///
607/// [`range_mut`]: BTreeMap::range_mut
608#[must_use = "iterators are lazy and do nothing unless consumed"]
609#[stable(feature = "btree_range", since = "1.17.0")]
610pub struct RangeMut<'a, K: 'a, V: 'a> {
611    inner: LeafRange<marker::ValMut<'a>, K, V>,
612
613    // Be invariant in `K` and `V`
614    _marker: PhantomData<&'a mut (K, V)>,
615}
616
617#[stable(feature = "collection_debug", since = "1.17.0")]
618impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
619    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620        let range = Range { inner: self.inner.reborrow() };
621        f.debug_list().entries(range).finish()
622    }
623}
624
625impl<K, V> BTreeMap<K, V> {
626    /// Makes a new, empty `BTreeMap`.
627    ///
628    /// Does not allocate anything on its own.
629    ///
630    /// # Examples
631    ///
632    /// ```
633    /// use std::collections::BTreeMap;
634    ///
635    /// let mut map = BTreeMap::new();
636    ///
637    /// // entries can now be inserted into the empty map
638    /// map.insert(1, "a");
639    /// ```
640    #[stable(feature = "rust1", since = "1.0.0")]
641    #[rustc_const_stable(feature = "const_btree_new", since = "1.66.0")]
642    #[inline]
643    #[must_use]
644    pub const fn new() -> BTreeMap<K, V> {
645        BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global), _marker: PhantomData }
646    }
647}
648
649impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
650    /// Clears the map, removing all elements.
651    ///
652    /// # Examples
653    ///
654    /// ```
655    /// use std::collections::BTreeMap;
656    ///
657    /// let mut a = BTreeMap::new();
658    /// a.insert(1, "a");
659    /// a.clear();
660    /// assert!(a.is_empty());
661    /// ```
662    #[stable(feature = "rust1", since = "1.0.0")]
663    pub fn clear(&mut self) {
664        // avoid moving the allocator
665        drop(BTreeMap {
666            root: mem::replace(&mut self.root, None),
667            length: mem::replace(&mut self.length, 0),
668            alloc: self.alloc.clone(),
669            _marker: PhantomData,
670        });
671    }
672
673    /// Makes a new empty BTreeMap with a reasonable choice for B.
674    ///
675    /// # Examples
676    ///
677    /// ```
678    /// # #![feature(allocator_api)]
679    /// # #![feature(btreemap_alloc)]
680    /// use std::collections::BTreeMap;
681    /// use std::alloc::Global;
682    ///
683    /// let mut map = BTreeMap::new_in(Global);
684    ///
685    /// // entries can now be inserted into the empty map
686    /// map.insert(1, "a");
687    /// ```
688    #[unstable(feature = "btreemap_alloc", issue = "32838")]
689    pub const fn new_in(alloc: A) -> BTreeMap<K, V, A> {
690        BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
691    }
692}
693
694impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
695    /// Returns a reference to the value corresponding to the key.
696    ///
697    /// The key may be any borrowed form of the map's key type, but the ordering
698    /// on the borrowed form *must* match the ordering on the key type.
699    ///
700    /// # Examples
701    ///
702    /// ```
703    /// use std::collections::BTreeMap;
704    ///
705    /// let mut map = BTreeMap::new();
706    /// map.insert(1, "a");
707    /// assert_eq!(map.get(&1), Some(&"a"));
708    /// assert_eq!(map.get(&2), None);
709    /// ```
710    #[stable(feature = "rust1", since = "1.0.0")]
711    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
712    where
713        K: Borrow<Q> + Ord,
714        Q: Ord,
715    {
716        let root_node = self.root.as_ref()?.reborrow();
717        match root_node.search_tree(key) {
718            Found(handle) => Some(handle.into_kv().1),
719            GoDown(_) => None,
720        }
721    }
722
723    /// Returns the key-value pair corresponding to the supplied key. This is
724    /// potentially useful:
725    /// - for key types where non-identical keys can be considered equal;
726    /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
727    /// - for getting a reference to a key with the same lifetime as the collection.
728    ///
729    /// The supplied key may be any borrowed form of the map's key type, but the ordering
730    /// on the borrowed form *must* match the ordering on the key type.
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// use std::cmp::Ordering;
736    /// use std::collections::BTreeMap;
737    ///
738    /// #[derive(Clone, Copy, Debug)]
739    /// struct S {
740    ///     id: u32,
741    /// #   #[allow(unused)] // prevents a "field `name` is never read" error
742    ///     name: &'static str, // ignored by equality and ordering operations
743    /// }
744    ///
745    /// impl PartialEq for S {
746    ///     fn eq(&self, other: &S) -> bool {
747    ///         self.id == other.id
748    ///     }
749    /// }
750    ///
751    /// impl Eq for S {}
752    ///
753    /// impl PartialOrd for S {
754    ///     fn partial_cmp(&self, other: &S) -> Option<Ordering> {
755    ///         self.id.partial_cmp(&other.id)
756    ///     }
757    /// }
758    ///
759    /// impl Ord for S {
760    ///     fn cmp(&self, other: &S) -> Ordering {
761    ///         self.id.cmp(&other.id)
762    ///     }
763    /// }
764    ///
765    /// let j_a = S { id: 1, name: "Jessica" };
766    /// let j_b = S { id: 1, name: "Jess" };
767    /// let p = S { id: 2, name: "Paul" };
768    /// assert_eq!(j_a, j_b);
769    ///
770    /// let mut map = BTreeMap::new();
771    /// map.insert(j_a, "Paris");
772    /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
773    /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
774    /// assert_eq!(map.get_key_value(&p), None);
775    /// ```
776    #[stable(feature = "map_get_key_value", since = "1.40.0")]
777    pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
778    where
779        K: Borrow<Q> + Ord,
780        Q: Ord,
781    {
782        let root_node = self.root.as_ref()?.reborrow();
783        match root_node.search_tree(k) {
784            Found(handle) => Some(handle.into_kv()),
785            GoDown(_) => None,
786        }
787    }
788
789    /// Returns the first key-value pair in the map.
790    /// The key in this pair is the minimum key in the map.
791    ///
792    /// # Examples
793    ///
794    /// ```
795    /// use std::collections::BTreeMap;
796    ///
797    /// let mut map = BTreeMap::new();
798    /// assert_eq!(map.first_key_value(), None);
799    /// map.insert(1, "b");
800    /// map.insert(2, "a");
801    /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
802    /// ```
803    #[stable(feature = "map_first_last", since = "1.66.0")]
804    pub fn first_key_value(&self) -> Option<(&K, &V)>
805    where
806        K: Ord,
807    {
808        let root_node = self.root.as_ref()?.reborrow();
809        root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
810    }
811
812    /// Returns the first entry in the map for in-place manipulation.
813    /// The key of this entry is the minimum key in the map.
814    ///
815    /// # Examples
816    ///
817    /// ```
818    /// use std::collections::BTreeMap;
819    ///
820    /// let mut map = BTreeMap::new();
821    /// map.insert(1, "a");
822    /// map.insert(2, "b");
823    /// if let Some(mut entry) = map.first_entry() {
824    ///     if *entry.key() > 0 {
825    ///         entry.insert("first");
826    ///     }
827    /// }
828    /// assert_eq!(*map.get(&1).unwrap(), "first");
829    /// assert_eq!(*map.get(&2).unwrap(), "b");
830    /// ```
831    #[stable(feature = "map_first_last", since = "1.66.0")]
832    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
833    where
834        K: Ord,
835    {
836        let (map, dormant_map) = DormantMutRef::new(self);
837        let root_node = map.root.as_mut()?.borrow_mut();
838        let kv = root_node.first_leaf_edge().right_kv().ok()?;
839        Some(OccupiedEntry {
840            handle: kv.forget_node_type(),
841            dormant_map,
842            alloc: (*map.alloc).clone(),
843            _marker: PhantomData,
844        })
845    }
846
847    /// Removes and returns the first element in the map.
848    /// The key of this element is the minimum key that was in the map.
849    ///
850    /// # Examples
851    ///
852    /// Draining elements in ascending order, while keeping a usable map each iteration.
853    ///
854    /// ```
855    /// use std::collections::BTreeMap;
856    ///
857    /// let mut map = BTreeMap::new();
858    /// map.insert(1, "a");
859    /// map.insert(2, "b");
860    /// while let Some((key, _val)) = map.pop_first() {
861    ///     assert!(map.iter().all(|(k, _v)| *k > key));
862    /// }
863    /// assert!(map.is_empty());
864    /// ```
865    #[stable(feature = "map_first_last", since = "1.66.0")]
866    pub fn pop_first(&mut self) -> Option<(K, V)>
867    where
868        K: Ord,
869    {
870        self.first_entry().map(|entry| entry.remove_entry())
871    }
872
873    /// Returns the last key-value pair in the map.
874    /// The key in this pair is the maximum key in the map.
875    ///
876    /// # Examples
877    ///
878    /// ```
879    /// use std::collections::BTreeMap;
880    ///
881    /// let mut map = BTreeMap::new();
882    /// map.insert(1, "b");
883    /// map.insert(2, "a");
884    /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
885    /// ```
886    #[stable(feature = "map_first_last", since = "1.66.0")]
887    pub fn last_key_value(&self) -> Option<(&K, &V)>
888    where
889        K: Ord,
890    {
891        let root_node = self.root.as_ref()?.reborrow();
892        root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
893    }
894
895    /// Returns the last entry in the map for in-place manipulation.
896    /// The key of this entry is the maximum key in the map.
897    ///
898    /// # Examples
899    ///
900    /// ```
901    /// use std::collections::BTreeMap;
902    ///
903    /// let mut map = BTreeMap::new();
904    /// map.insert(1, "a");
905    /// map.insert(2, "b");
906    /// if let Some(mut entry) = map.last_entry() {
907    ///     if *entry.key() > 0 {
908    ///         entry.insert("last");
909    ///     }
910    /// }
911    /// assert_eq!(*map.get(&1).unwrap(), "a");
912    /// assert_eq!(*map.get(&2).unwrap(), "last");
913    /// ```
914    #[stable(feature = "map_first_last", since = "1.66.0")]
915    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
916    where
917        K: Ord,
918    {
919        let (map, dormant_map) = DormantMutRef::new(self);
920        let root_node = map.root.as_mut()?.borrow_mut();
921        let kv = root_node.last_leaf_edge().left_kv().ok()?;
922        Some(OccupiedEntry {
923            handle: kv.forget_node_type(),
924            dormant_map,
925            alloc: (*map.alloc).clone(),
926            _marker: PhantomData,
927        })
928    }
929
930    /// Removes and returns the last element in the map.
931    /// The key of this element is the maximum key that was in the map.
932    ///
933    /// # Examples
934    ///
935    /// Draining elements in descending order, while keeping a usable map each iteration.
936    ///
937    /// ```
938    /// use std::collections::BTreeMap;
939    ///
940    /// let mut map = BTreeMap::new();
941    /// map.insert(1, "a");
942    /// map.insert(2, "b");
943    /// while let Some((key, _val)) = map.pop_last() {
944    ///     assert!(map.iter().all(|(k, _v)| *k < key));
945    /// }
946    /// assert!(map.is_empty());
947    /// ```
948    #[stable(feature = "map_first_last", since = "1.66.0")]
949    pub fn pop_last(&mut self) -> Option<(K, V)>
950    where
951        K: Ord,
952    {
953        self.last_entry().map(|entry| entry.remove_entry())
954    }
955
956    /// Returns `true` if the map contains a value for the specified key.
957    ///
958    /// The key may be any borrowed form of the map's key type, but the ordering
959    /// on the borrowed form *must* match the ordering on the key type.
960    ///
961    /// # Examples
962    ///
963    /// ```
964    /// use std::collections::BTreeMap;
965    ///
966    /// let mut map = BTreeMap::new();
967    /// map.insert(1, "a");
968    /// assert_eq!(map.contains_key(&1), true);
969    /// assert_eq!(map.contains_key(&2), false);
970    /// ```
971    #[stable(feature = "rust1", since = "1.0.0")]
972    #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_contains_key")]
973    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
974    where
975        K: Borrow<Q> + Ord,
976        Q: Ord,
977    {
978        self.get(key).is_some()
979    }
980
981    /// Returns a mutable reference to the value corresponding to the key.
982    ///
983    /// The key may be any borrowed form of the map's key type, but the ordering
984    /// on the borrowed form *must* match the ordering on the key type.
985    ///
986    /// # Examples
987    ///
988    /// ```
989    /// use std::collections::BTreeMap;
990    ///
991    /// let mut map = BTreeMap::new();
992    /// map.insert(1, "a");
993    /// if let Some(x) = map.get_mut(&1) {
994    ///     *x = "b";
995    /// }
996    /// assert_eq!(map[&1], "b");
997    /// ```
998    // See `get` for implementation notes, this is basically a copy-paste with mut's added
999    #[stable(feature = "rust1", since = "1.0.0")]
1000    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
1001    where
1002        K: Borrow<Q> + Ord,
1003        Q: Ord,
1004    {
1005        let root_node = self.root.as_mut()?.borrow_mut();
1006        match root_node.search_tree(key) {
1007            Found(handle) => Some(handle.into_val_mut()),
1008            GoDown(_) => None,
1009        }
1010    }
1011
1012    /// Inserts a key-value pair into the map.
1013    ///
1014    /// If the map did not have this key present, `None` is returned.
1015    ///
1016    /// If the map did have this key present, the value is updated, and the old
1017    /// value is returned. The key is not updated, though; this matters for
1018    /// types that can be `==` without being identical. See the [module-level
1019    /// documentation] for more.
1020    ///
1021    /// [module-level documentation]: index.html#insert-and-complex-keys
1022    ///
1023    /// # Examples
1024    ///
1025    /// ```
1026    /// use std::collections::BTreeMap;
1027    ///
1028    /// let mut map = BTreeMap::new();
1029    /// assert_eq!(map.insert(37, "a"), None);
1030    /// assert_eq!(map.is_empty(), false);
1031    ///
1032    /// map.insert(37, "b");
1033    /// assert_eq!(map.insert(37, "c"), Some("b"));
1034    /// assert_eq!(map[&37], "c");
1035    /// ```
1036    #[stable(feature = "rust1", since = "1.0.0")]
1037    #[rustc_confusables("push", "put", "set")]
1038    #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_insert")]
1039    pub fn insert(&mut self, key: K, value: V) -> Option<V>
1040    where
1041        K: Ord,
1042    {
1043        match self.entry(key) {
1044            Occupied(mut entry) => Some(entry.insert(value)),
1045            Vacant(entry) => {
1046                entry.insert(value);
1047                None
1048            }
1049        }
1050    }
1051
1052    /// Tries to insert a key-value pair into the map, and returns
1053    /// a mutable reference to the value in the entry.
1054    ///
1055    /// If the map already had this key present, nothing is updated, and
1056    /// an error containing the occupied entry and the value is returned.
1057    ///
1058    /// # Examples
1059    ///
1060    /// ```
1061    /// #![feature(map_try_insert)]
1062    ///
1063    /// use std::collections::BTreeMap;
1064    ///
1065    /// let mut map = BTreeMap::new();
1066    /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1067    ///
1068    /// let err = map.try_insert(37, "b").unwrap_err();
1069    /// assert_eq!(err.entry.key(), &37);
1070    /// assert_eq!(err.entry.get(), &"a");
1071    /// assert_eq!(err.value, "b");
1072    /// ```
1073    #[unstable(feature = "map_try_insert", issue = "82766")]
1074    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
1075    where
1076        K: Ord,
1077    {
1078        match self.entry(key) {
1079            Occupied(entry) => Err(OccupiedError { entry, value }),
1080            Vacant(entry) => Ok(entry.insert(value)),
1081        }
1082    }
1083
1084    /// Removes a key from the map, returning the value at the key if the key
1085    /// was previously in the map.
1086    ///
1087    /// The key may be any borrowed form of the map's key type, but the ordering
1088    /// on the borrowed form *must* match the ordering on the key type.
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```
1093    /// use std::collections::BTreeMap;
1094    ///
1095    /// let mut map = BTreeMap::new();
1096    /// map.insert(1, "a");
1097    /// assert_eq!(map.remove(&1), Some("a"));
1098    /// assert_eq!(map.remove(&1), None);
1099    /// ```
1100    #[stable(feature = "rust1", since = "1.0.0")]
1101    #[rustc_confusables("delete", "take")]
1102    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1103    where
1104        K: Borrow<Q> + Ord,
1105        Q: Ord,
1106    {
1107        self.remove_entry(key).map(|(_, v)| v)
1108    }
1109
1110    /// Removes a key from the map, returning the stored key and value if the key
1111    /// was previously in the map.
1112    ///
1113    /// The key may be any borrowed form of the map's key type, but the ordering
1114    /// on the borrowed form *must* match the ordering on the key type.
1115    ///
1116    /// # Examples
1117    ///
1118    /// ```
1119    /// use std::collections::BTreeMap;
1120    ///
1121    /// let mut map = BTreeMap::new();
1122    /// map.insert(1, "a");
1123    /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1124    /// assert_eq!(map.remove_entry(&1), None);
1125    /// ```
1126    #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1127    pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1128    where
1129        K: Borrow<Q> + Ord,
1130        Q: Ord,
1131    {
1132        let (map, dormant_map) = DormantMutRef::new(self);
1133        let root_node = map.root.as_mut()?.borrow_mut();
1134        match root_node.search_tree(key) {
1135            Found(handle) => Some(
1136                OccupiedEntry {
1137                    handle,
1138                    dormant_map,
1139                    alloc: (*map.alloc).clone(),
1140                    _marker: PhantomData,
1141                }
1142                .remove_entry(),
1143            ),
1144            GoDown(_) => None,
1145        }
1146    }
1147
1148    /// Retains only the elements specified by the predicate.
1149    ///
1150    /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1151    /// The elements are visited in ascending key order.
1152    ///
1153    /// # Examples
1154    ///
1155    /// ```
1156    /// use std::collections::BTreeMap;
1157    ///
1158    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1159    /// // Keep only the elements with even-numbered keys.
1160    /// map.retain(|&k, _| k % 2 == 0);
1161    /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1162    /// ```
1163    #[inline]
1164    #[stable(feature = "btree_retain", since = "1.53.0")]
1165    pub fn retain<F>(&mut self, mut f: F)
1166    where
1167        K: Ord,
1168        F: FnMut(&K, &mut V) -> bool,
1169    {
1170        self.extract_if(.., |k, v| !f(k, v)).for_each(drop);
1171    }
1172
1173    /// Moves all elements from `other` into `self`, leaving `other` empty.
1174    ///
1175    /// If a key from `other` is already present in `self`, the respective
1176    /// value from `self` will be overwritten with the respective value from `other`.
1177    ///
1178    /// # Examples
1179    ///
1180    /// ```
1181    /// use std::collections::BTreeMap;
1182    ///
1183    /// let mut a = BTreeMap::new();
1184    /// a.insert(1, "a");
1185    /// a.insert(2, "b");
1186    /// a.insert(3, "c"); // Note: Key (3) also present in b.
1187    ///
1188    /// let mut b = BTreeMap::new();
1189    /// b.insert(3, "d"); // Note: Key (3) also present in a.
1190    /// b.insert(4, "e");
1191    /// b.insert(5, "f");
1192    ///
1193    /// a.append(&mut b);
1194    ///
1195    /// assert_eq!(a.len(), 5);
1196    /// assert_eq!(b.len(), 0);
1197    ///
1198    /// assert_eq!(a[&1], "a");
1199    /// assert_eq!(a[&2], "b");
1200    /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1201    /// assert_eq!(a[&4], "e");
1202    /// assert_eq!(a[&5], "f");
1203    /// ```
1204    #[stable(feature = "btree_append", since = "1.11.0")]
1205    pub fn append(&mut self, other: &mut Self)
1206    where
1207        K: Ord,
1208        A: Clone,
1209    {
1210        // Do we have to append anything at all?
1211        if other.is_empty() {
1212            return;
1213        }
1214
1215        // We can just swap `self` and `other` if `self` is empty.
1216        if self.is_empty() {
1217            mem::swap(self, other);
1218            return;
1219        }
1220
1221        let self_iter = mem::replace(self, Self::new_in((*self.alloc).clone())).into_iter();
1222        let other_iter = mem::replace(other, Self::new_in((*self.alloc).clone())).into_iter();
1223        let root = self.root.get_or_insert_with(|| Root::new((*self.alloc).clone()));
1224        root.append_from_sorted_iters(
1225            self_iter,
1226            other_iter,
1227            &mut self.length,
1228            (*self.alloc).clone(),
1229        )
1230    }
1231
1232    /// Constructs a double-ended iterator over a sub-range of elements in the map.
1233    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1234    /// yield elements from min (inclusive) to max (exclusive).
1235    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1236    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1237    /// range from 4 to 10.
1238    ///
1239    /// # Panics
1240    ///
1241    /// Panics if range `start > end`.
1242    /// Panics if range `start == end` and both bounds are `Excluded`.
1243    ///
1244    /// # Examples
1245    ///
1246    /// ```
1247    /// use std::collections::BTreeMap;
1248    /// use std::ops::Bound::Included;
1249    ///
1250    /// let mut map = BTreeMap::new();
1251    /// map.insert(3, "a");
1252    /// map.insert(5, "b");
1253    /// map.insert(8, "c");
1254    /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1255    ///     println!("{key}: {value}");
1256    /// }
1257    /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1258    /// ```
1259    #[stable(feature = "btree_range", since = "1.17.0")]
1260    pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1261    where
1262        T: Ord,
1263        K: Borrow<T> + Ord,
1264        R: RangeBounds<T>,
1265    {
1266        if let Some(root) = &self.root {
1267            Range { inner: root.reborrow().range_search(range) }
1268        } else {
1269            Range { inner: LeafRange::none() }
1270        }
1271    }
1272
1273    /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1274    /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1275    /// yield elements from min (inclusive) to max (exclusive).
1276    /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1277    /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1278    /// range from 4 to 10.
1279    ///
1280    /// # Panics
1281    ///
1282    /// Panics if range `start > end`.
1283    /// Panics if range `start == end` and both bounds are `Excluded`.
1284    ///
1285    /// # Examples
1286    ///
1287    /// ```
1288    /// use std::collections::BTreeMap;
1289    ///
1290    /// let mut map: BTreeMap<&str, i32> =
1291    ///     [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1292    /// for (_, balance) in map.range_mut("B".."Cheryl") {
1293    ///     *balance += 100;
1294    /// }
1295    /// for (name, balance) in &map {
1296    ///     println!("{name} => {balance}");
1297    /// }
1298    /// ```
1299    #[stable(feature = "btree_range", since = "1.17.0")]
1300    pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1301    where
1302        T: Ord,
1303        K: Borrow<T> + Ord,
1304        R: RangeBounds<T>,
1305    {
1306        if let Some(root) = &mut self.root {
1307            RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1308        } else {
1309            RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1310        }
1311    }
1312
1313    /// Gets the given key's corresponding entry in the map for in-place manipulation.
1314    ///
1315    /// # Examples
1316    ///
1317    /// ```
1318    /// use std::collections::BTreeMap;
1319    ///
1320    /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1321    ///
1322    /// // count the number of occurrences of letters in the vec
1323    /// for x in ["a", "b", "a", "c", "a", "b"] {
1324    ///     count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1325    /// }
1326    ///
1327    /// assert_eq!(count["a"], 3);
1328    /// assert_eq!(count["b"], 2);
1329    /// assert_eq!(count["c"], 1);
1330    /// ```
1331    #[stable(feature = "rust1", since = "1.0.0")]
1332    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1333    where
1334        K: Ord,
1335    {
1336        let (map, dormant_map) = DormantMutRef::new(self);
1337        match map.root {
1338            None => Vacant(VacantEntry {
1339                key,
1340                handle: None,
1341                dormant_map,
1342                alloc: (*map.alloc).clone(),
1343                _marker: PhantomData,
1344            }),
1345            Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1346                Found(handle) => Occupied(OccupiedEntry {
1347                    handle,
1348                    dormant_map,
1349                    alloc: (*map.alloc).clone(),
1350                    _marker: PhantomData,
1351                }),
1352                GoDown(handle) => Vacant(VacantEntry {
1353                    key,
1354                    handle: Some(handle),
1355                    dormant_map,
1356                    alloc: (*map.alloc).clone(),
1357                    _marker: PhantomData,
1358                }),
1359            },
1360        }
1361    }
1362
1363    /// Splits the collection into two at the given key. Returns everything after the given key,
1364    /// including the key.
1365    ///
1366    /// # Examples
1367    ///
1368    /// ```
1369    /// use std::collections::BTreeMap;
1370    ///
1371    /// let mut a = BTreeMap::new();
1372    /// a.insert(1, "a");
1373    /// a.insert(2, "b");
1374    /// a.insert(3, "c");
1375    /// a.insert(17, "d");
1376    /// a.insert(41, "e");
1377    ///
1378    /// let b = a.split_off(&3);
1379    ///
1380    /// assert_eq!(a.len(), 2);
1381    /// assert_eq!(b.len(), 3);
1382    ///
1383    /// assert_eq!(a[&1], "a");
1384    /// assert_eq!(a[&2], "b");
1385    ///
1386    /// assert_eq!(b[&3], "c");
1387    /// assert_eq!(b[&17], "d");
1388    /// assert_eq!(b[&41], "e");
1389    /// ```
1390    #[stable(feature = "btree_split_off", since = "1.11.0")]
1391    pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1392    where
1393        K: Borrow<Q> + Ord,
1394        A: Clone,
1395    {
1396        if self.is_empty() {
1397            return Self::new_in((*self.alloc).clone());
1398        }
1399
1400        let total_num = self.len();
1401        let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1402
1403        let right_root = left_root.split_off(key, (*self.alloc).clone());
1404
1405        let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1406        self.length = new_left_len;
1407
1408        BTreeMap {
1409            root: Some(right_root),
1410            length: right_len,
1411            alloc: self.alloc.clone(),
1412            _marker: PhantomData,
1413        }
1414    }
1415
1416    /// Creates an iterator that visits elements (key-value pairs) in the specified range in
1417    /// ascending key order and uses a closure to determine if an element
1418    /// should be removed.
1419    ///
1420    /// If the closure returns `true`, the element is removed from the map and
1421    /// yielded. If the closure returns `false`, or panics, the element remains
1422    /// in the map and will not be yielded.
1423    ///
1424    /// The iterator also lets you mutate the value of each element in the
1425    /// closure, regardless of whether you choose to keep or remove it.
1426    ///
1427    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1428    /// or the iteration short-circuits, then the remaining elements will be retained.
1429    /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
1430    ///
1431    /// [`retain`]: BTreeMap::retain
1432    ///
1433    /// # Examples
1434    ///
1435    /// ```
1436    /// #![feature(btree_extract_if)]
1437    /// use std::collections::BTreeMap;
1438    ///
1439    /// // Splitting a map into even and odd keys, reusing the original map:
1440    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1441    /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1442    /// let odds = map;
1443    /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1444    /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1445    ///
1446    /// // Splitting a map into low and high halves, reusing the original map:
1447    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1448    /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1449    /// let high = map;
1450    /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1451    /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1452    /// ```
1453    #[unstable(feature = "btree_extract_if", issue = "70530")]
1454    pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1455    where
1456        K: Ord,
1457        R: RangeBounds<K>,
1458        F: FnMut(&K, &mut V) -> bool,
1459    {
1460        let (inner, alloc) = self.extract_if_inner(range);
1461        ExtractIf { pred, inner, alloc }
1462    }
1463
1464    pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1465    where
1466        K: Ord,
1467        R: RangeBounds<K>,
1468    {
1469        if let Some(root) = self.root.as_mut() {
1470            let (root, dormant_root) = DormantMutRef::new(root);
1471            let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1472            (
1473                ExtractIfInner {
1474                    length: &mut self.length,
1475                    dormant_root: Some(dormant_root),
1476                    cur_leaf_edge: Some(first),
1477                    range,
1478                },
1479                (*self.alloc).clone(),
1480            )
1481        } else {
1482            (
1483                ExtractIfInner {
1484                    length: &mut self.length,
1485                    dormant_root: None,
1486                    cur_leaf_edge: None,
1487                    range,
1488                },
1489                (*self.alloc).clone(),
1490            )
1491        }
1492    }
1493
1494    /// Creates a consuming iterator visiting all the keys, in sorted order.
1495    /// The map cannot be used after calling this.
1496    /// The iterator element type is `K`.
1497    ///
1498    /// # Examples
1499    ///
1500    /// ```
1501    /// use std::collections::BTreeMap;
1502    ///
1503    /// let mut a = BTreeMap::new();
1504    /// a.insert(2, "b");
1505    /// a.insert(1, "a");
1506    ///
1507    /// let keys: Vec<i32> = a.into_keys().collect();
1508    /// assert_eq!(keys, [1, 2]);
1509    /// ```
1510    #[inline]
1511    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1512    pub fn into_keys(self) -> IntoKeys<K, V, A> {
1513        IntoKeys { inner: self.into_iter() }
1514    }
1515
1516    /// Creates a consuming iterator visiting all the values, in order by key.
1517    /// The map cannot be used after calling this.
1518    /// The iterator element type is `V`.
1519    ///
1520    /// # Examples
1521    ///
1522    /// ```
1523    /// use std::collections::BTreeMap;
1524    ///
1525    /// let mut a = BTreeMap::new();
1526    /// a.insert(1, "hello");
1527    /// a.insert(2, "goodbye");
1528    ///
1529    /// let values: Vec<&str> = a.into_values().collect();
1530    /// assert_eq!(values, ["hello", "goodbye"]);
1531    /// ```
1532    #[inline]
1533    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1534    pub fn into_values(self) -> IntoValues<K, V, A> {
1535        IntoValues { inner: self.into_iter() }
1536    }
1537
1538    /// Makes a `BTreeMap` from a sorted iterator.
1539    pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1540    where
1541        K: Ord,
1542        I: IntoIterator<Item = (K, V)>,
1543    {
1544        let mut root = Root::new(alloc.clone());
1545        let mut length = 0;
1546        root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1547        BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1548    }
1549}
1550
1551#[stable(feature = "rust1", since = "1.0.0")]
1552impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, A> {
1553    type Item = (&'a K, &'a V);
1554    type IntoIter = Iter<'a, K, V>;
1555
1556    fn into_iter(self) -> Iter<'a, K, V> {
1557        self.iter()
1558    }
1559}
1560
1561#[stable(feature = "rust1", since = "1.0.0")]
1562impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1563    type Item = (&'a K, &'a V);
1564
1565    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1566        if self.length == 0 {
1567            None
1568        } else {
1569            self.length -= 1;
1570            Some(unsafe { self.range.next_unchecked() })
1571        }
1572    }
1573
1574    fn size_hint(&self) -> (usize, Option<usize>) {
1575        (self.length, Some(self.length))
1576    }
1577
1578    fn last(mut self) -> Option<(&'a K, &'a V)> {
1579        self.next_back()
1580    }
1581
1582    fn min(mut self) -> Option<(&'a K, &'a V)>
1583    where
1584        (&'a K, &'a V): Ord,
1585    {
1586        self.next()
1587    }
1588
1589    fn max(mut self) -> Option<(&'a K, &'a V)>
1590    where
1591        (&'a K, &'a V): Ord,
1592    {
1593        self.next_back()
1594    }
1595}
1596
1597#[stable(feature = "fused", since = "1.26.0")]
1598impl<K, V> FusedIterator for Iter<'_, K, V> {}
1599
1600#[stable(feature = "rust1", since = "1.0.0")]
1601impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1602    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1603        if self.length == 0 {
1604            None
1605        } else {
1606            self.length -= 1;
1607            Some(unsafe { self.range.next_back_unchecked() })
1608        }
1609    }
1610}
1611
1612#[stable(feature = "rust1", since = "1.0.0")]
1613impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1614    fn len(&self) -> usize {
1615        self.length
1616    }
1617}
1618
1619#[stable(feature = "rust1", since = "1.0.0")]
1620impl<K, V> Clone for Iter<'_, K, V> {
1621    fn clone(&self) -> Self {
1622        Iter { range: self.range.clone(), length: self.length }
1623    }
1624}
1625
1626#[stable(feature = "rust1", since = "1.0.0")]
1627impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1628    type Item = (&'a K, &'a mut V);
1629    type IntoIter = IterMut<'a, K, V>;
1630
1631    fn into_iter(self) -> IterMut<'a, K, V> {
1632        self.iter_mut()
1633    }
1634}
1635
1636#[stable(feature = "rust1", since = "1.0.0")]
1637impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1638    type Item = (&'a K, &'a mut V);
1639
1640    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1641        if self.length == 0 {
1642            None
1643        } else {
1644            self.length -= 1;
1645            Some(unsafe { self.range.next_unchecked() })
1646        }
1647    }
1648
1649    fn size_hint(&self) -> (usize, Option<usize>) {
1650        (self.length, Some(self.length))
1651    }
1652
1653    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1654        self.next_back()
1655    }
1656
1657    fn min(mut self) -> Option<(&'a K, &'a mut V)>
1658    where
1659        (&'a K, &'a mut V): Ord,
1660    {
1661        self.next()
1662    }
1663
1664    fn max(mut self) -> Option<(&'a K, &'a mut V)>
1665    where
1666        (&'a K, &'a mut V): Ord,
1667    {
1668        self.next_back()
1669    }
1670}
1671
1672#[stable(feature = "rust1", since = "1.0.0")]
1673impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1674    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1675        if self.length == 0 {
1676            None
1677        } else {
1678            self.length -= 1;
1679            Some(unsafe { self.range.next_back_unchecked() })
1680        }
1681    }
1682}
1683
1684#[stable(feature = "rust1", since = "1.0.0")]
1685impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1686    fn len(&self) -> usize {
1687        self.length
1688    }
1689}
1690
1691#[stable(feature = "fused", since = "1.26.0")]
1692impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1693
1694impl<'a, K, V> IterMut<'a, K, V> {
1695    /// Returns an iterator of references over the remaining items.
1696    #[inline]
1697    pub(super) fn iter(&self) -> Iter<'_, K, V> {
1698        Iter { range: self.range.reborrow(), length: self.length }
1699    }
1700}
1701
1702#[stable(feature = "rust1", since = "1.0.0")]
1703impl<K, V, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, A> {
1704    type Item = (K, V);
1705    type IntoIter = IntoIter<K, V, A>;
1706
1707    /// Gets an owning iterator over the entries of the map, sorted by key.
1708    fn into_iter(self) -> IntoIter<K, V, A> {
1709        let mut me = ManuallyDrop::new(self);
1710        if let Some(root) = me.root.take() {
1711            let full_range = root.into_dying().full_range();
1712
1713            IntoIter {
1714                range: full_range,
1715                length: me.length,
1716                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1717            }
1718        } else {
1719            IntoIter {
1720                range: LazyLeafRange::none(),
1721                length: 0,
1722                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1723            }
1724        }
1725    }
1726}
1727
1728#[stable(feature = "btree_drop", since = "1.7.0")]
1729impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1730    fn drop(&mut self) {
1731        struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1732
1733        impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1734            fn drop(&mut self) {
1735                // Continue the same loop we perform below. This only runs when unwinding, so we
1736                // don't have to care about panics this time (they'll abort).
1737                while let Some(kv) = self.0.dying_next() {
1738                    // SAFETY: we consume the dying handle immediately.
1739                    unsafe { kv.drop_key_val() };
1740                }
1741            }
1742        }
1743
1744        while let Some(kv) = self.dying_next() {
1745            let guard = DropGuard(self);
1746            // SAFETY: we don't touch the tree before consuming the dying handle.
1747            unsafe { kv.drop_key_val() };
1748            mem::forget(guard);
1749        }
1750    }
1751}
1752
1753impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1754    /// Core of a `next` method returning a dying KV handle,
1755    /// invalidated by further calls to this function and some others.
1756    fn dying_next(
1757        &mut self,
1758    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1759        if self.length == 0 {
1760            self.range.deallocating_end(self.alloc.clone());
1761            None
1762        } else {
1763            self.length -= 1;
1764            Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1765        }
1766    }
1767
1768    /// Core of a `next_back` method returning a dying KV handle,
1769    /// invalidated by further calls to this function and some others.
1770    fn dying_next_back(
1771        &mut self,
1772    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1773        if self.length == 0 {
1774            self.range.deallocating_end(self.alloc.clone());
1775            None
1776        } else {
1777            self.length -= 1;
1778            Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1779        }
1780    }
1781}
1782
1783#[stable(feature = "rust1", since = "1.0.0")]
1784impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1785    type Item = (K, V);
1786
1787    fn next(&mut self) -> Option<(K, V)> {
1788        // SAFETY: we consume the dying handle immediately.
1789        self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1790    }
1791
1792    fn size_hint(&self) -> (usize, Option<usize>) {
1793        (self.length, Some(self.length))
1794    }
1795}
1796
1797#[stable(feature = "rust1", since = "1.0.0")]
1798impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1799    fn next_back(&mut self) -> Option<(K, V)> {
1800        // SAFETY: we consume the dying handle immediately.
1801        self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1802    }
1803}
1804
1805#[stable(feature = "rust1", since = "1.0.0")]
1806impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1807    fn len(&self) -> usize {
1808        self.length
1809    }
1810}
1811
1812#[stable(feature = "fused", since = "1.26.0")]
1813impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1814
1815#[stable(feature = "rust1", since = "1.0.0")]
1816impl<'a, K, V> Iterator for Keys<'a, K, V> {
1817    type Item = &'a K;
1818
1819    fn next(&mut self) -> Option<&'a K> {
1820        self.inner.next().map(|(k, _)| k)
1821    }
1822
1823    fn size_hint(&self) -> (usize, Option<usize>) {
1824        self.inner.size_hint()
1825    }
1826
1827    fn last(mut self) -> Option<&'a K> {
1828        self.next_back()
1829    }
1830
1831    fn min(mut self) -> Option<&'a K>
1832    where
1833        &'a K: Ord,
1834    {
1835        self.next()
1836    }
1837
1838    fn max(mut self) -> Option<&'a K>
1839    where
1840        &'a K: Ord,
1841    {
1842        self.next_back()
1843    }
1844}
1845
1846#[stable(feature = "rust1", since = "1.0.0")]
1847impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1848    fn next_back(&mut self) -> Option<&'a K> {
1849        self.inner.next_back().map(|(k, _)| k)
1850    }
1851}
1852
1853#[stable(feature = "rust1", since = "1.0.0")]
1854impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1855    fn len(&self) -> usize {
1856        self.inner.len()
1857    }
1858}
1859
1860#[stable(feature = "fused", since = "1.26.0")]
1861impl<K, V> FusedIterator for Keys<'_, K, V> {}
1862
1863#[stable(feature = "rust1", since = "1.0.0")]
1864impl<K, V> Clone for Keys<'_, K, V> {
1865    fn clone(&self) -> Self {
1866        Keys { inner: self.inner.clone() }
1867    }
1868}
1869
1870#[stable(feature = "default_iters", since = "1.70.0")]
1871impl<K, V> Default for Keys<'_, K, V> {
1872    /// Creates an empty `btree_map::Keys`.
1873    ///
1874    /// ```
1875    /// # use std::collections::btree_map;
1876    /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
1877    /// assert_eq!(iter.len(), 0);
1878    /// ```
1879    fn default() -> Self {
1880        Keys { inner: Default::default() }
1881    }
1882}
1883
1884#[stable(feature = "rust1", since = "1.0.0")]
1885impl<'a, K, V> Iterator for Values<'a, K, V> {
1886    type Item = &'a V;
1887
1888    fn next(&mut self) -> Option<&'a V> {
1889        self.inner.next().map(|(_, v)| v)
1890    }
1891
1892    fn size_hint(&self) -> (usize, Option<usize>) {
1893        self.inner.size_hint()
1894    }
1895
1896    fn last(mut self) -> Option<&'a V> {
1897        self.next_back()
1898    }
1899}
1900
1901#[stable(feature = "rust1", since = "1.0.0")]
1902impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1903    fn next_back(&mut self) -> Option<&'a V> {
1904        self.inner.next_back().map(|(_, v)| v)
1905    }
1906}
1907
1908#[stable(feature = "rust1", since = "1.0.0")]
1909impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1910    fn len(&self) -> usize {
1911        self.inner.len()
1912    }
1913}
1914
1915#[stable(feature = "fused", since = "1.26.0")]
1916impl<K, V> FusedIterator for Values<'_, K, V> {}
1917
1918#[stable(feature = "rust1", since = "1.0.0")]
1919impl<K, V> Clone for Values<'_, K, V> {
1920    fn clone(&self) -> Self {
1921        Values { inner: self.inner.clone() }
1922    }
1923}
1924
1925#[stable(feature = "default_iters", since = "1.70.0")]
1926impl<K, V> Default for Values<'_, K, V> {
1927    /// Creates an empty `btree_map::Values`.
1928    ///
1929    /// ```
1930    /// # use std::collections::btree_map;
1931    /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
1932    /// assert_eq!(iter.len(), 0);
1933    /// ```
1934    fn default() -> Self {
1935        Values { inner: Default::default() }
1936    }
1937}
1938
1939/// An iterator produced by calling `extract_if` on BTreeMap.
1940#[unstable(feature = "btree_extract_if", issue = "70530")]
1941#[must_use = "iterators are lazy and do nothing unless consumed"]
1942pub struct ExtractIf<
1943    'a,
1944    K,
1945    V,
1946    R,
1947    F,
1948    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
1949> {
1950    pred: F,
1951    inner: ExtractIfInner<'a, K, V, R>,
1952    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1953    alloc: A,
1954}
1955
1956/// Most of the implementation of ExtractIf are generic over the type
1957/// of the predicate, thus also serving for BTreeSet::ExtractIf.
1958pub(super) struct ExtractIfInner<'a, K, V, R> {
1959    /// Reference to the length field in the borrowed map, updated live.
1960    length: &'a mut usize,
1961    /// Buried reference to the root field in the borrowed map.
1962    /// Wrapped in `Option` to allow drop handler to `take` it.
1963    dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1964    /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1965    /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1966    /// or if a panic occurred in the predicate.
1967    cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1968    /// Range over which iteration was requested.  We don't need the left side, but we
1969    /// can't extract the right side without requiring K: Clone.
1970    range: R,
1971}
1972
1973#[unstable(feature = "btree_extract_if", issue = "70530")]
1974impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
1975where
1976    K: fmt::Debug,
1977    V: fmt::Debug,
1978    A: Allocator + Clone,
1979{
1980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1981        f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
1982    }
1983}
1984
1985#[unstable(feature = "btree_extract_if", issue = "70530")]
1986impl<K, V, R, F, A: Allocator + Clone> Iterator for ExtractIf<'_, K, V, R, F, A>
1987where
1988    K: PartialOrd,
1989    R: RangeBounds<K>,
1990    F: FnMut(&K, &mut V) -> bool,
1991{
1992    type Item = (K, V);
1993
1994    fn next(&mut self) -> Option<(K, V)> {
1995        self.inner.next(&mut self.pred, self.alloc.clone())
1996    }
1997
1998    fn size_hint(&self) -> (usize, Option<usize>) {
1999        self.inner.size_hint()
2000    }
2001}
2002
2003impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2004    /// Allow Debug implementations to predict the next element.
2005    pub(super) fn peek(&self) -> Option<(&K, &V)> {
2006        let edge = self.cur_leaf_edge.as_ref()?;
2007        edge.reborrow().next_kv().ok().map(Handle::into_kv)
2008    }
2009
2010    /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2011    pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2012    where
2013        K: PartialOrd,
2014        R: RangeBounds<K>,
2015        F: FnMut(&K, &mut V) -> bool,
2016    {
2017        while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2018            let (k, v) = kv.kv_mut();
2019
2020            // On creation, we navigated directly to the left bound, so we need only check the
2021            // right bound here to decide whether to stop.
2022            match self.range.end_bound() {
2023                Bound::Included(ref end) if (*k).le(end) => (),
2024                Bound::Excluded(ref end) if (*k).lt(end) => (),
2025                Bound::Unbounded => (),
2026                _ => return None,
2027            }
2028
2029            if pred(k, v) {
2030                *self.length -= 1;
2031                let (kv, pos) = kv.remove_kv_tracking(
2032                    || {
2033                        // SAFETY: we will touch the root in a way that will not
2034                        // invalidate the position returned.
2035                        let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2036                        root.pop_internal_level(alloc.clone());
2037                        self.dormant_root = Some(DormantMutRef::new(root).1);
2038                    },
2039                    alloc.clone(),
2040                );
2041                self.cur_leaf_edge = Some(pos);
2042                return Some(kv);
2043            }
2044            self.cur_leaf_edge = Some(kv.next_leaf_edge());
2045        }
2046        None
2047    }
2048
2049    /// Implementation of a typical `ExtractIf::size_hint` method.
2050    pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2051        // In most of the btree iterators, `self.length` is the number of elements
2052        // yet to be visited. Here, it includes elements that were visited and that
2053        // the predicate decided not to drain. Making this upper bound more tight
2054        // during iteration would require an extra field.
2055        (0, Some(*self.length))
2056    }
2057}
2058
2059#[unstable(feature = "btree_extract_if", issue = "70530")]
2060impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2061where
2062    K: PartialOrd,
2063    R: RangeBounds<K>,
2064    F: FnMut(&K, &mut V) -> bool,
2065{
2066}
2067
2068#[stable(feature = "btree_range", since = "1.17.0")]
2069impl<'a, K, V> Iterator for Range<'a, K, V> {
2070    type Item = (&'a K, &'a V);
2071
2072    fn next(&mut self) -> Option<(&'a K, &'a V)> {
2073        self.inner.next_checked()
2074    }
2075
2076    fn last(mut self) -> Option<(&'a K, &'a V)> {
2077        self.next_back()
2078    }
2079
2080    fn min(mut self) -> Option<(&'a K, &'a V)>
2081    where
2082        (&'a K, &'a V): Ord,
2083    {
2084        self.next()
2085    }
2086
2087    fn max(mut self) -> Option<(&'a K, &'a V)>
2088    where
2089        (&'a K, &'a V): Ord,
2090    {
2091        self.next_back()
2092    }
2093}
2094
2095#[stable(feature = "default_iters", since = "1.70.0")]
2096impl<K, V> Default for Range<'_, K, V> {
2097    /// Creates an empty `btree_map::Range`.
2098    ///
2099    /// ```
2100    /// # use std::collections::btree_map;
2101    /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2102    /// assert_eq!(iter.count(), 0);
2103    /// ```
2104    fn default() -> Self {
2105        Range { inner: Default::default() }
2106    }
2107}
2108
2109#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2110impl<K, V> Default for RangeMut<'_, K, V> {
2111    /// Creates an empty `btree_map::RangeMut`.
2112    ///
2113    /// ```
2114    /// # use std::collections::btree_map;
2115    /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2116    /// assert_eq!(iter.count(), 0);
2117    /// ```
2118    fn default() -> Self {
2119        RangeMut { inner: Default::default(), _marker: PhantomData }
2120    }
2121}
2122
2123#[stable(feature = "map_values_mut", since = "1.10.0")]
2124impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2125    type Item = &'a mut V;
2126
2127    fn next(&mut self) -> Option<&'a mut V> {
2128        self.inner.next().map(|(_, v)| v)
2129    }
2130
2131    fn size_hint(&self) -> (usize, Option<usize>) {
2132        self.inner.size_hint()
2133    }
2134
2135    fn last(mut self) -> Option<&'a mut V> {
2136        self.next_back()
2137    }
2138}
2139
2140#[stable(feature = "map_values_mut", since = "1.10.0")]
2141impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2142    fn next_back(&mut self) -> Option<&'a mut V> {
2143        self.inner.next_back().map(|(_, v)| v)
2144    }
2145}
2146
2147#[stable(feature = "map_values_mut", since = "1.10.0")]
2148impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2149    fn len(&self) -> usize {
2150        self.inner.len()
2151    }
2152}
2153
2154#[stable(feature = "fused", since = "1.26.0")]
2155impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2156
2157#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2158impl<K, V> Default for ValuesMut<'_, K, V> {
2159    /// Creates an empty `btree_map::ValuesMut`.
2160    ///
2161    /// ```
2162    /// # use std::collections::btree_map;
2163    /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2164    /// assert_eq!(iter.count(), 0);
2165    /// ```
2166    fn default() -> Self {
2167        ValuesMut { inner: Default::default() }
2168    }
2169}
2170
2171#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2172impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
2173    type Item = K;
2174
2175    fn next(&mut self) -> Option<K> {
2176        self.inner.next().map(|(k, _)| k)
2177    }
2178
2179    fn size_hint(&self) -> (usize, Option<usize>) {
2180        self.inner.size_hint()
2181    }
2182
2183    fn last(mut self) -> Option<K> {
2184        self.next_back()
2185    }
2186
2187    fn min(mut self) -> Option<K>
2188    where
2189        K: Ord,
2190    {
2191        self.next()
2192    }
2193
2194    fn max(mut self) -> Option<K>
2195    where
2196        K: Ord,
2197    {
2198        self.next_back()
2199    }
2200}
2201
2202#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2203impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
2204    fn next_back(&mut self) -> Option<K> {
2205        self.inner.next_back().map(|(k, _)| k)
2206    }
2207}
2208
2209#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2210impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
2211    fn len(&self) -> usize {
2212        self.inner.len()
2213    }
2214}
2215
2216#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2217impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2218
2219#[stable(feature = "default_iters", since = "1.70.0")]
2220impl<K, V, A> Default for IntoKeys<K, V, A>
2221where
2222    A: Allocator + Default + Clone,
2223{
2224    /// Creates an empty `btree_map::IntoKeys`.
2225    ///
2226    /// ```
2227    /// # use std::collections::btree_map;
2228    /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2229    /// assert_eq!(iter.len(), 0);
2230    /// ```
2231    fn default() -> Self {
2232        IntoKeys { inner: Default::default() }
2233    }
2234}
2235
2236#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2237impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2238    type Item = V;
2239
2240    fn next(&mut self) -> Option<V> {
2241        self.inner.next().map(|(_, v)| v)
2242    }
2243
2244    fn size_hint(&self) -> (usize, Option<usize>) {
2245        self.inner.size_hint()
2246    }
2247
2248    fn last(mut self) -> Option<V> {
2249        self.next_back()
2250    }
2251}
2252
2253#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2254impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2255    fn next_back(&mut self) -> Option<V> {
2256        self.inner.next_back().map(|(_, v)| v)
2257    }
2258}
2259
2260#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2261impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2262    fn len(&self) -> usize {
2263        self.inner.len()
2264    }
2265}
2266
2267#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2268impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2269
2270#[stable(feature = "default_iters", since = "1.70.0")]
2271impl<K, V, A> Default for IntoValues<K, V, A>
2272where
2273    A: Allocator + Default + Clone,
2274{
2275    /// Creates an empty `btree_map::IntoValues`.
2276    ///
2277    /// ```
2278    /// # use std::collections::btree_map;
2279    /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2280    /// assert_eq!(iter.len(), 0);
2281    /// ```
2282    fn default() -> Self {
2283        IntoValues { inner: Default::default() }
2284    }
2285}
2286
2287#[stable(feature = "btree_range", since = "1.17.0")]
2288impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2289    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2290        self.inner.next_back_checked()
2291    }
2292}
2293
2294#[stable(feature = "fused", since = "1.26.0")]
2295impl<K, V> FusedIterator for Range<'_, K, V> {}
2296
2297#[stable(feature = "btree_range", since = "1.17.0")]
2298impl<K, V> Clone for Range<'_, K, V> {
2299    fn clone(&self) -> Self {
2300        Range { inner: self.inner.clone() }
2301    }
2302}
2303
2304#[stable(feature = "btree_range", since = "1.17.0")]
2305impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2306    type Item = (&'a K, &'a mut V);
2307
2308    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2309        self.inner.next_checked()
2310    }
2311
2312    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2313        self.next_back()
2314    }
2315
2316    fn min(mut self) -> Option<(&'a K, &'a mut V)>
2317    where
2318        (&'a K, &'a mut V): Ord,
2319    {
2320        self.next()
2321    }
2322
2323    fn max(mut self) -> Option<(&'a K, &'a mut V)>
2324    where
2325        (&'a K, &'a mut V): Ord,
2326    {
2327        self.next_back()
2328    }
2329}
2330
2331#[stable(feature = "btree_range", since = "1.17.0")]
2332impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2333    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2334        self.inner.next_back_checked()
2335    }
2336}
2337
2338#[stable(feature = "fused", since = "1.26.0")]
2339impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2340
2341#[stable(feature = "rust1", since = "1.0.0")]
2342impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2343    /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2344    ///
2345    /// If the iterator produces any pairs with equal keys,
2346    /// all but one of the corresponding values will be dropped.
2347    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2348        let mut inputs: Vec<_> = iter.into_iter().collect();
2349
2350        if inputs.is_empty() {
2351            return BTreeMap::new();
2352        }
2353
2354        // use stable sort to preserve the insertion order.
2355        inputs.sort_by(|a, b| a.0.cmp(&b.0));
2356        BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2357    }
2358}
2359
2360#[stable(feature = "rust1", since = "1.0.0")]
2361impl<K: Ord, V, A: Allocator + Clone> Extend<(K, V)> for BTreeMap<K, V, A> {
2362    #[inline]
2363    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2364        iter.into_iter().for_each(move |(k, v)| {
2365            self.insert(k, v);
2366        });
2367    }
2368
2369    #[inline]
2370    fn extend_one(&mut self, (k, v): (K, V)) {
2371        self.insert(k, v);
2372    }
2373}
2374
2375#[stable(feature = "extend_ref", since = "1.2.0")]
2376impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)>
2377    for BTreeMap<K, V, A>
2378{
2379    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2380        self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2381    }
2382
2383    #[inline]
2384    fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2385        self.insert(k, v);
2386    }
2387}
2388
2389#[stable(feature = "rust1", since = "1.0.0")]
2390impl<K: Hash, V: Hash, A: Allocator + Clone> Hash for BTreeMap<K, V, A> {
2391    fn hash<H: Hasher>(&self, state: &mut H) {
2392        state.write_length_prefix(self.len());
2393        for elt in self {
2394            elt.hash(state);
2395        }
2396    }
2397}
2398
2399#[stable(feature = "rust1", since = "1.0.0")]
2400impl<K, V> Default for BTreeMap<K, V> {
2401    /// Creates an empty `BTreeMap`.
2402    fn default() -> BTreeMap<K, V> {
2403        BTreeMap::new()
2404    }
2405}
2406
2407#[stable(feature = "rust1", since = "1.0.0")]
2408impl<K: PartialEq, V: PartialEq, A: Allocator + Clone> PartialEq for BTreeMap<K, V, A> {
2409    fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2410        self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2411    }
2412}
2413
2414#[stable(feature = "rust1", since = "1.0.0")]
2415impl<K: Eq, V: Eq, A: Allocator + Clone> Eq for BTreeMap<K, V, A> {}
2416
2417#[stable(feature = "rust1", since = "1.0.0")]
2418impl<K: PartialOrd, V: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, A> {
2419    #[inline]
2420    fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2421        self.iter().partial_cmp(other.iter())
2422    }
2423}
2424
2425#[stable(feature = "rust1", since = "1.0.0")]
2426impl<K: Ord, V: Ord, A: Allocator + Clone> Ord for BTreeMap<K, V, A> {
2427    #[inline]
2428    fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2429        self.iter().cmp(other.iter())
2430    }
2431}
2432
2433#[stable(feature = "rust1", since = "1.0.0")]
2434impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for BTreeMap<K, V, A> {
2435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2436        f.debug_map().entries(self.iter()).finish()
2437    }
2438}
2439
2440#[stable(feature = "rust1", since = "1.0.0")]
2441impl<K, Q: ?Sized, V, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, A>
2442where
2443    K: Borrow<Q> + Ord,
2444    Q: Ord,
2445{
2446    type Output = V;
2447
2448    /// Returns a reference to the value corresponding to the supplied key.
2449    ///
2450    /// # Panics
2451    ///
2452    /// Panics if the key is not present in the `BTreeMap`.
2453    #[inline]
2454    fn index(&self, key: &Q) -> &V {
2455        self.get(key).expect("no entry found for key")
2456    }
2457}
2458
2459#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2460impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2461    /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2462    ///
2463    /// If any entries in the array have equal keys,
2464    /// all but one of the corresponding values will be dropped.
2465    ///
2466    /// ```
2467    /// use std::collections::BTreeMap;
2468    ///
2469    /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2470    /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2471    /// assert_eq!(map1, map2);
2472    /// ```
2473    fn from(mut arr: [(K, V); N]) -> Self {
2474        if N == 0 {
2475            return BTreeMap::new();
2476        }
2477
2478        // use stable sort to preserve the insertion order.
2479        arr.sort_by(|a, b| a.0.cmp(&b.0));
2480        BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2481    }
2482}
2483
2484impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
2485    /// Gets an iterator over the entries of the map, sorted by key.
2486    ///
2487    /// # Examples
2488    ///
2489    /// ```
2490    /// use std::collections::BTreeMap;
2491    ///
2492    /// let mut map = BTreeMap::new();
2493    /// map.insert(3, "c");
2494    /// map.insert(2, "b");
2495    /// map.insert(1, "a");
2496    ///
2497    /// for (key, value) in map.iter() {
2498    ///     println!("{key}: {value}");
2499    /// }
2500    ///
2501    /// let (first_key, first_value) = map.iter().next().unwrap();
2502    /// assert_eq!((*first_key, *first_value), (1, "a"));
2503    /// ```
2504    #[stable(feature = "rust1", since = "1.0.0")]
2505    pub fn iter(&self) -> Iter<'_, K, V> {
2506        if let Some(root) = &self.root {
2507            let full_range = root.reborrow().full_range();
2508
2509            Iter { range: full_range, length: self.length }
2510        } else {
2511            Iter { range: LazyLeafRange::none(), length: 0 }
2512        }
2513    }
2514
2515    /// Gets a mutable iterator over the entries of the map, sorted by key.
2516    ///
2517    /// # Examples
2518    ///
2519    /// ```
2520    /// use std::collections::BTreeMap;
2521    ///
2522    /// let mut map = BTreeMap::from([
2523    ///    ("a", 1),
2524    ///    ("b", 2),
2525    ///    ("c", 3),
2526    /// ]);
2527    ///
2528    /// // add 10 to the value if the key isn't "a"
2529    /// for (key, value) in map.iter_mut() {
2530    ///     if key != &"a" {
2531    ///         *value += 10;
2532    ///     }
2533    /// }
2534    /// ```
2535    #[stable(feature = "rust1", since = "1.0.0")]
2536    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2537        if let Some(root) = &mut self.root {
2538            let full_range = root.borrow_valmut().full_range();
2539
2540            IterMut { range: full_range, length: self.length, _marker: PhantomData }
2541        } else {
2542            IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2543        }
2544    }
2545
2546    /// Gets an iterator over the keys of the map, in sorted order.
2547    ///
2548    /// # Examples
2549    ///
2550    /// ```
2551    /// use std::collections::BTreeMap;
2552    ///
2553    /// let mut a = BTreeMap::new();
2554    /// a.insert(2, "b");
2555    /// a.insert(1, "a");
2556    ///
2557    /// let keys: Vec<_> = a.keys().cloned().collect();
2558    /// assert_eq!(keys, [1, 2]);
2559    /// ```
2560    #[stable(feature = "rust1", since = "1.0.0")]
2561    pub fn keys(&self) -> Keys<'_, K, V> {
2562        Keys { inner: self.iter() }
2563    }
2564
2565    /// Gets an iterator over the values of the map, in order by key.
2566    ///
2567    /// # Examples
2568    ///
2569    /// ```
2570    /// use std::collections::BTreeMap;
2571    ///
2572    /// let mut a = BTreeMap::new();
2573    /// a.insert(1, "hello");
2574    /// a.insert(2, "goodbye");
2575    ///
2576    /// let values: Vec<&str> = a.values().cloned().collect();
2577    /// assert_eq!(values, ["hello", "goodbye"]);
2578    /// ```
2579    #[stable(feature = "rust1", since = "1.0.0")]
2580    pub fn values(&self) -> Values<'_, K, V> {
2581        Values { inner: self.iter() }
2582    }
2583
2584    /// Gets a mutable iterator over the values of the map, in order by key.
2585    ///
2586    /// # Examples
2587    ///
2588    /// ```
2589    /// use std::collections::BTreeMap;
2590    ///
2591    /// let mut a = BTreeMap::new();
2592    /// a.insert(1, String::from("hello"));
2593    /// a.insert(2, String::from("goodbye"));
2594    ///
2595    /// for value in a.values_mut() {
2596    ///     value.push_str("!");
2597    /// }
2598    ///
2599    /// let values: Vec<String> = a.values().cloned().collect();
2600    /// assert_eq!(values, [String::from("hello!"),
2601    ///                     String::from("goodbye!")]);
2602    /// ```
2603    #[stable(feature = "map_values_mut", since = "1.10.0")]
2604    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2605        ValuesMut { inner: self.iter_mut() }
2606    }
2607
2608    /// Returns the number of elements in the map.
2609    ///
2610    /// # Examples
2611    ///
2612    /// ```
2613    /// use std::collections::BTreeMap;
2614    ///
2615    /// let mut a = BTreeMap::new();
2616    /// assert_eq!(a.len(), 0);
2617    /// a.insert(1, "a");
2618    /// assert_eq!(a.len(), 1);
2619    /// ```
2620    #[must_use]
2621    #[stable(feature = "rust1", since = "1.0.0")]
2622    #[rustc_const_unstable(
2623        feature = "const_btree_len",
2624        issue = "71835",
2625        implied_by = "const_btree_new"
2626    )]
2627    #[rustc_confusables("length", "size")]
2628    pub const fn len(&self) -> usize {
2629        self.length
2630    }
2631
2632    /// Returns `true` if the map contains no elements.
2633    ///
2634    /// # Examples
2635    ///
2636    /// ```
2637    /// use std::collections::BTreeMap;
2638    ///
2639    /// let mut a = BTreeMap::new();
2640    /// assert!(a.is_empty());
2641    /// a.insert(1, "a");
2642    /// assert!(!a.is_empty());
2643    /// ```
2644    #[must_use]
2645    #[stable(feature = "rust1", since = "1.0.0")]
2646    #[rustc_const_unstable(
2647        feature = "const_btree_len",
2648        issue = "71835",
2649        implied_by = "const_btree_new"
2650    )]
2651    pub const fn is_empty(&self) -> bool {
2652        self.len() == 0
2653    }
2654
2655    /// Returns a [`Cursor`] pointing at the gap before the smallest key
2656    /// greater than the given bound.
2657    ///
2658    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2659    /// gap before the smallest key greater than or equal to `x`.
2660    ///
2661    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2662    /// gap before the smallest key greater than `x`.
2663    ///
2664    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2665    /// gap before the smallest key in the map.
2666    ///
2667    /// # Examples
2668    ///
2669    /// ```
2670    /// #![feature(btree_cursors)]
2671    ///
2672    /// use std::collections::BTreeMap;
2673    /// use std::ops::Bound;
2674    ///
2675    /// let map = BTreeMap::from([
2676    ///     (1, "a"),
2677    ///     (2, "b"),
2678    ///     (3, "c"),
2679    ///     (4, "d"),
2680    /// ]);
2681    ///
2682    /// let cursor = map.lower_bound(Bound::Included(&2));
2683    /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2684    /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2685    ///
2686    /// let cursor = map.lower_bound(Bound::Excluded(&2));
2687    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2688    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2689    ///
2690    /// let cursor = map.lower_bound(Bound::Unbounded);
2691    /// assert_eq!(cursor.peek_prev(), None);
2692    /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2693    /// ```
2694    #[unstable(feature = "btree_cursors", issue = "107540")]
2695    pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2696    where
2697        K: Borrow<Q> + Ord,
2698        Q: Ord,
2699    {
2700        let root_node = match self.root.as_ref() {
2701            None => return Cursor { current: None, root: None },
2702            Some(root) => root.reborrow(),
2703        };
2704        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2705        Cursor { current: Some(edge), root: self.root.as_ref() }
2706    }
2707
2708    /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2709    /// greater than the given bound.
2710    ///
2711    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2712    /// gap before the smallest key greater than or equal to `x`.
2713    ///
2714    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2715    /// gap before the smallest key greater than `x`.
2716    ///
2717    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2718    /// gap before the smallest key in the map.
2719    ///
2720    /// # Examples
2721    ///
2722    /// ```
2723    /// #![feature(btree_cursors)]
2724    ///
2725    /// use std::collections::BTreeMap;
2726    /// use std::ops::Bound;
2727    ///
2728    /// let mut map = BTreeMap::from([
2729    ///     (1, "a"),
2730    ///     (2, "b"),
2731    ///     (3, "c"),
2732    ///     (4, "d"),
2733    /// ]);
2734    ///
2735    /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2736    /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2737    /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2738    ///
2739    /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2740    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2741    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2742    ///
2743    /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2744    /// assert_eq!(cursor.peek_prev(), None);
2745    /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2746    /// ```
2747    #[unstable(feature = "btree_cursors", issue = "107540")]
2748    pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2749    where
2750        K: Borrow<Q> + Ord,
2751        Q: Ord,
2752    {
2753        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2754        let root_node = match root.as_mut() {
2755            None => {
2756                return CursorMut {
2757                    inner: CursorMutKey {
2758                        current: None,
2759                        root: dormant_root,
2760                        length: &mut self.length,
2761                        alloc: &mut *self.alloc,
2762                    },
2763                };
2764            }
2765            Some(root) => root.borrow_mut(),
2766        };
2767        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2768        CursorMut {
2769            inner: CursorMutKey {
2770                current: Some(edge),
2771                root: dormant_root,
2772                length: &mut self.length,
2773                alloc: &mut *self.alloc,
2774            },
2775        }
2776    }
2777
2778    /// Returns a [`Cursor`] pointing at the gap after the greatest key
2779    /// smaller than the given bound.
2780    ///
2781    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2782    /// gap after the greatest key smaller than or equal to `x`.
2783    ///
2784    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2785    /// gap after the greatest key smaller than `x`.
2786    ///
2787    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2788    /// gap after the greatest key in the map.
2789    ///
2790    /// # Examples
2791    ///
2792    /// ```
2793    /// #![feature(btree_cursors)]
2794    ///
2795    /// use std::collections::BTreeMap;
2796    /// use std::ops::Bound;
2797    ///
2798    /// let map = BTreeMap::from([
2799    ///     (1, "a"),
2800    ///     (2, "b"),
2801    ///     (3, "c"),
2802    ///     (4, "d"),
2803    /// ]);
2804    ///
2805    /// let cursor = map.upper_bound(Bound::Included(&3));
2806    /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
2807    /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
2808    ///
2809    /// let cursor = map.upper_bound(Bound::Excluded(&3));
2810    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2811    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2812    ///
2813    /// let cursor = map.upper_bound(Bound::Unbounded);
2814    /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
2815    /// assert_eq!(cursor.peek_next(), None);
2816    /// ```
2817    #[unstable(feature = "btree_cursors", issue = "107540")]
2818    pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2819    where
2820        K: Borrow<Q> + Ord,
2821        Q: Ord,
2822    {
2823        let root_node = match self.root.as_ref() {
2824            None => return Cursor { current: None, root: None },
2825            Some(root) => root.reborrow(),
2826        };
2827        let edge = root_node.upper_bound(SearchBound::from_range(bound));
2828        Cursor { current: Some(edge), root: self.root.as_ref() }
2829    }
2830
2831    /// Returns a [`CursorMut`] pointing at the gap after the greatest key
2832    /// smaller than the given bound.
2833    ///
2834    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2835    /// gap after the greatest key smaller than or equal to `x`.
2836    ///
2837    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2838    /// gap after the greatest key smaller than `x`.
2839    ///
2840    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2841    /// gap after the greatest key in the map.
2842    ///
2843    /// # Examples
2844    ///
2845    /// ```
2846    /// #![feature(btree_cursors)]
2847    ///
2848    /// use std::collections::BTreeMap;
2849    /// use std::ops::Bound;
2850    ///
2851    /// let mut map = BTreeMap::from([
2852    ///     (1, "a"),
2853    ///     (2, "b"),
2854    ///     (3, "c"),
2855    ///     (4, "d"),
2856    /// ]);
2857    ///
2858    /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
2859    /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
2860    /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
2861    ///
2862    /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
2863    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2864    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2865    ///
2866    /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
2867    /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
2868    /// assert_eq!(cursor.peek_next(), None);
2869    /// ```
2870    #[unstable(feature = "btree_cursors", issue = "107540")]
2871    pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2872    where
2873        K: Borrow<Q> + Ord,
2874        Q: Ord,
2875    {
2876        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2877        let root_node = match root.as_mut() {
2878            None => {
2879                return CursorMut {
2880                    inner: CursorMutKey {
2881                        current: None,
2882                        root: dormant_root,
2883                        length: &mut self.length,
2884                        alloc: &mut *self.alloc,
2885                    },
2886                };
2887            }
2888            Some(root) => root.borrow_mut(),
2889        };
2890        let edge = root_node.upper_bound(SearchBound::from_range(bound));
2891        CursorMut {
2892            inner: CursorMutKey {
2893                current: Some(edge),
2894                root: dormant_root,
2895                length: &mut self.length,
2896                alloc: &mut *self.alloc,
2897            },
2898        }
2899    }
2900}
2901
2902/// A cursor over a `BTreeMap`.
2903///
2904/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
2905///
2906/// Cursors always point to a gap between two elements in the map, and can
2907/// operate on the two immediately adjacent elements.
2908///
2909/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
2910#[unstable(feature = "btree_cursors", issue = "107540")]
2911pub struct Cursor<'a, K: 'a, V: 'a> {
2912    // If current is None then it means the tree has not been allocated yet.
2913    current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2914    root: Option<&'a node::Root<K, V>>,
2915}
2916
2917#[unstable(feature = "btree_cursors", issue = "107540")]
2918impl<K, V> Clone for Cursor<'_, K, V> {
2919    fn clone(&self) -> Self {
2920        let Cursor { current, root } = *self;
2921        Cursor { current, root }
2922    }
2923}
2924
2925#[unstable(feature = "btree_cursors", issue = "107540")]
2926impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
2927    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2928        f.write_str("Cursor")
2929    }
2930}
2931
2932/// A cursor over a `BTreeMap` with editing operations.
2933///
2934/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2935/// safely mutate the map during iteration. This is because the lifetime of its yielded
2936/// references is tied to its own lifetime, instead of just the underlying map. This means
2937/// cursors cannot yield multiple elements at once.
2938///
2939/// Cursors always point to a gap between two elements in the map, and can
2940/// operate on the two immediately adjacent elements.
2941///
2942/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
2943/// methods.
2944#[unstable(feature = "btree_cursors", issue = "107540")]
2945pub struct CursorMut<
2946    'a,
2947    K: 'a,
2948    V: 'a,
2949    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
2950> {
2951    inner: CursorMutKey<'a, K, V, A>,
2952}
2953
2954#[unstable(feature = "btree_cursors", issue = "107540")]
2955impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
2956    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2957        f.write_str("CursorMut")
2958    }
2959}
2960
2961/// A cursor over a `BTreeMap` with editing operations, and which allows
2962/// mutating the key of elements.
2963///
2964/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2965/// safely mutate the map during iteration. This is because the lifetime of its yielded
2966/// references is tied to its own lifetime, instead of just the underlying map. This means
2967/// cursors cannot yield multiple elements at once.
2968///
2969/// Cursors always point to a gap between two elements in the map, and can
2970/// operate on the two immediately adjacent elements.
2971///
2972/// A `CursorMutKey` is created from a [`CursorMut`] with the
2973/// [`CursorMut::with_mutable_key`] method.
2974///
2975/// # Safety
2976///
2977/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
2978/// invariants are maintained. Specifically:
2979///
2980/// * The key of the newly inserted element must be unique in the tree.
2981/// * All keys in the tree must remain in sorted order.
2982#[unstable(feature = "btree_cursors", issue = "107540")]
2983pub struct CursorMutKey<
2984    'a,
2985    K: 'a,
2986    V: 'a,
2987    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
2988> {
2989    // If current is None then it means the tree has not been allocated yet.
2990    current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2991    root: DormantMutRef<'a, Option<node::Root<K, V>>>,
2992    length: &'a mut usize,
2993    alloc: &'a mut A,
2994}
2995
2996#[unstable(feature = "btree_cursors", issue = "107540")]
2997impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
2998    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2999        f.write_str("CursorMutKey")
3000    }
3001}
3002
3003impl<'a, K, V> Cursor<'a, K, V> {
3004    /// Advances the cursor to the next gap, returning the key and value of the
3005    /// element that it moved over.
3006    ///
3007    /// If the cursor is already at the end of the map then `None` is returned
3008    /// and the cursor is not moved.
3009    #[unstable(feature = "btree_cursors", issue = "107540")]
3010    pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3011        let current = self.current.take()?;
3012        match current.next_kv() {
3013            Ok(kv) => {
3014                let result = kv.into_kv();
3015                self.current = Some(kv.next_leaf_edge());
3016                Some(result)
3017            }
3018            Err(root) => {
3019                self.current = Some(root.last_leaf_edge());
3020                None
3021            }
3022        }
3023    }
3024
3025    /// Advances the cursor to the previous gap, returning the key and value of
3026    /// the element that it moved over.
3027    ///
3028    /// If the cursor is already at the start of the map then `None` is returned
3029    /// and the cursor is not moved.
3030    #[unstable(feature = "btree_cursors", issue = "107540")]
3031    pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3032        let current = self.current.take()?;
3033        match current.next_back_kv() {
3034            Ok(kv) => {
3035                let result = kv.into_kv();
3036                self.current = Some(kv.next_back_leaf_edge());
3037                Some(result)
3038            }
3039            Err(root) => {
3040                self.current = Some(root.first_leaf_edge());
3041                None
3042            }
3043        }
3044    }
3045
3046    /// Returns a reference to the key and value of the next element without
3047    /// moving the cursor.
3048    ///
3049    /// If the cursor is at the end of the map then `None` is returned.
3050    #[unstable(feature = "btree_cursors", issue = "107540")]
3051    pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3052        self.clone().next()
3053    }
3054
3055    /// Returns a reference to the key and value of the previous element
3056    /// without moving the cursor.
3057    ///
3058    /// If the cursor is at the start of the map then `None` is returned.
3059    #[unstable(feature = "btree_cursors", issue = "107540")]
3060    pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3061        self.clone().prev()
3062    }
3063}
3064
3065impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3066    /// Advances the cursor to the next gap, returning the key and value of the
3067    /// element that it moved over.
3068    ///
3069    /// If the cursor is already at the end of the map then `None` is returned
3070    /// and the cursor is not moved.
3071    #[unstable(feature = "btree_cursors", issue = "107540")]
3072    pub fn next(&mut self) -> Option<(&K, &mut V)> {
3073        let (k, v) = self.inner.next()?;
3074        Some((&*k, v))
3075    }
3076
3077    /// Advances the cursor to the previous gap, returning the key and value of
3078    /// the element that it moved over.
3079    ///
3080    /// If the cursor is already at the start of the map then `None` is returned
3081    /// and the cursor is not moved.
3082    #[unstable(feature = "btree_cursors", issue = "107540")]
3083    pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3084        let (k, v) = self.inner.prev()?;
3085        Some((&*k, v))
3086    }
3087
3088    /// Returns a reference to the key and value of the next element without
3089    /// moving the cursor.
3090    ///
3091    /// If the cursor is at the end of the map then `None` is returned.
3092    #[unstable(feature = "btree_cursors", issue = "107540")]
3093    pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3094        let (k, v) = self.inner.peek_next()?;
3095        Some((&*k, v))
3096    }
3097
3098    /// Returns a reference to the key and value of the previous element
3099    /// without moving the cursor.
3100    ///
3101    /// If the cursor is at the start of the map then `None` is returned.
3102    #[unstable(feature = "btree_cursors", issue = "107540")]
3103    pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3104        let (k, v) = self.inner.peek_prev()?;
3105        Some((&*k, v))
3106    }
3107
3108    /// Returns a read-only cursor pointing to the same location as the
3109    /// `CursorMut`.
3110    ///
3111    /// The lifetime of the returned `Cursor` is bound to that of the
3112    /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3113    /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3114    #[unstable(feature = "btree_cursors", issue = "107540")]
3115    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3116        self.inner.as_cursor()
3117    }
3118
3119    /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3120    /// the key of elements in the tree.
3121    ///
3122    /// # Safety
3123    ///
3124    /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3125    /// invariants are maintained. Specifically:
3126    ///
3127    /// * The key of the newly inserted element must be unique in the tree.
3128    /// * All keys in the tree must remain in sorted order.
3129    #[unstable(feature = "btree_cursors", issue = "107540")]
3130    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3131        self.inner
3132    }
3133}
3134
3135impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3136    /// Advances the cursor to the next gap, returning the key and value of the
3137    /// element that it moved over.
3138    ///
3139    /// If the cursor is already at the end of the map then `None` is returned
3140    /// and the cursor is not moved.
3141    #[unstable(feature = "btree_cursors", issue = "107540")]
3142    pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3143        let current = self.current.take()?;
3144        match current.next_kv() {
3145            Ok(mut kv) => {
3146                // SAFETY: The key/value pointers remain valid even after the
3147                // cursor is moved forward. The lifetimes then prevent any
3148                // further access to the cursor.
3149                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3150                let (k, v) = (k as *mut _, v as *mut _);
3151                self.current = Some(kv.next_leaf_edge());
3152                Some(unsafe { (&mut *k, &mut *v) })
3153            }
3154            Err(root) => {
3155                self.current = Some(root.last_leaf_edge());
3156                None
3157            }
3158        }
3159    }
3160
3161    /// Advances the cursor to the previous gap, returning the key and value of
3162    /// the element that it moved over.
3163    ///
3164    /// If the cursor is already at the start of the map then `None` is returned
3165    /// and the cursor is not moved.
3166    #[unstable(feature = "btree_cursors", issue = "107540")]
3167    pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3168        let current = self.current.take()?;
3169        match current.next_back_kv() {
3170            Ok(mut kv) => {
3171                // SAFETY: The key/value pointers remain valid even after the
3172                // cursor is moved forward. The lifetimes then prevent any
3173                // further access to the cursor.
3174                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3175                let (k, v) = (k as *mut _, v as *mut _);
3176                self.current = Some(kv.next_back_leaf_edge());
3177                Some(unsafe { (&mut *k, &mut *v) })
3178            }
3179            Err(root) => {
3180                self.current = Some(root.first_leaf_edge());
3181                None
3182            }
3183        }
3184    }
3185
3186    /// Returns a reference to the key and value of the next element without
3187    /// moving the cursor.
3188    ///
3189    /// If the cursor is at the end of the map then `None` is returned.
3190    #[unstable(feature = "btree_cursors", issue = "107540")]
3191    pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3192        let current = self.current.as_mut()?;
3193        // SAFETY: We're not using this to mutate the tree.
3194        let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3195        Some(kv)
3196    }
3197
3198    /// Returns a reference to the key and value of the previous element
3199    /// without moving the cursor.
3200    ///
3201    /// If the cursor is at the start of the map then `None` is returned.
3202    #[unstable(feature = "btree_cursors", issue = "107540")]
3203    pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3204        let current = self.current.as_mut()?;
3205        // SAFETY: We're not using this to mutate the tree.
3206        let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3207        Some(kv)
3208    }
3209
3210    /// Returns a read-only cursor pointing to the same location as the
3211    /// `CursorMutKey`.
3212    ///
3213    /// The lifetime of the returned `Cursor` is bound to that of the
3214    /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3215    /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3216    #[unstable(feature = "btree_cursors", issue = "107540")]
3217    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3218        Cursor {
3219            // SAFETY: The tree is immutable while the cursor exists.
3220            root: unsafe { self.root.reborrow_shared().as_ref() },
3221            current: self.current.as_ref().map(|current| current.reborrow()),
3222        }
3223    }
3224}
3225
3226// Now the tree editing operations
3227impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> {
3228    /// Inserts a new key-value pair into the map in the gap that the
3229    /// cursor is currently pointing to.
3230    ///
3231    /// After the insertion the cursor will be pointing at the gap before the
3232    /// newly inserted element.
3233    ///
3234    /// # Safety
3235    ///
3236    /// You must ensure that the `BTreeMap` invariants are maintained.
3237    /// Specifically:
3238    ///
3239    /// * The key of the newly inserted element must be unique in the tree.
3240    /// * All keys in the tree must remain in sorted order.
3241    #[unstable(feature = "btree_cursors", issue = "107540")]
3242    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3243        let edge = match self.current.take() {
3244            None => {
3245                // Tree is empty, allocate a new root.
3246                // SAFETY: We have no other reference to the tree.
3247                let root = unsafe { self.root.reborrow() };
3248                debug_assert!(root.is_none());
3249                let mut node = NodeRef::new_leaf(self.alloc.clone());
3250                // SAFETY: We don't touch the root while the handle is alive.
3251                let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3252                *root = Some(node.forget_type());
3253                *self.length += 1;
3254                self.current = Some(handle.left_edge());
3255                return;
3256            }
3257            Some(current) => current,
3258        };
3259
3260        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3261            drop(ins.left);
3262            // SAFETY: The handle to the newly inserted value is always on a
3263            // leaf node, so adding a new root node doesn't invalidate it.
3264            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3265            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3266        });
3267        self.current = Some(handle.left_edge());
3268        *self.length += 1;
3269    }
3270
3271    /// Inserts a new key-value pair into the map in the gap that the
3272    /// cursor is currently pointing to.
3273    ///
3274    /// After the insertion the cursor will be pointing at the gap after the
3275    /// newly inserted element.
3276    ///
3277    /// # Safety
3278    ///
3279    /// You must ensure that the `BTreeMap` invariants are maintained.
3280    /// Specifically:
3281    ///
3282    /// * The key of the newly inserted element must be unique in the tree.
3283    /// * All keys in the tree must remain in sorted order.
3284    #[unstable(feature = "btree_cursors", issue = "107540")]
3285    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3286        let edge = match self.current.take() {
3287            None => {
3288                // SAFETY: We have no other reference to the tree.
3289                match unsafe { self.root.reborrow() } {
3290                    root @ None => {
3291                        // Tree is empty, allocate a new root.
3292                        let mut node = NodeRef::new_leaf(self.alloc.clone());
3293                        // SAFETY: We don't touch the root while the handle is alive.
3294                        let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3295                        *root = Some(node.forget_type());
3296                        *self.length += 1;
3297                        self.current = Some(handle.right_edge());
3298                        return;
3299                    }
3300                    Some(root) => root.borrow_mut().last_leaf_edge(),
3301                }
3302            }
3303            Some(current) => current,
3304        };
3305
3306        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3307            drop(ins.left);
3308            // SAFETY: The handle to the newly inserted value is always on a
3309            // leaf node, so adding a new root node doesn't invalidate it.
3310            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3311            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3312        });
3313        self.current = Some(handle.right_edge());
3314        *self.length += 1;
3315    }
3316
3317    /// Inserts a new key-value pair into the map in the gap that the
3318    /// cursor is currently pointing to.
3319    ///
3320    /// After the insertion the cursor will be pointing at the gap before the
3321    /// newly inserted element.
3322    ///
3323    /// If the inserted key is not greater than the key before the cursor
3324    /// (if any), or if it not less than the key after the cursor (if any),
3325    /// then an [`UnorderedKeyError`] is returned since this would
3326    /// invalidate the [`Ord`] invariant between the keys of the map.
3327    #[unstable(feature = "btree_cursors", issue = "107540")]
3328    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3329        if let Some((prev, _)) = self.peek_prev() {
3330            if &key <= prev {
3331                return Err(UnorderedKeyError {});
3332            }
3333        }
3334        if let Some((next, _)) = self.peek_next() {
3335            if &key >= next {
3336                return Err(UnorderedKeyError {});
3337            }
3338        }
3339        unsafe {
3340            self.insert_after_unchecked(key, value);
3341        }
3342        Ok(())
3343    }
3344
3345    /// Inserts a new key-value pair into the map in the gap that the
3346    /// cursor is currently pointing to.
3347    ///
3348    /// After the insertion the cursor will be pointing at the gap after the
3349    /// newly inserted element.
3350    ///
3351    /// If the inserted key is not greater than the key before the cursor
3352    /// (if any), or if it not less than the key after the cursor (if any),
3353    /// then an [`UnorderedKeyError`] is returned since this would
3354    /// invalidate the [`Ord`] invariant between the keys of the map.
3355    #[unstable(feature = "btree_cursors", issue = "107540")]
3356    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3357        if let Some((prev, _)) = self.peek_prev() {
3358            if &key <= prev {
3359                return Err(UnorderedKeyError {});
3360            }
3361        }
3362        if let Some((next, _)) = self.peek_next() {
3363            if &key >= next {
3364                return Err(UnorderedKeyError {});
3365            }
3366        }
3367        unsafe {
3368            self.insert_before_unchecked(key, value);
3369        }
3370        Ok(())
3371    }
3372
3373    /// Removes the next element from the `BTreeMap`.
3374    ///
3375    /// The element that was removed is returned. The cursor position is
3376    /// unchanged (before the removed element).
3377    #[unstable(feature = "btree_cursors", issue = "107540")]
3378    pub fn remove_next(&mut self) -> Option<(K, V)> {
3379        let current = self.current.take()?;
3380        if current.reborrow().next_kv().is_err() {
3381            self.current = Some(current);
3382            return None;
3383        }
3384        let mut emptied_internal_root = false;
3385        let (kv, pos) = current
3386            .next_kv()
3387            // This should be unwrap(), but that doesn't work because NodeRef
3388            // doesn't implement Debug. The condition is checked above.
3389            .ok()?
3390            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3391        self.current = Some(pos);
3392        *self.length -= 1;
3393        if emptied_internal_root {
3394            // SAFETY: This is safe since current does not point within the now
3395            // empty root node.
3396            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3397            root.pop_internal_level(self.alloc.clone());
3398        }
3399        Some(kv)
3400    }
3401
3402    /// Removes the preceding element from the `BTreeMap`.
3403    ///
3404    /// The element that was removed is returned. The cursor position is
3405    /// unchanged (after the removed element).
3406    #[unstable(feature = "btree_cursors", issue = "107540")]
3407    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3408        let current = self.current.take()?;
3409        if current.reborrow().next_back_kv().is_err() {
3410            self.current = Some(current);
3411            return None;
3412        }
3413        let mut emptied_internal_root = false;
3414        let (kv, pos) = current
3415            .next_back_kv()
3416            // This should be unwrap(), but that doesn't work because NodeRef
3417            // doesn't implement Debug. The condition is checked above.
3418            .ok()?
3419            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3420        self.current = Some(pos);
3421        *self.length -= 1;
3422        if emptied_internal_root {
3423            // SAFETY: This is safe since current does not point within the now
3424            // empty root node.
3425            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3426            root.pop_internal_level(self.alloc.clone());
3427        }
3428        Some(kv)
3429    }
3430}
3431
3432impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> {
3433    /// Inserts a new key-value pair into the map in the gap that the
3434    /// cursor is currently pointing to.
3435    ///
3436    /// After the insertion the cursor will be pointing at the gap after the
3437    /// newly inserted element.
3438    ///
3439    /// # Safety
3440    ///
3441    /// You must ensure that the `BTreeMap` invariants are maintained.
3442    /// Specifically:
3443    ///
3444    /// * The key of the newly inserted element must be unique in the tree.
3445    /// * All keys in the tree must remain in sorted order.
3446    #[unstable(feature = "btree_cursors", issue = "107540")]
3447    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3448        unsafe { self.inner.insert_after_unchecked(key, value) }
3449    }
3450
3451    /// Inserts a new key-value pair into the map in the gap that the
3452    /// cursor is currently pointing to.
3453    ///
3454    /// After the insertion the cursor will be pointing at the gap after the
3455    /// newly inserted element.
3456    ///
3457    /// # Safety
3458    ///
3459    /// You must ensure that the `BTreeMap` invariants are maintained.
3460    /// Specifically:
3461    ///
3462    /// * The key of the newly inserted element must be unique in the tree.
3463    /// * All keys in the tree must remain in sorted order.
3464    #[unstable(feature = "btree_cursors", issue = "107540")]
3465    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3466        unsafe { self.inner.insert_before_unchecked(key, value) }
3467    }
3468
3469    /// Inserts a new key-value pair into the map in the gap that the
3470    /// cursor is currently pointing to.
3471    ///
3472    /// After the insertion the cursor will be pointing at the gap before the
3473    /// newly inserted element.
3474    ///
3475    /// If the inserted key is not greater than the key before the cursor
3476    /// (if any), or if it not less than the key after the cursor (if any),
3477    /// then an [`UnorderedKeyError`] is returned since this would
3478    /// invalidate the [`Ord`] invariant between the keys of the map.
3479    #[unstable(feature = "btree_cursors", issue = "107540")]
3480    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3481        self.inner.insert_after(key, value)
3482    }
3483
3484    /// Inserts a new key-value pair into the map in the gap that the
3485    /// cursor is currently pointing to.
3486    ///
3487    /// After the insertion the cursor will be pointing at the gap after the
3488    /// newly inserted element.
3489    ///
3490    /// If the inserted key is not greater than the key before the cursor
3491    /// (if any), or if it not less than the key after the cursor (if any),
3492    /// then an [`UnorderedKeyError`] is returned since this would
3493    /// invalidate the [`Ord`] invariant between the keys of the map.
3494    #[unstable(feature = "btree_cursors", issue = "107540")]
3495    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3496        self.inner.insert_before(key, value)
3497    }
3498
3499    /// Removes the next element from the `BTreeMap`.
3500    ///
3501    /// The element that was removed is returned. The cursor position is
3502    /// unchanged (before the removed element).
3503    #[unstable(feature = "btree_cursors", issue = "107540")]
3504    pub fn remove_next(&mut self) -> Option<(K, V)> {
3505        self.inner.remove_next()
3506    }
3507
3508    /// Removes the preceding element from the `BTreeMap`.
3509    ///
3510    /// The element that was removed is returned. The cursor position is
3511    /// unchanged (after the removed element).
3512    #[unstable(feature = "btree_cursors", issue = "107540")]
3513    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3514        self.inner.remove_prev()
3515    }
3516}
3517
3518/// Error type returned by [`CursorMut::insert_before`] and
3519/// [`CursorMut::insert_after`] if the key being inserted is not properly
3520/// ordered with regards to adjacent keys.
3521#[derive(Clone, PartialEq, Eq, Debug)]
3522#[unstable(feature = "btree_cursors", issue = "107540")]
3523pub struct UnorderedKeyError {}
3524
3525#[unstable(feature = "btree_cursors", issue = "107540")]
3526impl fmt::Display for UnorderedKeyError {
3527    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3528        write!(f, "key is not properly ordered relative to neighbors")
3529    }
3530}
3531
3532#[unstable(feature = "btree_cursors", issue = "107540")]
3533impl Error for UnorderedKeyError {}
3534
3535#[cfg(test)]
3536mod tests;