ic_stable_memory/collections/btree_map/
mod.rs

1use crate::collections::btree_map::internal_node::InternalBTreeNode;
2use crate::collections::btree_map::iter::SBTreeMapIter;
3use crate::collections::btree_map::leaf_node::LeafBTreeNode;
4use crate::encoding::AsFixedSizeBytes;
5use crate::mem::allocator::EMPTY_PTR;
6use crate::mem::free_block::FreeBlock;
7use crate::mem::{StablePtr, StablePtrBuf};
8use crate::primitive::s_ref::SRef;
9use crate::primitive::s_ref_mut::SRefMut;
10use crate::primitive::StableType;
11use crate::utils::math::shuffle_bits;
12use crate::{isoprint, make_sure_can_allocate, OutOfMemory, SSlice};
13use std::borrow::Borrow;
14use std::fmt::{Debug, Formatter};
15use std::mem;
16
17pub(crate) const B: usize = 8;
18pub(crate) const CAPACITY: usize = 2 * B - 1;
19pub(crate) const MIN_LEN_AFTER_SPLIT: usize = B - 1;
20
21pub(crate) const CHILDREN_CAPACITY: usize = 2 * B;
22pub(crate) const CHILDREN_MIN_LEN_AFTER_SPLIT: usize = B;
23
24pub(crate) const NODE_TYPE_INTERNAL: u8 = 127;
25pub(crate) const NODE_TYPE_LEAF: u8 = 255;
26pub(crate) const NODE_TYPE_OFFSET: u64 = 0;
27
28pub(crate) mod internal_node;
29pub mod iter;
30pub(crate) mod leaf_node;
31
32/// Right-biased B-plus tree based map data structure
33///
34/// Entries are stored in ascending order of their keys. Use [std::cmp::Reverse] or a custom [std::cmp::Ord]
35/// impl, to differ the order.
36///
37/// `B` is `8`. This implementation is optimized to perform as few stable memory (de)allocations
38/// as possible. Also, this data structure implements several non-conventional functions in order to
39/// share code with other data structures, based on this one.
40///
41/// This is an "infinite" data structure - it can handle up to [u64::MAX] key-value entries.
42///
43/// Both `K` and `V` have to implement [StableType] and [AsFixedSizeBytes] traits. [SBTreeMap] also
44/// implements these trait, so you can nest it in other stable structures.
45pub struct SBTreeMap<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> {
46    root: Option<BTreeNode<K, V>>,
47    len: u64,
48    certified: bool,
49    stable_drop_flag: bool,
50    _stack: Vec<(InternalBTreeNode<K>, usize, usize)>,
51    _buf: Vec<u8>,
52}
53
54impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> SBTreeMap<K, V> {
55    /// Creates a new [SBTreeMap]
56    ///
57    /// Does not allocate any heap or stable memory.
58    #[inline]
59    pub fn new() -> Self {
60        Self {
61            root: None,
62            len: 0,
63            certified: false,
64            stable_drop_flag: true,
65            _stack: Vec::default(),
66            _buf: Vec::default(),
67        }
68    }
69
70    #[inline]
71    pub(crate) fn new_certified() -> Self {
72        Self {
73            root: None,
74            len: 0,
75            certified: true,
76            stable_drop_flag: true,
77            _stack: Vec::default(),
78            _buf: Vec::default(),
79        }
80    }
81
82    /// Inserts the provided key-value pair into this [SBTreeMap]
83    ///
84    /// May allocate stable and heap memory. If your canister is out of stable memory, will return
85    /// [Err] with the key-value pair that was about to get inserted.
86    ///
87    /// If the insertion is successful, returns [Option] with a value, that was previously stored
88    /// under this key.
89    ///
90    /// # Example
91    /// ```rust
92    /// # use ic_stable_memory::collections::SBTreeMap;
93    /// # use ic_stable_memory::stable_memory_init;
94    /// # unsafe { ic_stable_memory::mem::clear(); }
95    /// # stable_memory_init();
96    /// let mut map = SBTreeMap::new();
97    ///
98    /// match map.insert(10u64, 100u64) {
99    ///     Ok(prev) => println!("Success! Previous value == {prev:?}"),
100    ///     Err((k, v)) => println!("Out of memory. Unable to insert pair: {k}, {v}"),
101    /// };
102    /// ```
103    #[inline]
104    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)> {
105        self._insert(key, value, &mut LeveledList::None)
106    }
107
108    pub(crate) fn _insert(
109        &mut self,
110        key: K,
111        value: V,
112        modified: &mut LeveledList,
113    ) -> Result<Option<V>, (K, V)> {
114        if let Ok(mut node) = self.get_or_create_root() {
115            let mut leaf = loop {
116                match unsafe { node.copy() } {
117                    BTreeNode::Internal(internal_node) => {
118                        let node_len = internal_node.read_len();
119                        let child_idx = match internal_node.binary_search(&key, node_len) {
120                            Ok(idx) => idx + 1,
121                            Err(idx) => idx,
122                        };
123
124                        let child_ptr = internal_node.read_child_ptr_buf(child_idx);
125                        self.push_stack(internal_node, node_len, child_idx);
126
127                        node = BTreeNode::<K, V>::from_ptr(u64::from_fixed_size_bytes(&child_ptr));
128                    }
129                    BTreeNode::Leaf(leaf_node) => break unsafe { leaf_node.copy() },
130                }
131            };
132
133            // this call makes sure there is enough free stable memory to allocate everything else
134            // if it returns Ok - every other allocation after that should simply .unwrap()
135            let right_leaf = match self.insert_leaf(&mut leaf, key, value, modified)? {
136                Ok(v) => {
137                    self.clear_stack(modified);
138
139                    return Ok(Some(v));
140                }
141                Err(right_leaf_opt) => {
142                    if let Some(right_leaf) = right_leaf_opt {
143                        right_leaf
144                    } else {
145                        self.clear_stack(modified);
146                        self.len += 1;
147
148                        return Ok(None);
149                    }
150                }
151            };
152
153            let mut key_to_index = right_leaf.read_key_buf(0);
154            let mut ptr = right_leaf.as_ptr();
155
156            while let Some((mut parent, parent_len, idx)) = self.pop_stack() {
157                if let Some((right, _k)) = self.insert_internal(
158                    &mut parent,
159                    parent_len,
160                    idx,
161                    key_to_index,
162                    ptr.as_new_fixed_size_bytes(),
163                    modified,
164                ) {
165                    key_to_index = _k;
166                    ptr = right.as_ptr();
167                    node = BTreeNode::Internal(parent);
168                } else {
169                    self.clear_stack(modified);
170                    self.len += 1;
171
172                    return Ok(None);
173                }
174            }
175
176            // stack is empty now
177
178            let new_root = InternalBTreeNode::<K>::create(
179                &key_to_index,
180                &node.as_ptr().as_new_fixed_size_bytes(),
181                &ptr.as_new_fixed_size_bytes(),
182                self.certified,
183            )
184            .unwrap();
185
186            modified.insert_root(new_root.as_ptr());
187
188            self.root = Some(BTreeNode::Internal(new_root));
189            self.len += 1;
190
191            Ok(None)
192        } else {
193            Err((key, value))
194        }
195    }
196
197    /// Removes a key-value pair by the provided key
198    ///
199    /// Returns [None] if no pair was found by this key. May release some of stable memory occupied
200    /// by this stable structure.
201    ///
202    /// # Examples
203    /// ```rust
204    /// # use ic_stable_memory::collections::SBTreeMap;
205    /// # use ic_stable_memory::stable_memory_init;
206    /// # unsafe { ic_stable_memory::mem::clear(); }
207    /// # stable_memory_init();
208    /// let mut map = SBTreeMap::new();
209    ///
210    /// map.insert(1, 10).expect("Out of memory");
211    ///
212    /// assert_eq!(map.remove(&1).unwrap(), 10);
213    /// ```
214    ///
215    /// Borrowed type is also accepted. If your key type is, for example, [SBox] of [String],
216    /// then you can remove the pair by [String].
217    /// ```rust
218    /// # use ic_stable_memory::collections::SBTreeMap;
219    /// # use ic_stable_memory::{SBox, stable_memory_init};
220    /// # unsafe { ic_stable_memory::mem::clear(); }
221    /// # stable_memory_init();
222    /// let mut map = SBTreeMap::new();
223    ///
224    /// let str_key = String::from("The key");
225    /// let key = SBox::new(str_key.clone()).expect("Out of memory");
226    ///
227    /// map.insert(key, 10).expect("Out of memory");
228    ///
229    /// assert_eq!(map.remove(&str_key).unwrap(), 10);
230    /// ```
231    #[inline]
232    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
233    where
234        K: Borrow<Q>,
235        Q: Ord + ?Sized,
236    {
237        self._remove(key, &mut LeveledList::None)
238    }
239
240    pub(crate) fn _remove<Q>(&mut self, key: &Q, modified: &mut LeveledList) -> Option<V>
241    where
242        K: Borrow<Q>,
243        Q: Ord + ?Sized,
244    {
245        self.root.as_ref()?;
246
247        let mut node = unsafe { self.get_or_create_root().unwrap_unchecked() };
248        let mut found_internal_node = None;
249
250        // lookup for the leaf that may contain the key
251        let mut leaf = loop {
252            match node {
253                BTreeNode::Internal(internal_node) => {
254                    let node_len = internal_node.read_len();
255                    let child_idx = match internal_node.binary_search(key, node_len) {
256                        Ok(idx) => {
257                            debug_assert!(found_internal_node.is_none());
258                            found_internal_node = Some((unsafe { internal_node.copy() }, idx));
259
260                            idx + 1
261                        }
262                        Err(idx) => idx,
263                    };
264
265                    let child_ptr = internal_node.read_child_ptr_buf(child_idx);
266                    self.push_stack(internal_node, node_len, child_idx);
267
268                    node = BTreeNode::<K, V>::from_ptr(u64::from_fixed_size_bytes(&child_ptr));
269                }
270                BTreeNode::Leaf(leaf_node) => break unsafe { leaf_node.copy() },
271            }
272        };
273
274        let leaf_len = leaf.read_len();
275        let idx = leaf.binary_search(key, leaf_len).ok()?;
276
277        self.len -= 1;
278
279        // if possible to simply remove the key without violating - return early
280        if leaf_len > MIN_LEN_AFTER_SPLIT {
281            let v = leaf.remove_and_disown_by_idx(idx, leaf_len, &mut self._buf);
282            leaf.write_len(leaf_len - 1);
283
284            if let Some((mut fin, i)) = found_internal_node {
285                fin.write_key_buf(i, &leaf.read_key_buf(0));
286            }
287
288            modified.push(self.current_depth(), leaf.as_ptr());
289            self.clear_stack(modified);
290
291            return Some(v);
292        };
293
294        let stack_top_frame = self.peek_stack();
295
296        // if the only node in the tree is the root - return early
297        if stack_top_frame.is_none() {
298            let v = leaf.remove_and_disown_by_idx(idx, leaf_len, &mut self._buf);
299            leaf.write_len(leaf_len - 1);
300
301            modified.push(0, leaf.as_ptr());
302
303            return Some(v);
304        }
305
306        self.steal_from_sibling_leaf_or_merge(
307            stack_top_frame,
308            leaf,
309            idx,
310            found_internal_node,
311            modified,
312        )
313    }
314
315    /// Returns an immutable reference [SRef] to a value stored by the key
316    ///
317    /// See also [SBTreeMap::get_mut].
318    ///
319    /// If no such key-value pair is found, returns [None]
320    ///
321    /// Borrowed type is also accepted. If your key type is, for example, [SBox] of [String],
322    /// then you can get the value by [String].
323    ///
324    /// # Example
325    /// ```rust
326    /// # use ic_stable_memory::collections::SBTreeMap;
327    /// # use ic_stable_memory::{SBox, stable_memory_init};
328    /// # unsafe { ic_stable_memory::mem::clear(); }
329    /// # stable_memory_init();
330    /// let mut map = SBTreeMap::new();
331    ///
332    /// let str_key = String::from("The key");
333    /// let key = SBox::new(str_key.clone()).expect("Out of memory");
334    ///
335    /// map.insert(key, 10).expect("Out of memory");
336    ///
337    /// assert_eq!(*map.get(&str_key).unwrap(), 10);
338    /// ```
339    #[inline]
340    pub fn get<Q>(&self, key: &Q) -> Option<SRef<V>>
341    where
342        K: Borrow<Q>,
343        Q: Ord + ?Sized,
344    {
345        let (leaf_node, idx) = self.lookup(key, false)?;
346
347        Some(leaf_node.get_value(idx))
348    }
349
350    /// Returns a random key, deterministically deriving the randomness from the seed.
351    /// This function is usefull, when you have a source of real randomness.
352    ///
353    /// If the collection is empty, returns [None].
354    ///
355    /// Same seed on the same collection leads to the same returned key.
356    /// Same seed on a modified collection may still lead to the same returned key.
357    /// You can use [utils::math::shuffle_bits] function to pseudo-randomly generate more seeds.
358    pub fn get_random_key(&self, mut seed: u32) -> Option<SRef<K>> {
359        if self.is_empty() {
360            return None;
361        }
362
363        let mut node = self.get_root()?;
364
365        loop {
366            match node {
367                BTreeNode::Internal(i) => {
368                    let len = i.read_len();
369                    let idx = seed as usize % (len + 1);
370                    let child_ptr = u64::from_fixed_size_bytes(&i.read_child_ptr_buf(idx));
371
372                    seed = shuffle_bits(seed);
373
374                    node = BTreeNode::from_ptr(child_ptr);
375                }
376                BTreeNode::Leaf(l) => {
377                    let len = l.read_len();
378                    let idx = seed as usize % len;
379
380                    break Some(l.get_key(idx));
381                }
382            }
383        }
384    }
385
386    /// Returns a mutable reference [SRefMut] to a value stored by the key
387    ///
388    /// See also [SBTreeMap::get].
389    ///
390    /// If no such key-value pair is found, returns [None]
391    ///
392    /// Borrowed type is also accepted. If your key type is, for example, [SBox] of [String],
393    /// then you can get the value by [String].
394    #[inline]
395    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<SRefMut<V>>
396    where
397        K: Borrow<Q>,
398        Q: Ord + ?Sized,
399    {
400        self._get_mut(key, &mut LeveledList::None)
401    }
402
403    #[inline]
404    pub(crate) fn _get_mut<Q>(&mut self, key: &Q, modified: &mut LeveledList) -> Option<SRefMut<V>>
405    where
406        K: Borrow<Q>,
407        Q: Ord + ?Sized,
408    {
409        if modified.is_some() {
410            let mut modified_buf = Vec::new();
411
412            let mut level = 0;
413            let mut node = self.get_root()?;
414            loop {
415                match node {
416                    BTreeNode::Internal(internal_node) => {
417                        let child_idx =
418                            match internal_node.binary_search(key, internal_node.read_len()) {
419                                Ok(idx) => idx + 1,
420                                Err(idx) => idx,
421                            };
422
423                        modified_buf.push((level, internal_node.as_ptr()));
424                        level += 1;
425
426                        let child_ptr = u64::from_fixed_size_bytes(
427                            &internal_node.read_child_ptr_buf(child_idx),
428                        );
429                        node = BTreeNode::from_ptr(child_ptr);
430                    }
431                    BTreeNode::Leaf(mut leaf_node) => {
432                        return match leaf_node.binary_search(key, leaf_node.read_len()) {
433                            Ok(idx) => {
434                                for (l, ptr) in modified_buf {
435                                    modified.push(l, ptr);
436                                }
437
438                                modified.push(level, leaf_node.as_ptr());
439
440                                Some(leaf_node.get_value_mut(idx))
441                            }
442                            _ => None,
443                        }
444                    }
445                }
446            }
447        }
448
449        let (mut leaf_node, idx) = self.lookup(key, false)?;
450
451        Some(leaf_node.get_value_mut(idx))
452    }
453
454    /// Returns true if there exists a key-value pair stored by the provided key
455    ///
456    /// Borrowed type is also accepted. If your key type is, for example, [SBox] of [String],
457    /// then you can get the value by [String].
458    #[inline]
459    pub fn contains_key<Q>(&self, key: &Q) -> bool
460    where
461        K: Borrow<Q>,
462        Q: Ord + ?Sized,
463    {
464        self.lookup(key, true).is_some()
465    }
466
467    /// Returns an iterator over entries of this [SBTreeMap]
468    ///
469    /// Elements of this iterator are presented in ascending order.
470    ///
471    /// # Example
472    /// ```rust
473    /// # use ic_stable_memory::collections::SBTreeMap;
474    /// # use ic_stable_memory::stable_memory_init;
475    /// # unsafe { ic_stable_memory::mem::clear(); }
476    /// # stable_memory_init();
477    /// let mut map = SBTreeMap::new();
478    ///
479    /// for i in 0..100 {
480    ///     map.insert(i, i).expect("Out of memory");
481    /// }
482    ///
483    /// let mut i = 0;
484    /// for (k, v) in map.iter() {
485    ///     assert_eq!(*k, i);
486    ///     assert_eq!(*v, i);
487    ///
488    ///     i += 1;
489    /// }
490    ///
491    /// assert_eq!(i, 100);
492    /// ```
493    ///
494    /// One can use `.rev()` to get elements in reverse order.
495    ///
496    /// # Example
497    /// ```rust
498    /// # use ic_stable_memory::collections::SBTreeMap;
499    /// # use ic_stable_memory::stable_memory_init;
500    /// # unsafe { ic_stable_memory::mem::clear(); }
501    /// # stable_memory_init();
502    /// let mut map = SBTreeMap::new();
503    ///
504    /// for i in 0..100 {
505    ///     map.insert(i, i).expect("Out of memory");
506    /// }
507    ///
508    /// let mut i = 100;
509    /// for (k, v) in map.iter().rev() {
510    ///     i -= 1;
511    ///
512    ///     assert_eq!(*k, i);
513    ///     assert_eq!(*v, i);
514    /// }
515    ///
516    /// assert_eq!(i, 0);
517    /// ```
518    #[inline]
519    pub fn iter(&self) -> SBTreeMapIter<K, V> {
520        SBTreeMapIter::<K, V>::new(self)
521    }
522
523    /// Returns the length of this [SBTreeMap]
524    #[inline]
525    pub fn len(&self) -> u64 {
526        self.len
527    }
528
529    /// Returns [true] if the length of this [SBTreeMap] is `0`
530    #[inline]
531    pub fn is_empty(&self) -> bool {
532        self.len() == 0
533    }
534
535    /// Removes all key-value pairs from this collection, releasing all occupied stable memory
536    #[inline]
537    pub fn clear(&mut self) {
538        let mut old = mem::replace(self, Self::new());
539        self.stable_drop_flag = old.stable_drop_flag;
540        self.certified = old.certified;
541
542        unsafe { old.stable_drop() };
543    }
544
545    #[inline]
546    fn clear_stack(&mut self, modified: &mut LeveledList) {
547        match modified {
548            LeveledList::None => {
549                self._stack.clear();
550            }
551            LeveledList::Some(_) => {
552                while let Some((p, _, _)) = self._stack.pop() {
553                    modified.push(self.current_depth(), p.as_ptr());
554                }
555            }
556        }
557    }
558
559    #[inline]
560    fn current_depth(&self) -> usize {
561        self._stack.len()
562    }
563
564    #[inline]
565    fn push_stack(&mut self, node: InternalBTreeNode<K>, len: usize, child_idx: usize) {
566        self._stack.push((node, len, child_idx));
567    }
568
569    #[inline]
570    fn pop_stack(&mut self) -> Option<(InternalBTreeNode<K>, usize, usize)> {
571        self._stack.pop()
572    }
573
574    pub(crate) fn get_root(&self) -> Option<BTreeNode<K, V>> {
575        unsafe { self.root.as_ref().map(|it| it.copy()) }
576    }
577
578    pub(crate) fn set_certified(&mut self, val: bool) {
579        self.certified = val;
580    }
581
582    // WARNING: return_early == true will return nonsense leaf node and idx
583    fn lookup<Q>(&self, key: &Q, return_early: bool) -> Option<(LeafBTreeNode<K, V>, usize)>
584    where
585        K: Borrow<Q>,
586        Q: Ord + ?Sized,
587    {
588        let mut node = self.get_root()?;
589        loop {
590            match node {
591                BTreeNode::Internal(internal_node) => {
592                    let child_idx = match internal_node.binary_search(key, internal_node.read_len())
593                    {
594                        Ok(idx) => {
595                            if return_early {
596                                return unsafe { Some((LeafBTreeNode::from_ptr(0), 0)) };
597                            } else {
598                                idx + 1
599                            }
600                        }
601                        Err(idx) => idx,
602                    };
603
604                    let child_ptr =
605                        u64::from_fixed_size_bytes(&internal_node.read_child_ptr_buf(child_idx));
606                    node = BTreeNode::from_ptr(child_ptr);
607                }
608                BTreeNode::Leaf(leaf_node) => {
609                    return match leaf_node.binary_search(key, leaf_node.read_len()) {
610                        Ok(idx) => Some((leaf_node, idx)),
611                        _ => None,
612                    }
613                }
614            }
615        }
616    }
617
618    fn insert_leaf(
619        &mut self,
620        leaf_node: &mut LeafBTreeNode<K, V>,
621        mut key: K,
622        mut value: V,
623        modified: &mut LeveledList,
624    ) -> Result<Result<V, Option<LeafBTreeNode<K, V>>>, (K, V)> {
625        let leaf_node_len = leaf_node.read_len();
626        let insert_idx = match leaf_node.binary_search(&key, leaf_node_len) {
627            Ok(existing_idx) => {
628                // if there is already a key like that, return early
629                let prev_value: V = leaf_node.read_and_disown_value(existing_idx);
630                leaf_node.write_and_own_value(existing_idx, value);
631
632                modified.push(self.current_depth(), leaf_node.as_ptr());
633
634                return Ok(Ok(prev_value));
635            }
636            Err(idx) => idx,
637        };
638
639        let k = key.as_new_fixed_size_bytes();
640        let v = value.as_new_fixed_size_bytes();
641
642        // if there is enough space - simply insert and return early
643        if leaf_node_len < CAPACITY {
644            leaf_node.insert_key_buf(insert_idx, &k, leaf_node_len, &mut self._buf);
645            leaf_node.insert_value_buf(insert_idx, &v, leaf_node_len, &mut self._buf);
646
647            leaf_node.write_len(leaf_node_len + 1);
648
649            modified.push(self.current_depth(), leaf_node.as_ptr());
650
651            unsafe { key.stable_drop_flag_off() };
652            unsafe { value.stable_drop_flag_off() };
653
654            return Ok(Err(None));
655        }
656
657        // try passing an element to a neighbor, to make room for a new one
658        if self.pass_elem_to_sibling_leaf(leaf_node, &k, &v, insert_idx, modified) {
659            unsafe { key.stable_drop_flag_off() };
660            unsafe { value.stable_drop_flag_off() };
661
662            return Ok(Err(None));
663        }
664
665        // cheking if it is possible to allocate worst-case scenario amount of memory
666        let memory_to_allocate = (self._stack.len() + 1) as u64
667            * FreeBlock::to_total_size(InternalBTreeNode::<K>::calc_byte_size(self.certified))
668            + FreeBlock::to_total_size(LeafBTreeNode::<K, V>::calc_size_bytes(self.certified));
669
670        // we can unwrap all OutOfMemory errors if this check passes, without any consequences
671        if !make_sure_can_allocate(memory_to_allocate) {
672            return Err((key, value));
673        }
674
675        unsafe { key.stable_drop_flag_off() };
676        unsafe { value.stable_drop_flag_off() };
677
678        // split the leaf and insert so both leaves now have length of B
679        let mut right = if insert_idx < B {
680            let right = leaf_node
681                .split_max_len(true, &mut self._buf, self.certified)
682                .unwrap();
683            leaf_node.insert_key_buf(insert_idx, &k, MIN_LEN_AFTER_SPLIT, &mut self._buf);
684            leaf_node.insert_value_buf(insert_idx, &v, MIN_LEN_AFTER_SPLIT, &mut self._buf);
685
686            right
687        } else {
688            let mut right = leaf_node
689                .split_max_len(false, &mut self._buf, self.certified)
690                .unwrap();
691            right.insert_key_buf(insert_idx - B, &k, MIN_LEN_AFTER_SPLIT, &mut self._buf);
692            right.insert_value_buf(insert_idx - B, &v, MIN_LEN_AFTER_SPLIT, &mut self._buf);
693
694            right
695        };
696
697        leaf_node.write_len(B);
698        right.write_len(B);
699
700        modified.push(self.current_depth(), leaf_node.as_ptr());
701        modified.push(self.current_depth(), right.as_ptr());
702
703        Ok(Err(Some(right)))
704    }
705
706    fn insert_internal(
707        &mut self,
708        internal_node: &mut InternalBTreeNode<K>,
709        len: usize,
710        idx: usize,
711        key: K::Buf,
712        child_ptr: StablePtrBuf,
713        modified: &mut LeveledList,
714    ) -> Option<(InternalBTreeNode<K>, K::Buf)> {
715        if len < CAPACITY {
716            internal_node.insert_key_buf(idx, &key, len, &mut self._buf);
717            internal_node.insert_child_ptr_buf(idx + 1, &child_ptr, len + 1, &mut self._buf);
718
719            internal_node.write_len(len + 1);
720
721            modified.push(self.current_depth(), internal_node.as_ptr());
722
723            return None;
724        }
725
726        if self.pass_elem_to_sibling_internal(internal_node, idx, &key, &child_ptr, modified) {
727            return None;
728        }
729
730        // TODO: possible to optimize when idx == MIN_LEN_AFTER_SPLIT
731        let (mut right, mid) = internal_node
732            .split_max_len(&mut self._buf, self.certified)
733            .unwrap();
734
735        if idx <= MIN_LEN_AFTER_SPLIT {
736            internal_node.insert_key_buf(idx, &key, MIN_LEN_AFTER_SPLIT, &mut self._buf);
737            internal_node.insert_child_ptr_buf(idx + 1, &child_ptr, B, &mut self._buf);
738
739            internal_node.write_len(B);
740            right.write_len(MIN_LEN_AFTER_SPLIT);
741        } else {
742            right.insert_key_buf(idx - B, &key, MIN_LEN_AFTER_SPLIT, &mut self._buf);
743            right.insert_child_ptr_buf(idx - B + 1, &child_ptr, B, &mut self._buf);
744
745            internal_node.write_len(MIN_LEN_AFTER_SPLIT);
746            right.write_len(B);
747        }
748
749        modified.push(self.current_depth(), internal_node.as_ptr());
750        modified.push(self.current_depth(), right.as_ptr());
751
752        Some((right, mid))
753    }
754
755    fn pass_elem_to_sibling_leaf(
756        &mut self,
757        leaf_node: &mut LeafBTreeNode<K, V>,
758        key: &K::Buf,
759        value: &V::Buf,
760        insert_idx: usize,
761        modified: &mut LeveledList,
762    ) -> bool {
763        let stack_top_frame = self.peek_stack();
764        if stack_top_frame.is_none() {
765            return false;
766        }
767
768        let (mut parent, parent_len, parent_idx) = unsafe { stack_top_frame.unwrap_unchecked() };
769
770        if let Some(mut left_sibling) = parent.read_left_sibling::<LeafBTreeNode<K, V>>(parent_idx)
771        {
772            let left_sibling_len = left_sibling.read_len();
773
774            // if it is possible to pass to the left sibling - do that
775            if left_sibling_len < CAPACITY {
776                self.pass_to_left_sibling_leaf(
777                    &mut parent,
778                    parent_idx,
779                    leaf_node,
780                    &mut left_sibling,
781                    left_sibling_len,
782                    insert_idx,
783                    key,
784                    value,
785                );
786
787                modified.push(self.current_depth(), leaf_node.as_ptr());
788                modified.push(self.current_depth(), left_sibling.as_ptr());
789
790                return true;
791            }
792        }
793
794        if let Some(mut right_sibling) =
795            parent.read_right_sibling::<LeafBTreeNode<K, V>>(parent_idx, parent_len)
796        {
797            let right_sibling_len = right_sibling.read_len();
798
799            if right_sibling_len < CAPACITY {
800                self.pass_to_right_sibling_leaf(
801                    &mut parent,
802                    parent_idx,
803                    leaf_node,
804                    &mut right_sibling,
805                    right_sibling_len,
806                    insert_idx,
807                    key,
808                    value,
809                );
810
811                modified.push(self.current_depth(), leaf_node.as_ptr());
812                modified.push(self.current_depth(), right_sibling.as_ptr());
813
814                return true;
815            }
816        }
817
818        false
819    }
820
821    fn pass_to_right_sibling_leaf(
822        &mut self,
823        p: &mut InternalBTreeNode<K>,
824        p_idx: usize,
825        leaf: &mut LeafBTreeNode<K, V>,
826        rs: &mut LeafBTreeNode<K, V>,
827        rs_len: usize,
828        i_idx: usize,
829        key: &K::Buf,
830        value: &V::Buf,
831    ) {
832        if i_idx != CAPACITY {
833            rs.steal_from_left(rs_len, leaf, CAPACITY, p, p_idx, None, &mut self._buf);
834
835            leaf.insert_key_buf(i_idx, key, CAPACITY - 1, &mut self._buf);
836            leaf.insert_value_buf(i_idx, value, CAPACITY - 1, &mut self._buf);
837
838            rs.write_len(rs_len + 1);
839            return;
840        }
841
842        let last = Some((key, value));
843        rs.steal_from_left(rs_len, leaf, CAPACITY, p, p_idx, last, &mut self._buf);
844        rs.write_len(rs_len + 1);
845    }
846
847    fn pass_to_left_sibling_leaf(
848        &mut self,
849        p: &mut InternalBTreeNode<K>,
850        p_idx: usize,
851        leaf: &mut LeafBTreeNode<K, V>,
852        ls: &mut LeafBTreeNode<K, V>,
853        ls_len: usize,
854        i_idx: usize,
855        key: &K::Buf,
856        value: &V::Buf,
857    ) {
858        if i_idx != 1 {
859            ls.steal_from_right(ls_len, leaf, CAPACITY, p, p_idx - 1, None, &mut self._buf);
860
861            leaf.insert_key_buf(i_idx - 1, key, CAPACITY - 1, &mut self._buf);
862            leaf.insert_value_buf(i_idx - 1, value, CAPACITY - 1, &mut self._buf);
863
864            ls.write_len(ls_len + 1);
865            return;
866        };
867
868        let first = Some((key, value));
869        ls.steal_from_right(ls_len, leaf, CAPACITY, p, p_idx - 1, first, &mut self._buf);
870        ls.write_len(ls_len + 1);
871    }
872
873    fn pass_elem_to_sibling_internal(
874        &mut self,
875        internal_node: &mut InternalBTreeNode<K>,
876        idx: usize,
877        key: &K::Buf,
878        child_ptr: &StablePtrBuf,
879        modified: &mut LeveledList,
880    ) -> bool {
881        let stack_top_frame = self.peek_stack();
882        if stack_top_frame.is_none() {
883            return false;
884        }
885
886        let (mut parent, parent_len, parent_idx) = unsafe { stack_top_frame.unwrap_unchecked() };
887
888        if let Some(mut left_sibling) = parent.read_left_sibling::<InternalBTreeNode<K>>(parent_idx)
889        {
890            let left_sibling_len = left_sibling.read_len();
891
892            if left_sibling_len < CAPACITY {
893                self.pass_to_left_sibling_internal(
894                    &mut parent,
895                    parent_idx,
896                    internal_node,
897                    &mut left_sibling,
898                    left_sibling_len,
899                    idx,
900                    key,
901                    child_ptr,
902                );
903
904                modified.push(self.current_depth(), internal_node.as_ptr());
905                modified.push(self.current_depth(), left_sibling.as_ptr());
906
907                return true;
908            }
909        }
910
911        if let Some(mut right_sibling) =
912            parent.read_right_sibling::<InternalBTreeNode<K>>(parent_idx, parent_len)
913        {
914            let right_sibling_len = right_sibling.read_len();
915
916            if right_sibling_len < CAPACITY {
917                self.pass_to_right_sibling_internal(
918                    &mut parent,
919                    parent_idx,
920                    internal_node,
921                    &mut right_sibling,
922                    right_sibling_len,
923                    idx,
924                    key,
925                    child_ptr,
926                );
927
928                modified.push(self.current_depth(), internal_node.as_ptr());
929                modified.push(self.current_depth(), right_sibling.as_ptr());
930
931                return true;
932            }
933        }
934
935        false
936    }
937
938    fn pass_to_right_sibling_internal(
939        &mut self,
940        p: &mut InternalBTreeNode<K>,
941        p_idx: usize,
942        node: &mut InternalBTreeNode<K>,
943        rs: &mut InternalBTreeNode<K>,
944        rs_len: usize,
945        i_idx: usize,
946        key: &K::Buf,
947        child_ptr: &StablePtrBuf,
948    ) {
949        if i_idx != CAPACITY {
950            rs.steal_from_left(rs_len, node, CAPACITY, p, p_idx, None, &mut self._buf);
951
952            node.insert_key_buf(i_idx, key, CAPACITY - 1, &mut self._buf);
953            node.insert_child_ptr_buf(i_idx + 1, child_ptr, CAPACITY, &mut self._buf);
954
955            rs.write_len(rs_len + 1);
956            return;
957        }
958
959        let last = Some((key, child_ptr));
960        rs.steal_from_left(rs_len, node, CAPACITY, p, p_idx, last, &mut self._buf);
961        rs.write_len(rs_len + 1);
962    }
963
964    fn pass_to_left_sibling_internal(
965        &mut self,
966        p: &mut InternalBTreeNode<K>,
967        p_idx: usize,
968        node: &mut InternalBTreeNode<K>,
969        ls: &mut InternalBTreeNode<K>,
970        ls_len: usize,
971        i_idx: usize,
972        key: &K::Buf,
973        child_ptr: &StablePtrBuf,
974    ) {
975        if i_idx != 0 {
976            ls.steal_from_right(ls_len, node, CAPACITY, p, p_idx - 1, None, &mut self._buf);
977
978            node.insert_key_buf(i_idx - 1, key, CAPACITY - 1, &mut self._buf);
979            node.insert_child_ptr_buf(i_idx, child_ptr, CAPACITY, &mut self._buf);
980
981            ls.write_len(ls_len + 1);
982            return;
983        }
984
985        let first = Some((key, child_ptr));
986        ls.steal_from_right(ls_len, node, CAPACITY, p, p_idx - 1, first, &mut self._buf);
987        ls.write_len(ls_len + 1);
988    }
989
990    fn steal_from_sibling_leaf_or_merge(
991        &mut self,
992        stack_top_frame: Option<(InternalBTreeNode<K>, usize, usize)>,
993        mut leaf: LeafBTreeNode<K, V>,
994        idx: usize,
995        found_internal_node: Option<(InternalBTreeNode<K>, usize)>,
996        modified: &mut LeveledList,
997    ) -> Option<V> {
998        let (mut parent, parent_len, parent_idx) = unsafe { stack_top_frame.unwrap_unchecked() };
999
1000        if let Some(mut left_sibling) = parent.read_left_sibling::<LeafBTreeNode<K, V>>(parent_idx)
1001        {
1002            let left_sibling_len = left_sibling.read_len();
1003
1004            // if possible to steal - return early
1005            if left_sibling_len > MIN_LEN_AFTER_SPLIT {
1006                self.steal_from_left_sibling_leaf(
1007                    &mut leaf,
1008                    &mut left_sibling,
1009                    left_sibling_len,
1010                    &mut parent,
1011                    parent_idx - 1,
1012                );
1013
1014                // idx + 1, because after the rotation the leaf has one more key added before
1015                let v = leaf.remove_and_disown_by_idx(idx + 1, B, &mut self._buf);
1016
1017                if let Some((mut fin, i)) = found_internal_node {
1018                    fin.write_key_buf(i, &leaf.read_key_buf(0));
1019                }
1020
1021                modified.push(self.current_depth(), leaf.as_ptr());
1022                modified.push(self.current_depth(), left_sibling.as_ptr());
1023                self.clear_stack(modified);
1024
1025                return Some(v);
1026            }
1027
1028            if let Some(mut right_sibling) =
1029                parent.read_right_sibling::<LeafBTreeNode<K, V>>(parent_idx, parent_len)
1030            {
1031                let right_sibling_len = right_sibling.read_len();
1032
1033                // if possible to steal - return early
1034                if right_sibling_len > MIN_LEN_AFTER_SPLIT {
1035                    self.steal_from_right_sibling_leaf(
1036                        &mut leaf,
1037                        &mut right_sibling,
1038                        right_sibling_len,
1039                        &mut parent,
1040                        parent_idx,
1041                    );
1042
1043                    // just idx, because after rotation leaf has one more key added to the end
1044                    let v = leaf.remove_and_disown_by_idx(idx, B, &mut self._buf);
1045
1046                    if let Some((mut fin, i)) = found_internal_node {
1047                        fin.write_key_buf(i, &leaf.read_key_buf(0));
1048                    }
1049
1050                    modified.push(self.current_depth(), leaf.as_ptr());
1051                    modified.push(self.current_depth(), right_sibling.as_ptr());
1052                    self.clear_stack(modified);
1053
1054                    return Some(v);
1055                }
1056
1057                return self.merge_with_right_sibling_leaf(
1058                    leaf,
1059                    right_sibling,
1060                    idx,
1061                    found_internal_node,
1062                    modified,
1063                );
1064            }
1065
1066            return self.merge_with_left_sibling_leaf(leaf, left_sibling, idx, modified);
1067        }
1068
1069        if let Some(mut right_sibling) =
1070            parent.read_right_sibling::<LeafBTreeNode<K, V>>(parent_idx, parent_len)
1071        {
1072            let right_sibling_len = right_sibling.read_len();
1073
1074            // if possible to steal - return early
1075            if right_sibling_len > MIN_LEN_AFTER_SPLIT {
1076                self.steal_from_right_sibling_leaf(
1077                    &mut leaf,
1078                    &mut right_sibling,
1079                    right_sibling_len,
1080                    &mut parent,
1081                    parent_idx,
1082                );
1083
1084                // just idx, because after rotation leaf has one more key added to the end
1085                let v = leaf.remove_and_disown_by_idx(idx, B, &mut self._buf);
1086
1087                if let Some((mut fin, i)) = found_internal_node {
1088                    fin.write_key_buf(i, &leaf.read_key_buf(0));
1089                }
1090
1091                modified.push(self.current_depth(), leaf.as_ptr());
1092                modified.push(self.current_depth(), right_sibling.as_ptr());
1093                self.clear_stack(modified);
1094
1095                return Some(v);
1096            }
1097
1098            return self.merge_with_right_sibling_leaf(
1099                leaf,
1100                right_sibling,
1101                idx,
1102                found_internal_node,
1103                modified,
1104            );
1105        }
1106
1107        unreachable!();
1108    }
1109
1110    fn merge_with_right_sibling_leaf(
1111        &mut self,
1112        mut leaf: LeafBTreeNode<K, V>,
1113        right_sibling: LeafBTreeNode<K, V>,
1114        idx: usize,
1115        found_internal_node: Option<(InternalBTreeNode<K>, usize)>,
1116        modified: &mut LeveledList,
1117    ) -> Option<V> {
1118        modified.remove(self.current_depth(), right_sibling.as_ptr());
1119        modified.push(self.current_depth(), leaf.as_ptr());
1120
1121        // otherwise merge with right
1122        leaf.merge_min_len(right_sibling, &mut self._buf);
1123
1124        // just idx, because leaf keys stay unchanged
1125        let v = leaf.remove_and_disown_by_idx(idx, CAPACITY - 1, &mut self._buf);
1126        leaf.write_len(CAPACITY - 2);
1127
1128        if let Some((mut fin, i)) = found_internal_node {
1129            fin.write_key_buf(i, &leaf.read_key_buf(0));
1130        }
1131
1132        self.handle_stack_after_merge(true, leaf, modified);
1133
1134        Some(v)
1135    }
1136
1137    fn merge_with_left_sibling_leaf(
1138        &mut self,
1139        leaf: LeafBTreeNode<K, V>,
1140        mut left_sibling: LeafBTreeNode<K, V>,
1141        idx: usize,
1142        modified: &mut LeveledList,
1143    ) -> Option<V> {
1144        modified.remove(self.current_depth(), leaf.as_ptr());
1145        modified.push(self.current_depth(), left_sibling.as_ptr());
1146
1147        // if there is no right sibling - merge with left
1148        left_sibling.merge_min_len(leaf, &mut self._buf);
1149        // idx + MIN_LEN_AFTER_SPLIT, because all keys of leaf are added to the
1150        // end of left_sibling
1151        let v = left_sibling.remove_and_disown_by_idx(
1152            idx + MIN_LEN_AFTER_SPLIT,
1153            CAPACITY - 1,
1154            &mut self._buf,
1155        );
1156        left_sibling.write_len(CAPACITY - 2);
1157
1158        // no reason to handle 'found_internal_node', because the key is
1159        // guaranteed to be in the nearest parent and left_sibling keys are all
1160        // continue to present
1161
1162        self.handle_stack_after_merge(false, left_sibling, modified);
1163
1164        Some(v)
1165    }
1166
1167    fn steal_from_left_sibling_leaf(
1168        &mut self,
1169        leaf: &mut LeafBTreeNode<K, V>,
1170        left_sibling: &mut LeafBTreeNode<K, V>,
1171        left_sibling_len: usize,
1172        parent: &mut InternalBTreeNode<K>,
1173        parent_idx: usize,
1174    ) {
1175        leaf.steal_from_left(
1176            MIN_LEN_AFTER_SPLIT,
1177            left_sibling,
1178            left_sibling_len,
1179            parent,
1180            parent_idx,
1181            None,
1182            &mut self._buf,
1183        );
1184
1185        left_sibling.write_len(left_sibling_len - 1);
1186    }
1187
1188    fn steal_from_right_sibling_leaf(
1189        &mut self,
1190        leaf: &mut LeafBTreeNode<K, V>,
1191        right_sibling: &mut LeafBTreeNode<K, V>,
1192        right_sibling_len: usize,
1193        parent: &mut InternalBTreeNode<K>,
1194        parent_idx: usize,
1195    ) {
1196        leaf.steal_from_right(
1197            MIN_LEN_AFTER_SPLIT,
1198            right_sibling,
1199            right_sibling_len,
1200            parent,
1201            parent_idx,
1202            None,
1203            &mut self._buf,
1204        );
1205
1206        right_sibling.write_len(right_sibling_len - 1);
1207    }
1208
1209    fn handle_stack_after_merge(
1210        &mut self,
1211        mut merged_right: bool,
1212        leaf: LeafBTreeNode<K, V>,
1213        modified: &mut LeveledList,
1214    ) {
1215        let mut prev_node = BTreeNode::Leaf(leaf);
1216
1217        while let Some((mut node, node_len, remove_idx)) = self.pop_stack() {
1218            let (idx_to_remove, child_idx_to_remove) = if merged_right {
1219                (remove_idx, remove_idx + 1)
1220            } else {
1221                (remove_idx - 1, remove_idx)
1222            };
1223
1224            // if the node has enough keys, return early
1225            if node_len > MIN_LEN_AFTER_SPLIT {
1226                node.remove_key_buf(idx_to_remove, node_len, &mut self._buf);
1227                node.remove_child_ptr_buf(child_idx_to_remove, node_len + 1, &mut self._buf);
1228                node.write_len(node_len - 1);
1229
1230                modified.push(self.current_depth(), node.as_ptr());
1231                self.clear_stack(modified);
1232
1233                return;
1234            }
1235
1236            let stack_top_frame = self.peek_stack();
1237
1238            // if there is no parent, return early
1239            if stack_top_frame.is_none() {
1240                // if the root has only one key, make child the new root
1241                if node_len == 1 {
1242                    modified.remove_root();
1243
1244                    node.destroy();
1245                    self.root = Some(prev_node);
1246
1247                    return;
1248                }
1249
1250                // otherwise simply remove and return
1251                node.remove_key_buf(idx_to_remove, node_len, &mut self._buf);
1252                node.remove_child_ptr_buf(child_idx_to_remove, node_len + 1, &mut self._buf);
1253                node.write_len(node_len - 1);
1254
1255                modified.push(self.current_depth(), node.as_ptr());
1256
1257                return;
1258            }
1259
1260            let (mut parent, parent_len, parent_idx) =
1261                unsafe { stack_top_frame.unwrap_unchecked() };
1262
1263            if let Some(mut left_sibling) =
1264                parent.read_left_sibling::<InternalBTreeNode<K>>(parent_idx)
1265            {
1266                let left_sibling_len = left_sibling.read_len();
1267
1268                // steal from left if it is possible
1269                if left_sibling_len > MIN_LEN_AFTER_SPLIT {
1270                    modified.push(self.current_depth(), node.as_ptr());
1271                    modified.push(self.current_depth(), left_sibling.as_ptr());
1272
1273                    self.steal_from_left_sibling_internal(
1274                        node,
1275                        node_len,
1276                        idx_to_remove,
1277                        child_idx_to_remove,
1278                        left_sibling,
1279                        left_sibling_len,
1280                        parent,
1281                        parent_idx,
1282                    );
1283
1284                    self.clear_stack(modified);
1285
1286                    return;
1287                }
1288
1289                if let Some(right_sibling) =
1290                    parent.read_right_sibling::<InternalBTreeNode<K>>(parent_idx, parent_len)
1291                {
1292                    let right_sibling_len = right_sibling.read_len();
1293
1294                    // steal from right if it's possible
1295                    if right_sibling_len > MIN_LEN_AFTER_SPLIT {
1296                        modified.push(self.current_depth(), node.as_ptr());
1297                        modified.push(self.current_depth(), right_sibling.as_ptr());
1298
1299                        self.steal_from_right_sibling_internal(
1300                            node,
1301                            node_len,
1302                            idx_to_remove,
1303                            child_idx_to_remove,
1304                            right_sibling,
1305                            right_sibling_len,
1306                            parent,
1307                            parent_idx,
1308                        );
1309
1310                        self.clear_stack(modified);
1311
1312                        return;
1313                    }
1314
1315                    // otherwise merge with right
1316                    self.merge_with_right_sibling_internal(
1317                        &mut node,
1318                        idx_to_remove,
1319                        child_idx_to_remove,
1320                        right_sibling,
1321                        &mut parent,
1322                        parent_idx,
1323                        modified,
1324                    );
1325
1326                    merged_right = true;
1327                    prev_node = BTreeNode::Internal(node);
1328
1329                    continue;
1330                }
1331
1332                // otherwise merge with left
1333                self.merge_with_left_sibling_internal(
1334                    node,
1335                    idx_to_remove,
1336                    child_idx_to_remove,
1337                    &mut left_sibling,
1338                    &mut parent,
1339                    parent_idx,
1340                    modified,
1341                );
1342
1343                merged_right = false;
1344                prev_node = BTreeNode::Internal(left_sibling);
1345
1346                continue;
1347            }
1348
1349            if let Some(right_sibling) =
1350                parent.read_right_sibling::<InternalBTreeNode<K>>(parent_idx, parent_len)
1351            {
1352                let right_sibling_len = right_sibling.read_len();
1353
1354                // steal from right if it's possible
1355                if right_sibling_len > MIN_LEN_AFTER_SPLIT {
1356                    modified.push(self.current_depth(), node.as_ptr());
1357                    modified.push(self.current_depth(), right_sibling.as_ptr());
1358
1359                    self.steal_from_right_sibling_internal(
1360                        node,
1361                        node_len,
1362                        idx_to_remove,
1363                        child_idx_to_remove,
1364                        right_sibling,
1365                        right_sibling_len,
1366                        parent,
1367                        parent_idx,
1368                    );
1369
1370                    self.clear_stack(modified);
1371
1372                    return;
1373                }
1374
1375                // otherwise merge with right
1376                self.merge_with_right_sibling_internal(
1377                    &mut node,
1378                    idx_to_remove,
1379                    child_idx_to_remove,
1380                    right_sibling,
1381                    &mut parent,
1382                    parent_idx,
1383                    modified,
1384                );
1385
1386                merged_right = true;
1387                prev_node = BTreeNode::Internal(node);
1388
1389                continue;
1390            }
1391        }
1392    }
1393
1394    fn steal_from_right_sibling_internal(
1395        &mut self,
1396        mut node: InternalBTreeNode<K>,
1397        node_len: usize,
1398        idx_to_remove: usize,
1399        child_idx_to_remove: usize,
1400        mut right_sibling: InternalBTreeNode<K>,
1401        right_sibling_len: usize,
1402        mut parent: InternalBTreeNode<K>,
1403        parent_idx: usize,
1404    ) {
1405        node.steal_from_right(
1406            node_len,
1407            &mut right_sibling,
1408            right_sibling_len,
1409            &mut parent,
1410            parent_idx,
1411            None,
1412            &mut self._buf,
1413        );
1414        right_sibling.write_len(right_sibling_len - 1);
1415        node.remove_key_buf(idx_to_remove, B, &mut self._buf);
1416        node.remove_child_ptr_buf(child_idx_to_remove, B + 1, &mut self._buf);
1417    }
1418
1419    fn steal_from_left_sibling_internal(
1420        &mut self,
1421        mut node: InternalBTreeNode<K>,
1422        node_len: usize,
1423        idx_to_remove: usize,
1424        child_idx_to_remove: usize,
1425        mut left_sibling: InternalBTreeNode<K>,
1426        left_sibling_len: usize,
1427        mut parent: InternalBTreeNode<K>,
1428        parent_idx: usize,
1429    ) {
1430        node.steal_from_left(
1431            node_len,
1432            &mut left_sibling,
1433            left_sibling_len,
1434            &mut parent,
1435            parent_idx - 1,
1436            None,
1437            &mut self._buf,
1438        );
1439        left_sibling.write_len(left_sibling_len - 1);
1440        node.remove_key_buf(idx_to_remove + 1, B, &mut self._buf);
1441        node.remove_child_ptr_buf(child_idx_to_remove + 1, B + 1, &mut self._buf);
1442    }
1443
1444    fn merge_with_right_sibling_internal(
1445        &mut self,
1446        node: &mut InternalBTreeNode<K>,
1447        idx_to_remove: usize,
1448        child_idx_to_remove: usize,
1449        right_sibling: InternalBTreeNode<K>,
1450        parent: &mut InternalBTreeNode<K>,
1451        parent_idx: usize,
1452        modified: &mut LeveledList,
1453    ) {
1454        modified.remove(self.current_depth(), right_sibling.as_ptr());
1455        modified.push(self.current_depth(), node.as_ptr());
1456
1457        let mid_element = parent.read_key_buf(parent_idx);
1458        node.merge_min_len(&mid_element, right_sibling, &mut self._buf);
1459        node.remove_key_buf(idx_to_remove, CAPACITY, &mut self._buf);
1460        node.remove_child_ptr_buf(child_idx_to_remove, CHILDREN_CAPACITY, &mut self._buf);
1461        node.write_len(CAPACITY - 1);
1462    }
1463
1464    fn merge_with_left_sibling_internal(
1465        &mut self,
1466        node: InternalBTreeNode<K>,
1467        idx_to_remove: usize,
1468        child_idx_to_remove: usize,
1469        left_sibling: &mut InternalBTreeNode<K>,
1470        parent: &mut InternalBTreeNode<K>,
1471        parent_idx: usize,
1472        modified: &mut LeveledList,
1473    ) {
1474        modified.remove(self.current_depth(), node.as_ptr());
1475        modified.push(self.current_depth(), left_sibling.as_ptr());
1476
1477        let mid_element = parent.read_key_buf(parent_idx - 1);
1478        left_sibling.merge_min_len(&mid_element, node, &mut self._buf);
1479        left_sibling.remove_key_buf(idx_to_remove + B, CAPACITY, &mut self._buf);
1480        left_sibling.remove_child_ptr_buf(
1481            child_idx_to_remove + B,
1482            CHILDREN_CAPACITY,
1483            &mut self._buf,
1484        );
1485        left_sibling.write_len(CAPACITY - 1);
1486    }
1487
1488    fn peek_stack(&self) -> Option<(InternalBTreeNode<K>, usize, usize)> {
1489        self._stack
1490            .last()
1491            .map(|(n, l, i)| (unsafe { n.copy() }, *l, *i))
1492    }
1493
1494    fn get_or_create_root(&mut self) -> Result<BTreeNode<K, V>, OutOfMemory> {
1495        match &self.root {
1496            Some(r) => unsafe { Ok(r.copy()) },
1497            None => {
1498                let new_root = BTreeNode::<K, V>::Leaf(LeafBTreeNode::create(self.certified)?);
1499
1500                self.root = Some(new_root);
1501                unsafe { Ok(self.root.as_ref().unwrap_unchecked().copy()) }
1502            }
1503        }
1504    }
1505}
1506
1507impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> StableType
1508    for SBTreeMap<K, V>
1509{
1510    #[inline]
1511    unsafe fn stable_drop_flag_off(&mut self) {
1512        self.stable_drop_flag = false;
1513    }
1514
1515    #[inline]
1516    unsafe fn stable_drop_flag_on(&mut self) {
1517        self.stable_drop_flag = true;
1518    }
1519
1520    #[inline]
1521    fn should_stable_drop(&self) -> bool {
1522        self.stable_drop_flag
1523    }
1524
1525    unsafe fn stable_drop(&mut self) {
1526        if self.root.is_none() {
1527            return;
1528        }
1529
1530        let mut nodes = vec![unsafe { self.root.take().unwrap_unchecked() }];
1531        let mut new_nodes = Vec::new();
1532
1533        loop {
1534            if nodes.is_empty() {
1535                return;
1536            }
1537
1538            for _ in 0..nodes.len() {
1539                match unsafe { nodes.pop().unwrap_unchecked() } {
1540                    BTreeNode::Internal(internal) => {
1541                        for j in 0..(internal.read_len() + 1) {
1542                            let child_ptr_raw = internal.read_child_ptr_buf(j);
1543                            let child_ptr = u64::from_fixed_size_bytes(&child_ptr_raw);
1544                            let child = BTreeNode::<K, V>::from_ptr(child_ptr);
1545
1546                            new_nodes.push(child);
1547                        }
1548
1549                        internal.destroy();
1550                    }
1551                    BTreeNode::Leaf(mut leaf) => {
1552                        for j in 0..leaf.read_len() {
1553                            leaf.read_and_disown_key(j);
1554                            leaf.read_and_disown_value(j);
1555                        }
1556
1557                        leaf.destroy();
1558                    }
1559                }
1560            }
1561
1562            nodes = new_nodes;
1563            new_nodes = Vec::new();
1564        }
1565    }
1566}
1567
1568impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> Drop
1569    for SBTreeMap<K, V>
1570{
1571    fn drop(&mut self) {
1572        if self.should_stable_drop() {
1573            unsafe {
1574                self.stable_drop();
1575            }
1576        }
1577    }
1578}
1579
1580impl<K: StableType + AsFixedSizeBytes + Ord + Debug, V: StableType + AsFixedSizeBytes + Debug>
1581    SBTreeMap<K, V>
1582{
1583    pub fn debug_print_stack(&self) {
1584        isoprint(&format!(
1585            "STACK: {:?}",
1586            self._stack
1587                .iter()
1588                .map(|(p, l, i)| (p.as_ptr(), *l, *i))
1589                .collect::<Vec<_>>()
1590        ));
1591    }
1592
1593    pub fn debug_print(&self) {
1594        if self.len == 0 {
1595            isoprint("EMPTY BTREEMAP");
1596            return;
1597        }
1598
1599        let mut level = Vec::new();
1600        level.push(unsafe { self.root.as_ref().unwrap_unchecked().copy() });
1601
1602        loop {
1603            Self::print_level(&level);
1604
1605            let mut new_level = Vec::new();
1606            for node in level {
1607                if let BTreeNode::Internal(internal) = node {
1608                    let c_len = internal.read_len() + 1;
1609                    for i in 0..c_len {
1610                        let c = BTreeNode::<K, V>::from_ptr(u64::from_fixed_size_bytes(
1611                            &internal.read_child_ptr_buf(i),
1612                        ));
1613                        new_level.push(c);
1614                    }
1615                }
1616            }
1617
1618            if new_level.is_empty() {
1619                break;
1620            } else {
1621                level = new_level;
1622            }
1623        }
1624    }
1625
1626    fn print_level(level: &Vec<BTreeNode<K, V>>) {
1627        let mut result = String::new();
1628
1629        for node in level {
1630            result += &match node {
1631                BTreeNode::Internal(i) => i.to_string(),
1632                BTreeNode::Leaf(l) => l.to_string(),
1633            }
1634        }
1635
1636        isoprint(&result);
1637    }
1638}
1639
1640impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> Default
1641    for SBTreeMap<K, V>
1642{
1643    fn default() -> Self {
1644        Self::new()
1645    }
1646}
1647
1648impl<K: StableType + AsFixedSizeBytes + Ord, V: StableType + AsFixedSizeBytes> AsFixedSizeBytes
1649    for SBTreeMap<K, V>
1650{
1651    const SIZE: usize = u64::SIZE * 2;
1652    type Buf = [u8; u64::SIZE * 2];
1653
1654    fn as_fixed_size_bytes(&self, buf: &mut [u8]) {
1655        let ptr = if let Some(root) = &self.root {
1656            root.as_ptr()
1657        } else {
1658            EMPTY_PTR
1659        };
1660
1661        ptr.as_fixed_size_bytes(&mut buf[0..u64::SIZE]);
1662        self.len
1663            .as_fixed_size_bytes(&mut buf[u64::SIZE..(u64::SIZE * 2)]);
1664    }
1665
1666    fn from_fixed_size_bytes(buf: &[u8]) -> Self {
1667        let ptr = u64::from_fixed_size_bytes(&buf[0..u64::SIZE]);
1668        let len = u64::from_fixed_size_bytes(&buf[u64::SIZE..(u64::SIZE * 2)]);
1669
1670        Self {
1671            root: if ptr == EMPTY_PTR {
1672                None
1673            } else {
1674                Some(BTreeNode::from_ptr(ptr))
1675            },
1676            certified: false,
1677            len,
1678            stable_drop_flag: false,
1679            _buf: Vec::default(),
1680            _stack: Vec::default(),
1681        }
1682    }
1683}
1684
1685pub(crate) enum LeveledList {
1686    None,
1687    Some((Vec<Vec<u64>>, usize)),
1688}
1689
1690impl LeveledList {
1691    pub(crate) fn new() -> Self {
1692        Self::Some((vec![Vec::new()], 0))
1693    }
1694
1695    fn is_some(&self) -> bool {
1696        match self {
1697            LeveledList::None => false,
1698            _ => true,
1699        }
1700    }
1701
1702    fn insert_root(&mut self, ptr: u64) {
1703        match self {
1704            LeveledList::None => {}
1705            LeveledList::Some((v, max_level)) => {
1706                let root = vec![ptr];
1707                v.insert(0, root);
1708                *max_level += 1;
1709            }
1710        }
1711    }
1712
1713    fn remove_root(&mut self) {
1714        match self {
1715            LeveledList::None => {}
1716            LeveledList::Some((v, max_level)) => {
1717                v.remove(0);
1718                *max_level -= 1;
1719            }
1720        }
1721    }
1722
1723    fn push(&mut self, level: usize, ptr: u64) {
1724        match self {
1725            LeveledList::None => {}
1726            LeveledList::Some((v, max_level)) => {
1727                if level.gt(max_level) {
1728                    *max_level = level;
1729
1730                    v.resize_with(level + 1, Vec::new);
1731                }
1732
1733                match v[level].binary_search(&ptr) {
1734                    Ok(_) => {}
1735                    Err(idx) => v[level].insert(idx, ptr),
1736                };
1737            }
1738        }
1739    }
1740
1741    fn remove(&mut self, level: usize, ptr: u64) {
1742        match self {
1743            LeveledList::None => {}
1744            LeveledList::Some((v, _)) => {
1745                if let Some(level_list) = v.get_mut(level) {
1746                    if let Ok(idx) = level_list.binary_search(&ptr) {
1747                        level_list.remove(idx);
1748                    }
1749                }
1750            }
1751        }
1752    }
1753
1754    pub(crate) fn pop(&mut self) -> Option<u64> {
1755        match self {
1756            LeveledList::None => unreachable!(),
1757            LeveledList::Some((v, max_level)) => {
1758                let level_list = v.get_mut(*max_level)?;
1759                let mut ptr = level_list.pop();
1760
1761                while ptr.is_none() {
1762                    if *max_level == 0 {
1763                        return None;
1764                    }
1765
1766                    *max_level -= 1;
1767
1768                    ptr = v[*max_level].pop();
1769                }
1770
1771                ptr
1772            }
1773        }
1774    }
1775
1776    pub(crate) fn debug_print(&self) {
1777        match self {
1778            LeveledList::None => isoprint("LeveledList [Dummy]"),
1779            LeveledList::Some((v, max_level)) => {
1780                let mut str = String::from("LeveledList [");
1781                for i in 0..(*max_level + 1) {
1782                    str += format!("{} - ({:?})", i, v[i]).as_str();
1783                    if i < *max_level {
1784                        str += ", ";
1785                    }
1786                }
1787                str += "]";
1788
1789                isoprint(&str);
1790            }
1791        }
1792    }
1793}
1794
1795impl<K: StableType + AsFixedSizeBytes + Ord + Debug, V: StableType + AsFixedSizeBytes + Debug> Debug
1796    for SBTreeMap<K, V>
1797{
1798    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1799        f.write_str("{")?;
1800
1801        for (idx, (k, v)) in self.iter().enumerate() {
1802            k.fmt(f)?;
1803            f.write_str(": ")?;
1804            v.fmt(f)?;
1805
1806            if (idx as u64) < self.len() - 1 {
1807                f.write_str(", ")?;
1808            }
1809        }
1810
1811        f.write_str("}")
1812    }
1813}
1814
1815pub(crate) trait IBTreeNode {
1816    unsafe fn from_ptr(ptr: StablePtr) -> Self;
1817    fn as_ptr(&self) -> StablePtr;
1818    unsafe fn copy(&self) -> Self;
1819}
1820
1821pub(crate) enum BTreeNode<K, V> {
1822    Internal(InternalBTreeNode<K>),
1823    Leaf(LeafBTreeNode<K, V>),
1824}
1825
1826impl<K, V> BTreeNode<K, V> {
1827    pub(crate) fn from_ptr(ptr: StablePtr) -> Self {
1828        let node_type: u8 =
1829            unsafe { crate::mem::read_fixed_for_reference(SSlice::_offset(ptr, NODE_TYPE_OFFSET)) };
1830
1831        unsafe {
1832            match node_type {
1833                NODE_TYPE_INTERNAL => Self::Internal(InternalBTreeNode::<K>::from_ptr(ptr)),
1834                NODE_TYPE_LEAF => Self::Leaf(LeafBTreeNode::<K, V>::from_ptr(ptr)),
1835                _ => unreachable!(),
1836            }
1837        }
1838    }
1839
1840    pub(crate) fn as_ptr(&self) -> StablePtr {
1841        match self {
1842            Self::Internal(i) => i.as_ptr(),
1843            Self::Leaf(l) => l.as_ptr(),
1844        }
1845    }
1846
1847    pub(crate) unsafe fn copy(&self) -> Self {
1848        match self {
1849            Self::Internal(i) => Self::Internal(i.copy()),
1850            Self::Leaf(l) => Self::Leaf(l.copy()),
1851        }
1852    }
1853}
1854
1855#[cfg(test)]
1856mod tests {
1857    use crate::collections::btree_map::SBTreeMap;
1858    use crate::utils::test::generate_random_string;
1859    use crate::{
1860        _debug_validate_allocator, get_allocated_size, init_allocator, retrieve_custom_data,
1861        stable, stable_memory_init, stable_memory_post_upgrade, stable_memory_pre_upgrade,
1862        store_custom_data, SBox,
1863    };
1864    use rand::rngs::ThreadRng;
1865    use rand::seq::SliceRandom;
1866    use rand::{thread_rng, Rng};
1867    use std::collections::BTreeMap;
1868
1869    #[test]
1870    fn random_works_fine() {
1871        stable::clear();
1872        stable_memory_init();
1873
1874        {
1875            let iterations = 1000;
1876            let mut map = SBTreeMap::<u64, u64>::default();
1877
1878            let mut example = Vec::new();
1879            for i in 0..iterations {
1880                example.push(i as u64);
1881            }
1882            example.shuffle(&mut thread_rng());
1883
1884            for i in 0..iterations {
1885                map.debug_print_stack();
1886                assert!(map._stack.is_empty());
1887                assert!(map.insert(example[i], example[i]).unwrap().is_none());
1888
1889                for j in 0..i {
1890                    assert!(
1891                        map.contains_key(&example[j]),
1892                        "don't contain {}",
1893                        example[j]
1894                    );
1895                    assert_eq!(
1896                        *map.get(&example[j]).unwrap(),
1897                        example[j],
1898                        "unable to get {}",
1899                        example[j]
1900                    );
1901                }
1902            }
1903
1904            assert_eq!(map.insert(0, 1).unwrap().unwrap(), 0);
1905            assert_eq!(map.insert(0, 0).unwrap().unwrap(), 1);
1906
1907            map.debug_print();
1908
1909            example.shuffle(&mut thread_rng());
1910            for i in 0..iterations {
1911                assert!(map._stack.is_empty());
1912
1913                assert_eq!(map.remove(&example[i]), Some(example[i]));
1914
1915                for j in (i + 1)..iterations {
1916                    assert!(
1917                        map.contains_key(&example[j]),
1918                        "don't contain {}",
1919                        example[j]
1920                    );
1921                    assert_eq!(
1922                        *map.get(&example[j]).unwrap(),
1923                        example[j],
1924                        "unable to get {}",
1925                        example[j]
1926                    );
1927                }
1928            }
1929        }
1930
1931        _debug_validate_allocator();
1932        assert_eq!(get_allocated_size(), 0);
1933    }
1934
1935    #[test]
1936    fn iters_work_fine() {
1937        stable::clear();
1938        stable_memory_init();
1939
1940        {
1941            let mut map = SBTreeMap::<u64, u64>::default();
1942
1943            for i in 0..200 {
1944                map.insert(i, i);
1945            }
1946
1947            let mut i = 0u64;
1948
1949            for (mut k, mut v) in map.iter() {
1950                assert_eq!(i, *k);
1951                assert_eq!(i, *v);
1952
1953                print!("({:?}, {:?}), ", *k, *v);
1954
1955                i += 1;
1956            }
1957
1958            println!();
1959
1960            assert_eq!(i, 200);
1961        }
1962
1963        _debug_validate_allocator();
1964        assert_eq!(get_allocated_size(), 0);
1965    }
1966
1967    #[test]
1968    fn clear_works_fine() {
1969        stable::clear();
1970        stable_memory_init();
1971
1972        {
1973            let mut map = SBTreeMap::<SBox<u64>, SBox<u64>>::default();
1974
1975            for i in 0..500 {
1976                map.insert(SBox::new(i).unwrap(), SBox::new(i).unwrap())
1977                    .unwrap();
1978            }
1979
1980            map.clear();
1981        }
1982
1983        _debug_validate_allocator();
1984        assert_eq!(get_allocated_size(), 0);
1985    }
1986
1987    #[derive(Debug)]
1988    enum Action {
1989        Insert,
1990        Remove,
1991        Clear,
1992        CanisterUpgrade,
1993    }
1994
1995    struct Fuzzer {
1996        map: Option<SBTreeMap<SBox<String>, SBox<String>>>,
1997        example: BTreeMap<String, String>,
1998        keys: Vec<String>,
1999        rng: ThreadRng,
2000        log: Vec<Action>,
2001    }
2002
2003    impl Fuzzer {
2004        fn new() -> Fuzzer {
2005            Fuzzer {
2006                map: Some(SBTreeMap::new()),
2007                example: BTreeMap::new(),
2008                keys: Vec::new(),
2009                rng: thread_rng(),
2010                log: Vec::new(),
2011            }
2012        }
2013
2014        fn map(&mut self) -> &mut SBTreeMap<SBox<String>, SBox<String>> {
2015            self.map.as_mut().unwrap()
2016        }
2017
2018        fn next(&mut self) {
2019            let action = self.rng.gen_range(0..101);
2020
2021            match action {
2022                // INSERT ~60%
2023                0..=59 => {
2024                    let key = generate_random_string(&mut self.rng);
2025                    let value = generate_random_string(&mut self.rng);
2026
2027                    if let Ok(key_data) = SBox::new(key.clone()) {
2028                        if let Ok(val_data) = SBox::new(value.clone()) {
2029                            if self.map().insert(key_data, val_data).is_err() {
2030                                return;
2031                            }
2032                            self.example.insert(key.clone(), value);
2033
2034                            match self.keys.binary_search(&key) {
2035                                Ok(idx) => {}
2036                                Err(idx) => {
2037                                    self.keys.insert(idx, key);
2038                                }
2039                            };
2040
2041                            self.log.push(Action::Insert);
2042                        }
2043                    }
2044                }
2045                // REMOVE
2046                60..=89 => {
2047                    let len = self.map().len();
2048
2049                    if len == 0 {
2050                        return self.next();
2051                    }
2052
2053                    let idx: u64 = self.rng.gen_range(0..len);
2054                    let key = self.keys.remove(idx as usize);
2055
2056                    self.map().remove(&key).unwrap();
2057                    self.example.remove(&key).unwrap();
2058
2059                    self.log.push(Action::Remove);
2060                }
2061                // CLEAR
2062                90..=91 => {
2063                    self.map().clear();
2064                    self.example.clear();
2065
2066                    self.keys.clear();
2067
2068                    self.log.push(Action::Clear);
2069                }
2070                // CANISTER UPGRADE
2071                _ => match SBox::new(self.map.take().unwrap()) {
2072                    Ok(data) => {
2073                        store_custom_data(1, data);
2074
2075                        if stable_memory_pre_upgrade().is_ok() {
2076                            stable_memory_post_upgrade();
2077                        }
2078
2079                        self.map = retrieve_custom_data::<SBTreeMap<SBox<String>, SBox<String>>>(1)
2080                            .map(|it| it.into_inner());
2081
2082                        self.log.push(Action::CanisterUpgrade);
2083                    }
2084                    Err(map) => {
2085                        self.map = Some(map);
2086                    }
2087                },
2088            }
2089
2090            _debug_validate_allocator();
2091            assert_eq!(self.map().len() as usize, self.example.len());
2092
2093            // check random key
2094            let seed: u32 = self.rng.gen();
2095            let rand_key = self.map.as_ref().unwrap().get_random_key(seed);
2096            if self.map.as_ref().unwrap().is_empty() {
2097                assert!(rand_key.is_none());
2098            } else {
2099                assert!(rand_key.is_some());
2100            }
2101
2102            // check consistency
2103            for key in self.keys.clone() {
2104                let contains = self.map().contains_key(&key);
2105                assert!(contains);
2106
2107                assert_eq!(
2108                    self.map().get(&key).unwrap().clone(),
2109                    self.example.get(&key).unwrap().clone()
2110                );
2111            }
2112        }
2113    }
2114
2115    #[test]
2116    fn fuzzer_works_fine() {
2117        stable::clear();
2118        init_allocator(0);
2119
2120        {
2121            let mut fuzzer = Fuzzer::new();
2122
2123            for _ in 0..10_000 {
2124                fuzzer.next();
2125            }
2126        }
2127
2128        assert_eq!(get_allocated_size(), 0);
2129    }
2130
2131    #[test]
2132    fn fuzzer_works_fine_limited_memory() {
2133        stable::clear();
2134        init_allocator(10);
2135
2136        {
2137            let mut fuzzer = Fuzzer::new();
2138
2139            for _ in 0..10_000 {
2140                fuzzer.next();
2141            }
2142        }
2143
2144        assert_eq!(get_allocated_size(), 0);
2145    }
2146}