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