Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

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