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    /// use std::collections::BTreeMap;
1437    ///
1438    /// // Splitting a map into even and odd keys, reusing the original map:
1439    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1440    /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1441    /// let odds = map;
1442    /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1443    /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1444    ///
1445    /// // Splitting a map into low and high halves, reusing the original map:
1446    /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1447    /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1448    /// let high = map;
1449    /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1450    /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1451    /// ```
1452    #[stable(feature = "btree_extract_if", since = "CURRENT_RUSTC_VERSION")]
1453    pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1454    where
1455        K: Ord,
1456        R: RangeBounds<K>,
1457        F: FnMut(&K, &mut V) -> bool,
1458    {
1459        let (inner, alloc) = self.extract_if_inner(range);
1460        ExtractIf { pred, inner, alloc }
1461    }
1462
1463    pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1464    where
1465        K: Ord,
1466        R: RangeBounds<K>,
1467    {
1468        if let Some(root) = self.root.as_mut() {
1469            let (root, dormant_root) = DormantMutRef::new(root);
1470            let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1471            (
1472                ExtractIfInner {
1473                    length: &mut self.length,
1474                    dormant_root: Some(dormant_root),
1475                    cur_leaf_edge: Some(first),
1476                    range,
1477                },
1478                (*self.alloc).clone(),
1479            )
1480        } else {
1481            (
1482                ExtractIfInner {
1483                    length: &mut self.length,
1484                    dormant_root: None,
1485                    cur_leaf_edge: None,
1486                    range,
1487                },
1488                (*self.alloc).clone(),
1489            )
1490        }
1491    }
1492
1493    /// Creates a consuming iterator visiting all the keys, in sorted order.
1494    /// The map cannot be used after calling this.
1495    /// The iterator element type is `K`.
1496    ///
1497    /// # Examples
1498    ///
1499    /// ```
1500    /// use std::collections::BTreeMap;
1501    ///
1502    /// let mut a = BTreeMap::new();
1503    /// a.insert(2, "b");
1504    /// a.insert(1, "a");
1505    ///
1506    /// let keys: Vec<i32> = a.into_keys().collect();
1507    /// assert_eq!(keys, [1, 2]);
1508    /// ```
1509    #[inline]
1510    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1511    pub fn into_keys(self) -> IntoKeys<K, V, A> {
1512        IntoKeys { inner: self.into_iter() }
1513    }
1514
1515    /// Creates a consuming iterator visiting all the values, in order by key.
1516    /// The map cannot be used after calling this.
1517    /// The iterator element type is `V`.
1518    ///
1519    /// # Examples
1520    ///
1521    /// ```
1522    /// use std::collections::BTreeMap;
1523    ///
1524    /// let mut a = BTreeMap::new();
1525    /// a.insert(1, "hello");
1526    /// a.insert(2, "goodbye");
1527    ///
1528    /// let values: Vec<&str> = a.into_values().collect();
1529    /// assert_eq!(values, ["hello", "goodbye"]);
1530    /// ```
1531    #[inline]
1532    #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1533    pub fn into_values(self) -> IntoValues<K, V, A> {
1534        IntoValues { inner: self.into_iter() }
1535    }
1536
1537    /// Makes a `BTreeMap` from a sorted iterator.
1538    pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1539    where
1540        K: Ord,
1541        I: IntoIterator<Item = (K, V)>,
1542    {
1543        let mut root = Root::new(alloc.clone());
1544        let mut length = 0;
1545        root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1546        BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1547    }
1548}
1549
1550#[stable(feature = "rust1", since = "1.0.0")]
1551impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, A> {
1552    type Item = (&'a K, &'a V);
1553    type IntoIter = Iter<'a, K, V>;
1554
1555    fn into_iter(self) -> Iter<'a, K, V> {
1556        self.iter()
1557    }
1558}
1559
1560#[stable(feature = "rust1", since = "1.0.0")]
1561impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1562    type Item = (&'a K, &'a V);
1563
1564    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1565        if self.length == 0 {
1566            None
1567        } else {
1568            self.length -= 1;
1569            Some(unsafe { self.range.next_unchecked() })
1570        }
1571    }
1572
1573    fn size_hint(&self) -> (usize, Option<usize>) {
1574        (self.length, Some(self.length))
1575    }
1576
1577    fn last(mut self) -> Option<(&'a K, &'a V)> {
1578        self.next_back()
1579    }
1580
1581    fn min(mut self) -> Option<(&'a K, &'a V)>
1582    where
1583        (&'a K, &'a V): Ord,
1584    {
1585        self.next()
1586    }
1587
1588    fn max(mut self) -> Option<(&'a K, &'a V)>
1589    where
1590        (&'a K, &'a V): Ord,
1591    {
1592        self.next_back()
1593    }
1594}
1595
1596#[stable(feature = "fused", since = "1.26.0")]
1597impl<K, V> FusedIterator for Iter<'_, K, V> {}
1598
1599#[stable(feature = "rust1", since = "1.0.0")]
1600impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1601    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1602        if self.length == 0 {
1603            None
1604        } else {
1605            self.length -= 1;
1606            Some(unsafe { self.range.next_back_unchecked() })
1607        }
1608    }
1609}
1610
1611#[stable(feature = "rust1", since = "1.0.0")]
1612impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1613    fn len(&self) -> usize {
1614        self.length
1615    }
1616}
1617
1618#[stable(feature = "rust1", since = "1.0.0")]
1619impl<K, V> Clone for Iter<'_, K, V> {
1620    fn clone(&self) -> Self {
1621        Iter { range: self.range.clone(), length: self.length }
1622    }
1623}
1624
1625#[stable(feature = "rust1", since = "1.0.0")]
1626impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1627    type Item = (&'a K, &'a mut V);
1628    type IntoIter = IterMut<'a, K, V>;
1629
1630    fn into_iter(self) -> IterMut<'a, K, V> {
1631        self.iter_mut()
1632    }
1633}
1634
1635#[stable(feature = "rust1", since = "1.0.0")]
1636impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1637    type Item = (&'a K, &'a mut V);
1638
1639    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1640        if self.length == 0 {
1641            None
1642        } else {
1643            self.length -= 1;
1644            Some(unsafe { self.range.next_unchecked() })
1645        }
1646    }
1647
1648    fn size_hint(&self) -> (usize, Option<usize>) {
1649        (self.length, Some(self.length))
1650    }
1651
1652    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1653        self.next_back()
1654    }
1655
1656    fn min(mut self) -> Option<(&'a K, &'a mut V)>
1657    where
1658        (&'a K, &'a mut V): Ord,
1659    {
1660        self.next()
1661    }
1662
1663    fn max(mut self) -> Option<(&'a K, &'a mut V)>
1664    where
1665        (&'a K, &'a mut V): Ord,
1666    {
1667        self.next_back()
1668    }
1669}
1670
1671#[stable(feature = "rust1", since = "1.0.0")]
1672impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1673    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1674        if self.length == 0 {
1675            None
1676        } else {
1677            self.length -= 1;
1678            Some(unsafe { self.range.next_back_unchecked() })
1679        }
1680    }
1681}
1682
1683#[stable(feature = "rust1", since = "1.0.0")]
1684impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1685    fn len(&self) -> usize {
1686        self.length
1687    }
1688}
1689
1690#[stable(feature = "fused", since = "1.26.0")]
1691impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1692
1693impl<'a, K, V> IterMut<'a, K, V> {
1694    /// Returns an iterator of references over the remaining items.
1695    #[inline]
1696    pub(super) fn iter(&self) -> Iter<'_, K, V> {
1697        Iter { range: self.range.reborrow(), length: self.length }
1698    }
1699}
1700
1701#[stable(feature = "rust1", since = "1.0.0")]
1702impl<K, V, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, A> {
1703    type Item = (K, V);
1704    type IntoIter = IntoIter<K, V, A>;
1705
1706    /// Gets an owning iterator over the entries of the map, sorted by key.
1707    fn into_iter(self) -> IntoIter<K, V, A> {
1708        let mut me = ManuallyDrop::new(self);
1709        if let Some(root) = me.root.take() {
1710            let full_range = root.into_dying().full_range();
1711
1712            IntoIter {
1713                range: full_range,
1714                length: me.length,
1715                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1716            }
1717        } else {
1718            IntoIter {
1719                range: LazyLeafRange::none(),
1720                length: 0,
1721                alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1722            }
1723        }
1724    }
1725}
1726
1727#[stable(feature = "btree_drop", since = "1.7.0")]
1728impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1729    fn drop(&mut self) {
1730        struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1731
1732        impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1733            fn drop(&mut self) {
1734                // Continue the same loop we perform below. This only runs when unwinding, so we
1735                // don't have to care about panics this time (they'll abort).
1736                while let Some(kv) = self.0.dying_next() {
1737                    // SAFETY: we consume the dying handle immediately.
1738                    unsafe { kv.drop_key_val() };
1739                }
1740            }
1741        }
1742
1743        while let Some(kv) = self.dying_next() {
1744            let guard = DropGuard(self);
1745            // SAFETY: we don't touch the tree before consuming the dying handle.
1746            unsafe { kv.drop_key_val() };
1747            mem::forget(guard);
1748        }
1749    }
1750}
1751
1752impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1753    /// Core of a `next` method returning a dying KV handle,
1754    /// invalidated by further calls to this function and some others.
1755    fn dying_next(
1756        &mut self,
1757    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1758        if self.length == 0 {
1759            self.range.deallocating_end(self.alloc.clone());
1760            None
1761        } else {
1762            self.length -= 1;
1763            Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1764        }
1765    }
1766
1767    /// Core of a `next_back` method returning a dying KV handle,
1768    /// invalidated by further calls to this function and some others.
1769    fn dying_next_back(
1770        &mut self,
1771    ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1772        if self.length == 0 {
1773            self.range.deallocating_end(self.alloc.clone());
1774            None
1775        } else {
1776            self.length -= 1;
1777            Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1778        }
1779    }
1780}
1781
1782#[stable(feature = "rust1", since = "1.0.0")]
1783impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1784    type Item = (K, V);
1785
1786    fn next(&mut self) -> Option<(K, V)> {
1787        // SAFETY: we consume the dying handle immediately.
1788        self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1789    }
1790
1791    fn size_hint(&self) -> (usize, Option<usize>) {
1792        (self.length, Some(self.length))
1793    }
1794}
1795
1796#[stable(feature = "rust1", since = "1.0.0")]
1797impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1798    fn next_back(&mut self) -> Option<(K, V)> {
1799        // SAFETY: we consume the dying handle immediately.
1800        self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1801    }
1802}
1803
1804#[stable(feature = "rust1", since = "1.0.0")]
1805impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1806    fn len(&self) -> usize {
1807        self.length
1808    }
1809}
1810
1811#[stable(feature = "fused", since = "1.26.0")]
1812impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1813
1814#[stable(feature = "rust1", since = "1.0.0")]
1815impl<'a, K, V> Iterator for Keys<'a, K, V> {
1816    type Item = &'a K;
1817
1818    fn next(&mut self) -> Option<&'a K> {
1819        self.inner.next().map(|(k, _)| k)
1820    }
1821
1822    fn size_hint(&self) -> (usize, Option<usize>) {
1823        self.inner.size_hint()
1824    }
1825
1826    fn last(mut self) -> Option<&'a K> {
1827        self.next_back()
1828    }
1829
1830    fn min(mut self) -> Option<&'a K>
1831    where
1832        &'a K: Ord,
1833    {
1834        self.next()
1835    }
1836
1837    fn max(mut self) -> Option<&'a K>
1838    where
1839        &'a K: Ord,
1840    {
1841        self.next_back()
1842    }
1843}
1844
1845#[stable(feature = "rust1", since = "1.0.0")]
1846impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1847    fn next_back(&mut self) -> Option<&'a K> {
1848        self.inner.next_back().map(|(k, _)| k)
1849    }
1850}
1851
1852#[stable(feature = "rust1", since = "1.0.0")]
1853impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
1854    fn len(&self) -> usize {
1855        self.inner.len()
1856    }
1857}
1858
1859#[stable(feature = "fused", since = "1.26.0")]
1860impl<K, V> FusedIterator for Keys<'_, K, V> {}
1861
1862#[stable(feature = "rust1", since = "1.0.0")]
1863impl<K, V> Clone for Keys<'_, K, V> {
1864    fn clone(&self) -> Self {
1865        Keys { inner: self.inner.clone() }
1866    }
1867}
1868
1869#[stable(feature = "default_iters", since = "1.70.0")]
1870impl<K, V> Default for Keys<'_, K, V> {
1871    /// Creates an empty `btree_map::Keys`.
1872    ///
1873    /// ```
1874    /// # use std::collections::btree_map;
1875    /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
1876    /// assert_eq!(iter.len(), 0);
1877    /// ```
1878    fn default() -> Self {
1879        Keys { inner: Default::default() }
1880    }
1881}
1882
1883#[stable(feature = "rust1", since = "1.0.0")]
1884impl<'a, K, V> Iterator for Values<'a, K, V> {
1885    type Item = &'a V;
1886
1887    fn next(&mut self) -> Option<&'a V> {
1888        self.inner.next().map(|(_, v)| v)
1889    }
1890
1891    fn size_hint(&self) -> (usize, Option<usize>) {
1892        self.inner.size_hint()
1893    }
1894
1895    fn last(mut self) -> Option<&'a V> {
1896        self.next_back()
1897    }
1898}
1899
1900#[stable(feature = "rust1", since = "1.0.0")]
1901impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1902    fn next_back(&mut self) -> Option<&'a V> {
1903        self.inner.next_back().map(|(_, v)| v)
1904    }
1905}
1906
1907#[stable(feature = "rust1", since = "1.0.0")]
1908impl<K, V> ExactSizeIterator for Values<'_, K, V> {
1909    fn len(&self) -> usize {
1910        self.inner.len()
1911    }
1912}
1913
1914#[stable(feature = "fused", since = "1.26.0")]
1915impl<K, V> FusedIterator for Values<'_, K, V> {}
1916
1917#[stable(feature = "rust1", since = "1.0.0")]
1918impl<K, V> Clone for Values<'_, K, V> {
1919    fn clone(&self) -> Self {
1920        Values { inner: self.inner.clone() }
1921    }
1922}
1923
1924#[stable(feature = "default_iters", since = "1.70.0")]
1925impl<K, V> Default for Values<'_, K, V> {
1926    /// Creates an empty `btree_map::Values`.
1927    ///
1928    /// ```
1929    /// # use std::collections::btree_map;
1930    /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
1931    /// assert_eq!(iter.len(), 0);
1932    /// ```
1933    fn default() -> Self {
1934        Values { inner: Default::default() }
1935    }
1936}
1937
1938/// An iterator produced by calling `extract_if` on BTreeMap.
1939#[stable(feature = "btree_extract_if", since = "CURRENT_RUSTC_VERSION")]
1940#[must_use = "iterators are lazy and do nothing unless consumed"]
1941pub struct ExtractIf<
1942    'a,
1943    K,
1944    V,
1945    R,
1946    F,
1947    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
1948> {
1949    pred: F,
1950    inner: ExtractIfInner<'a, K, V, R>,
1951    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
1952    alloc: A,
1953}
1954
1955/// Most of the implementation of ExtractIf are generic over the type
1956/// of the predicate, thus also serving for BTreeSet::ExtractIf.
1957pub(super) struct ExtractIfInner<'a, K, V, R> {
1958    /// Reference to the length field in the borrowed map, updated live.
1959    length: &'a mut usize,
1960    /// Buried reference to the root field in the borrowed map.
1961    /// Wrapped in `Option` to allow drop handler to `take` it.
1962    dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
1963    /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
1964    /// Empty if the map has no root, if iteration went beyond the last leaf edge,
1965    /// or if a panic occurred in the predicate.
1966    cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
1967    /// Range over which iteration was requested.  We don't need the left side, but we
1968    /// can't extract the right side without requiring K: Clone.
1969    range: R,
1970}
1971
1972#[stable(feature = "btree_extract_if", since = "CURRENT_RUSTC_VERSION")]
1973impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
1974where
1975    K: fmt::Debug,
1976    V: fmt::Debug,
1977    A: Allocator + Clone,
1978{
1979    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1980        f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
1981    }
1982}
1983
1984#[stable(feature = "btree_extract_if", since = "CURRENT_RUSTC_VERSION")]
1985impl<K, V, R, F, A: Allocator + Clone> Iterator for ExtractIf<'_, K, V, R, F, A>
1986where
1987    K: PartialOrd,
1988    R: RangeBounds<K>,
1989    F: FnMut(&K, &mut V) -> bool,
1990{
1991    type Item = (K, V);
1992
1993    fn next(&mut self) -> Option<(K, V)> {
1994        self.inner.next(&mut self.pred, self.alloc.clone())
1995    }
1996
1997    fn size_hint(&self) -> (usize, Option<usize>) {
1998        self.inner.size_hint()
1999    }
2000}
2001
2002impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2003    /// Allow Debug implementations to predict the next element.
2004    pub(super) fn peek(&self) -> Option<(&K, &V)> {
2005        let edge = self.cur_leaf_edge.as_ref()?;
2006        edge.reborrow().next_kv().ok().map(Handle::into_kv)
2007    }
2008
2009    /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2010    pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2011    where
2012        K: PartialOrd,
2013        R: RangeBounds<K>,
2014        F: FnMut(&K, &mut V) -> bool,
2015    {
2016        while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2017            let (k, v) = kv.kv_mut();
2018
2019            // On creation, we navigated directly to the left bound, so we need only check the
2020            // right bound here to decide whether to stop.
2021            match self.range.end_bound() {
2022                Bound::Included(ref end) if (*k).le(end) => (),
2023                Bound::Excluded(ref end) if (*k).lt(end) => (),
2024                Bound::Unbounded => (),
2025                _ => return None,
2026            }
2027
2028            if pred(k, v) {
2029                *self.length -= 1;
2030                let (kv, pos) = kv.remove_kv_tracking(
2031                    || {
2032                        // SAFETY: we will touch the root in a way that will not
2033                        // invalidate the position returned.
2034                        let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2035                        root.pop_internal_level(alloc.clone());
2036                        self.dormant_root = Some(DormantMutRef::new(root).1);
2037                    },
2038                    alloc.clone(),
2039                );
2040                self.cur_leaf_edge = Some(pos);
2041                return Some(kv);
2042            }
2043            self.cur_leaf_edge = Some(kv.next_leaf_edge());
2044        }
2045        None
2046    }
2047
2048    /// Implementation of a typical `ExtractIf::size_hint` method.
2049    pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2050        // In most of the btree iterators, `self.length` is the number of elements
2051        // yet to be visited. Here, it includes elements that were visited and that
2052        // the predicate decided not to drain. Making this upper bound more tight
2053        // during iteration would require an extra field.
2054        (0, Some(*self.length))
2055    }
2056}
2057
2058#[stable(feature = "btree_extract_if", since = "CURRENT_RUSTC_VERSION")]
2059impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2060where
2061    K: PartialOrd,
2062    R: RangeBounds<K>,
2063    F: FnMut(&K, &mut V) -> bool,
2064{
2065}
2066
2067#[stable(feature = "btree_range", since = "1.17.0")]
2068impl<'a, K, V> Iterator for Range<'a, K, V> {
2069    type Item = (&'a K, &'a V);
2070
2071    fn next(&mut self) -> Option<(&'a K, &'a V)> {
2072        self.inner.next_checked()
2073    }
2074
2075    fn last(mut self) -> Option<(&'a K, &'a V)> {
2076        self.next_back()
2077    }
2078
2079    fn min(mut self) -> Option<(&'a K, &'a V)>
2080    where
2081        (&'a K, &'a V): Ord,
2082    {
2083        self.next()
2084    }
2085
2086    fn max(mut self) -> Option<(&'a K, &'a V)>
2087    where
2088        (&'a K, &'a V): Ord,
2089    {
2090        self.next_back()
2091    }
2092}
2093
2094#[stable(feature = "default_iters", since = "1.70.0")]
2095impl<K, V> Default for Range<'_, K, V> {
2096    /// Creates an empty `btree_map::Range`.
2097    ///
2098    /// ```
2099    /// # use std::collections::btree_map;
2100    /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2101    /// assert_eq!(iter.count(), 0);
2102    /// ```
2103    fn default() -> Self {
2104        Range { inner: Default::default() }
2105    }
2106}
2107
2108#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2109impl<K, V> Default for RangeMut<'_, K, V> {
2110    /// Creates an empty `btree_map::RangeMut`.
2111    ///
2112    /// ```
2113    /// # use std::collections::btree_map;
2114    /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2115    /// assert_eq!(iter.count(), 0);
2116    /// ```
2117    fn default() -> Self {
2118        RangeMut { inner: Default::default(), _marker: PhantomData }
2119    }
2120}
2121
2122#[stable(feature = "map_values_mut", since = "1.10.0")]
2123impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2124    type Item = &'a mut V;
2125
2126    fn next(&mut self) -> Option<&'a mut V> {
2127        self.inner.next().map(|(_, v)| v)
2128    }
2129
2130    fn size_hint(&self) -> (usize, Option<usize>) {
2131        self.inner.size_hint()
2132    }
2133
2134    fn last(mut self) -> Option<&'a mut V> {
2135        self.next_back()
2136    }
2137}
2138
2139#[stable(feature = "map_values_mut", since = "1.10.0")]
2140impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2141    fn next_back(&mut self) -> Option<&'a mut V> {
2142        self.inner.next_back().map(|(_, v)| v)
2143    }
2144}
2145
2146#[stable(feature = "map_values_mut", since = "1.10.0")]
2147impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2148    fn len(&self) -> usize {
2149        self.inner.len()
2150    }
2151}
2152
2153#[stable(feature = "fused", since = "1.26.0")]
2154impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2155
2156#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2157impl<K, V> Default for ValuesMut<'_, K, V> {
2158    /// Creates an empty `btree_map::ValuesMut`.
2159    ///
2160    /// ```
2161    /// # use std::collections::btree_map;
2162    /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2163    /// assert_eq!(iter.count(), 0);
2164    /// ```
2165    fn default() -> Self {
2166        ValuesMut { inner: Default::default() }
2167    }
2168}
2169
2170#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2171impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
2172    type Item = K;
2173
2174    fn next(&mut self) -> Option<K> {
2175        self.inner.next().map(|(k, _)| k)
2176    }
2177
2178    fn size_hint(&self) -> (usize, Option<usize>) {
2179        self.inner.size_hint()
2180    }
2181
2182    fn last(mut self) -> Option<K> {
2183        self.next_back()
2184    }
2185
2186    fn min(mut self) -> Option<K>
2187    where
2188        K: Ord,
2189    {
2190        self.next()
2191    }
2192
2193    fn max(mut self) -> Option<K>
2194    where
2195        K: Ord,
2196    {
2197        self.next_back()
2198    }
2199}
2200
2201#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2202impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
2203    fn next_back(&mut self) -> Option<K> {
2204        self.inner.next_back().map(|(k, _)| k)
2205    }
2206}
2207
2208#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2209impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
2210    fn len(&self) -> usize {
2211        self.inner.len()
2212    }
2213}
2214
2215#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2216impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2217
2218#[stable(feature = "default_iters", since = "1.70.0")]
2219impl<K, V, A> Default for IntoKeys<K, V, A>
2220where
2221    A: Allocator + Default + Clone,
2222{
2223    /// Creates an empty `btree_map::IntoKeys`.
2224    ///
2225    /// ```
2226    /// # use std::collections::btree_map;
2227    /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2228    /// assert_eq!(iter.len(), 0);
2229    /// ```
2230    fn default() -> Self {
2231        IntoKeys { inner: Default::default() }
2232    }
2233}
2234
2235#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2236impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2237    type Item = V;
2238
2239    fn next(&mut self) -> Option<V> {
2240        self.inner.next().map(|(_, v)| v)
2241    }
2242
2243    fn size_hint(&self) -> (usize, Option<usize>) {
2244        self.inner.size_hint()
2245    }
2246
2247    fn last(mut self) -> Option<V> {
2248        self.next_back()
2249    }
2250}
2251
2252#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2253impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2254    fn next_back(&mut self) -> Option<V> {
2255        self.inner.next_back().map(|(_, v)| v)
2256    }
2257}
2258
2259#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2260impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2261    fn len(&self) -> usize {
2262        self.inner.len()
2263    }
2264}
2265
2266#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2267impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2268
2269#[stable(feature = "default_iters", since = "1.70.0")]
2270impl<K, V, A> Default for IntoValues<K, V, A>
2271where
2272    A: Allocator + Default + Clone,
2273{
2274    /// Creates an empty `btree_map::IntoValues`.
2275    ///
2276    /// ```
2277    /// # use std::collections::btree_map;
2278    /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2279    /// assert_eq!(iter.len(), 0);
2280    /// ```
2281    fn default() -> Self {
2282        IntoValues { inner: Default::default() }
2283    }
2284}
2285
2286#[stable(feature = "btree_range", since = "1.17.0")]
2287impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2288    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2289        self.inner.next_back_checked()
2290    }
2291}
2292
2293#[stable(feature = "fused", since = "1.26.0")]
2294impl<K, V> FusedIterator for Range<'_, K, V> {}
2295
2296#[stable(feature = "btree_range", since = "1.17.0")]
2297impl<K, V> Clone for Range<'_, K, V> {
2298    fn clone(&self) -> Self {
2299        Range { inner: self.inner.clone() }
2300    }
2301}
2302
2303#[stable(feature = "btree_range", since = "1.17.0")]
2304impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2305    type Item = (&'a K, &'a mut V);
2306
2307    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2308        self.inner.next_checked()
2309    }
2310
2311    fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2312        self.next_back()
2313    }
2314
2315    fn min(mut self) -> Option<(&'a K, &'a mut V)>
2316    where
2317        (&'a K, &'a mut V): Ord,
2318    {
2319        self.next()
2320    }
2321
2322    fn max(mut self) -> Option<(&'a K, &'a mut V)>
2323    where
2324        (&'a K, &'a mut V): Ord,
2325    {
2326        self.next_back()
2327    }
2328}
2329
2330#[stable(feature = "btree_range", since = "1.17.0")]
2331impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2332    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2333        self.inner.next_back_checked()
2334    }
2335}
2336
2337#[stable(feature = "fused", since = "1.26.0")]
2338impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2339
2340#[stable(feature = "rust1", since = "1.0.0")]
2341impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2342    /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2343    ///
2344    /// If the iterator produces any pairs with equal keys,
2345    /// all but one of the corresponding values will be dropped.
2346    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2347        let mut inputs: Vec<_> = iter.into_iter().collect();
2348
2349        if inputs.is_empty() {
2350            return BTreeMap::new();
2351        }
2352
2353        // use stable sort to preserve the insertion order.
2354        inputs.sort_by(|a, b| a.0.cmp(&b.0));
2355        BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2356    }
2357}
2358
2359#[stable(feature = "rust1", since = "1.0.0")]
2360impl<K: Ord, V, A: Allocator + Clone> Extend<(K, V)> for BTreeMap<K, V, A> {
2361    #[inline]
2362    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2363        iter.into_iter().for_each(move |(k, v)| {
2364            self.insert(k, v);
2365        });
2366    }
2367
2368    #[inline]
2369    fn extend_one(&mut self, (k, v): (K, V)) {
2370        self.insert(k, v);
2371    }
2372}
2373
2374#[stable(feature = "extend_ref", since = "1.2.0")]
2375impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)>
2376    for BTreeMap<K, V, A>
2377{
2378    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2379        self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2380    }
2381
2382    #[inline]
2383    fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2384        self.insert(k, v);
2385    }
2386}
2387
2388#[stable(feature = "rust1", since = "1.0.0")]
2389impl<K: Hash, V: Hash, A: Allocator + Clone> Hash for BTreeMap<K, V, A> {
2390    fn hash<H: Hasher>(&self, state: &mut H) {
2391        state.write_length_prefix(self.len());
2392        for elt in self {
2393            elt.hash(state);
2394        }
2395    }
2396}
2397
2398#[stable(feature = "rust1", since = "1.0.0")]
2399impl<K, V> Default for BTreeMap<K, V> {
2400    /// Creates an empty `BTreeMap`.
2401    fn default() -> BTreeMap<K, V> {
2402        BTreeMap::new()
2403    }
2404}
2405
2406#[stable(feature = "rust1", since = "1.0.0")]
2407impl<K: PartialEq, V: PartialEq, A: Allocator + Clone> PartialEq for BTreeMap<K, V, A> {
2408    fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2409        self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2410    }
2411}
2412
2413#[stable(feature = "rust1", since = "1.0.0")]
2414impl<K: Eq, V: Eq, A: Allocator + Clone> Eq for BTreeMap<K, V, A> {}
2415
2416#[stable(feature = "rust1", since = "1.0.0")]
2417impl<K: PartialOrd, V: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, A> {
2418    #[inline]
2419    fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2420        self.iter().partial_cmp(other.iter())
2421    }
2422}
2423
2424#[stable(feature = "rust1", since = "1.0.0")]
2425impl<K: Ord, V: Ord, A: Allocator + Clone> Ord for BTreeMap<K, V, A> {
2426    #[inline]
2427    fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2428        self.iter().cmp(other.iter())
2429    }
2430}
2431
2432#[stable(feature = "rust1", since = "1.0.0")]
2433impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for BTreeMap<K, V, A> {
2434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2435        f.debug_map().entries(self.iter()).finish()
2436    }
2437}
2438
2439#[stable(feature = "rust1", since = "1.0.0")]
2440impl<K, Q: ?Sized, V, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, A>
2441where
2442    K: Borrow<Q> + Ord,
2443    Q: Ord,
2444{
2445    type Output = V;
2446
2447    /// Returns a reference to the value corresponding to the supplied key.
2448    ///
2449    /// # Panics
2450    ///
2451    /// Panics if the key is not present in the `BTreeMap`.
2452    #[inline]
2453    fn index(&self, key: &Q) -> &V {
2454        self.get(key).expect("no entry found for key")
2455    }
2456}
2457
2458#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2459impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2460    /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2461    ///
2462    /// If any entries in the array have equal keys,
2463    /// all but one of the corresponding values will be dropped.
2464    ///
2465    /// ```
2466    /// use std::collections::BTreeMap;
2467    ///
2468    /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2469    /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2470    /// assert_eq!(map1, map2);
2471    /// ```
2472    fn from(mut arr: [(K, V); N]) -> Self {
2473        if N == 0 {
2474            return BTreeMap::new();
2475        }
2476
2477        // use stable sort to preserve the insertion order.
2478        arr.sort_by(|a, b| a.0.cmp(&b.0));
2479        BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2480    }
2481}
2482
2483impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
2484    /// Gets an iterator over the entries of the map, sorted by key.
2485    ///
2486    /// # Examples
2487    ///
2488    /// ```
2489    /// use std::collections::BTreeMap;
2490    ///
2491    /// let mut map = BTreeMap::new();
2492    /// map.insert(3, "c");
2493    /// map.insert(2, "b");
2494    /// map.insert(1, "a");
2495    ///
2496    /// for (key, value) in map.iter() {
2497    ///     println!("{key}: {value}");
2498    /// }
2499    ///
2500    /// let (first_key, first_value) = map.iter().next().unwrap();
2501    /// assert_eq!((*first_key, *first_value), (1, "a"));
2502    /// ```
2503    #[stable(feature = "rust1", since = "1.0.0")]
2504    pub fn iter(&self) -> Iter<'_, K, V> {
2505        if let Some(root) = &self.root {
2506            let full_range = root.reborrow().full_range();
2507
2508            Iter { range: full_range, length: self.length }
2509        } else {
2510            Iter { range: LazyLeafRange::none(), length: 0 }
2511        }
2512    }
2513
2514    /// Gets a mutable iterator over the entries of the map, sorted by key.
2515    ///
2516    /// # Examples
2517    ///
2518    /// ```
2519    /// use std::collections::BTreeMap;
2520    ///
2521    /// let mut map = BTreeMap::from([
2522    ///    ("a", 1),
2523    ///    ("b", 2),
2524    ///    ("c", 3),
2525    /// ]);
2526    ///
2527    /// // add 10 to the value if the key isn't "a"
2528    /// for (key, value) in map.iter_mut() {
2529    ///     if key != &"a" {
2530    ///         *value += 10;
2531    ///     }
2532    /// }
2533    /// ```
2534    #[stable(feature = "rust1", since = "1.0.0")]
2535    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2536        if let Some(root) = &mut self.root {
2537            let full_range = root.borrow_valmut().full_range();
2538
2539            IterMut { range: full_range, length: self.length, _marker: PhantomData }
2540        } else {
2541            IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2542        }
2543    }
2544
2545    /// Gets an iterator over the keys of the map, in sorted order.
2546    ///
2547    /// # Examples
2548    ///
2549    /// ```
2550    /// use std::collections::BTreeMap;
2551    ///
2552    /// let mut a = BTreeMap::new();
2553    /// a.insert(2, "b");
2554    /// a.insert(1, "a");
2555    ///
2556    /// let keys: Vec<_> = a.keys().cloned().collect();
2557    /// assert_eq!(keys, [1, 2]);
2558    /// ```
2559    #[stable(feature = "rust1", since = "1.0.0")]
2560    pub fn keys(&self) -> Keys<'_, K, V> {
2561        Keys { inner: self.iter() }
2562    }
2563
2564    /// Gets an iterator over the values of the map, in order by key.
2565    ///
2566    /// # Examples
2567    ///
2568    /// ```
2569    /// use std::collections::BTreeMap;
2570    ///
2571    /// let mut a = BTreeMap::new();
2572    /// a.insert(1, "hello");
2573    /// a.insert(2, "goodbye");
2574    ///
2575    /// let values: Vec<&str> = a.values().cloned().collect();
2576    /// assert_eq!(values, ["hello", "goodbye"]);
2577    /// ```
2578    #[stable(feature = "rust1", since = "1.0.0")]
2579    pub fn values(&self) -> Values<'_, K, V> {
2580        Values { inner: self.iter() }
2581    }
2582
2583    /// Gets a mutable iterator over the values of the map, in order by key.
2584    ///
2585    /// # Examples
2586    ///
2587    /// ```
2588    /// use std::collections::BTreeMap;
2589    ///
2590    /// let mut a = BTreeMap::new();
2591    /// a.insert(1, String::from("hello"));
2592    /// a.insert(2, String::from("goodbye"));
2593    ///
2594    /// for value in a.values_mut() {
2595    ///     value.push_str("!");
2596    /// }
2597    ///
2598    /// let values: Vec<String> = a.values().cloned().collect();
2599    /// assert_eq!(values, [String::from("hello!"),
2600    ///                     String::from("goodbye!")]);
2601    /// ```
2602    #[stable(feature = "map_values_mut", since = "1.10.0")]
2603    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2604        ValuesMut { inner: self.iter_mut() }
2605    }
2606
2607    /// Returns the number of elements in the map.
2608    ///
2609    /// # Examples
2610    ///
2611    /// ```
2612    /// use std::collections::BTreeMap;
2613    ///
2614    /// let mut a = BTreeMap::new();
2615    /// assert_eq!(a.len(), 0);
2616    /// a.insert(1, "a");
2617    /// assert_eq!(a.len(), 1);
2618    /// ```
2619    #[must_use]
2620    #[stable(feature = "rust1", since = "1.0.0")]
2621    #[rustc_const_unstable(
2622        feature = "const_btree_len",
2623        issue = "71835",
2624        implied_by = "const_btree_new"
2625    )]
2626    #[rustc_confusables("length", "size")]
2627    pub const fn len(&self) -> usize {
2628        self.length
2629    }
2630
2631    /// Returns `true` if the map contains no elements.
2632    ///
2633    /// # Examples
2634    ///
2635    /// ```
2636    /// use std::collections::BTreeMap;
2637    ///
2638    /// let mut a = BTreeMap::new();
2639    /// assert!(a.is_empty());
2640    /// a.insert(1, "a");
2641    /// assert!(!a.is_empty());
2642    /// ```
2643    #[must_use]
2644    #[stable(feature = "rust1", since = "1.0.0")]
2645    #[rustc_const_unstable(
2646        feature = "const_btree_len",
2647        issue = "71835",
2648        implied_by = "const_btree_new"
2649    )]
2650    pub const fn is_empty(&self) -> bool {
2651        self.len() == 0
2652    }
2653
2654    /// Returns a [`Cursor`] pointing at the gap before the smallest key
2655    /// greater than the given bound.
2656    ///
2657    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2658    /// gap before the smallest key greater than or equal to `x`.
2659    ///
2660    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2661    /// gap before the smallest key greater than `x`.
2662    ///
2663    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2664    /// gap before the smallest key in the map.
2665    ///
2666    /// # Examples
2667    ///
2668    /// ```
2669    /// #![feature(btree_cursors)]
2670    ///
2671    /// use std::collections::BTreeMap;
2672    /// use std::ops::Bound;
2673    ///
2674    /// let map = BTreeMap::from([
2675    ///     (1, "a"),
2676    ///     (2, "b"),
2677    ///     (3, "c"),
2678    ///     (4, "d"),
2679    /// ]);
2680    ///
2681    /// let cursor = map.lower_bound(Bound::Included(&2));
2682    /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2683    /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2684    ///
2685    /// let cursor = map.lower_bound(Bound::Excluded(&2));
2686    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2687    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2688    ///
2689    /// let cursor = map.lower_bound(Bound::Unbounded);
2690    /// assert_eq!(cursor.peek_prev(), None);
2691    /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2692    /// ```
2693    #[unstable(feature = "btree_cursors", issue = "107540")]
2694    pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2695    where
2696        K: Borrow<Q> + Ord,
2697        Q: Ord,
2698    {
2699        let root_node = match self.root.as_ref() {
2700            None => return Cursor { current: None, root: None },
2701            Some(root) => root.reborrow(),
2702        };
2703        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2704        Cursor { current: Some(edge), root: self.root.as_ref() }
2705    }
2706
2707    /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2708    /// greater than the given bound.
2709    ///
2710    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2711    /// gap before the smallest key greater than or equal to `x`.
2712    ///
2713    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2714    /// gap before the smallest key greater than `x`.
2715    ///
2716    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2717    /// gap before the smallest key in the map.
2718    ///
2719    /// # Examples
2720    ///
2721    /// ```
2722    /// #![feature(btree_cursors)]
2723    ///
2724    /// use std::collections::BTreeMap;
2725    /// use std::ops::Bound;
2726    ///
2727    /// let mut map = BTreeMap::from([
2728    ///     (1, "a"),
2729    ///     (2, "b"),
2730    ///     (3, "c"),
2731    ///     (4, "d"),
2732    /// ]);
2733    ///
2734    /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2735    /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2736    /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2737    ///
2738    /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2739    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2740    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2741    ///
2742    /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2743    /// assert_eq!(cursor.peek_prev(), None);
2744    /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2745    /// ```
2746    #[unstable(feature = "btree_cursors", issue = "107540")]
2747    pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2748    where
2749        K: Borrow<Q> + Ord,
2750        Q: Ord,
2751    {
2752        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2753        let root_node = match root.as_mut() {
2754            None => {
2755                return CursorMut {
2756                    inner: CursorMutKey {
2757                        current: None,
2758                        root: dormant_root,
2759                        length: &mut self.length,
2760                        alloc: &mut *self.alloc,
2761                    },
2762                };
2763            }
2764            Some(root) => root.borrow_mut(),
2765        };
2766        let edge = root_node.lower_bound(SearchBound::from_range(bound));
2767        CursorMut {
2768            inner: CursorMutKey {
2769                current: Some(edge),
2770                root: dormant_root,
2771                length: &mut self.length,
2772                alloc: &mut *self.alloc,
2773            },
2774        }
2775    }
2776
2777    /// Returns a [`Cursor`] pointing at the gap after the greatest key
2778    /// smaller than the given bound.
2779    ///
2780    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2781    /// gap after the greatest key smaller than or equal to `x`.
2782    ///
2783    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2784    /// gap after the greatest key smaller than `x`.
2785    ///
2786    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2787    /// gap after the greatest key in the map.
2788    ///
2789    /// # Examples
2790    ///
2791    /// ```
2792    /// #![feature(btree_cursors)]
2793    ///
2794    /// use std::collections::BTreeMap;
2795    /// use std::ops::Bound;
2796    ///
2797    /// let map = BTreeMap::from([
2798    ///     (1, "a"),
2799    ///     (2, "b"),
2800    ///     (3, "c"),
2801    ///     (4, "d"),
2802    /// ]);
2803    ///
2804    /// let cursor = map.upper_bound(Bound::Included(&3));
2805    /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
2806    /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
2807    ///
2808    /// let cursor = map.upper_bound(Bound::Excluded(&3));
2809    /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2810    /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2811    ///
2812    /// let cursor = map.upper_bound(Bound::Unbounded);
2813    /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
2814    /// assert_eq!(cursor.peek_next(), None);
2815    /// ```
2816    #[unstable(feature = "btree_cursors", issue = "107540")]
2817    pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2818    where
2819        K: Borrow<Q> + Ord,
2820        Q: Ord,
2821    {
2822        let root_node = match self.root.as_ref() {
2823            None => return Cursor { current: None, root: None },
2824            Some(root) => root.reborrow(),
2825        };
2826        let edge = root_node.upper_bound(SearchBound::from_range(bound));
2827        Cursor { current: Some(edge), root: self.root.as_ref() }
2828    }
2829
2830    /// Returns a [`CursorMut`] pointing at the gap after the greatest key
2831    /// smaller than the given bound.
2832    ///
2833    /// Passing `Bound::Included(x)` will return a cursor pointing to the
2834    /// gap after the greatest key smaller than or equal to `x`.
2835    ///
2836    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2837    /// gap after the greatest key smaller than `x`.
2838    ///
2839    /// Passing `Bound::Unbounded` will return a cursor pointing to the
2840    /// gap after the greatest key in the map.
2841    ///
2842    /// # Examples
2843    ///
2844    /// ```
2845    /// #![feature(btree_cursors)]
2846    ///
2847    /// use std::collections::BTreeMap;
2848    /// use std::ops::Bound;
2849    ///
2850    /// let mut map = BTreeMap::from([
2851    ///     (1, "a"),
2852    ///     (2, "b"),
2853    ///     (3, "c"),
2854    ///     (4, "d"),
2855    /// ]);
2856    ///
2857    /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
2858    /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
2859    /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
2860    ///
2861    /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
2862    /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2863    /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2864    ///
2865    /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
2866    /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
2867    /// assert_eq!(cursor.peek_next(), None);
2868    /// ```
2869    #[unstable(feature = "btree_cursors", issue = "107540")]
2870    pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2871    where
2872        K: Borrow<Q> + Ord,
2873        Q: Ord,
2874    {
2875        let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2876        let root_node = match root.as_mut() {
2877            None => {
2878                return CursorMut {
2879                    inner: CursorMutKey {
2880                        current: None,
2881                        root: dormant_root,
2882                        length: &mut self.length,
2883                        alloc: &mut *self.alloc,
2884                    },
2885                };
2886            }
2887            Some(root) => root.borrow_mut(),
2888        };
2889        let edge = root_node.upper_bound(SearchBound::from_range(bound));
2890        CursorMut {
2891            inner: CursorMutKey {
2892                current: Some(edge),
2893                root: dormant_root,
2894                length: &mut self.length,
2895                alloc: &mut *self.alloc,
2896            },
2897        }
2898    }
2899}
2900
2901/// A cursor over a `BTreeMap`.
2902///
2903/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
2904///
2905/// Cursors always point to a gap between two elements in the map, and can
2906/// operate on the two immediately adjacent elements.
2907///
2908/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
2909#[unstable(feature = "btree_cursors", issue = "107540")]
2910pub struct Cursor<'a, K: 'a, V: 'a> {
2911    // If current is None then it means the tree has not been allocated yet.
2912    current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2913    root: Option<&'a node::Root<K, V>>,
2914}
2915
2916#[unstable(feature = "btree_cursors", issue = "107540")]
2917impl<K, V> Clone for Cursor<'_, K, V> {
2918    fn clone(&self) -> Self {
2919        let Cursor { current, root } = *self;
2920        Cursor { current, root }
2921    }
2922}
2923
2924#[unstable(feature = "btree_cursors", issue = "107540")]
2925impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
2926    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2927        f.write_str("Cursor")
2928    }
2929}
2930
2931/// A cursor over a `BTreeMap` with editing operations.
2932///
2933/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2934/// safely mutate the map during iteration. This is because the lifetime of its yielded
2935/// references is tied to its own lifetime, instead of just the underlying map. This means
2936/// cursors cannot yield multiple elements at once.
2937///
2938/// Cursors always point to a gap between two elements in the map, and can
2939/// operate on the two immediately adjacent elements.
2940///
2941/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
2942/// methods.
2943#[unstable(feature = "btree_cursors", issue = "107540")]
2944pub struct CursorMut<
2945    'a,
2946    K: 'a,
2947    V: 'a,
2948    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
2949> {
2950    inner: CursorMutKey<'a, K, V, A>,
2951}
2952
2953#[unstable(feature = "btree_cursors", issue = "107540")]
2954impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
2955    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2956        f.write_str("CursorMut")
2957    }
2958}
2959
2960/// A cursor over a `BTreeMap` with editing operations, and which allows
2961/// mutating the key of elements.
2962///
2963/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
2964/// safely mutate the map during iteration. This is because the lifetime of its yielded
2965/// references is tied to its own lifetime, instead of just the underlying map. This means
2966/// cursors cannot yield multiple elements at once.
2967///
2968/// Cursors always point to a gap between two elements in the map, and can
2969/// operate on the two immediately adjacent elements.
2970///
2971/// A `CursorMutKey` is created from a [`CursorMut`] with the
2972/// [`CursorMut::with_mutable_key`] method.
2973///
2974/// # Safety
2975///
2976/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
2977/// invariants are maintained. Specifically:
2978///
2979/// * The key of the newly inserted element must be unique in the tree.
2980/// * All keys in the tree must remain in sorted order.
2981#[unstable(feature = "btree_cursors", issue = "107540")]
2982pub struct CursorMutKey<
2983    'a,
2984    K: 'a,
2985    V: 'a,
2986    #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
2987> {
2988    // If current is None then it means the tree has not been allocated yet.
2989    current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2990    root: DormantMutRef<'a, Option<node::Root<K, V>>>,
2991    length: &'a mut usize,
2992    alloc: &'a mut A,
2993}
2994
2995#[unstable(feature = "btree_cursors", issue = "107540")]
2996impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
2997    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2998        f.write_str("CursorMutKey")
2999    }
3000}
3001
3002impl<'a, K, V> Cursor<'a, K, V> {
3003    /// Advances the cursor to the next gap, returning the key and value of the
3004    /// element that it moved over.
3005    ///
3006    /// If the cursor is already at the end of the map then `None` is returned
3007    /// and the cursor is not moved.
3008    #[unstable(feature = "btree_cursors", issue = "107540")]
3009    pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3010        let current = self.current.take()?;
3011        match current.next_kv() {
3012            Ok(kv) => {
3013                let result = kv.into_kv();
3014                self.current = Some(kv.next_leaf_edge());
3015                Some(result)
3016            }
3017            Err(root) => {
3018                self.current = Some(root.last_leaf_edge());
3019                None
3020            }
3021        }
3022    }
3023
3024    /// Advances the cursor to the previous gap, returning the key and value of
3025    /// the element that it moved over.
3026    ///
3027    /// If the cursor is already at the start of the map then `None` is returned
3028    /// and the cursor is not moved.
3029    #[unstable(feature = "btree_cursors", issue = "107540")]
3030    pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3031        let current = self.current.take()?;
3032        match current.next_back_kv() {
3033            Ok(kv) => {
3034                let result = kv.into_kv();
3035                self.current = Some(kv.next_back_leaf_edge());
3036                Some(result)
3037            }
3038            Err(root) => {
3039                self.current = Some(root.first_leaf_edge());
3040                None
3041            }
3042        }
3043    }
3044
3045    /// Returns a reference to the key and value of the next element without
3046    /// moving the cursor.
3047    ///
3048    /// If the cursor is at the end of the map then `None` is returned.
3049    #[unstable(feature = "btree_cursors", issue = "107540")]
3050    pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3051        self.clone().next()
3052    }
3053
3054    /// Returns a reference to the key and value of the previous element
3055    /// without moving the cursor.
3056    ///
3057    /// If the cursor is at the start of the map then `None` is returned.
3058    #[unstable(feature = "btree_cursors", issue = "107540")]
3059    pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3060        self.clone().prev()
3061    }
3062}
3063
3064impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3065    /// Advances the cursor to the next gap, returning the key and value of the
3066    /// element that it moved over.
3067    ///
3068    /// If the cursor is already at the end of the map then `None` is returned
3069    /// and the cursor is not moved.
3070    #[unstable(feature = "btree_cursors", issue = "107540")]
3071    pub fn next(&mut self) -> Option<(&K, &mut V)> {
3072        let (k, v) = self.inner.next()?;
3073        Some((&*k, v))
3074    }
3075
3076    /// Advances the cursor to the previous gap, returning the key and value of
3077    /// the element that it moved over.
3078    ///
3079    /// If the cursor is already at the start of the map then `None` is returned
3080    /// and the cursor is not moved.
3081    #[unstable(feature = "btree_cursors", issue = "107540")]
3082    pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3083        let (k, v) = self.inner.prev()?;
3084        Some((&*k, v))
3085    }
3086
3087    /// Returns a reference to the key and value of the next element without
3088    /// moving the cursor.
3089    ///
3090    /// If the cursor is at the end of the map then `None` is returned.
3091    #[unstable(feature = "btree_cursors", issue = "107540")]
3092    pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3093        let (k, v) = self.inner.peek_next()?;
3094        Some((&*k, v))
3095    }
3096
3097    /// Returns a reference to the key and value of the previous element
3098    /// without moving the cursor.
3099    ///
3100    /// If the cursor is at the start of the map then `None` is returned.
3101    #[unstable(feature = "btree_cursors", issue = "107540")]
3102    pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3103        let (k, v) = self.inner.peek_prev()?;
3104        Some((&*k, v))
3105    }
3106
3107    /// Returns a read-only cursor pointing to the same location as the
3108    /// `CursorMut`.
3109    ///
3110    /// The lifetime of the returned `Cursor` is bound to that of the
3111    /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3112    /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3113    #[unstable(feature = "btree_cursors", issue = "107540")]
3114    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3115        self.inner.as_cursor()
3116    }
3117
3118    /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3119    /// the key of elements in the tree.
3120    ///
3121    /// # Safety
3122    ///
3123    /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3124    /// invariants are maintained. Specifically:
3125    ///
3126    /// * The key of the newly inserted element must be unique in the tree.
3127    /// * All keys in the tree must remain in sorted order.
3128    #[unstable(feature = "btree_cursors", issue = "107540")]
3129    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3130        self.inner
3131    }
3132}
3133
3134impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3135    /// Advances the cursor to the next gap, returning the key and value of the
3136    /// element that it moved over.
3137    ///
3138    /// If the cursor is already at the end of the map then `None` is returned
3139    /// and the cursor is not moved.
3140    #[unstable(feature = "btree_cursors", issue = "107540")]
3141    pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3142        let current = self.current.take()?;
3143        match current.next_kv() {
3144            Ok(mut kv) => {
3145                // SAFETY: The key/value pointers remain valid even after the
3146                // cursor is moved forward. The lifetimes then prevent any
3147                // further access to the cursor.
3148                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3149                let (k, v) = (k as *mut _, v as *mut _);
3150                self.current = Some(kv.next_leaf_edge());
3151                Some(unsafe { (&mut *k, &mut *v) })
3152            }
3153            Err(root) => {
3154                self.current = Some(root.last_leaf_edge());
3155                None
3156            }
3157        }
3158    }
3159
3160    /// Advances the cursor to the previous gap, returning the key and value of
3161    /// the element that it moved over.
3162    ///
3163    /// If the cursor is already at the start of the map then `None` is returned
3164    /// and the cursor is not moved.
3165    #[unstable(feature = "btree_cursors", issue = "107540")]
3166    pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3167        let current = self.current.take()?;
3168        match current.next_back_kv() {
3169            Ok(mut kv) => {
3170                // SAFETY: The key/value pointers remain valid even after the
3171                // cursor is moved forward. The lifetimes then prevent any
3172                // further access to the cursor.
3173                let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3174                let (k, v) = (k as *mut _, v as *mut _);
3175                self.current = Some(kv.next_back_leaf_edge());
3176                Some(unsafe { (&mut *k, &mut *v) })
3177            }
3178            Err(root) => {
3179                self.current = Some(root.first_leaf_edge());
3180                None
3181            }
3182        }
3183    }
3184
3185    /// Returns a reference to the key and value of the next element without
3186    /// moving the cursor.
3187    ///
3188    /// If the cursor is at the end of the map then `None` is returned.
3189    #[unstable(feature = "btree_cursors", issue = "107540")]
3190    pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3191        let current = self.current.as_mut()?;
3192        // SAFETY: We're not using this to mutate the tree.
3193        let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3194        Some(kv)
3195    }
3196
3197    /// Returns a reference to the key and value of the previous element
3198    /// without moving the cursor.
3199    ///
3200    /// If the cursor is at the start of the map then `None` is returned.
3201    #[unstable(feature = "btree_cursors", issue = "107540")]
3202    pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3203        let current = self.current.as_mut()?;
3204        // SAFETY: We're not using this to mutate the tree.
3205        let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3206        Some(kv)
3207    }
3208
3209    /// Returns a read-only cursor pointing to the same location as the
3210    /// `CursorMutKey`.
3211    ///
3212    /// The lifetime of the returned `Cursor` is bound to that of the
3213    /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3214    /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3215    #[unstable(feature = "btree_cursors", issue = "107540")]
3216    pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3217        Cursor {
3218            // SAFETY: The tree is immutable while the cursor exists.
3219            root: unsafe { self.root.reborrow_shared().as_ref() },
3220            current: self.current.as_ref().map(|current| current.reborrow()),
3221        }
3222    }
3223}
3224
3225// Now the tree editing operations
3226impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> {
3227    /// Inserts a new key-value pair into the map in the gap that the
3228    /// cursor is currently pointing to.
3229    ///
3230    /// After the insertion the cursor will be pointing at the gap before the
3231    /// newly inserted element.
3232    ///
3233    /// # Safety
3234    ///
3235    /// You must ensure that the `BTreeMap` invariants are maintained.
3236    /// Specifically:
3237    ///
3238    /// * The key of the newly inserted element must be unique in the tree.
3239    /// * All keys in the tree must remain in sorted order.
3240    #[unstable(feature = "btree_cursors", issue = "107540")]
3241    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3242        let edge = match self.current.take() {
3243            None => {
3244                // Tree is empty, allocate a new root.
3245                // SAFETY: We have no other reference to the tree.
3246                let root = unsafe { self.root.reborrow() };
3247                debug_assert!(root.is_none());
3248                let mut node = NodeRef::new_leaf(self.alloc.clone());
3249                // SAFETY: We don't touch the root while the handle is alive.
3250                let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3251                *root = Some(node.forget_type());
3252                *self.length += 1;
3253                self.current = Some(handle.left_edge());
3254                return;
3255            }
3256            Some(current) => current,
3257        };
3258
3259        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3260            drop(ins.left);
3261            // SAFETY: The handle to the newly inserted value is always on a
3262            // leaf node, so adding a new root node doesn't invalidate it.
3263            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3264            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3265        });
3266        self.current = Some(handle.left_edge());
3267        *self.length += 1;
3268    }
3269
3270    /// Inserts a new key-value pair into the map in the gap that the
3271    /// cursor is currently pointing to.
3272    ///
3273    /// After the insertion the cursor will be pointing at the gap after the
3274    /// newly inserted element.
3275    ///
3276    /// # Safety
3277    ///
3278    /// You must ensure that the `BTreeMap` invariants are maintained.
3279    /// Specifically:
3280    ///
3281    /// * The key of the newly inserted element must be unique in the tree.
3282    /// * All keys in the tree must remain in sorted order.
3283    #[unstable(feature = "btree_cursors", issue = "107540")]
3284    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3285        let edge = match self.current.take() {
3286            None => {
3287                // SAFETY: We have no other reference to the tree.
3288                match unsafe { self.root.reborrow() } {
3289                    root @ None => {
3290                        // Tree is empty, allocate a new root.
3291                        let mut node = NodeRef::new_leaf(self.alloc.clone());
3292                        // SAFETY: We don't touch the root while the handle is alive.
3293                        let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3294                        *root = Some(node.forget_type());
3295                        *self.length += 1;
3296                        self.current = Some(handle.right_edge());
3297                        return;
3298                    }
3299                    Some(root) => root.borrow_mut().last_leaf_edge(),
3300                }
3301            }
3302            Some(current) => current,
3303        };
3304
3305        let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3306            drop(ins.left);
3307            // SAFETY: The handle to the newly inserted value is always on a
3308            // leaf node, so adding a new root node doesn't invalidate it.
3309            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3310            root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3311        });
3312        self.current = Some(handle.right_edge());
3313        *self.length += 1;
3314    }
3315
3316    /// Inserts a new key-value pair into the map in the gap that the
3317    /// cursor is currently pointing to.
3318    ///
3319    /// After the insertion the cursor will be pointing at the gap before the
3320    /// newly inserted element.
3321    ///
3322    /// If the inserted key is not greater than the key before the cursor
3323    /// (if any), or if it not less than the key after the cursor (if any),
3324    /// then an [`UnorderedKeyError`] is returned since this would
3325    /// invalidate the [`Ord`] invariant between the keys of the map.
3326    #[unstable(feature = "btree_cursors", issue = "107540")]
3327    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3328        if let Some((prev, _)) = self.peek_prev() {
3329            if &key <= prev {
3330                return Err(UnorderedKeyError {});
3331            }
3332        }
3333        if let Some((next, _)) = self.peek_next() {
3334            if &key >= next {
3335                return Err(UnorderedKeyError {});
3336            }
3337        }
3338        unsafe {
3339            self.insert_after_unchecked(key, value);
3340        }
3341        Ok(())
3342    }
3343
3344    /// Inserts a new key-value pair into the map in the gap that the
3345    /// cursor is currently pointing to.
3346    ///
3347    /// After the insertion the cursor will be pointing at the gap after the
3348    /// newly inserted element.
3349    ///
3350    /// If the inserted key is not greater than the key before the cursor
3351    /// (if any), or if it not less than the key after the cursor (if any),
3352    /// then an [`UnorderedKeyError`] is returned since this would
3353    /// invalidate the [`Ord`] invariant between the keys of the map.
3354    #[unstable(feature = "btree_cursors", issue = "107540")]
3355    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3356        if let Some((prev, _)) = self.peek_prev() {
3357            if &key <= prev {
3358                return Err(UnorderedKeyError {});
3359            }
3360        }
3361        if let Some((next, _)) = self.peek_next() {
3362            if &key >= next {
3363                return Err(UnorderedKeyError {});
3364            }
3365        }
3366        unsafe {
3367            self.insert_before_unchecked(key, value);
3368        }
3369        Ok(())
3370    }
3371
3372    /// Removes the next element from the `BTreeMap`.
3373    ///
3374    /// The element that was removed is returned. The cursor position is
3375    /// unchanged (before the removed element).
3376    #[unstable(feature = "btree_cursors", issue = "107540")]
3377    pub fn remove_next(&mut self) -> Option<(K, V)> {
3378        let current = self.current.take()?;
3379        if current.reborrow().next_kv().is_err() {
3380            self.current = Some(current);
3381            return None;
3382        }
3383        let mut emptied_internal_root = false;
3384        let (kv, pos) = current
3385            .next_kv()
3386            // This should be unwrap(), but that doesn't work because NodeRef
3387            // doesn't implement Debug. The condition is checked above.
3388            .ok()?
3389            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3390        self.current = Some(pos);
3391        *self.length -= 1;
3392        if emptied_internal_root {
3393            // SAFETY: This is safe since current does not point within the now
3394            // empty root node.
3395            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3396            root.pop_internal_level(self.alloc.clone());
3397        }
3398        Some(kv)
3399    }
3400
3401    /// Removes the preceding element from the `BTreeMap`.
3402    ///
3403    /// The element that was removed is returned. The cursor position is
3404    /// unchanged (after the removed element).
3405    #[unstable(feature = "btree_cursors", issue = "107540")]
3406    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3407        let current = self.current.take()?;
3408        if current.reborrow().next_back_kv().is_err() {
3409            self.current = Some(current);
3410            return None;
3411        }
3412        let mut emptied_internal_root = false;
3413        let (kv, pos) = current
3414            .next_back_kv()
3415            // This should be unwrap(), but that doesn't work because NodeRef
3416            // doesn't implement Debug. The condition is checked above.
3417            .ok()?
3418            .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3419        self.current = Some(pos);
3420        *self.length -= 1;
3421        if emptied_internal_root {
3422            // SAFETY: This is safe since current does not point within the now
3423            // empty root node.
3424            let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3425            root.pop_internal_level(self.alloc.clone());
3426        }
3427        Some(kv)
3428    }
3429}
3430
3431impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> {
3432    /// Inserts a new key-value pair into the map in the gap that the
3433    /// cursor is currently pointing to.
3434    ///
3435    /// After the insertion the cursor will be pointing at the gap after the
3436    /// newly inserted element.
3437    ///
3438    /// # Safety
3439    ///
3440    /// You must ensure that the `BTreeMap` invariants are maintained.
3441    /// Specifically:
3442    ///
3443    /// * The key of the newly inserted element must be unique in the tree.
3444    /// * All keys in the tree must remain in sorted order.
3445    #[unstable(feature = "btree_cursors", issue = "107540")]
3446    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3447        unsafe { self.inner.insert_after_unchecked(key, value) }
3448    }
3449
3450    /// Inserts a new key-value pair into the map in the gap that the
3451    /// cursor is currently pointing to.
3452    ///
3453    /// After the insertion the cursor will be pointing at the gap after the
3454    /// newly inserted element.
3455    ///
3456    /// # Safety
3457    ///
3458    /// You must ensure that the `BTreeMap` invariants are maintained.
3459    /// Specifically:
3460    ///
3461    /// * The key of the newly inserted element must be unique in the tree.
3462    /// * All keys in the tree must remain in sorted order.
3463    #[unstable(feature = "btree_cursors", issue = "107540")]
3464    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3465        unsafe { self.inner.insert_before_unchecked(key, value) }
3466    }
3467
3468    /// Inserts a new key-value pair into the map in the gap that the
3469    /// cursor is currently pointing to.
3470    ///
3471    /// After the insertion the cursor will be pointing at the gap before the
3472    /// newly inserted element.
3473    ///
3474    /// If the inserted key is not greater than the key before the cursor
3475    /// (if any), or if it not less than the key after the cursor (if any),
3476    /// then an [`UnorderedKeyError`] is returned since this would
3477    /// invalidate the [`Ord`] invariant between the keys of the map.
3478    #[unstable(feature = "btree_cursors", issue = "107540")]
3479    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3480        self.inner.insert_after(key, value)
3481    }
3482
3483    /// Inserts a new key-value pair into the map in the gap that the
3484    /// cursor is currently pointing to.
3485    ///
3486    /// After the insertion the cursor will be pointing at the gap after the
3487    /// newly inserted element.
3488    ///
3489    /// If the inserted key is not greater than the key before the cursor
3490    /// (if any), or if it not less than the key after the cursor (if any),
3491    /// then an [`UnorderedKeyError`] is returned since this would
3492    /// invalidate the [`Ord`] invariant between the keys of the map.
3493    #[unstable(feature = "btree_cursors", issue = "107540")]
3494    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3495        self.inner.insert_before(key, value)
3496    }
3497
3498    /// Removes the next element from the `BTreeMap`.
3499    ///
3500    /// The element that was removed is returned. The cursor position is
3501    /// unchanged (before the removed element).
3502    #[unstable(feature = "btree_cursors", issue = "107540")]
3503    pub fn remove_next(&mut self) -> Option<(K, V)> {
3504        self.inner.remove_next()
3505    }
3506
3507    /// Removes the preceding element from the `BTreeMap`.
3508    ///
3509    /// The element that was removed is returned. The cursor position is
3510    /// unchanged (after the removed element).
3511    #[unstable(feature = "btree_cursors", issue = "107540")]
3512    pub fn remove_prev(&mut self) -> Option<(K, V)> {
3513        self.inner.remove_prev()
3514    }
3515}
3516
3517/// Error type returned by [`CursorMut::insert_before`] and
3518/// [`CursorMut::insert_after`] if the key being inserted is not properly
3519/// ordered with regards to adjacent keys.
3520#[derive(Clone, PartialEq, Eq, Debug)]
3521#[unstable(feature = "btree_cursors", issue = "107540")]
3522pub struct UnorderedKeyError {}
3523
3524#[unstable(feature = "btree_cursors", issue = "107540")]
3525impl fmt::Display for UnorderedKeyError {
3526    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3527        write!(f, "key is not properly ordered relative to neighbors")
3528    }
3529}
3530
3531#[unstable(feature = "btree_cursors", issue = "107540")]
3532impl Error for UnorderedKeyError {}
3533
3534#[cfg(test)]
3535mod tests;