btree_plus_store/
map.rs

1use std::borrow::Borrow;
2use std::cell::RefCell;
3use std::cmp::Ordering;
4use std::collections::Bound;
5use std::fmt::{Debug, Formatter};
6use std::hash::{Hash, Hasher};
7use std::iter::FusedIterator;
8use std::marker::PhantomData;
9use std::mem::{forget, MaybeUninit};
10use std::ops::RangeBounds;
11use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
12use std::ptr::{drop_in_place, NonNull};
13use std::thread::panicking;
14
15use crate::cursor::Cursor;
16use crate::node::{address_after, address_before, normalize_address, Node, NodePtr, M};
17use crate::utils::PtrEq;
18use crate::BTreeStore;
19
20/// A b-tree map.
21///
22/// See [std::collections::BTreeMap] for more info.
23// TODO: impl Clone
24pub struct BTreeMap<'store, K, V> {
25    store: &'store BTreeStore<K, V>,
26    root: Option<NodePtr<K, V>>,
27    length: usize,
28    height: usize,
29    /// For dropck; the `Box` avoids making the `Unpin` impl more strict than before
30    _p: PhantomData<Box<(K, V)>>,
31}
32
33/// The result of looking up an address to retrieve or insert an entry
34enum Find<K, V> {
35    /// The tree is empty
36    NoRoot,
37    /// The entry would be before this address
38    Before { node: NodePtr<K, V>, idx: u16 },
39    /// The entry is at this address
40    At { node: NodePtr<K, V>, idx: u16 },
41}
42
43/// Pointer and index to the start and end entry for a range within a tree.
44///
45/// These bounds are always inclusive. Use `Option<NodeBounds<'a, K, V>>` to represent a
46/// potentially-empty range.
47struct NodeBounds<K, V> {
48    /// Start node (inclusive)
49    start_node: NodePtr<K, V>,
50    /// End node (inclusive)
51    end_node: NodePtr<K, V>,
52    /// Index in start node (inclusive)
53    start_index: u16,
54    /// Index in end node (inclusive)
55    end_index: u16,
56}
57
58impl<'store, K, V> BTreeMap<'store, K, V> {
59    /// Creates an empty `BTreeMap`.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use btree_plus_store::{BTreeMap, BTreeStore};
65    /// let store = BTreeStore::<&str, i32>::new();
66    /// let mut map = BTreeMap::new_in(&store);
67    /// ```
68    #[inline]
69    pub const fn new_in(store: &'store BTreeStore<K, V>) -> Self {
70        Self {
71            store,
72            root: None,
73            length: 0,
74            height: 0,
75            _p: PhantomData,
76        }
77    }
78
79    // region length
80    /// Returns the number of elements in the map.
81    #[inline]
82    pub fn len(&self) -> usize {
83        self.length
84    }
85
86    /// Returns `true` if the map contains no elements.
87    #[inline]
88    pub fn is_empty(&self) -> bool {
89        self.root.is_none()
90    }
91    // endregion
92
93    // region retrieval
94    /// Whether the map contains the key
95    #[inline]
96    pub fn contains_key<Q: Ord>(&self, key: &Q) -> bool
97    where
98        K: Borrow<Q>,
99    {
100        matches!(self.find(key), Find::At { .. })
101    }
102
103    /// Returns a reference to the value corresponding to the key.
104    #[inline]
105    pub fn get<Q: Ord>(&self, key: &Q) -> Option<&V>
106    where
107        K: Borrow<Q>,
108    {
109        match self.find(key) {
110            Find::At { node, idx } => unsafe { Some(node.as_ref().val(idx)) },
111            _ => None,
112        }
113    }
114
115    /// Returns a mutable reference to the value corresponding to the key.
116    #[inline]
117    pub fn get_mut<Q: Ord>(&mut self, key: &Q) -> Option<&mut V>
118    where
119        K: Borrow<Q>,
120    {
121        match self.find(key) {
122            Find::At { mut node, idx } => unsafe { Some(node.as_mut().val_mut(idx)) },
123            _ => None,
124        }
125    }
126
127    /// Returns a reference to the equivalent key
128    ///
129    /// This is (only) useful when `Q` is a different type than `K`.
130    #[inline]
131    pub fn get_key<Q: Ord>(&self, key: &Q) -> Option<&K>
132    where
133        K: Borrow<Q>,
134    {
135        match self.find(key) {
136            Find::At { node, idx } => unsafe { Some(node.as_ref().key(idx)) },
137            _ => None,
138        }
139    }
140
141    /// Returns a reference to the equivalent key and associated value
142    ///
143    /// This is (only) useful when `Q` is a different type than `K`.
144    #[inline]
145    pub fn get_key_value<Q: Ord>(&self, key: &Q) -> Option<(&K, &V)>
146    where
147        K: Borrow<Q>,
148    {
149        match self.find(key) {
150            Find::At { node, idx } => unsafe { Some(node.as_ref().key_val(idx)) },
151            _ => None,
152        }
153    }
154
155    /// Returns a reference to the equivalent key and mutable associated value
156    ///
157    /// This is (only) useful when `Q` is a different type than `K`.
158    #[inline]
159    pub fn get_key_value_mut<Q: Ord>(&mut self, key: &Q) -> Option<(&K, &mut V)>
160    where
161        K: Borrow<Q>,
162    {
163        match self.find(key) {
164            Find::At { mut node, idx } => unsafe { Some(node.as_mut().key_val_mut(idx)) },
165            _ => None,
166        }
167    }
168
169    /// Returns the first key and value
170    #[inline]
171    pub fn first_key_value(&self) -> Option<(&K, &V)> {
172        self.first_leaf()
173            .map(|node| unsafe { node.as_ref().first_key_value() })
174    }
175
176    /// Returns the first key and mutable value
177    #[inline]
178    pub fn first_key_value_mut(&mut self) -> Option<(&K, &mut V)> {
179        self.first_leaf()
180            .map(|mut node| unsafe { node.as_mut().first_key_value_mut() })
181    }
182
183    /// Returns the last key and value
184    #[inline]
185    pub fn last_key_value(&self) -> Option<(&K, &V)> {
186        self.last_leaf()
187            .map(|node| unsafe { node.as_ref().last_key_value() })
188    }
189
190    /// Returns the last key and mutable value
191    #[inline]
192    pub fn last_key_value_mut(&mut self) -> Option<(&K, &mut V)> {
193        self.last_leaf()
194            .map(|mut node| unsafe { node.as_mut().last_key_value_mut() })
195    }
196    // endregion
197
198    // region insertion and removal
199    /// Inserts a key-value pair into the map.
200    #[inline]
201    pub fn insert(&mut self, key: K, val: V) -> Option<V>
202    where
203        K: Clone + Ord,
204    {
205        match self.find(&key) {
206            Find::NoRoot => {
207                self.insert_root(key, val);
208                None
209            }
210            Find::Before { node, idx } => unsafe {
211                self.insert_before(key, val, node, idx);
212                None
213            },
214            Find::At { mut node, idx } => unsafe { Some(node.as_mut().replace_val(idx, val)) },
215        }
216    }
217
218    /// Get a reference to the value at the given key, or insert a new value if the key is not
219    /// present.
220    #[inline]
221    pub fn get_or_insert(&mut self, key: K, val: V) -> &mut V
222    where
223        K: Clone + Ord,
224    {
225        match self.find(&key) {
226            Find::NoRoot => unsafe {
227                self.insert_root(key, val);
228                self.root.unwrap().as_mut().val_mut(0)
229            },
230            Find::Before { node, idx } => unsafe {
231                // Maybe could optimize into a single lookup...
232                self.insert_before(key.clone(), val, node, idx);
233                self.get_mut(&key).unwrap()
234            },
235            Find::At { mut node, idx } => unsafe { node.as_mut().val_mut(idx) },
236        }
237    }
238
239    /// Removes the equivalent key and returns the actual key and value, if present.
240    #[inline]
241    pub fn remove_key_value<Q: Ord>(&mut self, key: &Q) -> Option<(K, V)>
242    where
243        K: Clone + Borrow<Q>,
244    {
245        match self.find(key) {
246            Find::NoRoot | Find::Before { .. } => None,
247            Find::At { mut node, idx } => unsafe {
248                let (key, val) = node.as_mut().remove_val(idx);
249                self.post_removal(node);
250                Some((key, val))
251            },
252        }
253    }
254
255    /// Removes the equivalent key and returns the value if present.
256    #[inline]
257    pub fn remove<Q: Ord>(&mut self, key: &Q) -> Option<V>
258    where
259        K: Clone + Borrow<Q>,
260    {
261        self.remove_key_value(key).map(|(_, val)| val)
262    }
263
264    /// Removes the first key and value as long as the map isn't empty
265    #[inline]
266    pub fn pop_first(&mut self) -> Option<(K, V)>
267    where
268        K: Clone,
269    {
270        self.first_leaf().map(|mut node| unsafe {
271            let (key, val) = node.as_mut().remove_val(0);
272            self.post_removal(node);
273            (key, val)
274        })
275    }
276
277    /// Removes the last key and value as long as the map isn't empty
278    #[inline]
279    pub fn pop_last(&mut self) -> Option<(K, V)>
280    where
281        K: Clone,
282    {
283        self.last_leaf().map(|mut node| unsafe {
284            let idx = node.as_ref().len - 1;
285            let (key, val) = node.as_mut().remove_val(idx);
286            self.post_removal(node);
287            (key, val)
288        })
289    }
290
291    /// Clears the map, removing all key-value pairs.
292    #[inline]
293    pub fn clear(&mut self) {
294        if let Some(root) = self.root.take() {
295            unsafe {
296                drop_node_ptr(root, self.height, &mut |n| self.store.dealloc(n));
297            }
298        }
299        self.length = 0;
300    }
301    // endregion
302
303    // region advanced
304    /// Transforms the value at the given key, inserting if we go from `None` to `Some` and removing
305    /// if we go from `Some` to `None`. Also returns a value.
306    ///
307    /// Also, if the function `panic`s we always remove the key, so this is effectively a
308    /// special-case of [`replace_with`](https://docs.rs/replace_with/latest/replace_with/) for the
309    /// map.
310    #[inline]
311    pub fn update_and_return<R>(
312        &mut self,
313        key: K,
314        update: impl FnOnce(Option<V>) -> (Option<V>, R),
315    ) -> R
316    where
317        K: Clone + Ord,
318    {
319        match self.find(&key) {
320            Find::NoRoot => match update(None) {
321                (None, r) => r,
322                (Some(val), r) => {
323                    self.insert_root(key, val);
324                    r
325                }
326            },
327            Find::At { mut node, idx } => unsafe {
328                match catch_unwind(AssertUnwindSafe(|| {
329                    let val = node.as_mut().read_val(idx);
330                    update(Some(val))
331                })) {
332                    Err(err) => {
333                        let (_key, value) = node.as_mut().remove_val(idx);
334                        forget(value);
335                        self.post_removal(node);
336                        resume_unwind(err);
337                    }
338                    Ok((None, r)) => {
339                        let (_key, value) = node.as_mut().remove_val(idx);
340                        forget(value);
341                        self.post_removal(node);
342                        r
343                    }
344                    Ok((Some(val), r)) => {
345                        node.as_mut().write_val(idx, val);
346                        r
347                    }
348                }
349            },
350            Find::Before { node, idx } => match update(None) {
351                (None, r) => r,
352                (Some(val), r) => unsafe {
353                    self.insert_before(key, val, node, idx);
354                    r
355                },
356            },
357        }
358    }
359
360    /// Transforms the value at the given key, inserting if we go from `None` to `Some` and removing
361    /// if we go from `Some` to `None`.
362    ///
363    /// Also, if the function `panic`s we always remove the key, so this is effectively a
364    /// special-case of [`replace_with`](https://docs.rs/replace_with/latest/replace_with/) for the
365    /// map.
366    #[inline]
367    pub fn update(&mut self, key: K, update: impl FnOnce(Option<V>) -> Option<V>)
368    where
369        K: Clone + Ord,
370    {
371        self.update_and_return(key, |val| (update(val), ()))
372    }
373
374    /// Validates the map, *panic*ing if it is invalid. Specifically, we check that the number of
375    /// entries in each node is within the b-tree invariant bounds, and that the keys are in order.
376    ///
377    /// Ideally, this should always be a no-op.
378    #[inline]
379    pub fn validate(&self)
380    where
381        K: Debug + Ord,
382        V: Debug,
383    {
384        unsafe fn validate_node<K: Debug + Ord, V: Debug>(
385            errors: &mut Vec<String>,
386            node: NodePtr<K, V>,
387            parent: Option<(NodePtr<K, V>, u16)>,
388            height: usize,
389            (mut prev_key, mut prev_leaf): (Option<NonNull<K>>, Option<NodePtr<K, V>>),
390        ) -> (usize, (NonNull<K>, NodePtr<K, V>)) {
391            let errors = RefCell::new(errors);
392            let assert2 = |node: NodePtr<K, V>, cond: bool, msg: &str| {
393                if !cond {
394                    (*errors.borrow_mut()).push(format!("{:X?} {}", node.as_ptr(), msg))
395                }
396            };
397            let assert = |cond: bool, msg: &str| {
398                if !cond {
399                    assert2(node, cond, msg)
400                }
401            };
402
403            let is_leaf = height == 0;
404            let node_ptr = node;
405            let node = node.as_ref();
406
407            assert(
408                node.parent().map(|p| p.0).ptr_eq(&parent.map(|p| p.0)),
409                "parent pointer is incorrect",
410            );
411            assert(
412                node.parent().map(|p| p.1).ptr_eq(&parent.map(|p| p.1)),
413                "parent index is incorrect",
414            );
415
416            let min_len = match parent {
417                None => 1,
418                Some(_) => M / 2,
419            } as u16;
420            let max_len = M as u16;
421            assert(node.len >= min_len, "has too few entries");
422            assert(node.len <= max_len, "has too many entries");
423
424            if is_leaf {
425                assert(node.prev().ptr_eq(&prev_leaf), "prev leaf is incorrect");
426                for i in 0..node.len {
427                    let key = node.key(i);
428
429                    if let Some(prev_key) = prev_key {
430                        let prev_key = prev_key.as_ref();
431                        assert(
432                            match i {
433                                0 => key >= prev_key,
434                                _ => key > prev_key,
435                            },
436                            &format!("key {} is out of order", i),
437                        );
438                    }
439
440                    prev_key = Some(NonNull::from(key));
441                }
442                (node.len as usize, (prev_key.unwrap(), node_ptr))
443            } else {
444                let mut len = 0;
445
446                for i in 0..node.len + 1 {
447                    if let Some(ki) = i.checked_sub(1) {
448                        let key = node.key(ki);
449
450                        if let Some(prev_key) = prev_key {
451                            let prev_key = prev_key.as_ref();
452                            assert(key > prev_key, &format!("key {} is out of order", i));
453                        }
454
455                        prev_key = Some(NonNull::from(key));
456                    }
457
458                    let child = node.edge(i);
459
460                    if height == 1 {
461                        if let Some(prev_leaf) = prev_leaf {
462                            let prev_leaf_ptr = prev_leaf;
463                            let prev_leaf = prev_leaf.as_ref();
464                            assert2(
465                                prev_leaf_ptr,
466                                prev_leaf.next().ptr_eq(&Some(child)),
467                                &format!(
468                                    "next leaf is incorrect (expected {:X?} got {:X?})",
469                                    child.as_ptr(),
470                                    as_nullable_ptr(prev_leaf.next())
471                                ),
472                            )
473                        }
474                    }
475
476                    let (child_len, (last_key, last_leaf)) = validate_node(
477                        *errors.borrow_mut(),
478                        child,
479                        Some((node_ptr, i)),
480                        height - 1,
481                        (prev_key, prev_leaf),
482                    );
483                    len += child_len;
484                    prev_key = Some(last_key);
485                    prev_leaf = Some(last_leaf);
486                }
487                (len, (prev_key.unwrap(), prev_leaf.unwrap()))
488            }
489        }
490        let mut errors = Vec::new();
491        if let Some(root) = self.root {
492            let (len, (_last_key, last_leaf)) =
493                unsafe { validate_node(&mut errors, root, None, self.height, (None, None)) };
494            if len != self.length {
495                errors.push(String::from("tree length isn't correct"))
496            };
497            if !unsafe { last_leaf.as_ref().next() }.ptr_eq(&None) {
498                errors.push(format!("{:X?} next leaf is incorrect", unsafe {
499                    last_leaf.as_ptr()
500                }))
501            }
502        }
503        if !errors.is_empty() {
504            panic!("invalid b-tree:\n{:?}\n- {}", self, errors.join("\n- "));
505        }
506    }
507
508    /// Prints the b-tree in ascii
509    #[inline]
510    pub fn print(&self, f: &mut Formatter<'_>) -> std::fmt::Result
511    where
512        K: Debug,
513        V: Debug,
514    {
515        unsafe fn print_node<K: Debug, V: Debug>(
516            f: &mut Formatter<'_>,
517            node: NodePtr<K, V>,
518            max_height: usize,
519            height: usize,
520        ) -> std::fmt::Result {
521            let is_leaf = height == 0;
522            let node_ptr = node;
523            let node = node.as_ref();
524            let indent = "│ ".repeat(max_height - height);
525            write!(f, "{}• {:X?}, parent = ", indent, node_ptr.as_ptr())?;
526            match node.parent() {
527                Some((parent, parent_idx)) => {
528                    write!(f, "({:X?}, {})", parent.as_ptr(), parent_idx)?
529                }
530                None => write!(f, "None")?,
531            }
532            if is_leaf {
533                writeln!(
534                    f,
535                    ", prev = {:X?}, next = {:X?}",
536                    as_nullable_ptr(node.prev()),
537                    as_nullable_ptr(node.next())
538                )?;
539                for i in 0..node.len {
540                    let bullet = if i == node.len - 1 { "└" } else { "├" };
541                    writeln!(
542                        f,
543                        "{}{} {:?} = {:?}",
544                        indent,
545                        bullet,
546                        node.key(i),
547                        node.val(i)
548                    )?;
549                }
550            } else {
551                writeln!(f)?;
552                for i in 0..node.len + 1 {
553                    if let Some(ki) = i.checked_sub(1) {
554                        let key = node.key(ki);
555                        writeln!(f, "{}├ {:?}", indent, key)?;
556                    }
557
558                    let child = node.edge(i);
559                    print_node(f, child, max_height, height - 1)?;
560                }
561                writeln!(f, "{}â””", indent)?;
562            }
563            Ok(())
564        }
565        if let Some(root) = self.root {
566            unsafe { print_node(f, root, self.height, self.height) }
567        } else {
568            writeln!(f, "empty")
569        }
570    }
571    // endregion
572
573    // region iteration
574    /// Iterates over the map's key-value pairs in order.
575    #[inline]
576    pub fn iter(&self) -> Iter<'_, K, V> {
577        Iter::new(self)
578    }
579
580    /// Iterates over the map's key-value pairs in order. Values are mutable
581    #[inline]
582    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
583        IterMut::new(self)
584    }
585
586    /// Iterates over the map's keys in order.
587    #[inline]
588    pub fn keys(&self) -> Keys<'_, K, V> {
589        Keys(self.iter())
590    }
591
592    /// Iterates over the map's values in order.
593    #[inline]
594    pub fn values(&self) -> Values<'_, K, V> {
595        Values(self.iter())
596    }
597
598    /// Iterates over the map's values in order. Values are mutable
599    #[inline]
600    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
601        ValuesMut(self.iter_mut())
602    }
603
604    /// Iterates over the map's key-value pairs in order, within the given range.
605    #[inline]
606    pub fn range<Q: Ord>(&self, bounds: impl RangeBounds<Q>) -> Range<'_, K, V>
607    where
608        K: Borrow<Q>,
609    {
610        Range::new(self, bounds)
611    }
612
613    /// Iterates over the map's key-value pairs in order, within the given range.. Values are mutable
614    #[inline]
615    pub fn range_mut<Q: Ord>(&mut self, bounds: impl RangeBounds<Q>) -> RangeMut<'_, K, V>
616    where
617        K: Borrow<Q>,
618    {
619        RangeMut::new(self, bounds)
620    }
621
622    /// Iterates over the map's keys in order, within the given range.
623    #[inline]
624    pub fn range_keys<Q: Ord>(&self, bounds: impl RangeBounds<Q>) -> impl Iterator<Item = &K> + '_
625    where
626        K: Borrow<Q>,
627    {
628        self.range(bounds).map(|(k, _)| k)
629    }
630
631    /// Iterates over the map's values in order, within the given range.
632    #[inline]
633    pub fn range_values<Q: Ord>(&self, bounds: impl RangeBounds<Q>) -> impl Iterator<Item = &V> + '_
634    where
635        K: Borrow<Q>,
636    {
637        self.range(bounds).map(|(_, v)| v)
638    }
639
640    /// Iterates over the map's values in order, within the given range. Values are mutable
641    #[inline]
642    pub fn range_values_mut<Q: Ord>(
643        &mut self,
644        bounds: impl RangeBounds<Q>,
645    ) -> impl Iterator<Item = &mut V> + '_
646    where
647        K: Borrow<Q>,
648    {
649        self.range_mut(bounds).map(|(_, v)| v)
650    }
651
652    // /// Drains elements.
653    // #[inline]
654    // pub fn drain(&mut self) -> Drain<'_, K, V> {
655    //     Drain::new(self)
656    // }
657
658    // /// Removes elements which don't pass the predicate
659    // #[inline]
660    // pub fn retain<F: FnMut(&K, &mut V) -> bool>(&mut self, mut f: F) {
661    //     self.drain_filter(|k, v| !f(k, v));
662    // }
663
664    // /// Drains elements according to the filter.
665    // #[inline]
666    // pub fn drain_filter<F: FnMut(&K, &mut V) -> bool>(&mut self, filter: F) -> DrainFilter<'_, K, V, F> {
667    //     DrainFilter::new(self, filter)
668    // }
669
670    // /// Drains elements within the given range
671    // #[inline]
672    // pub fn drain_range<Q: Ord>(&mut self, bounds: impl RangeBounds<Q>) -> DrainRange<'_, K, V> where K: Borrow<Q> {
673    //     DrainRange::new(self, bounds)
674    // }
675
676    // /// Removes elements within the range which don't pass the predicate
677    // #[inline]
678    // pub fn retain_range<Q: Ord, F: FnMut(&K, &mut V) -> bool>(&mut self, bounds: impl RangeBounds<Q>, mut f: F) where K: Borrow<Q> {
679    //     self.drain_filter_range(bounds, |k, v| !f(k, v));
680    // }
681
682    // /// Drains elements within the given range according to the filter
683    // #[inline]
684    // pub fn drain_filter_range<Q: Ord, F: FnMut(&K, &mut V) -> bool>(&mut self, bounds: impl RangeBounds<Q>, mut filter: F) -> DrainFilterRange<'_, K, V, F> where K: Borrow<Q> {
685    //     DrainFilterRange::new(self, bounds, filter)
686    // }
687    // endregion
688
689    // region b-tree misc
690    #[inline]
691    fn first_leaf(&self) -> Option<NodePtr<K, V>> {
692        let mut node = self.root?;
693        for _ in 0..self.height {
694            node = unsafe { node.as_ref().edge(0) };
695        }
696        Some(node)
697    }
698
699    #[inline]
700    fn last_leaf(&self) -> Option<NodePtr<K, V>> {
701        let mut node = self.root?;
702        for _ in 0..self.height {
703            node = unsafe { node.as_ref().edge(node.as_ref().len) };
704        }
705        Some(node)
706    }
707
708    #[inline]
709    fn find<Q: Ord>(&self, key: &Q) -> Find<K, V>
710    where
711        K: Borrow<Q>,
712    {
713        let Some(mut node) = self.root else {
714            return Find::NoRoot
715        };
716        let mut height = self.height;
717        loop {
718            match unsafe { node.as_ref().keys() }.binary_search_by(|k| k.borrow().cmp(key)) {
719                Ok(idx) => {
720                    let idx = idx as u16;
721                    if height == 0 {
722                        break Find::At { node, idx };
723                    }
724                    height -= 1;
725                    node = unsafe { node.as_ref().edge(idx + 1) }
726                }
727                Err(idx) => {
728                    let idx = idx as u16;
729                    if height == 0 {
730                        break Find::Before { node, idx };
731                    }
732                    height -= 1;
733                    node = unsafe { node.as_ref().edge(idx) }
734                }
735            }
736        }
737    }
738
739    #[inline]
740    fn node_bounds<Q: Ord>(&self, bounds: impl RangeBounds<Q>) -> Option<NodeBounds<K, V>>
741    where
742        K: Borrow<Q>,
743    {
744        let (start_node, start_index) = match bounds.start_bound() {
745            Bound::Included(bound) => match self.find(bound) {
746                Find::NoRoot => return None,
747                Find::Before { node, idx } => unsafe { normalize_address(node, idx) }?,
748                Find::At { node, idx } => (node, idx),
749            },
750            Bound::Excluded(bound) => match self.find(bound) {
751                Find::NoRoot => return None,
752                // normalize_address handles if idx == len, which means we are past this node and
753                // may be at the end.
754                Find::Before { node, idx } => unsafe { normalize_address(node, idx) }?,
755                Find::At { node, idx } => unsafe { address_after(node, idx) }?,
756            },
757            Bound::Unbounded => (self.first_leaf()?, 0),
758        };
759        let (end_node, end_index) = match bounds.end_bound() {
760            Bound::Included(bound) => match self.find(bound) {
761                Find::NoRoot => return None,
762                Find::Before { node, idx } => unsafe { address_before(node, idx) }?,
763                Find::At { node, idx } => (node, idx),
764            },
765            Bound::Excluded(bound) => match self.find(bound) {
766                Find::NoRoot => return None,
767                Find::Before { node, idx } | Find::At { node, idx } => {
768                    unsafe { address_before(node, idx) }?
769                }
770            },
771            Bound::Unbounded => self
772                .last_leaf()
773                .map(|leaf| unsafe { (leaf, leaf.as_ref().len - 1) })?,
774        };
775
776        // Check for overlap (only need to check if address_after(start) == end)
777        if (start_node.ptr_eq(&end_node) && start_index == end_index + 1)
778            || (start_index == 0 && unsafe { start_node.as_ref().prev() }.ptr_eq(&Some(end_node)))
779        {
780            return None;
781        }
782
783        // Actually create
784        Some(NodeBounds {
785            start_node,
786            end_node,
787            start_index,
788            end_index,
789        })
790    }
791
792    #[inline]
793    fn insert_root(&mut self, key: K, val: V) {
794        debug_assert_eq!(self.length, 0);
795        let mut root = Node::leaf();
796        unsafe {
797            root.insert_val(0, key, val);
798        }
799        self.root = Some(self.store.alloc(root));
800        self.length += 1;
801    }
802
803    #[inline]
804    unsafe fn insert_before(&mut self, mut key: K, val: V, mut node: NodePtr<K, V>, idx: u16)
805    where
806        K: Clone,
807    {
808        if (node.as_ref().len as usize) < M {
809            node.as_mut().insert_val(idx, key, val);
810        } else {
811            // Rebalance (overflow)
812
813            // First split
814            // `key` gets replaced with the "split" (median) key, and `node` gets replaced with the
815            // left node
816            let mut right = self
817                .store
818                .alloc(node.as_mut().split_leaf(idx, &mut key, val));
819            node.as_mut().set_next(Some(right));
820            right.as_mut().set_prev(Some(node));
821            if let Some(mut right_next) = right.as_ref().next() {
822                right_next.as_mut().set_prev(Some(right));
823            }
824
825            loop {
826                let Some((mut parent, idx)) = node.as_ref().parent() else {
827                    // At root: create a new root with the split key, left, and right nodes
828                    self.height += 1;
829                    let mut left = node;
830                    let mut root = self.store.alloc(Node::internal());
831                    left.as_mut().set_parent(root, 0);
832                    // Has to be before insert_edge, otherwise we try to modify a deallocated edge,
833                    // because the tree has 0 edges but insert_edge always expects at least 1.
834                    // Furthermore, we need correct parent_idx, which is why we set both to 0.
835                    right.as_mut().set_parent(root, 0);
836                    root.as_mut().set_last_edge(right);
837                    root.as_mut().insert_edge(0, false, key, left);
838                    self.root = Some(root);
839                    break
840                };
841
842                // Insert split key and right into parent. left is already in parent at idx, so
843                // insert key at idx and right at idx + 1. We must handle the case where the parent
844                // overflows too...
845                right.as_mut().set_parent(parent, idx + 1);
846                if (parent.as_ref().len as usize) < M {
847                    // The parent won't overflow, actually insert into parent
848                    parent.as_mut().insert_edge(idx, true, key, right);
849                    break;
850                }
851                // The parent will overflow too, so we split the parent when inserting idx/key/right
852                // split_internal will replace key with the split key and node with the left node,
853                // and we re-assign right to the right node (we don't just pass as a &mut like we do
854                // with key because it must be allocated). Then insert the new internal parent-right
855                // node in its parent, and so on, until we either find a suitable parent or reach
856                // the root.
857                node = parent;
858                right = self
859                    .store
860                    .alloc(node.as_mut().split_internal(idx, &mut key, right));
861                for right_child in right.as_mut().edges_mut() {
862                    right_child.as_mut().parent = Some(right);
863                }
864            }
865        }
866        self.length += 1;
867    }
868
869    #[inline]
870    unsafe fn post_removal(&mut self, mut node: NodePtr<K, V>)
871    where
872        K: Clone,
873    {
874        self.length -= 1;
875
876        // Rebalance (underflow)
877        let mut is_leaf = true;
878        while (node.as_ref().len as usize) < M / 2 {
879            let Some((mut parent, idx)) = node.as_ref().parent() else {
880                // Node is root. Root node can have less than M < 2 children
881                if is_leaf {
882                    // If the root is a leaf, it can have min 1 child. Otherwise, the tree
883                    // is empty.
884                    if node.as_ref().len == 0 {
885                        self.root = None;
886                    }
887                } else if node.as_ref().len < 1 {
888                    // If the root is internal, it can have min 1 child (= 2 edges). Otherwise, the
889                    // remaining edge becomes the new root.
890                    self.height -= 1;
891                    self.root = Some(node.as_ref().edge(0));
892                    self.store.dealloc(node);
893                    self.root.as_mut().unwrap().as_mut().clear_parent();
894                }
895                break
896            };
897
898            // Try to redistribute with prev sibling
899            if idx > 0 {
900                let mut prev = parent.as_ref().edge(idx - 1);
901                if (prev.as_ref().len as usize) > M / 2 {
902                    if is_leaf {
903                        let (key, val) = prev.as_mut().remove_val(prev.as_ref().len - 1);
904                        node.as_mut().insert_val(0, key.clone(), val);
905                        parent.as_mut().replace_key(idx - 1, key);
906                    } else {
907                        let (key, mut edge) = prev.as_mut().remove_last_edge();
908                        let key = parent.as_mut().replace_key(idx - 1, key);
909                        edge.as_mut().set_parent(node, 0);
910                        node.as_mut().insert_edge(0, false, key, edge);
911                    }
912                    break;
913                }
914            }
915
916            // Try to redistribute with next sibling
917            if idx < parent.as_ref().len {
918                let mut next = parent.as_ref().edge(idx + 1);
919                if (next.as_ref().len as usize) > M / 2 {
920                    if is_leaf {
921                        parent
922                            .as_mut()
923                            .replace_key(idx, next.as_ref().key(1).clone());
924                        let (key, val) = next.as_mut().remove_val(0);
925                        node.as_mut().insert_val(node.as_ref().len, key, val);
926                    } else {
927                        let (key, mut edge) = next.as_mut().remove_edge(0, false);
928                        let key = parent.as_mut().replace_key(idx, key);
929                        let len = node.as_ref().len;
930                        edge.as_mut().set_parent(node, len + 1);
931                        node.as_mut().insert_edge(len, true, key, edge);
932                    }
933                    break;
934                }
935            }
936
937            // Merge with prev sibling or next sibling. We prioritize prev just because, but
938            // must choose next if idx == 0
939            if idx > 0 {
940                let mut prev = parent.as_mut().edge(idx - 1);
941                if is_leaf {
942                    node.as_mut().merge_prev_leaf(prev.as_mut());
943                    if let Some(mut new_prev) = node.as_ref().prev() {
944                        new_prev.as_mut().set_next(Some(node));
945                    }
946                } else {
947                    let key = parent.as_ref().key(idx - 1).clone();
948                    for child in prev.as_mut().edges_mut() {
949                        child.as_mut().parent = Some(node);
950                    }
951                    node.as_mut().merge_prev_internal(key, prev.as_mut());
952                }
953
954                // Dealloc and remove absorbed (empty) node and fix indices of the nodes
955                // after
956                let (_key, edge) = parent.as_mut().remove_edge(idx - 1, false);
957                debug_assert!(edge.ptr_eq(&prev));
958                self.store.dealloc(prev);
959            } else {
960                let mut next = parent.as_mut().edge(idx + 1);
961                if is_leaf {
962                    node.as_mut().merge_next_leaf(next.as_mut());
963                    if let Some(mut new_next) = node.as_ref().next() {
964                        new_next.as_mut().set_prev(Some(node));
965                    }
966                } else {
967                    let key = parent.as_ref().key(idx).clone();
968                    for child in next.as_mut().edges_mut() {
969                        child.as_mut().parent = Some(node);
970                    }
971                    node.as_mut().merge_next_internal(key, next.as_mut());
972                }
973
974                // Dealloc and remove absorbed (empty) node and fix indices of the nodes
975                // after
976                let (_key, edge) = parent.as_mut().remove_edge(idx, true);
977                debug_assert!(edge.ptr_eq(&next));
978                self.store.dealloc(next);
979            }
980
981            // Since we merged, we may now have to redistribute or merge the parent since it
982            // has 1 less child
983            node = parent;
984            is_leaf = false;
985        }
986    }
987    // endregion
988}
989
990impl<K, V> NodeBounds<K, V> {
991    #[inline]
992    fn start(&self) -> (NodePtr<K, V>, u16) {
993        (self.start_node, self.start_index)
994    }
995
996    #[inline]
997    fn end(&self) -> (NodePtr<K, V>, u16) {
998        (self.end_node, self.end_index)
999    }
1000}
1001
1002// region common trait impls
1003impl<'store, K: Debug, V: Debug> Debug for BTreeMap<'store, K, V> {
1004    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1005        self.print(f)
1006    }
1007}
1008
1009impl<'store, K: PartialEq, V: PartialEq> PartialEq for BTreeMap<'store, K, V> {
1010    fn eq(&self, other: &Self) -> bool {
1011        self.iter().eq(other.iter())
1012    }
1013}
1014
1015impl<'store, K: Eq, V: Eq> Eq for BTreeMap<'store, K, V> {}
1016
1017impl<'store, K: PartialOrd, V: PartialOrd> PartialOrd for BTreeMap<'store, K, V> {
1018    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1019        self.iter().partial_cmp(other.iter())
1020    }
1021}
1022
1023impl<'store, K: Ord, V: Ord> Ord for BTreeMap<'store, K, V> {
1024    fn cmp(&self, other: &Self) -> Ordering {
1025        self.iter().cmp(other.iter())
1026    }
1027}
1028
1029impl<'store, K: Hash, V: Hash> Hash for BTreeMap<'store, K, V> {
1030    fn hash<H: Hasher>(&self, state: &mut H) {
1031        for (k, v) in self.iter() {
1032            k.hash(state);
1033            v.hash(state);
1034        }
1035    }
1036}
1037// endregion
1038
1039// region drop and dealloc
1040impl<'store, K, V> Drop for BTreeMap<'store, K, V> {
1041    #[inline]
1042    fn drop(&mut self) {
1043        if panicking() {
1044            // TODO: Drop when panicking without causing UB (need to reorder some operations)
1045            return;
1046        }
1047
1048        if let Some(root) = self.root.take() {
1049            unsafe { drop_node_ptr(root, self.height, &mut |n| self.store.dealloc(n)) }
1050        }
1051    }
1052}
1053
1054unsafe fn drop_node_ptr<K, V>(
1055    mut node: NodePtr<K, V>,
1056    height: usize,
1057    dealloc: &mut impl FnMut(NodePtr<K, V>),
1058) {
1059    let node_ref = node.as_mut();
1060
1061    for key in node_ref.keys_mut() {
1062        drop_in_place(key as *mut _);
1063    }
1064    if height > 0 {
1065        for &child in node_ref.edges() {
1066            drop_node_ptr(child, height - 1, dealloc);
1067        }
1068    } else {
1069        for val in node_ref.vals_mut() {
1070            drop_in_place(val as *mut _);
1071        }
1072    }
1073
1074    dealloc(node);
1075}
1076
1077/// If this address is at the start of the node, deallocates the node, then checks if it's at the
1078/// start of its parent, if so deallocates its parent, and so on.
1079///
1080/// Doesn't drop any of the nodes' contents
1081unsafe fn dealloc_up_firsts<K, V>(
1082    mut address: (NodePtr<K, V>, u16),
1083    mut dealloc: impl FnMut(NodePtr<K, V>),
1084) {
1085    loop {
1086        let (node, idx) = address;
1087
1088        debug_assert!(
1089            idx <= node.as_ref().len,
1090            "sanity check failed: address.idx > address.node.len (invariant broke BEFORE this call)"
1091        );
1092        if idx != 0 {
1093            break;
1094        }
1095
1096        let parent = node.as_ref().parent();
1097        dealloc(node);
1098
1099        let Some(parent) = parent else {
1100            break
1101        };
1102        address = parent;
1103    }
1104}
1105
1106/// If this address is at the end of the node, deallocates the node, then checks if it's at the end
1107/// of its parent, if so deallocates its parent, and so on.
1108///
1109/// Doesn't drop any of the nodes' contents
1110#[inline]
1111unsafe fn dealloc_up_lasts<K, V>(
1112    (mut node, mut idx): (NodePtr<K, V>, u16),
1113    mut dealloc: impl FnMut(NodePtr<K, V>),
1114) {
1115    debug_assert!(
1116        idx < node.as_ref().len,
1117        "sanity check failed: address.idx >= address.node.len (invariant broke BEFORE this call)"
1118    );
1119    if idx != node.as_ref().len - 1 {
1120        return;
1121    }
1122
1123    while let Some(parent) = {
1124        let parent = node.as_ref().parent();
1125        dealloc(node);
1126        parent
1127    } {
1128        node = parent.0;
1129        idx = parent.1;
1130
1131        debug_assert!(
1132            idx <= node.as_ref().len,
1133            "sanity check failed: address.idx > address.node.len (invariant broke BEFORE this call)"
1134        );
1135        if idx != node.as_ref().len {
1136            break;
1137        }
1138    }
1139}
1140// endregion
1141
1142//noinspection DuplicatedCode
1143// region iterator impls
1144impl<'store: 'a, 'a, K, V> IntoIterator for &'a BTreeMap<'store, K, V> {
1145    type Item = (&'a K, &'a V);
1146    type IntoIter = Iter<'a, K, V>;
1147
1148    #[inline]
1149    fn into_iter(self) -> Self::IntoIter {
1150        self.iter()
1151    }
1152}
1153
1154impl<'store: 'a, 'a, K, V> IntoIterator for &'a mut BTreeMap<'store, K, V> {
1155    type Item = (&'a K, &'a mut V);
1156    type IntoIter = IterMut<'a, K, V>;
1157
1158    #[inline]
1159    fn into_iter(self) -> Self::IntoIter {
1160        self.iter_mut()
1161    }
1162}
1163
1164impl<'store, K, V> IntoIterator for BTreeMap<'store, K, V> {
1165    type Item = (K, V);
1166    type IntoIter = IntoIter<'store, K, V>;
1167
1168    #[inline]
1169    fn into_iter(self) -> Self::IntoIter {
1170        IntoIter::new(self)
1171    }
1172}
1173// endregion
1174
1175// region iterators (almost all boilerplate)
1176// region Iter
1177pub struct Iter<'a, K, V> {
1178    cursor: Cursor<'a, K, V>,
1179    back_cursor: Cursor<'a, K, V>,
1180    length: usize,
1181    _p: PhantomData<(&'a K, &'a V)>,
1182}
1183
1184//noinspection DuplicatedCode
1185impl<'a, K, V> Iter<'a, K, V> {
1186    #[inline]
1187    fn new(tree: &'a BTreeMap<K, V>) -> Self {
1188        Self {
1189            cursor: unsafe { Cursor::new(tree.first_leaf(), 0) },
1190            back_cursor: unsafe { Cursor::new_at_end(tree.last_leaf()) },
1191            length: tree.length,
1192            _p: PhantomData,
1193        }
1194    }
1195
1196    /// Get the next element without advancing the iterator
1197    #[inline]
1198    pub fn peek(&self) -> Option<(&'a K, &'a V)> {
1199        if self.length == 0 {
1200            return None;
1201        }
1202        self.cursor.key_value()
1203    }
1204
1205    /// Get the next back element without advancing the back iterator
1206    #[inline]
1207    pub fn peek_back(&self) -> Option<(&'a K, &'a V)> {
1208        if self.length == 0 {
1209            return None;
1210        }
1211        self.back_cursor.key_value()
1212    }
1213
1214    /// Equivalent to `next` except *panics* if iteration is done.
1215    #[inline]
1216    pub fn advance(&mut self) {
1217        if self.length == 0 {
1218            panic!("iteration is done");
1219        }
1220        self.cursor.advance();
1221        self.length -= 1;
1222    }
1223
1224    /// Equivalent to `next_back` except *panics* if iteration is done.
1225    #[inline]
1226    pub fn advance_back(&mut self) {
1227        if self.length == 0 {
1228            panic!("iteration is done");
1229        }
1230        self.back_cursor.advance_back();
1231        self.length -= 1;
1232    }
1233}
1234
1235impl<'a, K, V> Iterator for Iter<'a, K, V> {
1236    type Item = (&'a K, &'a V);
1237
1238    #[inline]
1239    fn next(&mut self) -> Option<Self::Item> {
1240        let key_value = self.peek()?;
1241        self.advance();
1242        Some(key_value)
1243    }
1244
1245    #[inline]
1246    fn size_hint(&self) -> (usize, Option<usize>) {
1247        (self.length, Some(self.length))
1248    }
1249}
1250
1251impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1252    #[inline]
1253    fn next_back(&mut self) -> Option<Self::Item> {
1254        let key_value = self.peek_back()?;
1255        self.advance_back();
1256        Some(key_value)
1257    }
1258}
1259
1260impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1261    #[inline]
1262    fn len(&self) -> usize {
1263        self.length
1264    }
1265}
1266
1267impl<'a, K, V> FusedIterator for Iter<'a, K, V> {}
1268// endregion
1269
1270// region IterMut
1271pub struct IterMut<'a, K, V> {
1272    cursor: Cursor<'a, K, V>,
1273    back_cursor: Cursor<'a, K, V>,
1274    length: usize,
1275    /// Unlike in [Cursor], reference to `V` is mutable
1276    _p: PhantomData<(&'a K, &'a mut V)>,
1277}
1278
1279//noinspection DuplicatedCode
1280impl<'a, K, V> IterMut<'a, K, V> {
1281    #[inline]
1282    fn new(tree: &'a BTreeMap<K, V>) -> Self {
1283        Self {
1284            cursor: unsafe { Cursor::new(tree.first_leaf(), 0) },
1285            back_cursor: unsafe { Cursor::new_at_end(tree.last_leaf()) },
1286            length: tree.length,
1287            _p: PhantomData,
1288        }
1289    }
1290
1291    /// Get the next element without advancing the iterator
1292    #[inline]
1293    pub fn peek(&self) -> Option<(&'a K, &'a V)> {
1294        if self.length == 0 {
1295            return None;
1296        }
1297        self.cursor.key_value()
1298    }
1299
1300    /// Get the next back element without advancing the back iterator
1301    #[inline]
1302    pub fn peek_back(&self) -> Option<(&'a K, &'a V)> {
1303        if self.length == 0 {
1304            return None;
1305        }
1306        self.back_cursor.key_value()
1307    }
1308
1309    /// Get the next element without advancing the iterator
1310    #[inline]
1311    pub fn peek_mut(&mut self) -> Option<(&'a K, &'a mut V)> {
1312        if self.length == 0 {
1313            return None;
1314        }
1315        unsafe { self.cursor.key_value_mut() }
1316    }
1317
1318    /// Get the next back element without advancing the back iterator
1319    #[inline]
1320    pub fn peek_back_mut(&mut self) -> Option<(&'a K, &'a mut V)> {
1321        if self.length == 0 {
1322            return None;
1323        }
1324        unsafe { self.back_cursor.key_value_mut() }
1325    }
1326
1327    /// Equivalent to `next` except *panics* if iteration is done.
1328    #[inline]
1329    pub fn advance(&mut self) {
1330        if self.length == 0 {
1331            panic!("iteration is done");
1332        }
1333        self.cursor.advance();
1334        self.length -= 1;
1335    }
1336
1337    /// Equivalent to `next_back` except *panics* if iteration is done.
1338    #[inline]
1339    pub fn advance_back(&mut self) {
1340        if self.length == 0 {
1341            panic!("iteration is done");
1342        }
1343        self.back_cursor.advance_back();
1344        self.length -= 1;
1345    }
1346}
1347
1348impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1349    type Item = (&'a K, &'a mut V);
1350
1351    #[inline]
1352    fn next(&mut self) -> Option<Self::Item> {
1353        let key_value = self.peek_mut()?;
1354        self.advance();
1355        Some(key_value)
1356    }
1357
1358    #[inline]
1359    fn size_hint(&self) -> (usize, Option<usize>) {
1360        (self.length, Some(self.length))
1361    }
1362}
1363
1364impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1365    #[inline]
1366    fn next_back(&mut self) -> Option<Self::Item> {
1367        let key_value = self.peek_back_mut()?;
1368        self.advance_back();
1369        Some(key_value)
1370    }
1371}
1372
1373impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1374    #[inline]
1375    fn len(&self) -> usize {
1376        self.length
1377    }
1378}
1379
1380impl<'a, K, V> FusedIterator for IterMut<'a, K, V> {}
1381// endregion
1382
1383// region IntoIter
1384pub struct IntoIter<'store, K, V> {
1385    store: &'store BTreeStore<K, V>,
1386    cursor: Cursor<'store, K, V>,
1387    back_cursor: Cursor<'store, K, V>,
1388    length: usize,
1389    /// Unlike in [Cursor], `K` and `V` are owned
1390    _p: PhantomData<(K, V)>,
1391}
1392
1393impl<'store, K, V> IntoIter<'store, K, V> {
1394    #[inline]
1395    fn new(tree: BTreeMap<'store, K, V>) -> Self {
1396        let result = Self {
1397            store: tree.store,
1398            cursor: unsafe { Cursor::new(tree.first_leaf(), 0) },
1399            back_cursor: unsafe { Cursor::new_at_end(tree.last_leaf()) },
1400            length: tree.length,
1401            _p: PhantomData,
1402        };
1403        // We drop the tree's nodes, so prevent it drop dropping when it drops itself.
1404        // This should be equivalent to `tree.root = None`
1405        forget(tree);
1406        result
1407    }
1408}
1409
1410impl<'store, K, V> Iterator for IntoIter<'store, K, V> {
1411    type Item = (K, V);
1412
1413    #[inline]
1414    fn next(&mut self) -> Option<Self::Item> {
1415        if self.length == 0 {
1416            return None;
1417        }
1418        unsafe {
1419            let key_value = self.cursor.read_key_value().unwrap();
1420            let address = self.cursor.address().unwrap();
1421            self.cursor.advance();
1422            dealloc_up_lasts(address, |n| self.store.dealloc(n));
1423            self.length -= 1;
1424            Some(key_value)
1425        }
1426    }
1427
1428    #[inline]
1429    fn size_hint(&self) -> (usize, Option<usize>) {
1430        (self.length, Some(self.length))
1431    }
1432}
1433
1434impl<'a, K, V> DoubleEndedIterator for IntoIter<'a, K, V> {
1435    #[inline]
1436    fn next_back(&mut self) -> Option<Self::Item> {
1437        if self.length == 0 {
1438            return None;
1439        }
1440        unsafe {
1441            let key_value = self.back_cursor.read_key_value().unwrap();
1442            let address = self.back_cursor.address().unwrap();
1443            self.back_cursor.advance_back();
1444            dealloc_up_firsts(address, |n| self.store.dealloc(n));
1445            self.length -= 1;
1446            Some(key_value)
1447        }
1448    }
1449}
1450
1451impl<'store, K, V> ExactSizeIterator for IntoIter<'store, K, V> {
1452    #[inline]
1453    fn len(&self) -> usize {
1454        self.length
1455    }
1456}
1457
1458impl<'store, K, V> FusedIterator for IntoIter<'store, K, V> {}
1459// endregion
1460
1461// region Keys
1462pub struct Keys<'a, K, V>(Iter<'a, K, V>);
1463
1464impl<'a, K, V> Iterator for Keys<'a, K, V> {
1465    type Item = &'a K;
1466
1467    #[inline]
1468    fn next(&mut self) -> Option<Self::Item> {
1469        self.0.next().map(|(k, _)| k)
1470    }
1471
1472    #[inline]
1473    fn size_hint(&self) -> (usize, Option<usize>) {
1474        self.0.size_hint()
1475    }
1476}
1477
1478impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1479    #[inline]
1480    fn next_back(&mut self) -> Option<Self::Item> {
1481        self.0.next_back().map(|(k, _)| k)
1482    }
1483}
1484
1485impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1486    #[inline]
1487    fn len(&self) -> usize {
1488        self.0.len()
1489    }
1490}
1491
1492impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
1493// endregion
1494
1495// region Values
1496pub struct Values<'a, K, V>(Iter<'a, K, V>);
1497
1498impl<'a, K, V> Iterator for Values<'a, K, V> {
1499    type Item = &'a V;
1500
1501    #[inline]
1502    fn next(&mut self) -> Option<Self::Item> {
1503        self.0.next().map(|(_, v)| v)
1504    }
1505
1506    #[inline]
1507    fn size_hint(&self) -> (usize, Option<usize>) {
1508        self.0.size_hint()
1509    }
1510}
1511
1512impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1513    #[inline]
1514    fn next_back(&mut self) -> Option<Self::Item> {
1515        self.0.next_back().map(|(_, v)| v)
1516    }
1517}
1518
1519impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1520    #[inline]
1521    fn len(&self) -> usize {
1522        self.0.len()
1523    }
1524}
1525
1526impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
1527// endregion
1528
1529// region ValuesMut
1530pub struct ValuesMut<'a, K, V>(IterMut<'a, K, V>);
1531
1532impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
1533    type Item = &'a mut V;
1534
1535    #[inline]
1536    fn next(&mut self) -> Option<Self::Item> {
1537        self.0.next().map(|(_, v)| v)
1538    }
1539
1540    #[inline]
1541    fn size_hint(&self) -> (usize, Option<usize>) {
1542        self.0.size_hint()
1543    }
1544}
1545
1546impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
1547    #[inline]
1548    fn next_back(&mut self) -> Option<Self::Item> {
1549        self.0.next_back().map(|(_, v)| v)
1550    }
1551}
1552
1553impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> {
1554    #[inline]
1555    fn len(&self) -> usize {
1556        self.0.len()
1557    }
1558}
1559
1560impl<'a, K, V> FusedIterator for ValuesMut<'a, K, V> {}
1561// endregion
1562
1563// region Range
1564pub struct Range<'a, K, V> {
1565    cursor: Cursor<'a, K, V>,
1566    back_cursor: Cursor<'a, K, V>,
1567    bounds: MaybeUninit<NodeBounds<K, V>>,
1568    _p: PhantomData<(&'a K, &'a V)>,
1569}
1570
1571//noinspection DuplicatedCode
1572impl<'a, K, V> Range<'a, K, V> {
1573    #[inline]
1574    fn new<Q: Ord>(tree: &'a BTreeMap<K, V>, bounds: impl RangeBounds<Q>) -> Self
1575    where
1576        K: Borrow<Q>,
1577    {
1578        let bounds = tree.node_bounds(bounds);
1579        let cursor = match bounds.as_ref().map(|b| b.start()) {
1580            None => Cursor::new_detached(),
1581            Some((start_node, start_idx)) => unsafe { Cursor::new(Some(start_node), start_idx) },
1582        };
1583        let back_cursor = match bounds.as_ref().map(|b| b.end()) {
1584            None => Cursor::new_detached(),
1585            Some((end_node, end_idx)) => unsafe { Cursor::new(Some(end_node), end_idx) },
1586        };
1587        let bounds = match bounds {
1588            None => MaybeUninit::uninit(),
1589            Some(bounds) => MaybeUninit::new(bounds),
1590        };
1591        Self {
1592            cursor,
1593            back_cursor,
1594            bounds,
1595            _p: PhantomData,
1596        }
1597    }
1598
1599    /// Get the next element without advancing the iterator
1600    #[inline]
1601    pub fn peek(&self) -> Option<(&'a K, &'a V)> {
1602        self.cursor.key_value()
1603    }
1604
1605    /// Get the next back element without advancing the back iterator
1606    #[inline]
1607    pub fn peek_back(&self) -> Option<(&'a K, &'a V)> {
1608        self.back_cursor.key_value()
1609    }
1610
1611    /// Equivalent to `next` except *panics* if iteration is done.
1612    #[inline]
1613    pub fn advance(&mut self) {
1614        self.cursor.advance();
1615        if !self.cursor.is_attached() {
1616            self.back_cursor.detach();
1617        } else if self
1618            .cursor
1619            .address()
1620            .ptr_eq(&Some(unsafe { self.bounds.assume_init_ref() }.end()))
1621        {
1622            self.cursor.detach();
1623            self.back_cursor.detach()
1624        }
1625    }
1626
1627    /// Equivalent to `next_back` except *panics* if iteration is done.
1628    #[inline]
1629    pub fn advance_back(&mut self) {
1630        self.back_cursor.advance_back();
1631        if !self.back_cursor.is_attached() {
1632            self.cursor.detach();
1633        } else if self
1634            .back_cursor
1635            .address()
1636            .ptr_eq(&Some(unsafe { self.bounds.assume_init_ref() }.start()))
1637        {
1638            self.cursor.detach();
1639            self.back_cursor.detach()
1640        }
1641    }
1642}
1643
1644impl<'a, K, V> Iterator for Range<'a, K, V> {
1645    type Item = (&'a K, &'a V);
1646
1647    #[inline]
1648    fn next(&mut self) -> Option<Self::Item> {
1649        let key_value = self.peek()?;
1650        self.advance();
1651        Some(key_value)
1652    }
1653}
1654
1655impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
1656    #[inline]
1657    fn next_back(&mut self) -> Option<Self::Item> {
1658        let key_value = self.peek_back()?;
1659        self.advance_back();
1660        Some(key_value)
1661    }
1662}
1663
1664impl<'a, K, V> FusedIterator for Range<'a, K, V> {}
1665// endregion
1666
1667// region RangeMut
1668pub struct RangeMut<'a, K, V> {
1669    cursor: Cursor<'a, K, V>,
1670    back_cursor: Cursor<'a, K, V>,
1671    bounds: MaybeUninit<NodeBounds<K, V>>,
1672    /// Unlike [Cursor], the reference to `V` is mutable
1673    _p: PhantomData<(&'a K, &'a mut V)>,
1674}
1675
1676//noinspection DuplicatedCode
1677impl<'a, K, V> RangeMut<'a, K, V> {
1678    #[inline]
1679    fn new<Q: Ord>(tree: &'a BTreeMap<K, V>, bounds: impl RangeBounds<Q>) -> Self
1680    where
1681        K: Borrow<Q>,
1682    {
1683        let bounds = tree.node_bounds(bounds);
1684        let cursor = match bounds.as_ref().map(|b| b.start()) {
1685            None => Cursor::new_detached(),
1686            Some((start_node, start_idx)) => unsafe { Cursor::new(Some(start_node), start_idx) },
1687        };
1688        let back_cursor = match bounds.as_ref().map(|b| b.end()) {
1689            None => Cursor::new_detached(),
1690            Some((end_node, end_idx)) => unsafe { Cursor::new(Some(end_node), end_idx) },
1691        };
1692        let bounds = match bounds {
1693            None => MaybeUninit::uninit(),
1694            Some(bounds) => MaybeUninit::new(bounds),
1695        };
1696        Self {
1697            cursor,
1698            back_cursor,
1699            bounds,
1700            _p: PhantomData,
1701        }
1702    }
1703
1704    /// Get the next element without advancing the iterator
1705    #[inline]
1706    pub fn peek(&self) -> Option<(&'a K, &'a V)> {
1707        self.cursor.key_value()
1708    }
1709
1710    /// Get the next back element without advancing the back iterator
1711    #[inline]
1712    pub fn peek_back(&self) -> Option<(&'a K, &'a V)> {
1713        self.back_cursor.key_value()
1714    }
1715
1716    /// Get the next element without advancing the iterator, with the value reference mutable
1717    #[inline]
1718    pub fn peek_mut(&mut self) -> Option<(&'a K, &'a mut V)> {
1719        unsafe { self.cursor.key_value_mut() }
1720    }
1721
1722    /// Get the next back element without advancing the back iterator, with the value reference
1723    /// mutable
1724    #[inline]
1725    pub fn peek_back_mut(&mut self) -> Option<(&'a K, &'a mut V)> {
1726        unsafe { self.back_cursor.key_value_mut() }
1727    }
1728
1729    /// Equivalent to `next` except *panics* if iteration is done.
1730    #[inline]
1731    pub fn advance(&mut self) {
1732        self.cursor.advance();
1733        if !self.cursor.is_attached() {
1734            self.back_cursor.detach();
1735        } else if self
1736            .cursor
1737            .address()
1738            .ptr_eq(&Some(unsafe { self.bounds.assume_init_ref() }.end()))
1739        {
1740            self.cursor.detach();
1741            self.back_cursor.detach()
1742        }
1743    }
1744
1745    /// Equivalent to `next_back` except *panics* if iteration is done.
1746    #[inline]
1747    pub fn advance_back(&mut self) {
1748        self.back_cursor.advance_back();
1749        if !self.back_cursor.is_attached() {
1750            self.cursor.detach();
1751        } else if self
1752            .back_cursor
1753            .address()
1754            .ptr_eq(&Some(unsafe { self.bounds.assume_init_ref() }.start()))
1755        {
1756            self.cursor.detach();
1757            self.back_cursor.detach()
1758        }
1759    }
1760}
1761
1762impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
1763    type Item = (&'a K, &'a mut V);
1764
1765    #[inline]
1766    fn next(&mut self) -> Option<Self::Item> {
1767        let key_value = self.peek_mut()?;
1768        self.advance();
1769        Some(key_value)
1770    }
1771}
1772
1773impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
1774    #[inline]
1775    fn next_back(&mut self) -> Option<Self::Item> {
1776        let key_value = self.peek_back_mut()?;
1777        self.advance_back();
1778        Some(key_value)
1779    }
1780}
1781
1782impl<'a, K, V> FusedIterator for RangeMut<'a, K, V> {}
1783// endregion
1784// endregion
1785
1786#[cfg(feature = "copyable")]
1787impl<'store, K, V> crate::copyable::sealed::BTree<'store, K, V> for BTreeMap<'store, K, V> {
1788    #[inline]
1789    fn assert_store(&self, store: &BTreeStore<K, V>) {
1790        assert_eq!(
1791            NonNull::from(self.store),
1792            NonNull::from(store),
1793            "b-tree is not from this store"
1794        );
1795    }
1796
1797    #[inline]
1798    fn nodes(&self) -> crate::copyable::sealed::NodeIter<'store, K, V> {
1799        crate::copyable::sealed::NodeIter::new(self.root, self.height)
1800    }
1801}
1802
1803unsafe fn as_nullable_ptr<K, V>(ptr: Option<NodePtr<K, V>>) -> *const Node<K, V> {
1804    match ptr {
1805        Some(ptr) => ptr.as_ptr().as_ptr(),
1806        None => std::ptr::null(),
1807    }
1808}