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