rune_alloc/btree/
map.rs

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