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