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