btree_experiment/
lib.rs

1#![deny(missing_docs)]
2#![cfg_attr(test, feature(btree_cursors, assert_matches))]
3
4//! This crate implements a [`BTreeMap`] similar to [`std::collections::BTreeMap`].
5//!
6//! The standard BtreeMap can use up to twice as much memory as required, this BTreeMap
7//! only allocates what is needed ( or a little more to avoid allocating too often ), so
8//! memory use can be up to 50% less.
9//!
10//! # Example
11//!
12//! ```
13//!     use btree_experiment::BTreeMap;
14//!     let mut mymap = BTreeMap::new();
15//!     mymap.insert("England", "London");
16//!     mymap.insert("France", "Paris");
17//!     println!("The capital of France is {}", mymap["France"]);
18//! ```
19//!
20//!# Features
21//!
22//! This crate supports the following cargo features:
23//! - `serde` : enables serialisation of [`BTreeMap`] via serde crate.
24//! - `unsafe-optim` : uses unsafe code for extra optimisation.
25
26use std::{
27    borrow::Borrow,
28    cmp::Ordering,
29    error::Error,
30    fmt,
31    fmt::Debug,
32    iter::FusedIterator,
33    marker::PhantomData,
34    mem,
35    ops::{Bound, RangeBounds},
36};
37
38/// `BTreeMap` similar to [`std::collections::BTreeMap`].
39///
40/// General guide to implementation:
41///
42/// [`BTreeMap`] has a length and a `Tree`, where `Tree` is an enum that can be `Leaf` or `NonLeaf`.
43///
44/// The [Entry] API is implemented using [`CursorMut`].
45///
46/// [`CursorMut`] is implemented using [`CursorMutKey`] which has a stack of raw pointer/index pairs
47/// to keep track of non-leaf positions.
48///
49/// Roughly speaking, unsafe code is limited to the vecs module and the implementation of [`CursorMut`] and [`CursorMutKey`].
50
51#[derive(Clone)]
52pub struct BTreeMap<K, V, A: AllocTuning = DefaultAllocTuning> {
53    len: usize,
54    tree: Tree<K, V>,
55    atune: A,
56}
57impl<K, V> Default for BTreeMap<K, V> {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl<K, V> BTreeMap<K, V> {
64    /// Returns a new, empty map.
65    #[must_use]
66    pub fn new() -> Self {
67        Self::with_tuning(DefaultAllocTuning::default())
68    }
69}
70
71impl<K, V, A: AllocTuning> BTreeMap<K, V, A> {
72    #[cfg(test)]
73    pub(crate) fn check(&self) {}
74
75    /// Returns a new, empty map with specified allocation tuning.
76    ///
77    /// # Example
78    ///
79    /// ```
80    ///     use btree_experiment::{BTreeMap,DefaultAllocTuning};
81    ///     let mut mymap = BTreeMap::with_tuning(DefaultAllocTuning::new(8,2));
82    ///     mymap.insert("England", "London");
83    ///     mymap.insert("France", "Paris");
84    ///     println!("The capital of France is {}", mymap["France"]);
85    /// ```
86    #[must_use]
87    pub fn with_tuning(atune: A) -> Self {
88        Self {
89            len: 0,
90            tree: Tree::new(),
91            atune,
92        }
93    }
94
95    /// Get a cloned copy of the tuning.
96    pub fn get_tuning(&self) -> A {
97        self.atune.clone()
98    }
99
100    /// Update the allocation tuning for the map.
101    pub fn set_tuning(&mut self, atune: A) -> A {
102        mem::replace(&mut self.atune, atune)
103    }
104
105    /// Clear the map.
106    pub fn clear(&mut self) {
107        self.len = 0;
108        self.tree = Tree::new();
109    }
110
111    /// Get number of key-value pairs in the map.
112    #[must_use]
113    pub fn len(&self) -> usize {
114        self.len
115    }
116
117    /// Is the map empty?
118    #[must_use]
119    pub fn is_empty(&self) -> bool {
120        self.len == 0
121    }
122
123    /// Get Entry for map key.
124    pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
125    where
126        K: Ord,
127    {
128        let cursor = self.lower_bound_mut(Bound::Included(&key));
129        let found = if let Some(kv) = cursor.peek_next() {
130            kv.0 == &key
131        } else {
132            false
133        };
134        if found {
135            Entry::Occupied(OccupiedEntry { cursor })
136        } else {
137            Entry::Vacant(VacantEntry { key, cursor })
138        }
139    }
140
141    /// Get first Entry.
142    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
143    where
144        K: Ord,
145    {
146        if self.is_empty() {
147            None
148        } else {
149            let cursor = self.lower_bound_mut(Bound::Unbounded);
150            Some(OccupiedEntry { cursor })
151        }
152    }
153
154    /// Get last Entry.
155    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
156    where
157        K: Ord,
158    {
159        if self.is_empty() {
160            None
161        } else {
162            let mut cursor = self.upper_bound_mut(Bound::Unbounded);
163            cursor.prev();
164            Some(OccupiedEntry { cursor })
165        }
166    }
167
168    /// Insert key-value pair into map, or if key is already in map, replaces value and returns old value.
169    pub fn insert(&mut self, key: K, value: V) -> Option<V>
170    where
171        K: Ord,
172    {
173        let mut x = InsertCtx {
174            value: Some(value),
175            split: None,
176            atune: &self.atune,
177        };
178        self.tree.insert(key, &mut x);
179        if let Some(split) = x.split {
180            self.tree.new_root(split);
181        }
182        if x.value.is_none() {
183            self.len += 1;
184        }
185        x.value
186    }
187
188    /// Tries to insert a key-value pair into the map, and returns
189    /// a mutable reference to the value in the entry.
190    ///
191    /// If the map already had this key present, nothing is updated, and
192    /// an error containing the occupied entry and the value is returned.
193    pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
194    where
195        K: Ord,
196    {
197        match self.entry(key) {
198            Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
199            Entry::Vacant(entry) => Ok(entry.insert(value)),
200        }
201    }
202
203    /// Does the map have an entry for the specified key.
204    pub fn contains_key<Q>(&self, key: &Q) -> bool
205    where
206        K: Borrow<Q> + Ord,
207        Q: Ord + ?Sized,
208    {
209        self.get(key).is_some()
210    }
211
212    /// Remove key-value pair from map, returning just the value.
213    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
214    where
215        K: Borrow<Q> + Ord,
216        Q: Ord + ?Sized,
217    {
218        self.remove_entry(key).map(|(_k, v)| v)
219    }
220
221    /// Remove key-value pair from map.
222    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
223    where
224        K: Borrow<Q> + Ord,
225        Q: Ord + ?Sized,
226    {
227        let result = self.tree.remove(key, &self.atune)?;
228        self.len -= 1;
229        Some(result)
230    }
231
232    /// Remove first key-value pair from map.
233    pub fn pop_first(&mut self) -> Option<(K, V)> {
234        let result = self.tree.pop_first(&self.atune)?;
235        self.len -= 1;
236        Some(result)
237    }
238
239    /// Remove last key-value pair from map.
240    pub fn pop_last(&mut self) -> Option<(K, V)> {
241        let result = self.tree.pop_last(&self.atune)?;
242        self.len -= 1;
243        Some(result)
244    }
245
246    /// Remove all key-value pairs, visited in ascending order, for which f returns false.
247    pub fn retain<F>(&mut self, mut f: F)
248    where
249        F: FnMut(&K, &mut V) -> bool,
250        K: Ord,
251    {
252        let mut c = self.lower_bound_mut(Bound::Unbounded);
253        while let Some((k, v)) = c.next() {
254            if !f(k, v) {
255                c.remove_prev();
256            }
257        }
258    }
259
260    /// Get reference to the value corresponding to the key.
261    pub fn get<Q>(&self, key: &Q) -> Option<&V>
262    where
263        K: Borrow<Q> + Ord,
264        Q: Ord + ?Sized,
265    {
266        self.tree.get(key)
267    }
268
269    /// Get a mutable reference to the value corresponding to the key.
270    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
271    where
272        K: Borrow<Q> + Ord,
273        Q: Ord + ?Sized,
274    {
275        self.tree.get_mut(key)
276    }
277
278    /// Get references to the corresponding key and value.
279    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
280    where
281        K: Borrow<Q> + Ord,
282        Q: Ord + ?Sized,
283    {
284        self.tree.get_key_value(key)
285    }
286
287    /// Get references to first key and value.
288    #[must_use]
289    pub fn first_key_value(&self) -> Option<(&K, &V)> {
290        self.tree.iter().next()
291    }
292
293    /// Gets references to last key and value.
294    #[must_use]
295    pub fn last_key_value(&self) -> Option<(&K, &V)> {
296        self.tree.iter().next_back()
297    }
298
299    /// Moves all elements from `other` into `self`, leaving `other` empty.
300    ///
301    /// If a key from `other` is already present in `self`, the respective
302    /// value from `self` will be overwritten with the respective value from `other`.
303    pub fn append(&mut self, other: &mut BTreeMap<K, V, A>)
304    where
305        K: Ord,
306    {
307        let rep = Tree::new();
308        let tree = mem::replace(&mut other.tree, rep);
309        let temp = BTreeMap {
310            len: other.len,
311            tree,
312            atune: other.atune.clone(),
313        };
314        other.len = 0;
315        for (k, v) in temp {
316            self.insert(k, v);
317        }
318    }
319
320    /// Splits the collection into two at the given key.
321    /// Returns everything after the given key, including the key.
322    pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
323    where
324        K: Borrow<Q> + Ord,
325        A: Default,
326    {
327        let mut map = Self::with_tuning(self.atune.clone());
328        let mut from = self.lower_bound_mut(Bound::Included(key));
329        let mut to = map.lower_bound_mut(Bound::Unbounded);
330        while let Some((k, v)) = from.remove_next() {
331            unsafe {
332                to.insert_before_unchecked(k, v);
333            }
334        }
335        map
336    }
337
338    /// Returns iterator that visits all elements (key-value pairs) in ascending key order
339    /// and uses a closure to determine if an element should be removed.
340    pub fn extract_if<F>(&mut self, pred: F) -> ExtractIf<'_, K, V, A, F>
341    where
342        K: Ord,
343        F: FnMut(&K, &mut V) -> bool,
344    {
345        let source = self.lower_bound_mut(Bound::Unbounded);
346        ExtractIf { source, pred }
347    }
348
349    /// Get iterator of references to key-value pairs.
350    #[must_use]
351    pub fn iter(&self) -> Iter<'_, K, V> {
352        Iter {
353            len: self.len,
354            inner: self.tree.iter(),
355        }
356    }
357
358    /// Get iterator of mutable references to key-value pairs.
359    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
360        IterMut {
361            len: self.len,
362            inner: self.tree.iter_mut(),
363        }
364    }
365
366    /// Get iterator for range of references to key-value pairs.
367    pub fn range<T, R>(&self, range: R) -> Range<'_, K, V>
368    where
369        T: Ord + ?Sized,
370        K: Borrow<T> + Ord,
371        R: RangeBounds<T>,
372    {
373        check_range(&range);
374        self.tree.range(&range)
375    }
376
377    /// Get iterator for range of mutable references to key-value pairs.
378    /// A key can be mutated, provided it does not change the map order.
379    pub fn range_mut<T, R>(&mut self, range: R) -> RangeMut<'_, K, V>
380    where
381        T: Ord + ?Sized,
382        K: Borrow<T> + Ord,
383        R: RangeBounds<T>,
384    {
385        check_range(&range);
386        self.tree.range_mut(&range)
387    }
388
389    /// Get iterator of references to keys.
390    #[must_use]
391    pub fn keys(&self) -> Keys<'_, K, V> {
392        Keys(self.iter())
393    }
394
395    /// Get iterator of references to values.
396    #[must_use]
397    pub fn values(&self) -> Values<'_, K, V> {
398        Values(self.iter())
399    }
400
401    /// Get iterator of mutable references to values.
402    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
403        ValuesMut(self.iter_mut())
404    }
405
406    /// Get consuming iterator that returns all the keys, in sorted order.
407    #[must_use]
408    pub fn into_keys(self) -> IntoKeys<K, V> {
409        IntoKeys(self.into_iter())
410    }
411
412    /// Get consuming iterator that returns all the values, in sorted order.
413    #[must_use]
414    pub fn into_values(self) -> IntoValues<K, V> {
415        IntoValues(self.into_iter())
416    }
417
418    /// Get cursor positioned just after bound.
419    #[must_use]
420    pub fn lower_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V, A>
421    where
422        K: Borrow<Q> + Ord,
423        Q: Ord + ?Sized,
424    {
425        Cursor::lower_bound(self, bound)
426    }
427
428    /// Get cursor positioned just before bound.
429    #[must_use]
430    pub fn upper_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V, A>
431    where
432        K: Borrow<Q> + Ord,
433        Q: Ord + ?Sized,
434    {
435        Cursor::upper_bound(self, bound)
436    }
437
438    /// Get a cursor positioned just after bound that permits map mutation.
439    pub fn lower_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
440    where
441        K: Borrow<Q> + Ord,
442        Q: Ord + ?Sized,
443    {
444        CursorMut::lower_bound(self, bound)
445    }
446
447    /// Get a cursor positioned just before bound that permits map mutation.
448    pub fn upper_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
449    where
450        K: Borrow<Q> + Ord,
451        Q: Ord + ?Sized,
452    {
453        CursorMut::upper_bound(self, bound)
454    }
455} // End impl BTreeMap
456
457use std::hash::{Hash, Hasher};
458impl<K: Hash, V: Hash> Hash for BTreeMap<K, V> {
459    fn hash<H: Hasher>(&self, state: &mut H) {
460        // state.write_length_prefix(self.len());
461        for elt in self {
462            elt.hash(state);
463        }
464    }
465}
466impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
467    fn eq(&self, other: &BTreeMap<K, V>) -> bool {
468        self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a == b)
469    }
470}
471impl<K: Eq, V: Eq> Eq for BTreeMap<K, V> {}
472
473impl<K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<K, V> {
474    fn partial_cmp(&self, other: &BTreeMap<K, V>) -> Option<Ordering> {
475        self.iter().partial_cmp(other.iter())
476    }
477}
478impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
479    fn cmp(&self, other: &BTreeMap<K, V>) -> Ordering {
480        self.iter().cmp(other.iter())
481    }
482}
483impl<K, V, A: AllocTuning> IntoIterator for BTreeMap<K, V, A> {
484    type Item = (K, V);
485    type IntoIter = IntoIter<K, V>;
486
487    /// Convert `BTreeMap` to [`IntoIter`].
488    fn into_iter(self) -> IntoIter<K, V> {
489        IntoIter::new(self)
490    }
491}
492impl<'a, K, V> IntoIterator for &'a BTreeMap<K, V> {
493    type Item = (&'a K, &'a V);
494    type IntoIter = Iter<'a, K, V>;
495    fn into_iter(self) -> Iter<'a, K, V> {
496        self.iter()
497    }
498}
499impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
500    type Item = (&'a K, &'a mut V);
501    type IntoIter = IterMut<'a, K, V>;
502    fn into_iter(self) -> IterMut<'a, K, V> {
503        self.iter_mut()
504    }
505}
506impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
507    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
508        let mut map = BTreeMap::new();
509        for (k, v) in iter {
510            map.insert(k, v);
511        }
512        map
513    }
514}
515impl<K, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V>
516where
517    K: Ord,
518{
519    fn from(arr: [(K, V); N]) -> BTreeMap<K, V> {
520        let mut map = BTreeMap::new();
521        for (k, v) in arr {
522            map.insert(k, v);
523        }
524        map
525    }
526}
527impl<K, V> Extend<(K, V)> for BTreeMap<K, V>
528where
529    K: Ord,
530{
531    fn extend<T>(&mut self, iter: T)
532    where
533        T: IntoIterator<Item = (K, V)>,
534    {
535        for (k, v) in iter {
536            self.insert(k, v);
537        }
538    }
539}
540impl<'a, K, V> Extend<(&'a K, &'a V)> for BTreeMap<K, V>
541where
542    K: Ord + Copy,
543    V: Copy,
544{
545    fn extend<I>(&mut self, iter: I)
546    where
547        I: IntoIterator<Item = (&'a K, &'a V)>,
548    {
549        for (&k, &v) in iter {
550            self.insert(k, v);
551        }
552    }
553}
554impl<K, Q, V> std::ops::Index<&Q> for BTreeMap<K, V>
555where
556    K: Borrow<Q> + Ord,
557    Q: Ord + ?Sized,
558{
559    type Output = V;
560
561    /// Returns a reference to the value corresponding to the supplied key.
562    ///
563    /// Panics if the key is not present in the `BTreeMap`.
564    #[inline]
565    fn index(&self, key: &Q) -> &V {
566        self.get(key).expect("no entry found for key")
567    }
568}
569impl<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        f.debug_map().entries(self.iter()).finish()
572    }
573}
574
575#[cfg(feature = "serde")]
576use serde::{
577    de::{MapAccess, Visitor},
578    ser::SerializeMap,
579    Deserialize, Deserializer, Serialize,
580};
581
582#[cfg(feature = "serde")]
583impl<K, V> Serialize for BTreeMap<K, V>
584where
585    K: serde::Serialize,
586    V: serde::Serialize,
587{
588    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
589    where
590        S: serde::Serializer,
591    {
592        let mut map = serializer.serialize_map(Some(self.len()))?;
593        for (k, v) in self {
594            map.serialize_entry(k, v)?;
595        }
596        map.end()
597    }
598}
599
600#[cfg(feature = "serde")]
601struct BTreeMapVisitor<K, V> {
602    marker: PhantomData<fn() -> BTreeMap<K, V>>,
603}
604
605#[cfg(feature = "serde")]
606impl<K, V> BTreeMapVisitor<K, V> {
607    fn new() -> Self {
608        BTreeMapVisitor {
609            marker: PhantomData,
610        }
611    }
612}
613
614#[cfg(feature = "serde")]
615impl<'de, K, V> Visitor<'de> for BTreeMapVisitor<K, V>
616where
617    K: Deserialize<'de> + Ord,
618    V: Deserialize<'de>,
619{
620    type Value = BTreeMap<K, V>;
621
622    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
623        formatter.write_str("BTreeMap")
624    }
625
626    fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
627    where
628        M: MapAccess<'de>,
629    {
630        let mut map = BTreeMap::new();
631        let mut tuning = map.get_tuning();
632        tuning.set_seq();
633        let save = map.set_tuning(tuning);
634        {
635            let mut c = map.lower_bound_mut(Bound::Unbounded);
636            loop {
637                if let Some((k, v)) = access.next_entry()? {
638                    if let Some((pk, _)) = c.peek_prev() {
639                        if pk >= &k {
640                            map.insert(k, v);
641                            break;
642                        }
643                    }
644                    unsafe {
645                        c.insert_before_unchecked(k, v);
646                    }
647                } else {
648                    return Ok(map);
649                }
650            }
651        }
652        map.set_tuning(save);
653        while let Some((k, v)) = access.next_entry()? {
654            map.insert(k, v);
655        }
656        return Ok(map);
657    }
658}
659
660#[cfg(feature = "serde")]
661impl<'de, K, V> Deserialize<'de> for BTreeMap<K, V>
662where
663    K: Deserialize<'de> + Ord,
664    V: Deserialize<'de>,
665{
666    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
667    where
668        D: Deserializer<'de>,
669    {
670        deserializer.deserialize_map(BTreeMapVisitor::new())
671    }
672}
673
674/// Type returned by [AllocTuning::full_action].
675pub enum FullAction {
676    /// Vec is to be split at indicated point with the indicated new allocations.
677    Split(usize, usize, usize),
678    /// Vec is to be extended to indicated length.
679    Extend(usize),
680}
681
682/// Trait for controlling storage allocation for [BTreeMap].
683pub trait AllocTuning: Clone + Default {
684    /// Determine what to do when the size of an underlying BTree vector needs to be increased.
685    fn full_action(&self, i: usize, len: usize) -> FullAction;
686    /// Returns the new allocation if the allocation should be reduced based on the current length and allocation.
687    fn space_action(&self, state: (usize, usize)) -> Option<usize>;
688    /// Set allocation mode to be optimal for sequential (ordered) inserts.
689    fn set_seq(&mut self);
690}
691
692/// Default implementation of [AllocTuning]. Default branch is 64, default allocation unit is 8.
693#[derive(Clone)]
694pub struct DefaultAllocTuning {
695    branch: u16,
696    alloc_unit: u8,
697}
698impl Default for DefaultAllocTuning {
699    fn default() -> Self {
700        Self {
701            branch: 64,
702            alloc_unit: 8,
703        }
704    }
705}
706impl AllocTuning for DefaultAllocTuning {
707    fn full_action(&self, i: usize, len: usize) -> FullAction {
708        let lim = (self.branch as usize) * 2 + 1;
709        if len >= lim {
710            let b = len / 2;
711            let r = usize::from(i > b);
712            let au = self.alloc_unit as usize;
713            FullAction::Split(b, b + (1 - r) * au, (len - b - 1) + r * au)
714        } else {
715            let mut na = len + self.alloc_unit as usize;
716            if na > lim {
717                na = lim;
718            }
719            FullAction::Extend(na)
720        }
721    }
722    fn space_action(&self, (len, alloc): (usize, usize)) -> Option<usize> {
723        if alloc - len >= self.alloc_unit as usize {
724            Some(len)
725        } else {
726            None
727        }
728    }
729    fn set_seq(&mut self) {
730        self.alloc_unit = u8::MAX;
731    }
732}
733impl DefaultAllocTuning {
734    /// Construct with specified branch and allocation unit.
735    pub fn new(branch: u16, alloc_unit: u8) -> Self {
736        assert!(branch >= 6);
737        assert!(branch <= 512);
738        assert!(alloc_unit > 0);
739        Self { branch, alloc_unit }
740    }
741}
742
743// Vector types.
744type StkVec<T> = arrayvec::ArrayVec<T, 15>;
745
746mod vecs;
747use vecs::*;
748
749type TreeVec<K, V> = ShortVec<Tree<K, V>>;
750
751type Split<K, V> = ((K, V), Tree<K, V>);
752
753struct InsertCtx<'a, K, V, A: AllocTuning> {
754    value: Option<V>,
755    split: Option<Split<K, V>>,
756    atune: &'a A,
757}
758
759fn check_range<T, R>(range: &R)
760where
761    T: Ord + ?Sized,
762    R: RangeBounds<T>,
763{
764    use Bound::{Excluded, Included};
765    match (range.start_bound(), range.end_bound()) {
766        (Included(s) | Excluded(s), Included(e)) | (Included(s), Excluded(e)) => {
767            assert!(e >= s, "range start is greater than range end in BTreeMap");
768        }
769        (Excluded(s), Excluded(e)) => {
770            assert!(
771                e != s,
772                "range start and end are equal and excluded in BTreeMap"
773            );
774            assert!(e >= s, "range start is greater than range end in BTreeMap");
775        }
776        _ => {}
777    }
778}
779
780#[derive(Debug, Clone)]
781enum Tree<K, V> {
782    L(Leaf<K, V>),
783    NL(NonLeaf<K, V>),
784}
785impl<K, V> Default for Tree<K, V> {
786    fn default() -> Self {
787        Self::new()
788    }
789}
790impl<K, V> Tree<K, V> {
791    fn new() -> Self {
792        Tree::L(Leaf::new())
793    }
794
795    fn insert<A: AllocTuning>(&mut self, key: K, x: &mut InsertCtx<K, V, A>)
796    where
797        K: Ord,
798    {
799        match self {
800            Tree::L(leaf) => leaf.insert(key, x),
801            Tree::NL(nonleaf) => nonleaf.insert(key, x),
802        }
803    }
804
805    fn new_root(&mut self, (med, right): Split<K, V>) {
806        let mut nl = NonLeafInner::new();
807        nl.v.0.set_alloc(1);
808        nl.v.0.push(med);
809        nl.c.set_alloc(2);
810        nl.c.push(mem::take(self));
811        nl.c.push(right);
812        *self = Tree::NL(nl);
813    }
814
815    unsafe fn nonleaf(&mut self) -> &mut NonLeaf<K, V> {
816        match self {
817            Tree::NL(nl) => nl,
818            Tree::L(_) => unsafe { std::hint::unreachable_unchecked() },
819        }
820    }
821
822    unsafe fn leaf(&mut self) -> &mut Leaf<K, V> {
823        match self {
824            Tree::L(leaf) => leaf,
825            Tree::NL(_) => unsafe { std::hint::unreachable_unchecked() },
826        }
827    }
828
829    fn remove<Q, A: AllocTuning>(&mut self, key: &Q, atune: &A) -> Option<(K, V)>
830    where
831        K: Borrow<Q> + Ord,
832        Q: Ord + ?Sized,
833    {
834        match self {
835            Tree::L(leaf) => leaf.remove(key, atune),
836            Tree::NL(nonleaf) => nonleaf.remove(key, atune),
837        }
838    }
839
840    fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
841    where
842        K: Borrow<Q> + Ord,
843        Q: Ord + ?Sized,
844    {
845        let mut s = self;
846        loop {
847            match s {
848                Tree::L(leaf) => return leaf.get_key_value(key),
849                Tree::NL(nl) => match nl.v.look(key) {
850                    Ok(i) => return Some(nl.v.0.ix(i)),
851                    Err(i) => s = nl.c.ix(i),
852                },
853            }
854        }
855    }
856
857    fn get<Q>(&self, key: &Q) -> Option<&V>
858    where
859        K: Borrow<Q> + Ord,
860        Q: Ord + ?Sized,
861    {
862        let mut s = self;
863        loop {
864            match s {
865                Tree::L(leaf) => return leaf.get(key),
866                Tree::NL(nl) => match nl.v.look(key) {
867                    Ok(i) => return Some(nl.v.0.ixv(i)),
868                    Err(i) => s = nl.c.ix(i),
869                },
870            }
871        }
872    }
873
874    fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
875    where
876        K: Borrow<Q> + Ord,
877        Q: Ord + ?Sized,
878    {
879        let mut s = self;
880        loop {
881            match s {
882                Tree::L(leaf) => return leaf.get_mut(key),
883                Tree::NL(nl) => match nl.v.look(key) {
884                    Ok(i) => return Some(nl.v.0.ixmv(i)),
885                    Err(i) => s = nl.c.ixm(i),
886                },
887            }
888        }
889    }
890
891    fn pop_first<A: AllocTuning>(&mut self, atune: &A) -> Option<(K, V)> {
892        match self {
893            Tree::L(leaf) => leaf.pop_first(atune),
894            Tree::NL(nonleaf) => nonleaf.pop_first(atune),
895        }
896    }
897
898    fn pop_last<A: AllocTuning>(&mut self, atune: &A) -> Option<(K, V)> {
899        match self {
900            Tree::L(leaf) => leaf.pop_last(atune),
901            Tree::NL(nonleaf) => nonleaf.pop_last(atune),
902        }
903    }
904
905    fn iter_mut(&mut self) -> RangeMut<'_, K, V> {
906        let mut x = RangeMut::new();
907        x.push_tree(self, true);
908        x
909    }
910
911    fn iter(&self) -> Range<'_, K, V> {
912        let mut x = Range::new();
913        x.push_tree(self, true);
914        x
915    }
916
917    fn range_mut<T, R>(&mut self, range: &R) -> RangeMut<'_, K, V>
918    where
919        T: Ord + ?Sized,
920        K: Borrow<T> + Ord,
921        R: RangeBounds<T>,
922    {
923        let mut x = RangeMut::new();
924        x.push_range(self, range, true);
925        x
926    }
927
928    fn range<T, R>(&self, range: &R) -> Range<'_, K, V>
929    where
930        T: Ord + ?Sized,
931        K: Borrow<T> + Ord,
932        R: RangeBounds<T>,
933    {
934        let mut x = Range::new();
935        x.push_range(self, range, true);
936        x
937    }
938} // End impl Tree
939
940impl<K, V> Default for Leaf<K, V> {
941    fn default() -> Self {
942        Self::new()
943    }
944}
945
946#[derive(Debug, Clone)]
947struct Leaf<K, V>(PairVec<K, V>);
948
949impl<K, V> Leaf<K, V> {
950    fn new() -> Self {
951        Self(PairVec::new())
952    }
953
954    fn full(&self) -> bool {
955        self.0.full()
956    }
957
958    fn into_iter(mut self) -> IntoIterPairVec<K, V> {
959        let v = mem::take(&mut self.0);
960        v.into_iter()
961    }
962
963    fn look_to<Q>(&self, n: usize, key: &Q) -> Result<usize, usize>
964    where
965        K: Borrow<Q> + Ord,
966        Q: Ord + ?Sized,
967    {
968        self.0.search_to(n, key)
969    }
970
971    #[inline]
972    fn look<Q>(&self, key: &Q) -> Result<usize, usize>
973    where
974        K: Borrow<Q> + Ord,
975        Q: Ord + ?Sized,
976    {
977        self.0.search(key)
978    }
979
980    fn skip<Q>(&self, key: &Q) -> usize
981    where
982        K: Borrow<Q> + Ord,
983        Q: Ord + ?Sized,
984    {
985        match self.0.search(key) {
986            Ok(i) | Err(i) => i,
987        }
988    }
989
990    fn skip_over<Q>(&self, key: &Q) -> usize
991    where
992        K: Borrow<Q> + Ord,
993        Q: Ord + ?Sized,
994    {
995        match self.0.search(key) {
996            Ok(i) => i + 1,
997            Err(i) => i,
998        }
999    }
1000
1001    fn get_lower<Q>(&self, bound: Bound<&Q>) -> usize
1002    where
1003        K: Borrow<Q> + Ord,
1004        Q: Ord + ?Sized,
1005    {
1006        match bound {
1007            Bound::Unbounded => 0,
1008            Bound::Included(k) => self.skip(k),
1009            Bound::Excluded(k) => self.skip_over(k),
1010        }
1011    }
1012
1013    fn get_upper<Q>(&self, bound: Bound<&Q>) -> usize
1014    where
1015        K: Borrow<Q> + Ord,
1016        Q: Ord + ?Sized,
1017    {
1018        match bound {
1019            Bound::Unbounded => self.0.len(),
1020            Bound::Included(k) => self.skip_over(k),
1021            Bound::Excluded(k) => self.skip(k),
1022        }
1023    }
1024
1025    fn insert<A: AllocTuning>(&mut self, key: K, x: &mut InsertCtx<K, V, A>)
1026    where
1027        K: Ord,
1028    {
1029        let mut i = match self.look(&key) {
1030            Ok(i) => {
1031                let value = x.value.take().unwrap();
1032                let (k, v) = self.0.ixbm(i);
1033                *k = key;
1034                x.value = Some(mem::replace(v, value));
1035                return;
1036            }
1037            Err(i) => i,
1038        };
1039        let value = x.value.take().unwrap();
1040        if self.full() {
1041            match x.atune.full_action(i, self.0.len()) {
1042                FullAction::Split(b, a1, a2) => {
1043                    let (med, mut right) = self.0.split(b, a1, a2);
1044                    if i > b {
1045                        i -= b + 1;
1046                        assert!(i < a2);
1047                        right.insert(i, (key, value));
1048                    } else {
1049                        assert!(i < a1);
1050                        self.0.insert(i, (key, value));
1051                    }
1052                    let right = Tree::L(Self(right));
1053                    x.split = Some((med, right));
1054                    return;
1055                }
1056                FullAction::Extend(na) => self.0.set_alloc(na),
1057            }
1058        }
1059        self.0.insert(i, (key, value));
1060    }
1061
1062    fn remove<Q, A: AllocTuning>(&mut self, key: &Q, atune: &A) -> Option<(K, V)>
1063    where
1064        K: Borrow<Q> + Ord,
1065        Q: Ord + ?Sized,
1066    {
1067        let ix = self.look(key).ok()?;
1068        let result = self.0.remove(ix);
1069        if let Some(na) = atune.space_action(self.0.state()) {
1070            self.0.set_alloc(na);
1071        }
1072        Some(result)
1073    }
1074
1075    #[inline]
1076    fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
1077    where
1078        K: Borrow<Q> + Ord,
1079        Q: Ord + ?Sized,
1080    {
1081        Some(self.0.ix(self.look(key).ok()?))
1082    }
1083
1084    #[inline]
1085    fn get<Q>(&self, key: &Q) -> Option<&V>
1086    where
1087        K: Borrow<Q> + Ord,
1088        Q: Ord + ?Sized,
1089    {
1090        Some(self.0.ixv(self.look(key).ok()?))
1091    }
1092
1093    #[inline]
1094    fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
1095    where
1096        K: Borrow<Q> + Ord,
1097        Q: Ord + ?Sized,
1098    {
1099        Some(self.0.ixmv(self.look(key).ok()?))
1100    }
1101
1102    fn pop_first<A: AllocTuning>(&mut self, atune: &A) -> Option<(K, V)> {
1103        if self.0.is_empty() {
1104            return None;
1105        }
1106        let result = Some(self.0.remove(0));
1107        if let Some(na) = atune.space_action(self.0.state()) {
1108            self.0.set_alloc(na);
1109        }
1110        result
1111    }
1112
1113    fn pop_last<A: AllocTuning>(&mut self, atune: &A) -> Option<(K, V)> {
1114        if self.0.is_empty() {
1115            return None;
1116        }
1117        let result = self.0.pop();
1118        if let Some(na) = atune.space_action(self.0.state()) {
1119            self.0.set_alloc(na);
1120        }
1121        result
1122    }
1123
1124    fn get_xy<T, R>(&self, range: &R) -> (usize, usize)
1125    where
1126        T: Ord + ?Sized,
1127        K: Borrow<T> + Ord,
1128        R: RangeBounds<T>,
1129    {
1130        let y = match range.end_bound() {
1131            Bound::Unbounded => self.0.len(),
1132            Bound::Included(k) => self.skip_over(k),
1133            Bound::Excluded(k) => self.skip(k),
1134        };
1135        let x = match range.start_bound() {
1136            Bound::Unbounded => 0,
1137            Bound::Included(k) => match self.look_to(y, k) {
1138                Ok(i) => i,
1139                Err(i) => i,
1140            },
1141            Bound::Excluded(k) => match self.look_to(y, k) {
1142                Ok(i) => i + 1,
1143                Err(i) => i,
1144            },
1145        };
1146        (x, y)
1147    }
1148
1149    fn iter_mut(&mut self) -> IterMutPairVec<'_, K, V> {
1150        self.0.iter_mut()
1151    }
1152
1153    fn iter(&self) -> IterPairVec<'_, K, V> {
1154        self.0.iter()
1155    }
1156} // End impl Leaf
1157
1158/* Boxing NonLeaf saves some memory by reducing size of Tree enum */
1159type NonLeaf<K, V> = Box<NonLeafInner<K, V>>;
1160
1161#[derive(Debug, Clone)]
1162struct NonLeafInner<K, V> {
1163    v: Leaf<K, V>,
1164    c: TreeVec<K, V>,
1165}
1166impl<K, V> NonLeafInner<K, V> {
1167    fn new() -> Box<Self> {
1168        Box::new(Self {
1169            v: Leaf::new(),
1170            c: TreeVec::new(),
1171        })
1172    }
1173
1174    #[allow(clippy::type_complexity)]
1175    fn into_iter(mut self) -> (IntoIterPairVec<K, V>, IntoIterShortVec<Tree<K, V>>) {
1176        let v = mem::take(&mut self.v);
1177        let c = mem::take(&mut self.c);
1178        (v.into_iter(), c.into_iter())
1179    }
1180
1181    fn remove_at<A: AllocTuning>(&mut self, i: usize, atune: &A) -> ((K, V), usize) {
1182        if let Some(kv) = self.c.ixm(i).pop_last(atune) {
1183            let (kp, vp) = self.v.0.ixbm(i);
1184            let k = mem::replace(kp, kv.0);
1185            let v = mem::replace(vp, kv.1);
1186            ((k, v), i + 1)
1187        } else {
1188            self.c.remove(i);
1189            let kv = self.v.0.remove(i);
1190            if let Some(na) = atune.space_action(self.v.0.state()) {
1191                self.v.0.set_alloc(na);
1192                self.c.set_alloc(na + 1);
1193            }
1194            (kv, i)
1195        }
1196    }
1197
1198    fn split(&mut self, b: usize, a1: usize, a2: usize) -> ((K, V), Box<Self>) {
1199        let (med, right) = self.v.0.split(b, a1, a2);
1200        let right = Box::new(Self {
1201            v: Leaf(right),
1202            c: self.c.split(b + 1, a1 + 1, a2 + 1),
1203        });
1204        debug_assert!(right.v.0.alloc + 1 == right.c.alloc);
1205        debug_assert!(self.v.0.alloc + 1 == self.c.alloc);
1206        (med, right)
1207    }
1208
1209    fn insert<A: AllocTuning>(&mut self, key: K, x: &mut InsertCtx<K, V, A>)
1210    where
1211        K: Ord,
1212    {
1213        match self.v.look(&key) {
1214            Ok(i) => {
1215                let value = x.value.take().unwrap();
1216                let (kp, vp) = self.v.0.ixbm(i);
1217                *kp = key;
1218                x.value = Some(mem::replace(vp, value));
1219            }
1220            Err(mut i) => {
1221                self.c.ixm(i).insert(key, x);
1222                if let Some((med, right)) = x.split.take() {
1223                    if self.v.full() {
1224                        match x.atune.full_action(i, self.v.0.len()) {
1225                            FullAction::Split(b, a1, a2) => {
1226                                let (pmed, mut pright) = self.split(b, a1, a2);
1227                                if i > b {
1228                                    i -= b + 1;
1229                                    assert!(i < a2);
1230                                    pright.v.0.insert(i, med);
1231                                    pright.c.insert(i + 1, right);
1232                                } else {
1233                                    assert!(i < a1);
1234                                    self.v.0.insert(i, med);
1235                                    self.c.insert(i + 1, right);
1236                                }
1237                                x.split = Some((pmed, Tree::NL(pright)));
1238                                return;
1239                            }
1240                            FullAction::Extend(to) => {
1241                                self.v.0.set_alloc(to);
1242                                self.c.set_alloc(to + 1);
1243                            }
1244                        }
1245                    }
1246                    self.v.0.insert(i, med);
1247                    self.c.insert(i + 1, right);
1248                }
1249            }
1250        }
1251    }
1252
1253    fn remove<Q, A: AllocTuning>(&mut self, key: &Q, atune: &A) -> Option<(K, V)>
1254    where
1255        K: Borrow<Q> + Ord,
1256        Q: Ord + ?Sized,
1257    {
1258        match self.v.look(key) {
1259            Ok(i) => Some(self.remove_at(i, atune).0),
1260            Err(i) => self.c.ixm(i).remove(key, atune),
1261        }
1262    }
1263
1264    fn pop_first<A: AllocTuning>(&mut self, atune: &A) -> Option<(K, V)> {
1265        if let Some(x) = self.c.ixm(0).pop_first(atune) {
1266            Some(x)
1267        } else if self.v.0.is_empty() {
1268            None
1269        } else {
1270            self.c.remove(0);
1271            let result = Some(self.v.0.remove(0));
1272            if let Some(na) = atune.space_action(self.v.0.state()) {
1273                self.v.0.set_alloc(na);
1274                self.c.set_alloc(na + 1);
1275            }
1276            result
1277        }
1278    }
1279
1280    fn pop_last<A: AllocTuning>(&mut self, atune: &A) -> Option<(K, V)> {
1281        let i = self.c.len();
1282        if let Some(x) = self.c.ixm(i - 1).pop_last(atune) {
1283            Some(x)
1284        } else if self.v.0.is_empty() {
1285            None
1286        } else {
1287            self.c.pop();
1288            let result = self.v.0.pop();
1289            if let Some(na) = atune.space_action(self.v.0.state()) {
1290                self.v.0.set_alloc(na);
1291                self.c.set_alloc(na + 1);
1292            }
1293            result
1294        }
1295    }
1296} // End impl NonLeafInner
1297
1298/// Error returned by [`BTreeMap::try_insert`].
1299pub struct OccupiedError<'a, K, V, A: AllocTuning>
1300where
1301    K: 'a,
1302    V: 'a,
1303{
1304    /// Occupied entry, has the key that was not inserted.
1305    pub entry: OccupiedEntry<'a, K, V, A>,
1306    /// Value that was not inserted.
1307    pub value: V,
1308}
1309impl<K: Debug + Ord, V: Debug, A: AllocTuning> Debug for OccupiedError<'_, K, V, A> {
1310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1311        f.debug_struct("OccupiedError")
1312            .field("key", self.entry.key())
1313            .field("old_value", self.entry.get())
1314            .field("new_value", &self.value)
1315            .finish()
1316    }
1317}
1318impl<'a, K: Debug + Ord, V: Debug, A: AllocTuning> fmt::Display for OccupiedError<'a, K, V, A> {
1319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320        write!(
1321            f,
1322            "failed to insert {:?}, key {:?} already exists with value {:?}",
1323            self.value,
1324            self.entry.key(),
1325            self.entry.get(),
1326        )
1327    }
1328}
1329impl<'a, K: Debug + Ord, V: Debug, A: AllocTuning> Error for OccupiedError<'a, K, V, A> {}
1330
1331/// Entry in `BTreeMap`, returned by [`BTreeMap::entry`].
1332pub enum Entry<'a, K, V, A: AllocTuning> {
1333    /// Vacant entry - map doesn't yet contain key.
1334    Vacant(VacantEntry<'a, K, V, A>),
1335    /// Occupied entry - map already contains key.
1336    Occupied(OccupiedEntry<'a, K, V, A>),
1337}
1338impl<'a, K, V, A: AllocTuning> Entry<'a, K, V, A>
1339where
1340    K: Ord,
1341{
1342    /// Get reference to entry key.
1343    pub fn key(&self) -> &K {
1344        match self {
1345            Entry::Vacant(e) => &e.key,
1346            Entry::Occupied(e) => e.key(),
1347        }
1348    }
1349
1350    /// Insert default value, returning mutable reference to inserted value.
1351    pub fn or_default(self) -> &'a mut V
1352    where
1353        V: Default,
1354    {
1355        match self {
1356            Entry::Vacant(e) => e.insert(Default::default()),
1357            Entry::Occupied(e) => e.into_mut(),
1358        }
1359    }
1360
1361    /// Insert value, returning mutable reference to inserted value.
1362    pub fn or_insert(self, value: V) -> &'a mut V {
1363        match self {
1364            Entry::Vacant(e) => e.insert(value),
1365            Entry::Occupied(e) => e.into_mut(),
1366        }
1367    }
1368
1369    /// Insert default value obtained from function, returning mutable reference to inserted value.
1370    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
1371    where
1372        F: FnOnce() -> V,
1373    {
1374        match self {
1375            Entry::Vacant(e) => e.insert(default()),
1376            Entry::Occupied(e) => e.into_mut(),
1377        }
1378    }
1379
1380    /// Insert default value obtained from function called with key, returning mutable reference to inserted value.
1381    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
1382    where
1383        F: FnOnce(&K) -> V,
1384    {
1385        match self {
1386            Entry::Vacant(e) => {
1387                let value = default(e.key());
1388                e.insert(value)
1389            }
1390            Entry::Occupied(e) => e.into_mut(),
1391        }
1392    }
1393
1394    /// Modify existing value ( if entry is occupied ).
1395    pub fn and_modify<F>(mut self, f: F) -> Entry<'a, K, V, A>
1396    where
1397        F: FnOnce(&mut V),
1398    {
1399        match &mut self {
1400            Entry::Vacant(_e) => {}
1401            Entry::Occupied(e) => {
1402                let v = e.get_mut();
1403                f(v);
1404            }
1405        }
1406        self
1407    }
1408}
1409
1410/// Vacant [Entry].
1411pub struct VacantEntry<'a, K, V, A: AllocTuning> {
1412    key: K,
1413    cursor: CursorMut<'a, K, V, A>,
1414}
1415
1416impl<'a, K: Debug + Ord, V, A: AllocTuning> Debug for VacantEntry<'a, K, V, A> {
1417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1418        f.debug_tuple("VacantEntry").field(self.key()).finish()
1419    }
1420}
1421
1422impl<'a, K, V, A: AllocTuning> VacantEntry<'a, K, V, A>
1423where
1424    K: Ord,
1425{
1426    /// Get reference to entry key.
1427    pub fn key(&self) -> &K {
1428        &self.key
1429    }
1430
1431    /// Get entry key.
1432    pub fn into_key(self) -> K {
1433        self.key
1434    }
1435
1436    /// Insert value into map returning reference to inserted value.
1437    pub fn insert(mut self, value: V) -> &'a mut V {
1438        unsafe { self.cursor.insert_after_unchecked(self.key, value) };
1439        self.cursor.into_mut()
1440    }
1441}
1442
1443/// Occupied [Entry].
1444pub struct OccupiedEntry<'a, K, V, A: AllocTuning> {
1445    cursor: CursorMut<'a, K, V, A>,
1446}
1447impl<K: Debug + Ord, V: Debug, A: AllocTuning> Debug for OccupiedEntry<'_, K, V, A> {
1448    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1449        f.debug_struct("OccupiedEntry")
1450            .field("key", self.key())
1451            .field("value", self.get())
1452            .finish()
1453    }
1454}
1455
1456impl<'a, K, V, A: AllocTuning> OccupiedEntry<'a, K, V, A>
1457where
1458    K: Ord,
1459{
1460    /// Get reference to entry key.
1461    #[must_use]
1462    pub fn key(&self) -> &K {
1463        self.cursor.peek_next().unwrap().0
1464    }
1465
1466    /// Remove (key,value) from map, returning key and value.
1467    #[must_use]
1468    pub fn remove_entry(mut self) -> (K, V) {
1469        self.cursor.remove_next().unwrap()
1470    }
1471
1472    /// Remove (key,value) from map, returning the value.
1473    #[must_use]
1474    pub fn remove(self) -> V {
1475        self.remove_entry().1
1476    }
1477
1478    /// Get reference to the value.
1479    #[must_use]
1480    pub fn get(&self) -> &V {
1481        self.cursor.peek_next().unwrap().1
1482    }
1483
1484    /// Get mutable reference to the value.
1485    pub fn get_mut(&mut self) -> &mut V {
1486        self.cursor.peek_next().unwrap().1
1487    }
1488
1489    /// Get mutable reference to the value, consuming the entry.
1490    #[must_use]
1491    pub fn into_mut(self) -> &'a mut V {
1492        self.cursor.into_mut()
1493    }
1494
1495    /// Update the value returns the old value.
1496    pub fn insert(&mut self, value: V) -> V {
1497        mem::replace(self.get_mut(), value)
1498    }
1499}
1500
1501// Mutable reference iteration.
1502
1503enum StealResultMut<'a, K, V> {
1504    KV((&'a K, &'a mut V)), // Key-value pair.
1505    CT(&'a mut Tree<K, V>), // Child Tree.
1506    Nothing,
1507}
1508
1509/// Iterator returned by [`BTreeMap::iter_mut`].
1510#[derive(Debug, Default)]
1511pub struct IterMut<'a, K, V> {
1512    len: usize,
1513    inner: RangeMut<'a, K, V>,
1514}
1515impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1516    type Item = (&'a K, &'a mut V);
1517    fn next(&mut self) -> Option<Self::Item> {
1518        if self.len == 0 {
1519            None
1520        } else {
1521            self.len -= 1;
1522            self.inner.next()
1523        }
1524    }
1525    fn size_hint(&self) -> (usize, Option<usize>) {
1526        (self.len, Some(self.len))
1527    }
1528}
1529impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1530    fn len(&self) -> usize {
1531        self.len
1532    }
1533}
1534impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1535    fn next_back(&mut self) -> Option<Self::Item> {
1536        if self.len == 0 {
1537            None
1538        } else {
1539            self.len -= 1;
1540            self.inner.next_back()
1541        }
1542    }
1543}
1544impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1545
1546#[derive(Debug)]
1547struct StkMut<'a, K, V> {
1548    v: IterMutPairVec<'a, K, V>,
1549    c: std::slice::IterMut<'a, Tree<K, V>>,
1550}
1551
1552/// Iterator returned by [`BTreeMap::range_mut`].
1553#[derive(Debug, Default)]
1554pub struct RangeMut<'a, K, V> {
1555    /* There are two iterations going on to implement DoubleEndedIterator.
1556       fwd_leaf and fwd_stk are initially used for forward (next) iteration,
1557       once they are exhausted, key-value pairs and child trees are "stolen" from
1558       bck_stk and bck_leaf which are (conversely) initially used for next_back iteration.
1559    */
1560    fwd_leaf: IterMutPairVec<'a, K, V>,
1561    bck_leaf: IterMutPairVec<'a, K, V>,
1562    fwd_stk: StkVec<StkMut<'a, K, V>>,
1563    bck_stk: StkVec<StkMut<'a, K, V>>,
1564}
1565impl<'a, K, V> RangeMut<'a, K, V> {
1566    fn new() -> Self {
1567        Self {
1568            fwd_leaf: IterMutPairVec::default(),
1569            bck_leaf: IterMutPairVec::default(),
1570            fwd_stk: StkVec::new(),
1571            bck_stk: StkVec::new(),
1572        }
1573    }
1574    fn push_tree(&mut self, tree: &'a mut Tree<K, V>, both: bool) {
1575        match tree {
1576            Tree::L(leaf) => self.fwd_leaf = leaf.iter_mut(),
1577            Tree::NL(nl) => {
1578                let (v, mut c) = (nl.v.0.iter_mut(), nl.c.iter_mut());
1579                let ct = c.next();
1580                let ct_back = if both { c.next_back() } else { None };
1581                let both = both && ct_back.is_none();
1582                self.fwd_stk.push(StkMut { v, c });
1583                if let Some(ct) = ct {
1584                    self.push_tree(ct, both);
1585                }
1586                if let Some(ct_back) = ct_back {
1587                    self.push_tree_back(ct_back);
1588                }
1589            }
1590        }
1591    }
1592    fn push_range<T, R>(&mut self, tree: &'a mut Tree<K, V>, range: &R, both: bool)
1593    where
1594        T: Ord + ?Sized,
1595        K: Borrow<T> + Ord,
1596        R: RangeBounds<T>,
1597    {
1598        match tree {
1599            Tree::L(leaf) => {
1600                let (x, y) = leaf.get_xy(range);
1601                self.fwd_leaf = leaf.0.range_mut(x, y);
1602            }
1603            Tree::NL(nl) => {
1604                let (x, y) = nl.v.get_xy(range);
1605                let (v, mut c) = (nl.v.0.range_mut(x, y), nl.c[x..=y].iter_mut());
1606
1607                let ct = c.next();
1608                let ct_back = if both { c.next_back() } else { None };
1609                let both = both && ct_back.is_none();
1610
1611                self.fwd_stk.push(StkMut { v, c });
1612                if let Some(ct) = ct {
1613                    self.push_range(ct, range, both);
1614                }
1615                if let Some(ct_back) = ct_back {
1616                    self.push_range_back(ct_back, range);
1617                }
1618            }
1619        }
1620    }
1621    fn push_range_back<T, R>(&mut self, tree: &'a mut Tree<K, V>, range: &R)
1622    where
1623        T: Ord + ?Sized,
1624        K: Borrow<T> + Ord,
1625        R: RangeBounds<T>,
1626    {
1627        match tree {
1628            Tree::L(leaf) => {
1629                let (x, y) = leaf.get_xy(range);
1630                self.bck_leaf = leaf.0.range_mut(x, y);
1631            }
1632            Tree::NL(nl) => {
1633                let (x, y) = nl.v.get_xy(range);
1634                let (v, mut c) = (nl.v.0.range_mut(x, y), nl.c[x..=y].iter_mut());
1635                let ct_back = c.next_back();
1636                self.bck_stk.push(StkMut { v, c });
1637                if let Some(ct_back) = ct_back {
1638                    self.push_range_back(ct_back, range);
1639                }
1640            }
1641        }
1642    }
1643    fn push_tree_back(&mut self, tree: &'a mut Tree<K, V>) {
1644        match tree {
1645            Tree::L(leaf) => self.bck_leaf = leaf.iter_mut(),
1646            Tree::NL(nl) => {
1647                let (v, mut c) = (nl.v.0.iter_mut(), nl.c.iter_mut());
1648                let ct_back = c.next_back();
1649                self.bck_stk.push(StkMut { v, c });
1650                if let Some(ct_back) = ct_back {
1651                    self.push_tree_back(ct_back);
1652                }
1653            }
1654        }
1655    }
1656    fn steal_bck(&mut self) -> StealResultMut<'a, K, V> {
1657        for s in &mut self.bck_stk {
1658            if s.v.len() > s.c.len() {
1659                return StealResultMut::KV(s.v.next().unwrap());
1660            } else if let Some(ct) = s.c.next() {
1661                return StealResultMut::CT(ct);
1662            }
1663        }
1664        StealResultMut::Nothing
1665    }
1666    fn steal_fwd(&mut self) -> StealResultMut<'a, K, V> {
1667        for s in &mut self.fwd_stk {
1668            if s.v.len() > s.c.len() {
1669                return StealResultMut::KV(s.v.next_back().unwrap());
1670            } else if let Some(ct) = s.c.next_back() {
1671                return StealResultMut::CT(ct);
1672            }
1673        }
1674        StealResultMut::Nothing
1675    }
1676    #[cold]
1677    fn next_inner(&mut self) -> Option<(&'a K, &'a mut V)> {
1678        loop {
1679            if let Some(s) = self.fwd_stk.last_mut() {
1680                if let Some(kv) = s.v.next() {
1681                    if let Some(ct) = s.c.next() {
1682                        self.push_tree(ct, false);
1683                    }
1684                    return Some(kv);
1685                }
1686                self.fwd_stk.pop();
1687            } else {
1688                match self.steal_bck() {
1689                    StealResultMut::KV(kv) => return Some(kv),
1690                    StealResultMut::CT(ct) => {
1691                        self.push_tree(ct, false);
1692                        if let Some(x) = self.fwd_leaf.next() {
1693                            return Some(x);
1694                        }
1695                    }
1696                    StealResultMut::Nothing => {
1697                        if let Some(x) = self.bck_leaf.next() {
1698                            return Some(x);
1699                        }
1700                        return None;
1701                    }
1702                }
1703            }
1704        }
1705    }
1706    #[cold]
1707    fn next_back_inner(&mut self) -> Option<(&'a K, &'a mut V)> {
1708        loop {
1709            if let Some(s) = self.bck_stk.last_mut() {
1710                if let Some(kv) = s.v.next_back() {
1711                    if let Some(ct) = s.c.next_back() {
1712                        self.push_tree_back(ct);
1713                    }
1714                    return Some(kv);
1715                }
1716                self.bck_stk.pop();
1717            } else {
1718                match self.steal_fwd() {
1719                    StealResultMut::KV(kv) => return Some(kv),
1720                    StealResultMut::CT(ct) => {
1721                        self.push_tree_back(ct);
1722                        if let Some(x) = self.bck_leaf.next_back() {
1723                            return Some(x);
1724                        }
1725                    }
1726                    StealResultMut::Nothing => {
1727                        if let Some(x) = self.fwd_leaf.next_back() {
1728                            return Some(x);
1729                        }
1730                        return None;
1731                    }
1732                }
1733            }
1734        }
1735    }
1736}
1737impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1738    type Item = (&'a K, &'a mut V);
1739    fn next(&mut self) -> Option<Self::Item> {
1740        if let Some(x) = self.fwd_leaf.next() {
1741            return Some(x);
1742        }
1743        self.next_inner()
1744    }
1745}
1746impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1747    fn next_back(&mut self) -> Option<Self::Item> {
1748        if let Some(x) = self.bck_leaf.next_back() {
1749            return Some(x);
1750        }
1751        self.next_back_inner()
1752    }
1753}
1754impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1755
1756// Consuming iteration.
1757
1758enum StealResultCon<K, V> {
1759    KV((K, V)),     // Key-value pair.
1760    CT(Tree<K, V>), // Child Tree.
1761    Nothing,
1762}
1763
1764/// Consuming iterator for [`BTreeMap`].
1765pub struct IntoIter<K, V> {
1766    len: usize,
1767    inner: IntoIterInner<K, V>,
1768}
1769impl<K, V> IntoIter<K, V> {
1770    fn new<A: AllocTuning>(bt: BTreeMap<K, V, A>) -> Self {
1771        let mut s = Self {
1772            len: bt.len(),
1773            inner: IntoIterInner::new(),
1774        };
1775        s.inner.push_tree(bt.tree, true);
1776        s
1777    }
1778}
1779impl<K, V> Iterator for IntoIter<K, V> {
1780    type Item = (K, V);
1781    fn next(&mut self) -> Option<Self::Item> {
1782        let result = self.inner.next()?;
1783        self.len -= 1;
1784        Some(result)
1785    }
1786    fn size_hint(&self) -> (usize, Option<usize>) {
1787        (self.len, Some(self.len))
1788    }
1789}
1790impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1791    fn next_back(&mut self) -> Option<Self::Item> {
1792        let result = self.inner.next_back()?;
1793        self.len -= 1;
1794        Some(result)
1795    }
1796}
1797impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1798    fn len(&self) -> usize {
1799        self.len
1800    }
1801}
1802impl<K, V> FusedIterator for IntoIter<K, V> {}
1803
1804struct StkCon<K, V> {
1805    v: IntoIterPairVec<K, V>,
1806    c: IntoIterShortVec<Tree<K, V>>,
1807}
1808
1809struct IntoIterInner<K, V> {
1810    fwd_leaf: IntoIterPairVec<K, V>,
1811    bck_leaf: IntoIterPairVec<K, V>,
1812    fwd_stk: StkVec<StkCon<K, V>>,
1813    bck_stk: StkVec<StkCon<K, V>>,
1814}
1815impl<K, V> IntoIterInner<K, V> {
1816    fn new() -> Self {
1817        Self {
1818            fwd_leaf: IntoIterPairVec::default(),
1819            bck_leaf: IntoIterPairVec::default(),
1820            fwd_stk: StkVec::new(),
1821            bck_stk: StkVec::new(),
1822        }
1823    }
1824    fn push_tree(&mut self, tree: Tree<K, V>, both: bool) {
1825        match tree {
1826            Tree::L(leaf) => self.fwd_leaf = leaf.into_iter(),
1827            Tree::NL(nl) => {
1828                let (v, mut c) = nl.into_iter();
1829                let ct = c.next();
1830                let ct_back = if both { c.next_back() } else { None };
1831                let both = both && ct_back.is_none();
1832                self.fwd_stk.push(StkCon { v, c });
1833                if let Some(ct) = ct {
1834                    self.push_tree(ct, both);
1835                }
1836                if let Some(ct_back) = ct_back {
1837                    self.push_tree_back(ct_back);
1838                }
1839            }
1840        }
1841    }
1842    fn push_tree_back(&mut self, tree: Tree<K, V>) {
1843        match tree {
1844            Tree::L(leaf) => self.bck_leaf = leaf.into_iter(),
1845            Tree::NL(nl) => {
1846                let (v, mut c) = nl.into_iter();
1847                let ct_back = c.next_back();
1848                self.bck_stk.push(StkCon { v, c });
1849                if let Some(ct_back) = ct_back {
1850                    self.push_tree_back(ct_back);
1851                }
1852            }
1853        }
1854    }
1855    fn steal_bck(&mut self) -> StealResultCon<K, V> {
1856        for s in &mut self.bck_stk {
1857            if s.v.len() > s.c.len() {
1858                return StealResultCon::KV(s.v.next().unwrap());
1859            } else if let Some(ct) = s.c.next() {
1860                return StealResultCon::CT(ct);
1861            }
1862        }
1863        StealResultCon::Nothing
1864    }
1865    fn steal_fwd(&mut self) -> StealResultCon<K, V> {
1866        for s in &mut self.fwd_stk {
1867            if s.v.len() > s.c.len() {
1868                return StealResultCon::KV(s.v.next_back().unwrap());
1869            } else if let Some(ct) = s.c.next_back() {
1870                return StealResultCon::CT(ct);
1871            }
1872        }
1873        StealResultCon::Nothing
1874    }
1875    #[cold]
1876    fn next_inner(&mut self) -> Option<(K, V)> {
1877        loop {
1878            if let Some(s) = self.fwd_stk.last_mut() {
1879                if let Some(kv) = s.v.next() {
1880                    if let Some(ct) = s.c.next() {
1881                        self.push_tree(ct, false);
1882                    }
1883                    return Some(kv);
1884                }
1885                self.fwd_stk.pop();
1886            } else {
1887                match self.steal_bck() {
1888                    StealResultCon::KV(kv) => return Some(kv),
1889                    StealResultCon::CT(ct) => {
1890                        self.push_tree(ct, false);
1891                        if let Some(x) = self.fwd_leaf.next() {
1892                            return Some(x);
1893                        }
1894                    }
1895                    StealResultCon::Nothing => {
1896                        if let Some(x) = self.bck_leaf.next() {
1897                            return Some(x);
1898                        }
1899                        return None;
1900                    }
1901                }
1902            }
1903        }
1904    }
1905    #[cold]
1906    fn next_back_inner(&mut self) -> Option<(K, V)> {
1907        loop {
1908            if let Some(s) = self.bck_stk.last_mut() {
1909                if let Some(kv) = s.v.next_back() {
1910                    if let Some(ct) = s.c.next_back() {
1911                        self.push_tree_back(ct);
1912                    }
1913                    return Some(kv);
1914                }
1915                self.bck_stk.pop();
1916            } else {
1917                match self.steal_fwd() {
1918                    StealResultCon::KV(kv) => return Some(kv),
1919                    StealResultCon::CT(ct) => {
1920                        self.push_tree_back(ct);
1921                        if let Some(x) = self.bck_leaf.next_back() {
1922                            return Some(x);
1923                        }
1924                    }
1925                    StealResultCon::Nothing => {
1926                        if let Some(x) = self.fwd_leaf.next_back() {
1927                            return Some(x);
1928                        }
1929                        return None;
1930                    }
1931                }
1932            }
1933        }
1934    }
1935}
1936impl<K, V> Iterator for IntoIterInner<K, V> {
1937    type Item = (K, V);
1938    fn next(&mut self) -> Option<Self::Item> {
1939        if let Some(x) = self.fwd_leaf.next() {
1940            return Some(x);
1941        }
1942        self.next_inner()
1943    }
1944}
1945impl<K, V> DoubleEndedIterator for IntoIterInner<K, V> {
1946    fn next_back(&mut self) -> Option<Self::Item> {
1947        if let Some(x) = self.bck_leaf.next_back() {
1948            return Some(x);
1949        }
1950        self.next_back_inner()
1951    }
1952}
1953
1954// Immutable reference iteration.
1955
1956enum StealResult<'a, K, V> {
1957    KV((&'a K, &'a V)), // Key-value pair.
1958    CT(&'a Tree<K, V>), // Child Tree.
1959    Nothing,
1960}
1961
1962/// Iterator returned by [`BTreeMap::iter`].
1963#[derive(Clone, Debug, Default)]
1964pub struct Iter<'a, K, V> {
1965    len: usize,
1966    inner: Range<'a, K, V>,
1967}
1968impl<'a, K, V> Iterator for Iter<'a, K, V> {
1969    type Item = (&'a K, &'a V);
1970    fn next(&mut self) -> Option<Self::Item> {
1971        if self.len == 0 {
1972            None
1973        } else {
1974            self.len -= 1;
1975            self.inner.next()
1976        }
1977    }
1978    fn size_hint(&self) -> (usize, Option<usize>) {
1979        (self.len, Some(self.len))
1980    }
1981}
1982impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1983    fn len(&self) -> usize {
1984        self.len
1985    }
1986}
1987impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1988    fn next_back(&mut self) -> Option<Self::Item> {
1989        if self.len == 0 {
1990            None
1991        } else {
1992            self.len -= 1;
1993            self.inner.next_back()
1994        }
1995    }
1996}
1997impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1998
1999#[derive(Clone, Debug)]
2000struct Stk<'a, K, V> {
2001    v: IterPairVec<'a, K, V>,
2002    c: std::slice::Iter<'a, Tree<K, V>>,
2003}
2004
2005/// Iterator returned by [`BTreeMap::range`].
2006#[derive(Clone, Debug, Default)]
2007pub struct Range<'a, K, V> {
2008    fwd_leaf: IterPairVec<'a, K, V>,
2009    bck_leaf: IterPairVec<'a, K, V>,
2010    fwd_stk: StkVec<Stk<'a, K, V>>,
2011    bck_stk: StkVec<Stk<'a, K, V>>,
2012}
2013impl<'a, K, V> Range<'a, K, V> {
2014    fn new() -> Self {
2015        Self {
2016            fwd_leaf: IterPairVec::default(),
2017            bck_leaf: IterPairVec::default(),
2018            fwd_stk: StkVec::new(),
2019            bck_stk: StkVec::new(),
2020        }
2021    }
2022    fn push_tree(&mut self, tree: &'a Tree<K, V>, both: bool) {
2023        match tree {
2024            Tree::L(leaf) => self.fwd_leaf = leaf.0.iter(),
2025            Tree::NL(nl) => {
2026                let (v, mut c) = (nl.v.0.iter(), nl.c.iter());
2027                let ct = c.next();
2028                let ct_back = if both { c.next_back() } else { None };
2029                let both = both && ct_back.is_none();
2030                self.fwd_stk.push(Stk { v, c });
2031                if let Some(ct) = ct {
2032                    self.push_tree(ct, both);
2033                }
2034                if let Some(ct_back) = ct_back {
2035                    self.push_tree_back(ct_back);
2036                }
2037            }
2038        }
2039    }
2040    fn push_range<T, R>(&mut self, tree: &'a Tree<K, V>, range: &R, both: bool)
2041    where
2042        T: Ord + ?Sized,
2043        K: Borrow<T> + Ord,
2044        R: RangeBounds<T>,
2045    {
2046        match tree {
2047            Tree::L(leaf) => {
2048                let (x, y) = leaf.get_xy(range);
2049                self.fwd_leaf = leaf.0.range(x, y);
2050            }
2051            Tree::NL(nl) => {
2052                let (x, y) = nl.v.get_xy(range);
2053                let (v, mut c) = (nl.v.0.range(x, y), nl.c[x..=y].iter());
2054
2055                let ct = c.next();
2056                let ct_back = if both { c.next_back() } else { None };
2057                let both = both && ct_back.is_none();
2058
2059                self.fwd_stk.push(Stk { v, c });
2060                if let Some(ct) = ct {
2061                    self.push_range(ct, range, both);
2062                }
2063                if let Some(ct_back) = ct_back {
2064                    self.push_range_back(ct_back, range);
2065                }
2066            }
2067        }
2068    }
2069    fn push_range_back<T, R>(&mut self, tree: &'a Tree<K, V>, range: &R)
2070    where
2071        T: Ord + ?Sized,
2072        K: Borrow<T> + Ord,
2073        R: RangeBounds<T>,
2074    {
2075        match tree {
2076            Tree::L(leaf) => {
2077                let (x, y) = leaf.get_xy(range);
2078                self.bck_leaf = leaf.0.range(x, y);
2079            }
2080            Tree::NL(nl) => {
2081                let (x, y) = nl.v.get_xy(range);
2082                let (v, mut c) = (nl.v.0.range(x, y), nl.c[x..=y].iter());
2083                let ct_back = c.next_back();
2084                self.bck_stk.push(Stk { v, c });
2085                if let Some(ct_back) = ct_back {
2086                    self.push_range_back(ct_back, range);
2087                }
2088            }
2089        }
2090    }
2091    fn push_tree_back(&mut self, tree: &'a Tree<K, V>) {
2092        match tree {
2093            Tree::L(leaf) => {
2094                self.bck_leaf = leaf.iter();
2095            }
2096            Tree::NL(nl) => {
2097                let (v, mut c) = (nl.v.0.iter(), nl.c.iter());
2098                let ct_back = c.next_back();
2099                self.bck_stk.push(Stk { v, c });
2100                if let Some(ct_back) = ct_back {
2101                    self.push_tree_back(ct_back);
2102                }
2103            }
2104        }
2105    }
2106    fn steal_bck(&mut self) -> StealResult<'a, K, V> {
2107        for s in &mut self.bck_stk {
2108            if s.v.len() > s.c.len() {
2109                return StealResult::KV(s.v.next().unwrap());
2110            } else if let Some(ct) = s.c.next() {
2111                return StealResult::CT(ct);
2112            }
2113        }
2114        StealResult::Nothing
2115    }
2116    fn steal_fwd(&mut self) -> StealResult<'a, K, V> {
2117        for s in &mut self.fwd_stk {
2118            if s.v.len() > s.c.len() {
2119                return StealResult::KV(s.v.next_back().unwrap());
2120            } else if let Some(ct) = s.c.next_back() {
2121                return StealResult::CT(ct);
2122            }
2123        }
2124        StealResult::Nothing
2125    }
2126    #[cold]
2127    fn next_inner(&mut self) -> Option<(&'a K, &'a V)> {
2128        loop {
2129            if let Some(s) = self.fwd_stk.last_mut() {
2130                if let Some(kv) = s.v.next() {
2131                    if let Some(ct) = s.c.next() {
2132                        self.push_tree(ct, false);
2133                    }
2134                    return Some(kv);
2135                }
2136                self.fwd_stk.pop();
2137            } else {
2138                match self.steal_bck() {
2139                    StealResult::KV(kv) => return Some(kv),
2140                    StealResult::CT(ct) => {
2141                        self.push_tree(ct, false);
2142                        if let Some(x) = self.fwd_leaf.next() {
2143                            return Some(x);
2144                        }
2145                    }
2146                    StealResult::Nothing => {
2147                        if let Some(x) = self.bck_leaf.next() {
2148                            return Some(x);
2149                        }
2150                        return None;
2151                    }
2152                }
2153            }
2154        }
2155    }
2156    #[cold]
2157    fn next_back_inner(&mut self) -> Option<(&'a K, &'a V)> {
2158        loop {
2159            if let Some(s) = self.bck_stk.last_mut() {
2160                if let Some(kv) = s.v.next_back() {
2161                    if let Some(ct) = s.c.next_back() {
2162                        self.push_tree_back(ct);
2163                    }
2164                    return Some(kv);
2165                }
2166                self.bck_stk.pop();
2167            } else {
2168                match self.steal_fwd() {
2169                    StealResult::KV(kv) => return Some(kv),
2170                    StealResult::CT(ct) => {
2171                        self.push_tree_back(ct);
2172                        if let Some(x) = self.bck_leaf.next_back() {
2173                            return Some(x);
2174                        }
2175                    }
2176                    StealResult::Nothing => {
2177                        if let Some(x) = self.fwd_leaf.next_back() {
2178                            return Some(x);
2179                        }
2180                        return None;
2181                    }
2182                }
2183            }
2184        }
2185    }
2186}
2187impl<'a, K, V> Iterator for Range<'a, K, V> {
2188    type Item = (&'a K, &'a V);
2189    fn next(&mut self) -> Option<Self::Item> {
2190        if let Some(x) = self.fwd_leaf.next() {
2191            return Some(x);
2192        }
2193        self.next_inner()
2194    }
2195}
2196impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2197    fn next_back(&mut self) -> Option<Self::Item> {
2198        if let Some(x) = self.bck_leaf.next_back() {
2199            return Some(x);
2200        }
2201        self.next_back_inner()
2202    }
2203}
2204impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
2205
2206/// Consuming iterator returned by [`BTreeMap::into_keys`].
2207pub struct IntoKeys<K, V>(IntoIter<K, V>);
2208impl<K, V> Iterator for IntoKeys<K, V> {
2209    type Item = K;
2210    fn next(&mut self) -> Option<Self::Item> {
2211        Some(self.0.next()?.0)
2212    }
2213    fn size_hint(&self) -> (usize, Option<usize>) {
2214        self.0.size_hint()
2215    }
2216}
2217impl<K, V> DoubleEndedIterator for IntoKeys<K, V> {
2218    fn next_back(&mut self) -> Option<Self::Item> {
2219        Some(self.0.next_back()?.0)
2220    }
2221}
2222impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
2223    fn len(&self) -> usize {
2224        self.0.len()
2225    }
2226}
2227impl<K, V> FusedIterator for IntoKeys<K, V> {}
2228
2229/// Consuming iterator returned by [`BTreeMap::into_values`].
2230pub struct IntoValues<K, V>(IntoIter<K, V>);
2231impl<K, V> Iterator for IntoValues<K, V> {
2232    type Item = V;
2233    fn next(&mut self) -> Option<Self::Item> {
2234        Some(self.0.next()?.1)
2235    }
2236    fn size_hint(&self) -> (usize, Option<usize>) {
2237        self.0.size_hint()
2238    }
2239}
2240impl<K, V> DoubleEndedIterator for IntoValues<K, V> {
2241    fn next_back(&mut self) -> Option<Self::Item> {
2242        Some(self.0.next_back()?.1)
2243    }
2244}
2245impl<K, V> ExactSizeIterator for IntoValues<K, V> {
2246    fn len(&self) -> usize {
2247        self.0.len()
2248    }
2249}
2250impl<K, V> FusedIterator for IntoValues<K, V> {}
2251
2252// Trivial iterators.
2253
2254/// Iterator returned by [`BTreeMap::values_mut`].
2255#[derive(Debug)]
2256pub struct ValuesMut<'a, K, V>(IterMut<'a, K, V>);
2257impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2258    type Item = &'a mut V;
2259    fn next(&mut self) -> Option<Self::Item> {
2260        self.0.next().map(|(_, v)| v)
2261    }
2262}
2263impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2264    fn next_back(&mut self) -> Option<Self::Item> {
2265        self.0.next_back().map(|(_, v)| v)
2266    }
2267}
2268impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
2269    fn len(&self) -> usize {
2270        self.0.len()
2271    }
2272}
2273impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
2274
2275/// Iterator returned by [`BTreeMap::values`].
2276#[derive(Clone, Debug, Default)]
2277pub struct Values<'a, K, V>(Iter<'a, K, V>);
2278impl<'a, K, V> Iterator for Values<'a, K, V> {
2279    type Item = &'a V;
2280    fn next(&mut self) -> Option<Self::Item> {
2281        self.0.next().map(|(_, v)| v)
2282    }
2283}
2284impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
2285    fn next_back(&mut self) -> Option<Self::Item> {
2286        self.0.next_back().map(|(_, v)| v)
2287    }
2288}
2289impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
2290    fn len(&self) -> usize {
2291        self.0.len()
2292    }
2293}
2294impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
2295
2296/// Iterator returned by [`BTreeMap::keys`].
2297#[derive(Clone, Debug, Default)]
2298pub struct Keys<'a, K, V>(Iter<'a, K, V>);
2299impl<'a, K, V> Iterator for Keys<'a, K, V> {
2300    type Item = &'a K;
2301    fn next(&mut self) -> Option<Self::Item> {
2302        self.0.next().map(|(k, _)| k)
2303    }
2304}
2305impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
2306    fn next_back(&mut self) -> Option<Self::Item> {
2307        self.0.next_back().map(|(k, _)| k)
2308    }
2309}
2310impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
2311    fn len(&self) -> usize {
2312        self.0.len()
2313    }
2314}
2315impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
2316
2317/// Iterator returned by [`BTreeMap::extract_if`].
2318// #[derive(Debug)]
2319pub struct ExtractIf<'a, K, V, A: AllocTuning, F>
2320where
2321    F: FnMut(&K, &mut V) -> bool,
2322{
2323    source: CursorMut<'a, K, V, A>,
2324    pred: F,
2325}
2326impl<K, V, A: AllocTuning, F> fmt::Debug for ExtractIf<'_, K, V, A, F>
2327where
2328    K: fmt::Debug,
2329    V: fmt::Debug,
2330    F: FnMut(&K, &mut V) -> bool,
2331{
2332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2333        f.debug_tuple("ExtractIf")
2334            .field(&self.source.peek_next())
2335            .finish()
2336    }
2337}
2338impl<'a, K, V, A: AllocTuning, F> Iterator for ExtractIf<'a, K, V, A, F>
2339where
2340    F: FnMut(&K, &mut V) -> bool,
2341{
2342    type Item = (K, V);
2343    fn next(&mut self) -> Option<Self::Item> {
2344        loop {
2345            let (k, v) = self.source.peek_next()?;
2346            if (self.pred)(k, v) {
2347                return self.source.remove_next();
2348            }
2349            self.source.next();
2350        }
2351    }
2352}
2353impl<'a, K, V, A: AllocTuning, F> FusedIterator for ExtractIf<'a, K, V, A, F> where
2354    F: FnMut(&K, &mut V) -> bool
2355{
2356}
2357
2358// Cursors.
2359
2360/// Error type for [`CursorMut::insert_before`] and [`CursorMut::insert_after`].
2361#[derive(Clone, PartialEq, Eq, Debug)]
2362pub struct UnorderedKeyError {}
2363impl fmt::Display for UnorderedKeyError {
2364    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2365        write!(f, "key is not properly ordered relative to neighbors")
2366    }
2367}
2368impl std::error::Error for UnorderedKeyError {}
2369
2370/// Cursor that allows mutation of map, returned by [`BTreeMap::lower_bound_mut`], [`BTreeMap::upper_bound_mut`].
2371pub struct CursorMut<'a, K, V, A: AllocTuning>(CursorMutKey<'a, K, V, A>);
2372impl<'a, K, V, A: AllocTuning> CursorMut<'a, K, V, A> {
2373    fn lower_bound<Q>(map: &'a mut BTreeMap<K, V, A>, bound: Bound<&Q>) -> Self
2374    where
2375        K: Borrow<Q> + Ord,
2376        Q: Ord + ?Sized,
2377    {
2378        unsafe {
2379            // Converting map to raw pointer here is necessary to keep Miri happy
2380            // although not when using MIRIFLAGS=-Zmiri-tree-borrows.
2381            let map: *mut BTreeMap<K, V, A> = map;
2382            let mut s = CursorMutKey::make(map);
2383            s.push_lower(&mut (*map).tree, bound);
2384            Self(s)
2385        }
2386    }
2387
2388    fn upper_bound<Q>(map: &'a mut BTreeMap<K, V, A>, bound: Bound<&Q>) -> Self
2389    where
2390        K: Borrow<Q> + Ord,
2391        Q: Ord + ?Sized,
2392    {
2393        unsafe {
2394            let map: *mut BTreeMap<K, V, A> = map;
2395            let mut s = CursorMutKey::make(map);
2396            s.push_upper(&mut (*map).tree, bound);
2397            Self(s)
2398        }
2399    }
2400
2401    /// Insert leaving cursor after newly inserted element.
2402    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>
2403    where
2404        K: Ord,
2405    {
2406        self.0.insert_before(key, value)
2407    }
2408
2409    /// Insert leaving cursor before newly inserted element.
2410    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>
2411    where
2412        K: Ord,
2413    {
2414        self.0.insert_after(key, value)
2415    }
2416
2417    /// Insert leaving cursor after newly inserted element.
2418    /// # Safety
2419    ///
2420    /// Keys must be unique and in sorted order.
2421    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
2422        self.0.insert_before_unchecked(key, value);
2423    }
2424
2425    /// Insert leaving cursor before newly inserted element.
2426    /// # Safety
2427    ///
2428    /// Keys must be unique and in sorted order.
2429    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
2430        self.0.insert_after_unchecked(key, value);
2431    }
2432
2433    /// Remove previous element.
2434    pub fn remove_prev(&mut self) -> Option<(K, V)> {
2435        self.0.remove_prev()
2436    }
2437
2438    /// Remove next element.
2439    pub fn remove_next(&mut self) -> Option<(K, V)> {
2440        self.0.remove_next()
2441    }
2442
2443    /// Advance the cursor, returns references to the key and value of the element that it moved over.
2444    #[allow(clippy::should_implement_trait)]
2445    pub fn next(&mut self) -> Option<(&K, &mut V)> {
2446        let (k, v) = self.0.next()?;
2447        Some((&*k, v))
2448    }
2449
2450    /// Move the cursor back, returns references to the key and value of the element that it moved over.
2451    pub fn prev(&mut self) -> Option<(&K, &mut V)> {
2452        let (k, v) = self.0.prev()?;
2453        Some((&*k, v))
2454    }
2455
2456    /// Get references to the next key/value pair.
2457    #[must_use]
2458    pub fn peek_next(&self) -> Option<(&K, &mut V)> {
2459        let (k, v) = self.0.peek_next()?;
2460        Some((&*k, v))
2461    }
2462
2463    /// Get references to the previous key/value pair.
2464    #[must_use]
2465    pub fn peek_prev(&self) -> Option<(&K, &mut V)> {
2466        let (k, v) = self.0.peek_prev()?;
2467        Some((&*k, v))
2468    }
2469
2470    /// Converts the cursor into a `CursorMutKey`, which allows mutating the key of elements in the tree.
2471    /// # Safety
2472    ///
2473    /// Keys must be unique and in sorted order.
2474    #[must_use]
2475    pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
2476        self.0
2477    }
2478
2479    /// Returns a read-only cursor pointing to the same location as the `CursorMut`.
2480    #[must_use]
2481    pub fn as_cursor(&self) -> Cursor<'_, K, V, A> {
2482        self.0.as_cursor()
2483    }
2484
2485    /// This is needed for the implementation of the [Entry] API.
2486    fn into_mut(self) -> &'a mut V {
2487        self.0.into_mut()
2488    }
2489}
2490
2491/// Cursor that allows mutation of map keys, returned by [`CursorMut::with_mutable_key`].
2492pub struct CursorMutKey<'a, K, V, A: AllocTuning> {
2493    map: *mut BTreeMap<K, V, A>,
2494    leaf: Option<*mut Leaf<K, V>>,
2495    index: usize,
2496    stack: StkVec<(*mut NonLeaf<K, V>, usize)>,
2497    _pd: PhantomData<&'a mut BTreeMap<K, V, A>>,
2498}
2499
2500unsafe impl<'a, K, V, A: AllocTuning> Send for CursorMutKey<'a, K, V, A> {}
2501unsafe impl<'a, K, V, A: AllocTuning> Sync for CursorMutKey<'a, K, V, A> {}
2502
2503impl<'a, K, V, A: AllocTuning> CursorMutKey<'a, K, V, A> {
2504    fn make(map: *mut BTreeMap<K, V, A>) -> Self {
2505        Self {
2506            map,
2507            leaf: None,
2508            index: 0,
2509            stack: StkVec::new(),
2510            _pd: PhantomData,
2511        }
2512    }
2513
2514    fn push_lower<Q>(&mut self, mut tree: &mut Tree<K, V>, bound: Bound<&Q>)
2515    where
2516        K: Borrow<Q> + Ord,
2517        Q: Ord + ?Sized,
2518    {
2519        loop {
2520            match tree {
2521                Tree::L(leaf) => {
2522                    self.index = leaf.get_lower(bound);
2523                    self.leaf = Some(leaf);
2524                    break;
2525                }
2526                Tree::NL(nl) => {
2527                    let ix = nl.v.get_lower(bound);
2528                    self.stack.push((nl, ix));
2529                    tree = nl.c.ixm(ix);
2530                }
2531            }
2532        }
2533    }
2534
2535    fn push_upper<Q>(&mut self, mut tree: &mut Tree<K, V>, bound: Bound<&Q>)
2536    where
2537        K: Borrow<Q> + Ord,
2538        Q: Ord + ?Sized,
2539    {
2540        loop {
2541            match tree {
2542                Tree::L(leaf) => {
2543                    self.index = leaf.get_upper(bound);
2544                    self.leaf = Some(leaf);
2545                    break;
2546                }
2547                Tree::NL(nl) => {
2548                    let ix = nl.v.get_upper(bound);
2549                    self.stack.push((nl, ix));
2550                    tree = nl.c.ixm(ix);
2551                }
2552            }
2553        }
2554    }
2555
2556    fn push(&mut self, mut tsp: usize, mut tree: &mut Tree<K, V>) {
2557        loop {
2558            match tree {
2559                Tree::L(leaf) => {
2560                    self.index = 0;
2561                    self.leaf = Some(leaf);
2562                    break;
2563                }
2564                Tree::NL(nl) => {
2565                    self.stack[tsp] = (nl, 0);
2566                    tree = nl.c.ixm(0);
2567                    tsp += 1;
2568                }
2569            }
2570        }
2571    }
2572
2573    fn push_back(&mut self, mut tsp: usize, mut tree: &mut Tree<K, V>) {
2574        loop {
2575            match tree {
2576                Tree::L(leaf) => {
2577                    self.index = leaf.0.len();
2578                    self.leaf = Some(leaf);
2579                    break;
2580                }
2581                Tree::NL(nl) => {
2582                    let ix = nl.v.0.len();
2583                    self.stack[tsp] = (nl, ix);
2584                    tree = nl.c.ixm(ix);
2585                    tsp += 1;
2586                }
2587            }
2588        }
2589    }
2590
2591    /// Insert leaving cursor after newly inserted element.
2592    pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>
2593    where
2594        K: Ord,
2595    {
2596        if let Some((prev, _)) = self.peek_prev() {
2597            if &key <= prev {
2598                return Err(UnorderedKeyError {});
2599            }
2600        }
2601        if let Some((next, _)) = self.peek_next() {
2602            if &key >= next {
2603                return Err(UnorderedKeyError {});
2604            }
2605        }
2606        unsafe {
2607            self.insert_before_unchecked(key, value);
2608        }
2609        Ok(())
2610    }
2611
2612    /// Insert leaving cursor before newly inserted element.
2613    pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>
2614    where
2615        K: Ord,
2616    {
2617        if let Some((prev, _)) = self.peek_prev() {
2618            if &key <= prev {
2619                return Err(UnorderedKeyError {});
2620            }
2621        }
2622        if let Some((next, _)) = self.peek_next() {
2623            if &key >= next {
2624                return Err(UnorderedKeyError {});
2625            }
2626        }
2627        unsafe {
2628            self.insert_after_unchecked(key, value);
2629        }
2630        Ok(())
2631    }
2632
2633    /// Insert leaving cursor after newly inserted element.
2634    /// # Safety
2635    ///
2636    /// Keys must be unique and in sorted order.
2637    pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
2638        self.insert_after_unchecked(key, value);
2639        self.index += 1;
2640    }
2641
2642    /// Insert leaving cursor before newly inserted element.
2643    /// # Safety
2644    ///
2645    /// Keys must be unique and in sorted order.
2646    pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
2647        unsafe {
2648            (*self.map).len += 1;
2649            let mut leaf = self.leaf.unwrap_unchecked();
2650            if (*leaf).full() {
2651                let a = &(*self.map).atune;
2652                match a.full_action(self.index, (*leaf).0.len()) {
2653                    FullAction::Split(b, a1, a2) => {
2654                        let (med, right) = (*leaf).0.split(b, a1, a2);
2655                        let right = Tree::L(Leaf(right));
2656                        let r = usize::from(self.index > b);
2657                        self.index -= r * (b + 1);
2658                        assert!(self.index < if r == 1 { a2 } else { a1 });
2659                        let t = self.save_split(med, right, r);
2660                        leaf = (*t).leaf();
2661                        self.leaf = Some(leaf);
2662                    }
2663                    FullAction::Extend(to) => (*leaf).0.set_alloc(to),
2664                }
2665            }
2666            (*leaf).0.insert(self.index, (key, value));
2667        }
2668    }
2669
2670    fn save_split(&mut self, med: (K, V), tree: Tree<K, V>, r: usize) -> *mut Tree<K, V> {
2671        unsafe {
2672            if let Some((mut nl, mut ix)) = self.stack.pop() {
2673                if (*nl).v.full() {
2674                    let a = &(*self.map).atune;
2675                    match a.full_action(ix, (*nl).v.0.len()) {
2676                        FullAction::Split(b, a1, a2) => {
2677                            let (med, right) = (*nl).split(b, a1, a2);
2678                            let r = usize::from(ix > b);
2679                            ix -= r * (b + 1);
2680                            assert!(ix < if r == 1 { a2 } else { a1 });
2681                            let t = self.save_split(med, Tree::NL(right), r);
2682                            nl = (*t).nonleaf();
2683                        }
2684                        FullAction::Extend(to) => {
2685                            (*nl).v.0.set_alloc(to);
2686                            (*nl).c.set_alloc(to + 1);
2687                        }
2688                    }
2689                }
2690                (*nl).v.0.insert(ix, med);
2691                (*nl).c.insert(ix + 1, tree);
2692                ix += r;
2693                self.stack.push((nl, ix));
2694                (*nl).c.ixm(ix)
2695            } else {
2696                (*self.map).tree.new_root((med, tree));
2697                let nl = (*self.map).tree.nonleaf();
2698                self.stack.push((nl, r));
2699                nl.c.ixm(r)
2700            }
2701        }
2702    }
2703
2704    /// Remove previous element.
2705    pub fn remove_prev(&mut self) -> Option<(K, V)> {
2706        self.prev()?;
2707        self.remove_next()
2708    }
2709
2710    /// Remove next element.
2711    pub fn remove_next(&mut self) -> Option<(K, V)> {
2712        unsafe {
2713            let leaf = self.leaf.unwrap_unchecked();
2714            if self.index == (*leaf).0.len() {
2715                let mut tsp = self.stack.len();
2716                while tsp > 0 {
2717                    tsp -= 1;
2718                    let (nl, ix) = self.stack[tsp];
2719                    if ix < (*nl).v.0.len() {
2720                        let a = &(*self.map).atune;
2721                        let (kv, ix) = (*nl).remove_at(ix, a);
2722                        self.stack[tsp] = (nl, ix);
2723                        self.push(tsp + 1, (*nl).c.ixm(ix));
2724                        (*self.map).len -= 1;
2725                        return Some(kv);
2726                    }
2727                }
2728                None
2729            } else {
2730                (*self.map).len -= 1;
2731                Some((*leaf).0.remove(self.index))
2732            }
2733        }
2734    }
2735
2736    /// Advance the cursor, returns references to the key and value of the element that it moved over.
2737    #[allow(clippy::should_implement_trait)]
2738    pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
2739        unsafe {
2740            let leaf = self.leaf.unwrap_unchecked();
2741            if self.index == (*leaf).0.len() {
2742                let mut tsp = self.stack.len();
2743                while tsp > 0 {
2744                    tsp -= 1;
2745                    let (nl, mut ix) = self.stack[tsp];
2746                    if ix < (*nl).v.0.len() {
2747                        let kv = (*nl).v.0.ixbm(ix);
2748                        ix += 1;
2749                        self.stack[tsp] = (nl, ix);
2750                        self.push(tsp + 1, (*nl).c.ixm(ix));
2751                        return Some(kv);
2752                    }
2753                }
2754                None
2755            } else {
2756                let kv = (*leaf).0.ixbm(self.index);
2757                self.index += 1;
2758                Some(kv)
2759            }
2760        }
2761    }
2762
2763    /// Move the cursor back, returns references to the key and value of the element that it moved over.
2764    pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
2765        unsafe {
2766            if self.index == 0 {
2767                let mut tsp = self.stack.len();
2768                while tsp > 0 {
2769                    tsp -= 1;
2770                    let (nl, mut ix) = self.stack[tsp];
2771                    if ix > 0 {
2772                        ix -= 1;
2773                        let kv = (*nl).v.0.ixbm(ix);
2774                        self.stack[tsp] = (nl, ix);
2775                        self.push_back(tsp + 1, (*nl).c.ixm(ix));
2776                        return Some(kv);
2777                    }
2778                }
2779                None
2780            } else {
2781                let leaf = self.leaf.unwrap_unchecked();
2782                self.index -= 1;
2783                Some((*leaf).0.ixbm(self.index))
2784            }
2785        }
2786    }
2787
2788    /// Returns mutable references to the next key/value pair.
2789    #[must_use]
2790    pub fn peek_next(&self) -> Option<(&mut K, &mut V)> {
2791        unsafe {
2792            let leaf = self.leaf.unwrap_unchecked();
2793            if self.index == (*leaf).0.len() {
2794                for (nl, ix) in self.stack.iter().rev() {
2795                    if *ix < (**nl).v.0.len() {
2796                        return Some((**nl).v.0.ixbm(*ix));
2797                    }
2798                }
2799                None
2800            } else {
2801                Some((*leaf).0.ixbm(self.index))
2802            }
2803        }
2804    }
2805    /// Returns mutable references to the previous key/value pair.
2806    #[must_use]
2807    pub fn peek_prev(&self) -> Option<(&mut K, &mut V)> {
2808        unsafe {
2809            if self.index == 0 {
2810                for (nl, ix) in self.stack.iter().rev() {
2811                    if *ix > 0 {
2812                        return Some((**nl).v.0.ixbm(*ix - 1));
2813                    }
2814                }
2815                None
2816            } else {
2817                let leaf = self.leaf.unwrap_unchecked();
2818                Some((*leaf).0.ixbm(self.index - 1))
2819            }
2820        }
2821    }
2822
2823    /// Returns a read-only cursor pointing to the same location as the `CursorMutKey`.
2824    #[must_use]
2825    pub fn as_cursor(&self) -> Cursor<'_, K, V, A> {
2826        unsafe {
2827            let mut c = Cursor::make();
2828            c.index = self.index;
2829            c.leaf = Some(&*self.leaf.unwrap());
2830            for (nl, ix) in &self.stack {
2831                c.stack.push((&(**nl), *ix));
2832            }
2833            c
2834        }
2835    }
2836
2837    /// This is needed for the implementation of the [Entry] API.
2838    fn into_mut(self) -> &'a mut V {
2839        unsafe {
2840            let leaf = self.leaf.unwrap_unchecked();
2841            (*leaf).0.ixmv(self.index)
2842        }
2843    }
2844}
2845
2846/// Cursor returned by [`BTreeMap::lower_bound`], [`BTreeMap::upper_bound`].
2847#[derive(Debug, Clone)]
2848pub struct Cursor<'a, K, V, A: AllocTuning> {
2849    leaf: Option<*const Leaf<K, V>>,
2850    index: usize,
2851    stack: StkVec<(*const NonLeaf<K, V>, usize)>,
2852    _pd: PhantomData<&'a BTreeMap<K, V, A>>,
2853}
2854
2855unsafe impl<'a, K, V, A: AllocTuning> Send for Cursor<'a, K, V, A> {}
2856unsafe impl<'a, K, V, A: AllocTuning> Sync for Cursor<'a, K, V, A> {}
2857
2858impl<'a, K, V, A: AllocTuning> Cursor<'a, K, V, A> {
2859    fn make() -> Self {
2860        Self {
2861            leaf: None,
2862            index: 0,
2863            stack: StkVec::new(),
2864            _pd: PhantomData,
2865        }
2866    }
2867
2868    fn lower_bound<Q>(bt: &'a BTreeMap<K, V, A>, bound: Bound<&Q>) -> Self
2869    where
2870        K: Borrow<Q> + Ord,
2871        Q: Ord + ?Sized,
2872    {
2873        let mut s = Self::make();
2874        s.push_lower(&bt.tree, bound);
2875        s
2876    }
2877
2878    fn upper_bound<Q>(bt: &'a BTreeMap<K, V, A>, bound: Bound<&Q>) -> Self
2879    where
2880        K: Borrow<Q> + Ord,
2881        Q: Ord + ?Sized,
2882    {
2883        let mut s = Self::make();
2884        s.push_upper(&bt.tree, bound);
2885        s
2886    }
2887
2888    fn push_lower<Q>(&mut self, mut tree: &'a Tree<K, V>, bound: Bound<&Q>)
2889    where
2890        K: Borrow<Q> + Ord,
2891        Q: Ord + ?Sized,
2892    {
2893        loop {
2894            match tree {
2895                Tree::L(leaf) => {
2896                    self.leaf = Some(leaf);
2897                    self.index = leaf.get_lower(bound);
2898                    break;
2899                }
2900                Tree::NL(nl) => {
2901                    let ix = nl.v.get_lower(bound);
2902                    self.stack.push((nl, ix));
2903                    tree = nl.c.ix(ix);
2904                }
2905            }
2906        }
2907    }
2908
2909    fn push_upper<Q>(&mut self, mut tree: &'a Tree<K, V>, bound: Bound<&Q>)
2910    where
2911        K: Borrow<Q> + Ord,
2912        Q: Ord + ?Sized,
2913    {
2914        loop {
2915            match tree {
2916                Tree::L(leaf) => {
2917                    self.leaf = Some(leaf);
2918                    self.index = leaf.get_upper(bound);
2919                    break;
2920                }
2921                Tree::NL(nl) => {
2922                    let ix = nl.v.get_upper(bound);
2923                    self.stack.push((nl, ix));
2924                    tree = nl.c.ix(ix);
2925                }
2926            }
2927        }
2928    }
2929
2930    fn push(&mut self, mut tsp: usize, mut tree: &Tree<K, V>) {
2931        loop {
2932            match tree {
2933                Tree::L(leaf) => {
2934                    self.leaf = Some(leaf);
2935                    self.index = 0;
2936                    break;
2937                }
2938                Tree::NL(nl) => {
2939                    self.stack[tsp] = (nl, 0);
2940                    tree = nl.c.ix(0);
2941                    tsp += 1;
2942                }
2943            }
2944        }
2945    }
2946
2947    fn push_back(&mut self, mut tsp: usize, mut tree: &Tree<K, V>) {
2948        loop {
2949            match tree {
2950                Tree::L(leaf) => {
2951                    self.leaf = Some(leaf);
2952                    self.index = leaf.0.len();
2953                    break;
2954                }
2955                Tree::NL(nl) => {
2956                    let ix = nl.v.0.len();
2957                    self.stack[tsp] = (nl, ix);
2958                    tree = nl.c.ix(ix);
2959                    tsp += 1;
2960                }
2961            }
2962        }
2963    }
2964
2965    /// Advance the cursor, returns references to the key and value of the element that it moved over.
2966    #[allow(clippy::should_implement_trait)]
2967    pub fn next(&mut self) -> Option<(&K, &V)> {
2968        unsafe {
2969            let leaf = self.leaf.unwrap_unchecked();
2970            if self.index == (*leaf).0.len() {
2971                let mut tsp = self.stack.len();
2972                while tsp > 0 {
2973                    tsp -= 1;
2974                    let (nl, mut ix) = self.stack[tsp];
2975                    if ix < (*nl).v.0.len() {
2976                        let kv = (*nl).v.0.ix(ix);
2977                        ix += 1;
2978                        self.stack[tsp] = (nl, ix);
2979                        let ct = (*nl).c.ix(ix);
2980                        self.push(tsp + 1, ct);
2981                        return Some(kv);
2982                    }
2983                }
2984                None
2985            } else {
2986                let kv = (*leaf).0.ix(self.index);
2987                self.index += 1;
2988                Some(kv)
2989            }
2990        }
2991    }
2992
2993    /// Move the cursor back, returns references to the key and value of the element that it moved over.
2994    pub fn prev(&mut self) -> Option<(&K, &V)> {
2995        unsafe {
2996            let leaf = self.leaf.unwrap_unchecked();
2997            if self.index == 0 {
2998                let mut tsp = self.stack.len();
2999                while tsp > 0 {
3000                    tsp -= 1;
3001                    let (nl, mut ix) = self.stack[tsp];
3002                    if ix > 0 {
3003                        ix -= 1;
3004                        let kv = (*nl).v.0.ix(ix);
3005                        self.stack[tsp] = (nl, ix);
3006                        let ct = (*nl).c.ix(ix);
3007                        self.push_back(tsp + 1, ct);
3008                        return Some(kv);
3009                    }
3010                }
3011                None
3012            } else {
3013                self.index -= 1;
3014                Some((*leaf).0.ix(self.index))
3015            }
3016        }
3017    }
3018
3019    /// Returns references to the next key/value pair.
3020    #[must_use]
3021    pub fn peek_next(&self) -> Option<(&K, &V)> {
3022        unsafe {
3023            let leaf = self.leaf.unwrap_unchecked();
3024            if self.index == (*leaf).0.len() {
3025                for (nl, ix) in self.stack.iter().rev() {
3026                    if *ix < (**nl).v.0.len() {
3027                        return Some((**nl).v.0.ix(*ix));
3028                    }
3029                }
3030                None
3031            } else {
3032                Some((*leaf).0.ix(self.index))
3033            }
3034        }
3035    }
3036    /// Returns references to the previous key/value pair.
3037    #[must_use]
3038    pub fn peek_prev(&self) -> Option<(&K, &V)> {
3039        unsafe {
3040            let leaf = self.leaf.unwrap_unchecked();
3041            if self.index == 0 {
3042                for (nl, ix) in self.stack.iter().rev() {
3043                    if *ix > 0 {
3044                        return Some((**nl).v.0.ix(*ix - 1));
3045                    }
3046                }
3047                None
3048            } else {
3049                Some((*leaf).0.ix(self.index - 1))
3050            }
3051        }
3052    }
3053}
3054
3055// Tests.
3056
3057#[cfg(all(test, not(miri), feature = "cap"))]
3058use {cap::Cap, std::alloc};
3059
3060#[cfg(all(test, not(miri), feature = "cap"))]
3061#[global_allocator]
3062static ALLOCATOR: Cap<alloc::System> = Cap::new(alloc::System, usize::max_value());
3063
3064#[cfg(test)]
3065fn print_memory() {
3066    #[cfg(all(test, not(miri), feature = "cap"))]
3067    println!("Memory allocated: {} bytes", ALLOCATOR.allocated());
3068}
3069
3070/* mimalloc cannot be used with miri */
3071#[cfg(all(test, not(miri), not(feature = "cap")))]
3072use mimalloc::MiMalloc;
3073
3074#[cfg(all(test, not(miri), not(feature = "cap")))]
3075#[global_allocator]
3076static GLOBAL: MiMalloc = MiMalloc;
3077
3078#[cfg(test)]
3079mod mytests;
3080
3081// #[cfg(test)]
3082// mod stdtests; // Increases compile/link time to 9 seconds from 3 seconds, so sometimes commented out!