Skip to main content

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