Skip to main content

alloc/collections/btree/
map.rs

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