Skip to main content

alloc/collections/btree/
map.rs

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