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