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