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