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