generic_btree/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3
4use core::{fmt::Debug, ops::Range};
5use std::collections::{BTreeSet, VecDeque};
6use std::ops::AddAssign;
7use std::{cmp::Ordering, mem::take, ops::RangeBounds};
8
9pub(crate) use heapless::Vec as HeaplessVec;
10use itertools::Itertools;
11use rle::{CanRemove, TryInsert};
12use rustc_hash::{FxHashMap, FxHashSet};
13use thunderdome::Arena;
14use thunderdome::Index as RawArenaIndex;
15
16pub use generic_impl::*;
17
18use crate::rle::{HasLength, Mergeable, Sliceable};
19
20mod generic_impl;
21pub mod iter;
22
23pub mod rle;
24
25pub type HeapVec<T> = Vec<T>;
26
27const MAX_CHILDREN_NUM: usize = 12;
28
29/// `Elem` should has length. `offset` in search result should always >= `Elem.rle_len()`
30pub trait BTreeTrait {
31    /// Sometime an [Elem] with length of 0, but it's not empty.
32    ///
33    /// The empty [Elem]s are the ones that can be safely ignored.
34    type Elem: Debug + HasLength + Sliceable + Mergeable + TryInsert + CanRemove;
35    type Cache: Debug + Default + Clone + Eq;
36    type CacheDiff: Debug + Default + CanRemove;
37    // Whether we should use cache diff by default
38    const USE_DIFF: bool = true;
39
40    /// If diff.is_some, return value should be some too
41    fn calc_cache_internal(cache: &mut Self::Cache, caches: &[Child<Self>]) -> Self::CacheDiff;
42    fn apply_cache_diff(cache: &mut Self::Cache, diff: &Self::CacheDiff);
43    fn merge_cache_diff(diff1: &mut Self::CacheDiff, diff2: &Self::CacheDiff);
44    fn get_elem_cache(elem: &Self::Elem) -> Self::Cache;
45    fn new_cache_to_diff(cache: &Self::Cache) -> Self::CacheDiff;
46    fn sub_cache(cache_lhs: &Self::Cache, cache_rhs: &Self::Cache) -> Self::CacheDiff;
47}
48
49pub trait Query<B: BTreeTrait> {
50    type QueryArg: Clone;
51
52    fn init(target: &Self::QueryArg) -> Self;
53
54    fn find_node(&mut self, target: &Self::QueryArg, child_caches: &[Child<B>]) -> FindResult;
55
56    /// Confirm the search result and returns (offset, found)
57    ///
58    /// If elem is not target, `found=false`
59    fn confirm_elem(&mut self, q: &Self::QueryArg, elem: &B::Elem) -> (usize, bool);
60}
61
62pub struct BTree<B: BTreeTrait> {
63    /// internal nodes
64    in_nodes: Arena<Node<B>>,
65    /// leaf nodes
66    leaf_nodes: Arena<LeafNode<B::Elem>>,
67    /// root is always a internal node
68    /// TODO: we may use a constant as root index
69    root: ArenaIndex,
70    root_cache: B::Cache,
71}
72
73impl<Elem: Clone, B: BTreeTrait<Elem = Elem>> Clone for BTree<B> {
74    fn clone(&self) -> Self {
75        Self {
76            in_nodes: self.in_nodes.clone(),
77            leaf_nodes: self.leaf_nodes.clone(),
78            root: self.root,
79            root_cache: self.root_cache.clone(),
80        }
81    }
82}
83
84pub struct FindResult {
85    pub index: usize,
86    pub offset: usize,
87    pub found: bool,
88}
89
90impl FindResult {
91    pub fn new_found(index: usize, offset: usize) -> Self {
92        Self {
93            index,
94            offset,
95            found: true,
96        }
97    }
98
99    pub fn new_missing(index: usize, offset: usize) -> Self {
100        Self {
101            index,
102            offset,
103            found: false,
104        }
105    }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109struct Idx {
110    pub arena: ArenaIndex,
111    pub arr: u8,
112}
113
114impl Idx {
115    pub fn new(arena: ArenaIndex, arr: u8) -> Self {
116        Self { arena, arr }
117    }
118}
119
120type NodePath = HeaplessVec<Idx, 10>;
121
122#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)]
123pub struct Cursor {
124    pub leaf: LeafIndex,
125    pub offset: usize,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Copy)]
129pub struct QueryResult {
130    pub cursor: Cursor,
131    pub found: bool,
132}
133
134/// Exposed arena index
135///
136/// Only exposed arena index of leaf node.
137///
138///
139#[repr(transparent)]
140#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
141pub struct LeafIndex(RawArenaIndex);
142
143impl LeafIndex {
144    pub fn inner(&self) -> RawArenaIndex {
145        self.0
146    }
147}
148
149#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
150pub enum ArenaIndex {
151    Leaf(RawArenaIndex),
152    Internal(RawArenaIndex),
153}
154
155impl ArenaIndex {
156    fn unwrap(self) -> RawArenaIndex {
157        match self {
158            ArenaIndex::Leaf(x) => x,
159            ArenaIndex::Internal(x) => x,
160        }
161    }
162
163    pub fn unwrap_leaf(self) -> RawArenaIndex {
164        match self {
165            ArenaIndex::Leaf(x) => x,
166            ArenaIndex::Internal(_) => panic!("unwrap_leaf on internal node"),
167        }
168    }
169
170    pub fn unwrap_internal(self) -> RawArenaIndex {
171        match self {
172            ArenaIndex::Leaf(_) => panic!("unwrap_internal on leaf node"),
173            ArenaIndex::Internal(x) => x,
174        }
175    }
176}
177
178impl From<LeafIndex> for ArenaIndex {
179    fn from(value: LeafIndex) -> Self {
180        Self::Leaf(value.0)
181    }
182}
183
184impl From<RawArenaIndex> for LeafIndex {
185    fn from(value: RawArenaIndex) -> Self {
186        Self(value)
187    }
188}
189
190/// A slice of element
191///
192/// - `start` is Some(start_offset) when it's first element of the given range.
193/// - `end` is Some(end_offset) when it's last element of the given range.
194#[derive(Debug)]
195pub struct ElemSlice<'a, Elem> {
196    cursor: Cursor,
197    pub elem: &'a Elem,
198    pub start: Option<usize>,
199    pub end: Option<usize>,
200}
201
202impl<'a, Elem> ElemSlice<'a, Elem> {
203    pub fn cursor(&self) -> &Cursor {
204        &self.cursor
205    }
206}
207
208impl QueryResult {
209    pub fn elem<'b, Elem: Debug, B: BTreeTrait<Elem = Elem>>(
210        &self,
211        tree: &'b BTree<B>,
212    ) -> Option<&'b Elem> {
213        tree.leaf_nodes.get(self.cursor().leaf.0).map(|x| &x.elem)
214    }
215
216    #[inline(always)]
217    pub fn cursor(&self) -> Cursor {
218        self.cursor
219    }
220
221    #[inline(always)]
222    pub fn leaf(&self) -> LeafIndex {
223        self.cursor().leaf
224    }
225
226    #[inline(always)]
227    pub fn offset(&self) -> usize {
228        self.cursor().offset
229    }
230
231    #[inline(always)]
232    pub fn found(&self) -> bool {
233        self.found
234    }
235
236    #[inline(always)]
237    pub fn arena(&self) -> RawArenaIndex {
238        self.cursor.leaf.0
239    }
240}
241
242#[derive(Debug, Clone)]
243pub struct LeafNode<Elem> {
244    elem: Elem,
245    parent: RawArenaIndex,
246}
247
248impl<T> LeafNode<T> {
249    pub fn parent(&self) -> ArenaIndex {
250        ArenaIndex::Internal(self.parent)
251    }
252
253    pub fn elem(&self) -> &T {
254        &self.elem
255    }
256}
257
258impl<T: Sliceable> LeafNode<T> {
259    fn split(&mut self, offset: usize) -> Self {
260        let new_elem = self.elem.split(offset);
261        Self {
262            elem: new_elem,
263            parent: self.parent,
264        }
265    }
266}
267
268pub struct Node<B: BTreeTrait> {
269    parent: Option<ArenaIndex>,
270    parent_slot: u8,
271    children: HeaplessVec<Child<B>, MAX_CHILDREN_NUM>,
272}
273
274#[repr(transparent)]
275#[derive(Debug, Default, Clone)]
276pub struct SplittedLeaves {
277    pub arr: HeaplessVec<LeafIndex, 2>,
278}
279
280impl SplittedLeaves {
281    #[inline]
282    fn push_option(&mut self, leaf: Option<ArenaIndex>) {
283        if let Some(leaf) = leaf {
284            self.arr.push(leaf.unwrap().into()).unwrap();
285        }
286    }
287
288    #[inline]
289    fn push(&mut self, leaf: ArenaIndex) {
290        self.arr.push(leaf.unwrap().into()).unwrap();
291    }
292}
293
294impl<Cache: Debug, Elem: Debug, B: BTreeTrait<Elem = Elem, Cache = Cache>> Debug for BTree<B> {
295    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
296        fn fmt_node<Cache: Debug, Elem: Debug, B: BTreeTrait<Elem = Elem>>(
297            tree: &BTree<B>,
298            node_idx: ArenaIndex,
299            f: &mut core::fmt::Formatter<'_>,
300            indent_size: usize,
301        ) -> core::fmt::Result {
302            match node_idx {
303                ArenaIndex::Leaf(_) => {}
304                ArenaIndex::Internal(_) => {
305                    let node = tree.get_internal(node_idx);
306                    for child in node.children.iter() {
307                        indent(f, indent_size)?;
308                        if child.is_internal() {
309                            let child_node = tree.get_internal(child.arena);
310                            f.write_fmt(format_args!(
311                                "{} Arena({:?}) Cache: {:?}\n",
312                                child_node.parent_slot, &child.arena, &child.cache
313                            ))?;
314                            fmt_node::<Cache, Elem, B>(tree, child.arena, f, indent_size + 1)?;
315                        } else {
316                            let node = tree.get_leaf(child.arena);
317                            f.write_fmt(format_args!(
318                                "Leaf({:?}) Arena({:?}) Parent({:?}) Cache: {:?}\n",
319                                &node.elem, child.arena, node.parent, &child.cache
320                            ))?;
321                        }
322                    }
323                }
324            }
325
326            Ok(())
327        }
328
329        fn indent(f: &mut core::fmt::Formatter<'_>, indent: usize) -> core::fmt::Result {
330            for _ in 0..indent {
331                f.write_str("    ")?;
332            }
333            Ok(())
334        }
335
336        f.write_str("BTree\n")?;
337        indent(f, 1)?;
338        f.write_fmt(format_args!(
339            "Root Arena({:?}) Cache: {:?}\n",
340            &self.root, &self.root_cache
341        ))?;
342        fmt_node::<Cache, Elem, B>(self, self.root, f, 1)
343    }
344}
345
346impl<Cache: Debug, Elem: Debug, B: BTreeTrait<Elem = Elem, Cache = Cache>> Debug for Node<B> {
347    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
348        f.debug_struct("Node")
349            .field("children", &self.children)
350            .finish()
351    }
352}
353
354impl<Cache: Debug, Elem: Debug, B: BTreeTrait<Elem = Elem, Cache = Cache>> Debug for Child<B> {
355    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
356        f.debug_struct("Child")
357            .field("index", &self.arena)
358            .field("cache", &self.cache)
359            .finish()
360    }
361}
362
363impl<Elem: Clone, B: BTreeTrait<Elem = Elem>> Clone for Node<B> {
364    fn clone(&self) -> Self {
365        Self {
366            parent: self.parent,
367            parent_slot: self.parent_slot,
368            children: self.children.clone(),
369        }
370    }
371}
372
373pub struct Child<B: ?Sized + BTreeTrait> {
374    pub arena: ArenaIndex,
375    pub cache: B::Cache,
376}
377
378impl<B: ?Sized + BTreeTrait> Child<B> {
379    #[inline]
380    fn is_internal(&self) -> bool {
381        matches!(self.arena, ArenaIndex::Internal(_))
382    }
383
384    #[inline]
385    #[allow(unused)]
386    fn is_leaf(&self) -> bool {
387        matches!(self.arena, ArenaIndex::Leaf(_))
388    }
389}
390
391impl<B: BTreeTrait> Clone for Child<B> {
392    fn clone(&self) -> Self {
393        Self {
394            arena: self.arena,
395            cache: self.cache.clone(),
396        }
397    }
398}
399
400impl<B: BTreeTrait> Child<B> {
401    pub fn cache(&self) -> &B::Cache {
402        &self.cache
403    }
404
405    fn new(arena: ArenaIndex, cache: B::Cache) -> Self {
406        Self { arena, cache }
407    }
408}
409
410impl<B: BTreeTrait> Node<B> {
411    #[inline(always)]
412    pub fn new() -> Self {
413        Self {
414            parent: None,
415            parent_slot: u8::MAX,
416            children: HeaplessVec::new(),
417        }
418    }
419
420    #[inline(always)]
421    pub fn is_full(&self) -> bool {
422        self.children.len() >= MAX_CHILDREN_NUM
423    }
424
425    #[inline(always)]
426    pub fn is_lack(&self) -> bool {
427        self.children.len() < MAX_CHILDREN_NUM / 2
428    }
429
430    #[inline(always)]
431    pub fn len(&self) -> usize {
432        self.children.len()
433    }
434
435    #[inline(always)]
436    pub fn is_empty(&self) -> bool {
437        self.len() == 0
438    }
439
440    #[inline(always)]
441    pub fn is_child_leaf(&self) -> bool {
442        if self.children.is_empty() {
443            return true;
444        }
445
446        self.children[0].is_leaf()
447    }
448
449    /// if diff is not provided, the cache will be calculated from scratch
450    #[inline(always)]
451    fn calc_cache(&self, cache: &mut B::Cache, diff: Option<B::CacheDiff>) -> B::CacheDiff {
452        match diff {
453            Some(inner) => {
454                B::apply_cache_diff(cache, &inner);
455                inner
456            }
457            None => B::calc_cache_internal(cache, &self.children),
458        }
459    }
460}
461
462impl<B: BTreeTrait> Default for Node<B> {
463    fn default() -> Self {
464        Self::new()
465    }
466}
467
468type LeafDirtyMap<Diff> = FxHashMap<ArenaIndex, Diff>;
469
470/// Whether the parent node is lack of children
471#[repr(transparent)]
472struct LackInfo {
473    /// if Some, the parent node is lack
474    parent_lack: Option<ArenaIndex>,
475}
476
477impl<B: BTreeTrait> BTree<B> {
478    pub fn new() -> Self {
479        let mut arena = Arena::new();
480        let root = arena.insert(Node::new());
481        Self {
482            in_nodes: arena,
483            leaf_nodes: Arena::new(),
484            root: ArenaIndex::Internal(root),
485            root_cache: B::Cache::default(),
486        }
487    }
488
489    /// Get the number of nodes in the tree.
490    /// It includes all the internal nodes and the leaf nodes.
491    #[inline(always)]
492    pub fn node_len(&self) -> usize {
493        self.in_nodes.len() + self.leaf_nodes.len()
494    }
495
496    /// Insert new element to the tree.
497    ///
498    /// Returns (insert_pos, splitted_leaves)
499    pub fn insert<Q>(&mut self, q: &Q::QueryArg, data: B::Elem) -> (Cursor, SplittedLeaves)
500    where
501        Q: Query<B>,
502    {
503        let Some(result) = self.query::<Q>(q) else {
504            return (self.push(data), Default::default());
505        };
506
507        self.insert_by_path(result.cursor, data)
508    }
509
510    pub fn insert_by_path(&mut self, cursor: Cursor, data: B::Elem) -> (Cursor, SplittedLeaves) {
511        let index = cursor.leaf;
512        let leaf = self.leaf_nodes.get_mut(index.0).unwrap();
513        let mut parent_idx = leaf.parent();
514        let cache_diff = if B::USE_DIFF {
515            Some(B::new_cache_to_diff(&B::get_elem_cache(&data)))
516        } else {
517            None
518        };
519
520        let mut is_full = false;
521        let mut splitted: SplittedLeaves = Default::default();
522        let ans = match leaf.elem.try_insert(cursor.offset, data) {
523            Ok(_) => cursor,
524            Err(data) => {
525                // Try to merge
526                if cursor.offset == 0 && data.can_merge(&leaf.elem) {
527                    leaf.elem.merge_left(&data);
528                    Cursor {
529                        leaf: index,
530                        offset: 0,
531                    }
532                } else if cursor.offset == leaf.elem.rle_len() && leaf.elem.can_merge(&data) {
533                    let offset = leaf.elem.rle_len();
534                    leaf.elem.merge_right(&data);
535                    Cursor {
536                        leaf: index,
537                        offset,
538                    }
539                } else {
540                    // Insert new leaf node
541                    let SplitInfo {
542                        parent_idx: parent_index,
543                        insert_slot: insert_index,
544                        new_leaf,
545                        ..
546                    } = self.split_leaf_if_needed(cursor);
547                    parent_idx = ArenaIndex::Internal(parent_index);
548                    let child = self.alloc_leaf_child(data, parent_index);
549                    let ans = child.arena;
550                    splitted.push_option(new_leaf);
551                    let parent = self.in_nodes.get_mut(parent_index).unwrap();
552                    parent.children.insert(insert_index, child).unwrap();
553                    is_full = parent.is_full();
554                    Cursor {
555                        leaf: ans.unwrap().into(),
556                        offset: 0,
557                    }
558                }
559            }
560        };
561
562        self.recursive_update_cache(cursor.leaf.into(), B::USE_DIFF, cache_diff);
563        if is_full {
564            self.split(parent_idx);
565        }
566
567        (ans, splitted)
568    }
569
570    fn alloc_leaf_child(
571        &mut self,
572        data: <B as BTreeTrait>::Elem,
573        parent_index: RawArenaIndex,
574    ) -> Child<B> {
575        let elem_cache = B::get_elem_cache(&data);
576        let new_leaf_index = self.alloc_new_leaf(LeafNode {
577            elem: data,
578            parent: parent_index,
579        });
580        Child {
581            arena: new_leaf_index,
582            cache: elem_cache,
583        }
584    }
585
586    /// Split a leaf node at offset if it's not the start/end of the leaf node.
587    ///
588    /// This method should be called when inserting at target pos.
589    fn split_leaf_if_needed(&mut self, pos: Cursor) -> SplitInfo {
590        let leaf = self.leaf_nodes.get_mut(pos.leaf.0).unwrap();
591        let parent_idx = leaf.parent;
592        let parent = self.in_nodes.get_mut(leaf.parent).unwrap();
593        let mut new_pos = Some(pos);
594        let mut rt_new_leaf = None;
595        let leaf_slot = parent
596            .children
597            .iter()
598            .position(|x| x.arena.unwrap() == pos.leaf.0)
599            .unwrap();
600        let left_neighbour = if leaf_slot == 0 {
601            None
602        } else {
603            Some(parent.children[leaf_slot - 1].arena.unwrap().into())
604        };
605        let insert_pos = if pos.offset == 0 {
606            leaf_slot
607        } else if pos.offset == leaf.elem.rle_len() {
608            if leaf_slot + 1 < parent.children.len() {
609                new_pos = Some(Cursor {
610                    leaf: parent.children[leaf_slot + 1].arena.unwrap().into(),
611                    offset: 0,
612                });
613            } else {
614                new_pos = self.next_elem(pos);
615            }
616            leaf_slot + 1
617        } else {
618            assert!(
619                pos.offset < leaf.elem.rle_len(),
620                "elem.rle_len={} but pos.offset={} Elem:{:?}",
621                leaf.elem.rle_len(),
622                pos.offset,
623                &leaf.elem
624            );
625
626            if parent.children.len() + 1 >= MAX_CHILDREN_NUM {
627                self.split(ArenaIndex::Internal(parent_idx));
628                // parent may be changed because of splitting
629                return self.split_leaf_if_needed(pos);
630            }
631
632            let new_leaf = leaf.split(pos.offset);
633            let left_cache = B::get_elem_cache(&leaf.elem);
634            let cache = B::get_elem_cache(&new_leaf.elem);
635            // alloc new leaf node
636            let leaf_arena_index = {
637                let arena_index = self.leaf_nodes.insert(new_leaf);
638                ArenaIndex::Leaf(arena_index)
639            };
640            rt_new_leaf = Some(leaf_arena_index);
641            new_pos = Some(Cursor {
642                leaf: leaf_arena_index.unwrap().into(),
643                offset: 0,
644            });
645            parent.children[leaf_slot].cache = left_cache;
646            parent
647                .children
648                .insert(
649                    leaf_slot + 1,
650                    Child {
651                        arena: leaf_arena_index,
652                        cache,
653                    },
654                )
655                .unwrap();
656
657            leaf_slot + 1
658        };
659
660        SplitInfo {
661            left_neighbour,
662            new_pos,
663            parent_idx,
664            insert_slot: insert_pos,
665            new_leaf: rt_new_leaf,
666        }
667    }
668
669    fn alloc_new_leaf(&mut self, leaf: LeafNode<B::Elem>) -> ArenaIndex {
670        let arena_index = self.leaf_nodes.insert(leaf);
671        ArenaIndex::Leaf(arena_index)
672    }
673
674    /// Insert many elements into the tree at once
675    ///
676    /// It will invoke [`BTreeTrait::insert_batch`]
677    pub fn insert_many_by_cursor(
678        &mut self,
679        cursor: Option<Cursor>,
680        mut data_iter: impl Iterator<Item = B::Elem>,
681    ) {
682        let Some(first) = data_iter.next() else {
683            return;
684        };
685
686        let Some(second) = data_iter.next() else {
687            if let Some(c) = cursor {
688                self.insert_by_path(c, first);
689                return;
690            } else {
691                self.push(first);
692                return;
693            }
694        };
695
696        let mut data = Vec::with_capacity(data_iter.size_hint().0 + 2);
697        data.push(first);
698        data.push(second);
699        for elem in data_iter {
700            data.push(elem);
701        }
702
703        merge_adj(&mut data);
704        if data.len() == 1 {
705            if let Some(c) = cursor {
706                self.insert_by_path(c, data.pop().unwrap());
707                return;
708            } else {
709                self.push(data.pop().unwrap());
710                return;
711            }
712        }
713
714        if cursor.is_none() && self.is_empty() {
715            assert!(self.is_empty());
716            let (new_root, _) = self.create_subtrees_from_elem(data);
717            self.in_nodes.remove(self.root.unwrap()).unwrap();
718            self.root = new_root;
719            return;
720        }
721
722        // dbg!(cursor, &data);
723        // dbg!(&self);
724        let cursor = cursor.expect("Cursor must be provided when tree is not empty");
725        let SplitInfo {
726            new_pos,
727            left_neighbour,
728            ..
729        } = self.split_leaf_if_needed(cursor);
730        let mut inserted = 0;
731        if let Some(left) = left_neighbour {
732            let left_node = self.leaf_nodes.get_mut(left.0).unwrap();
733            let mut i = 0;
734            while i < data.len() && left_node.elem.can_merge(&data[i]) {
735                left_node.elem.merge_right(&data[i]);
736                i += 1;
737            }
738
739            self.recursive_update_cache(left.into(), B::USE_DIFF, None);
740            inserted = i;
741        }
742
743        let mut pos = new_pos.unwrap_or(cursor);
744        // TODO: PERF this can be optimized further
745        for item in data.drain(inserted..).rev() {
746            let (p, _) = self.insert_by_path(pos, item);
747            pos = p
748        }
749    }
750
751    /// The returned height starts from 0. Leaf level is 0.
752    ///
753    /// Returns (newly created subtree's root, height)
754    fn create_subtrees_from_elem(&mut self, data: Vec<B::Elem>) -> (ArenaIndex, usize) {
755        let mut height = 0;
756        let mut nodes = Vec::with_capacity(data.len() / MAX_CHILDREN_NUM + 1);
757        for elem in data.into_iter().chunks(MAX_CHILDREN_NUM).into_iter() {
758            let parent_index = self.in_nodes.insert(Node {
759                parent: None,
760                parent_slot: 0,
761                children: Default::default(),
762            });
763
764            nodes.push(parent_index);
765            let parent = self.in_nodes.get_mut(parent_index).unwrap();
766            for (i, elem) in elem.enumerate() {
767                let leaf = {
768                    // alloc new leaf child
769                    let elem_cache = B::get_elem_cache(&elem);
770                    let new_leaf_index = {
771                        let leaf = LeafNode {
772                            elem,
773                            parent: parent_index,
774                        };
775                        let arena_index = self.leaf_nodes.insert(leaf);
776                        ArenaIndex::Leaf(arena_index)
777                    };
778                    Child {
779                        arena: new_leaf_index,
780                        cache: elem_cache,
781                    }
782                };
783                parent.children[i] = leaf;
784            }
785        }
786
787        while nodes.len() > 1 {
788            let mut new_nodes = Vec::with_capacity(nodes.len() / MAX_CHILDREN_NUM + 1);
789            for chunk in nodes.into_iter().chunks(MAX_CHILDREN_NUM).into_iter() {
790                let parent_index = self.in_nodes.insert(Node {
791                    parent: None,
792                    parent_slot: 0,
793                    children: Default::default(),
794                });
795
796                new_nodes.push(parent_index);
797                for (i, child_idx) in chunk.enumerate() {
798                    let (parent, child) = self.in_nodes.get2_mut(parent_index, child_idx);
799                    let parent = parent.unwrap();
800                    let child = child.unwrap();
801                    let mut cache = B::Cache::default();
802                    B::calc_cache_internal(&mut cache, &child.children);
803                    parent.children[i] = Child {
804                        arena: ArenaIndex::Internal(child_idx),
805                        cache,
806                    };
807                    child.parent = Some(ArenaIndex::Internal(parent_index));
808                    child.parent_slot = i as u8;
809                }
810            }
811            nodes = new_nodes;
812            height += 1;
813        }
814
815        (ArenaIndex::Internal(nodes[0]), height)
816    }
817
818    /// Shift by offset 1.
819    ///
820    /// It will not stay on empty spans but scan forward
821    pub fn shift_path_by_one_offset(&self, mut path: Cursor) -> Option<Cursor>
822    where
823        B::Elem: rle::HasLength,
824    {
825        let leaf = self.leaf_nodes.get(path.leaf.0).unwrap();
826        if path.offset + 1 < leaf.elem.rle_len() {
827            path.offset += 1;
828            return Some(path);
829        }
830
831        let mut parent_idx = leaf.parent;
832        let mut parent = self.in_nodes.get(leaf.parent).unwrap();
833        let mut elem_slot_index = Self::get_leaf_slot(path.leaf.0, parent);
834        path.offset += 1;
835        loop {
836            if elem_slot_index == parent.children.len() {
837                if let Some(next) = self.next_same_level_in_node(ArenaIndex::Internal(parent_idx)) {
838                    elem_slot_index = 0;
839                    path.offset = 0;
840                    parent_idx = next.unwrap_internal();
841                    parent = self.in_nodes.get(parent_idx).unwrap();
842                } else {
843                    return None;
844                }
845            }
846
847            let elem = &parent.children[elem_slot_index];
848            let leaf = self.leaf_nodes.get(elem.arena.unwrap()).unwrap();
849            // skip empty span
850            if leaf.elem.rle_len() <= path.offset {
851                path.offset -= leaf.elem.rle_len();
852                elem_slot_index += 1;
853            } else {
854                path.leaf = elem.arena.unwrap_leaf().into();
855                break;
856            }
857        }
858
859        Some(path)
860    }
861
862    fn get_leaf_slot(leaf_arena_index: RawArenaIndex, parent: &Node<B>) -> usize {
863        parent
864            .children
865            .iter()
866            .position(|x| x.arena.unwrap_leaf() == leaf_arena_index)
867            .unwrap()
868    }
869
870    /// Query the tree by custom query type
871    ///
872    /// Return None if the tree is empty
873    pub fn query<Q>(&self, query: &Q::QueryArg) -> Option<QueryResult>
874    where
875        Q: Query<B>,
876    {
877        self.query_with_finder_return::<Q>(query).0
878    }
879
880    pub fn query_with_finder_return<Q>(&self, query: &Q::QueryArg) -> (Option<QueryResult>, Q)
881    where
882        Q: Query<B>,
883    {
884        let mut finder = Q::init(query);
885        if self.is_empty() {
886            return (None, finder);
887        }
888
889        let mut node = self.in_nodes.get(self.root.unwrap()).unwrap();
890        let mut index;
891        let mut found = true;
892        loop {
893            let result = finder.find_node(query, &node.children);
894            debug_assert!(!node.children.is_empty());
895            let i = result.index;
896            found = found && result.found;
897            index = node.children[i].arena;
898            match index {
899                ArenaIndex::Internal(index) => {
900                    node = self.in_nodes.get(index).unwrap();
901                }
902                ArenaIndex::Leaf(_) => {
903                    let (offset, leaf_found) = finder.confirm_elem(
904                        query,
905                        &self.leaf_nodes.get(index.unwrap_leaf()).unwrap().elem,
906                    );
907                    return (
908                        Some(QueryResult {
909                            cursor: Cursor {
910                                leaf: index.unwrap_leaf().into(),
911                                offset,
912                            },
913                            found: found && leaf_found,
914                        }),
915                        finder,
916                    );
917                }
918            }
919        }
920    }
921
922    pub fn get_elem_mut(&mut self, leaf: LeafIndex) -> Option<&mut B::Elem> {
923        let node = self.leaf_nodes.get_mut(leaf.0)?;
924        Some(&mut node.elem)
925    }
926
927    pub fn get_elem(&self, leaf: LeafIndex) -> Option<&<B as BTreeTrait>::Elem> {
928        self.leaf_nodes.get(leaf.0).map(|x| &x.elem)
929    }
930
931    /// Remove leaf node from the tree
932    ///
933    /// If it's already removed, this method will return None
934    pub fn remove_leaf(&mut self, path: Cursor) -> Option<B::Elem> {
935        let leaf = self.leaf_nodes.get_mut(path.leaf.0)?;
936        let parent_idx = leaf.parent();
937        let parent = self.in_nodes.get_mut(leaf.parent).unwrap();
938        let index = Self::get_leaf_slot(path.leaf.0, parent);
939        let child = parent.children.remove(index);
940        let is_lack = parent.is_lack();
941        let is_empty = parent.is_empty();
942        debug_assert_eq!(child.arena.unwrap(), path.leaf.0);
943        let elem = self.leaf_nodes.remove(child.arena.unwrap()).unwrap().elem;
944
945        self.recursive_update_cache(parent_idx, B::USE_DIFF, None);
946        if is_empty {
947            self.remove_internal_node(parent_idx.unwrap());
948        } else if is_lack {
949            self.handle_lack_recursively(parent_idx);
950        }
951
952        Some(elem)
953    }
954
955    fn remove_internal_node(&mut self, node: RawArenaIndex) {
956        if node == self.root.unwrap() {
957            return;
958        }
959
960        let node = self.in_nodes.remove(node).unwrap();
961        if let Some(parent_idx) = node.parent {
962            let parent = self.in_nodes.get_mut(parent_idx.unwrap_internal()).unwrap();
963            parent.children.remove(node.parent_slot as usize);
964            let is_lack = parent.is_lack();
965            let is_empty = parent.is_empty();
966            self.update_children_parent_slot_from(parent_idx, node.parent_slot as usize);
967            if is_empty {
968                self.remove_internal_node(parent_idx.unwrap_internal());
969            } else if is_lack {
970                self.handle_lack_recursively(parent_idx);
971            }
972        } else {
973            // ignore remove root
974            unreachable!()
975        }
976    }
977
978    /// Update the elements in place.
979    ///
980    /// If the range.start or range.end is in the middle of a leaf node, the leaf node
981    /// will be splitted into two leaf nodes. The new leaf nodes will be returned.
982    ///
983    /// F should returns `Some(cache_diff)` if cache needs to be updated. Otherwise, returns None.
984    ///
985    /// If the given range has zero length, f will still be called, and the slice will
986    /// have same `start` and `end` field
987    ///
988    /// TODO: need better test coverage
989    pub fn update<F>(&mut self, range: Range<Cursor>, f: &mut F) -> SplittedLeaves
990    where
991        F: FnMut(&mut B::Elem) -> Option<B::CacheDiff>,
992    {
993        let mut splitted = SplittedLeaves::default();
994        let start = range.start;
995        let SplitInfo {
996            new_pos: end,
997            new_leaf,
998            ..
999        } = self.split_leaf_if_needed(range.end);
1000        splitted.push_option(new_leaf);
1001        let SplitInfo {
1002            new_pos: start,
1003            new_leaf,
1004            ..
1005        } = self.split_leaf_if_needed(start);
1006        splitted.push_option(new_leaf);
1007        let Some(start) = start else {
1008            return splitted;
1009        };
1010        let start_leaf = start.leaf;
1011        let mut path = self.get_path(start_leaf.into());
1012        let mut dirty_map: LeafDirtyMap<B::CacheDiff> = FxHashMap::default();
1013        let mut to_remove = Vec::default();
1014
1015        loop {
1016            let current_leaf = path.last().unwrap();
1017            if let Some(end) = end {
1018                if current_leaf.arena.unwrap_leaf() == end.leaf.0 {
1019                    break;
1020                }
1021            }
1022
1023            let node = self
1024                .leaf_nodes
1025                .get_mut(current_leaf.arena.unwrap_leaf())
1026                .unwrap();
1027            let cache_diff = f(&mut node.elem);
1028            if node.elem.can_remove() {
1029                to_remove.push(current_leaf.arena);
1030            }
1031
1032            if let Some(diff) = cache_diff {
1033                add_leaf_dirty_map(current_leaf.arena, &mut dirty_map, diff);
1034            }
1035
1036            if !self.next_sibling(&mut path) {
1037                break;
1038            }
1039        }
1040
1041        if !dirty_map.is_empty() {
1042            self.update_dirty_cache_map(dirty_map);
1043        } else {
1044            self.in_nodes
1045                .get(self.root.unwrap_internal())
1046                .unwrap()
1047                .calc_cache(&mut self.root_cache, None);
1048        }
1049
1050        for leaf in to_remove {
1051            self.remove_leaf(Cursor {
1052                leaf: leaf.unwrap().into(),
1053                offset: 0,
1054            });
1055        }
1056        splitted
1057    }
1058
1059    /// Prefer begin of the next leaf node than end of the current leaf node
1060    ///
1061    /// When path.offset == leaf.rle_len(), this method will return
1062    /// the next leaf node with offset 0
1063    #[allow(unused)]
1064    pub fn prefer_right(&self, path: Cursor) -> Option<Cursor> {
1065        if path.offset == 0 {
1066            return Some(path);
1067        }
1068
1069        let leaf = self.leaf_nodes.get(path.leaf.0).unwrap();
1070        if path.offset == leaf.elem.rle_len() {
1071            self.next_elem(path)
1072        } else {
1073            Some(path)
1074        }
1075    }
1076
1077    /// Prefer end of the previous leaf node than begin of the current leaf node
1078    ///
1079    /// When path.offset == 0, this method will return
1080    /// the previous leaf node with offset leaf.rle_len()
1081    #[allow(unused)]
1082    pub fn prefer_left(&self, path: Cursor) -> Option<Cursor> {
1083        if path.offset != 0 {
1084            return Some(path);
1085        }
1086
1087        let elem = self.prev_elem(path);
1088        if let Some(elem) = elem {
1089            let leaf = self.leaf_nodes.get(elem.leaf.0).unwrap();
1090            Some(Cursor {
1091                leaf: elem.leaf,
1092                offset: leaf.elem.rle_len(),
1093            })
1094        } else {
1095            None
1096        }
1097    }
1098
1099    /// Update leaf node's elements.
1100    ///
1101    /// `f` returns Option<(cache_diff, new_insert_1, new_insert2)>
1102    ///
1103    /// - If returned value is `None`, the cache will not be updated.
1104    /// - If leaf_node.can_remove(), it will be removed from the tree.
1105    ///
1106    /// Returns (path, splitted_leaves), if is is still valid after this method. (If the leaf node is removed, the path will be None)
1107    pub fn update_leaf_by_search<Q: Query<B>>(
1108        &mut self,
1109        q: &Q::QueryArg,
1110        f: impl FnOnce(
1111            &mut B::Elem,
1112            QueryResult,
1113        ) -> Option<(B::CacheDiff, Option<B::Elem>, Option<B::Elem>)>,
1114    ) -> (Option<Cursor>, SplittedLeaves) {
1115        if self.is_empty() {
1116            panic!("update_leaf_by_search called on empty tree");
1117        }
1118
1119        let mut splitted = SplittedLeaves::default();
1120        let mut finder = Q::init(q);
1121        let mut path = NodePath::default();
1122        let mut node_idx = self.root;
1123        let mut child_arr_pos = 0;
1124        while let ArenaIndex::Internal(node_idx_inner) = node_idx {
1125            path.push(Idx {
1126                arena: ArenaIndex::Internal(node_idx_inner),
1127                arr: child_arr_pos,
1128            })
1129            .unwrap();
1130            let node = self.in_nodes.get(node_idx_inner).unwrap();
1131            let result = finder.find_node(q, &node.children);
1132            child_arr_pos = result.index as u8;
1133            node_idx = node.children[result.index].arena;
1134        }
1135
1136        let leaf = self.get_leaf_mut(node_idx);
1137        let (offset, found) = finder.confirm_elem(q, &leaf.elem);
1138        let ans = QueryResult {
1139            cursor: Cursor {
1140                leaf: node_idx.unwrap_leaf().into(),
1141                offset,
1142            },
1143            found,
1144        };
1145        let Some((diff, new_insert_1, new_insert_2)) = f(&mut leaf.elem, ans) else {
1146            return (Some(ans.cursor), splitted);
1147        };
1148
1149        if new_insert_2.is_some() {
1150            unimplemented!()
1151        }
1152
1153        // Delete
1154        if leaf.elem.can_remove() {
1155            // handle deletion
1156            // leaf node should be deleted
1157            assert!(new_insert_1.is_none());
1158            assert!(new_insert_2.is_none());
1159            self.leaf_nodes.remove(node_idx.unwrap()).unwrap();
1160            let mut is_first = true;
1161            let mut is_child_lack = false;
1162            let mut child_idx = node_idx;
1163
1164            // iterate from leaf to root, child to parent
1165            while let Some(Idx {
1166                arena: parent_idx,
1167                arr: parent_arr_pos,
1168            }) = path.pop()
1169            {
1170                let parent = self.get_internal_mut(parent_idx);
1171                if is_first {
1172                    parent.children.remove(child_arr_pos as usize);
1173                    is_first = false;
1174                } else {
1175                    B::apply_cache_diff(&mut parent.children[child_arr_pos as usize].cache, &diff);
1176                }
1177
1178                let is_lack = parent.is_lack();
1179
1180                if is_child_lack {
1181                    self.handle_lack_single_layer(child_idx);
1182                }
1183
1184                is_child_lack = is_lack;
1185                child_idx = parent_idx;
1186                child_arr_pos = parent_arr_pos;
1187            }
1188
1189            B::apply_cache_diff(&mut self.root_cache, &diff);
1190
1191            if is_child_lack {
1192                let root = self.get_internal_mut(self.root);
1193                if root.children.len() == 1 && !root.is_child_leaf() {
1194                    self.try_reduce_levels();
1195                }
1196            }
1197
1198            return (None, splitted);
1199        }
1200
1201        let mut new_cache_and_child = None;
1202        if let Some(new_insert_1) = new_insert_1 {
1203            let cache = B::get_elem_cache(&leaf.elem);
1204            let child = self.alloc_leaf_child(new_insert_1, path.last().unwrap().arena.unwrap());
1205            splitted.push(child.arena);
1206            new_cache_and_child = Some((cache, child));
1207        }
1208
1209        while let Some(Idx {
1210            arena: parent_idx,
1211            arr: parent_arr_pos,
1212        }) = path.pop()
1213        {
1214            let parent = self.get_internal_mut(parent_idx);
1215            match take(&mut new_cache_and_child) {
1216                Some((cache, child)) => {
1217                    parent.children[child_arr_pos as usize].cache = cache;
1218                    parent
1219                        .children
1220                        .insert(child_arr_pos as usize + 1, child)
1221                        .unwrap();
1222                    let is_full = parent.is_full();
1223                    if !parent.is_child_leaf() {
1224                        self.update_children_parent_slot_from(
1225                            parent_idx,
1226                            child_arr_pos as usize + 1,
1227                        );
1228                    }
1229                    if is_full {
1230                        let (_, _, this_cache, right_child) = self.split_node(parent_idx, None);
1231                        new_cache_and_child = Some((this_cache, right_child));
1232                    }
1233                }
1234                None => {
1235                    B::apply_cache_diff(&mut parent.children[child_arr_pos as usize].cache, &diff);
1236                }
1237            }
1238
1239            child_arr_pos = parent_arr_pos;
1240        }
1241
1242        if let Some((cache, child)) = new_cache_and_child {
1243            self.split_root(cache, child);
1244        } else {
1245            B::apply_cache_diff(&mut self.root_cache, &diff);
1246        }
1247
1248        (Some(ans.cursor), splitted)
1249    }
1250
1251    /// Update leaf node's elements, return true if cache need to be updated
1252    ///
1253    /// `f` returns (is_cache_updated, cache_diff, new_insert_1, new_insert2)
1254    ///
1255    /// - If leaf_node.can_remove(), it will be removed from the tree.
1256    ///
1257    /// Returns true if the node_idx is still valid. (If the leaf node is removed, it will return false).
1258    pub fn update_leaf(
1259        &mut self,
1260        node_idx: LeafIndex,
1261        f: impl FnOnce(&mut B::Elem) -> (bool, Option<B::Elem>, Option<B::Elem>),
1262    ) -> (bool, SplittedLeaves) {
1263        let mut splitted = SplittedLeaves::default();
1264        let node = self.leaf_nodes.get_mut(node_idx.0).unwrap();
1265        let mut parent_idx = node.parent();
1266        let (need_update_cache, mut new_insert_1, mut new_insert_2) = f(&mut node.elem);
1267        {
1268            // Normalize returned values
1269            //
1270            // If the node can be removed, then both new_insert_1 & new_insert_2 should be None
1271            // The priority is node.elem > new_insert_1 > new_insert_2
1272            //
1273            // And new_insert_1 and new_insert_2 should not match `can_remove` condition
1274            if let Some(ref new_1) = new_insert_1 {
1275                if new_1.can_remove() {
1276                    new_insert_1 = new_insert_2.take();
1277                    if let Some(ref new_1) = new_insert_1 {
1278                        if new_1.can_remove() {
1279                            new_insert_1 = None;
1280                        }
1281                    }
1282                }
1283            }
1284
1285            if let Some(ref new_2) = new_insert_2 {
1286                if new_2.can_remove() {
1287                    new_insert_2 = None;
1288                } else if new_insert_1.is_none() {
1289                    std::mem::swap(&mut new_insert_1, &mut new_insert_2);
1290                }
1291            }
1292
1293            if node.elem.can_remove() {
1294                if let Some(new_1) = new_insert_1 {
1295                    node.elem = new_1;
1296                    new_insert_1 = new_insert_2.take();
1297                }
1298            }
1299        }
1300
1301        let deleted = node.elem.can_remove();
1302
1303        if need_update_cache {
1304            self.recursive_update_cache(node_idx.into(), B::USE_DIFF, None);
1305        }
1306
1307        if deleted {
1308            debug_assert!(new_insert_1.is_none());
1309            debug_assert!(new_insert_2.is_none());
1310            self.leaf_nodes.remove(node_idx.0).unwrap();
1311            let parent = self.in_nodes.get_mut(parent_idx.unwrap()).unwrap();
1312            let slot = Self::get_leaf_slot(node_idx.0, parent);
1313            parent.children.remove(slot);
1314            let is_lack = parent.is_lack();
1315            if is_lack {
1316                self.handle_lack_recursively(parent_idx);
1317            }
1318
1319            (false, splitted)
1320        } else if new_insert_1.is_none() {
1321            debug_assert!(new_insert_2.is_none());
1322            return (true, splitted);
1323        } else {
1324            if new_insert_1.is_some() && new_insert_2.is_none() {
1325                // try merge new insert to next element
1326                let parent = self.in_nodes.get_mut(parent_idx.unwrap()).unwrap();
1327                let slot = Self::get_leaf_slot(node_idx.0, parent);
1328                if slot + 1 < parent.children.len() {
1329                    let next_idx = parent.children[slot + 1].arena.unwrap().into();
1330                    let next = self.get_elem_mut(next_idx).unwrap();
1331                    let new = new_insert_1.as_ref().unwrap();
1332                    if new.can_merge(next) {
1333                        next.merge_left(new);
1334                        self.recursive_update_cache(next_idx.into(), B::USE_DIFF, None);
1335                        splitted.push(next_idx.into());
1336                        return (true, splitted);
1337                    }
1338                }
1339            }
1340
1341            let count = if new_insert_1.is_some() { 1 } else { 0 }
1342                + if new_insert_2.is_some() { 1 } else { 0 };
1343            let parent = self.in_nodes.get_mut(parent_idx.unwrap()).unwrap();
1344            let parent = if parent.children.len() + count >= MAX_CHILDREN_NUM {
1345                self.split(parent_idx);
1346                let node = self.leaf_nodes.get(node_idx.0).unwrap();
1347                parent_idx = node.parent();
1348                self.in_nodes.get_mut(parent_idx.unwrap()).unwrap()
1349            } else {
1350                parent
1351            };
1352
1353            let new: HeaplessVec<_, 2> = new_insert_1
1354                .into_iter()
1355                .chain(new_insert_2)
1356                .map(|elem| {
1357                    // Allocate new leaf node
1358                    let parent_index = parent_idx.unwrap();
1359                    let elem_cache = B::get_elem_cache(&elem);
1360                    let new_leaf_index = {
1361                        let leaf = LeafNode {
1362                            elem,
1363                            parent: parent_index,
1364                        };
1365                        let arena_index = self.leaf_nodes.insert(leaf);
1366                        ArenaIndex::Leaf(arena_index)
1367                    };
1368                    Child {
1369                        arena: new_leaf_index,
1370                        cache: elem_cache,
1371                    }
1372                })
1373                .collect();
1374            let slot = Self::get_leaf_slot(node_idx.0, parent);
1375            for (i, v) in new.into_iter().enumerate() {
1376                splitted.push(v.arena);
1377                parent.children.insert(slot + 1 + i, v).unwrap();
1378            }
1379
1380            assert!(!parent.is_full());
1381            self.recursive_update_cache(parent_idx, B::USE_DIFF, None);
1382            (true, splitted)
1383        }
1384    }
1385
1386    /// Update the given leaves with the given function in the given range.
1387    ///
1388    /// - The range descibes the range inside the leaf node.
1389    /// - There can be multiple ranges in the same leaf node.
1390    /// - The cahce will be recalculated for each affected node
1391    /// - It doesn't guarantee the applying order
1392    ///
1393    /// Currently, the time complexity is O(m^2) for each leaf node,
1394    /// where m is the number of ranges inside the same leaf node.
1395    /// If we have a really large m, this function need to be optimized.
1396    pub fn update_leaves_with_arg_in_ranges<A: Debug>(
1397        &mut self,
1398        mut args: Vec<(LeafIndex, Range<usize>, A)>,
1399        mut f: impl FnMut(&mut B::Elem, &A),
1400    ) -> Vec<LeafIndex> {
1401        args.sort_by_key(|x| x.0);
1402        let mut new_leaves = Vec::new();
1403        let mut dirty_map: LeafDirtyMap<B::CacheDiff> = Default::default();
1404        let mut new_elems_at_cursor: FxHashMap<Cursor, Vec<B::Elem>> = Default::default();
1405        for (leaf, group) in &args.into_iter().group_by(|x| x.0) {
1406            // This loop doesn't change the shape of the tree.  It only changes each leaf element.
1407            // A leaf element may be splitted into several parts. The first part stay in the tree,
1408            // while the rest of them are inserted into `new_elem_at_cursor`, which will be inserted
1409            // into the tree later.
1410            let leaf_node = self.leaf_nodes.get_mut(leaf.0).unwrap();
1411            let len = leaf_node.elem().rle_len();
1412            let mut split_at = BTreeSet::new();
1413            // PERF we can avoid this alloc and `group_by`
1414            let group: Vec<_> = group.into_iter().collect();
1415            for (_, range, _) in group.iter() {
1416                split_at.insert(range.start);
1417                split_at.insert(range.end);
1418            }
1419
1420            split_at.remove(&0);
1421            split_at.remove(&len);
1422
1423            // leaf_node.elem is the first elem
1424            let old_cache = B::get_elem_cache(&leaf_node.elem);
1425            if split_at.is_empty() {
1426                // doesn't need to split
1427                for (_, range, a) in group.iter() {
1428                    assert_eq!(range.start, 0);
1429                    assert_eq!(range.end, len);
1430                    f(&mut leaf_node.elem, a);
1431                }
1432            } else {
1433                let mut new_elems = Vec::new();
1434
1435                let first_split = split_at.first().copied().unwrap();
1436
1437                // handle first element
1438                let mut elem = leaf_node.elem.split(first_split);
1439                for (_, r, a) in group.iter() {
1440                    if r.start == 0 {
1441                        f(&mut leaf_node.elem, a);
1442                    }
1443                }
1444
1445                // handle elements in the middle
1446                let mut last_index = first_split;
1447                for &index in split_at.iter().skip(1) {
1448                    let next_elem = elem.split(index - last_index);
1449                    let cur_range = last_index..index;
1450                    for (_, r, a) in group.iter() {
1451                        if r.start <= cur_range.start && cur_range.end <= r.end {
1452                            f(&mut elem, a);
1453                        }
1454                    }
1455
1456                    new_elems.push(elem);
1457                    elem = next_elem;
1458                    last_index = index;
1459                }
1460
1461                // handle the last element
1462                for (_, r, a) in group.iter() {
1463                    if r.end == len {
1464                        f(&mut elem, a);
1465                    }
1466                }
1467
1468                new_elems.push(elem);
1469                new_elems_at_cursor.insert(
1470                    Cursor {
1471                        leaf,
1472                        offset: leaf_node.elem().rle_len(),
1473                    },
1474                    new_elems,
1475                );
1476            }
1477
1478            let new_cache = B::get_elem_cache(&leaf_node.elem);
1479            let diff = B::sub_cache(&new_cache, &old_cache);
1480            dirty_map.insert(leaf.into(), diff);
1481        }
1482
1483        // update cache
1484        self.update_dirty_cache_map(dirty_map);
1485
1486        // PERF we can use batch insert to optimize this
1487        // insert the new leaf nodes
1488        for (mut cursor, elems) in new_elems_at_cursor {
1489            for elem in elems.into_iter() {
1490                // PERF can use insert many to optimize when it's supported
1491                let result = self.insert_by_path(cursor, elem);
1492                let len = self.get_elem(result.0.leaf).unwrap().rle_len();
1493                new_leaves.push(result.0.leaf);
1494                debug_assert_eq!(result.1.arr.len(), 0);
1495                cursor = Cursor {
1496                    leaf: result.0.leaf,
1497                    offset: len,
1498                };
1499            }
1500        }
1501
1502        new_leaves
1503    }
1504
1505    fn update_root_cache(&mut self) {
1506        self.in_nodes
1507            .get(self.root.unwrap_internal())
1508            .unwrap()
1509            .calc_cache(&mut self.root_cache, None);
1510    }
1511
1512    fn update_dirty_cache_map(&mut self, mut diff_map: LeafDirtyMap<B::CacheDiff>) {
1513        // diff_map only contains leaf nodes when this function is called
1514        let mut visit_set: FxHashSet<ArenaIndex> = diff_map.keys().copied().collect();
1515        while !visit_set.is_empty() {
1516            for child_idx in take(&mut visit_set) {
1517                let (parent_idx, cache_diff) = match child_idx {
1518                    ArenaIndex::Leaf(leaf_idx) => {
1519                        let node = self.leaf_nodes.get(leaf_idx).unwrap();
1520                        let parent_idx = node.parent;
1521                        let parent = self.in_nodes.get_mut(parent_idx).unwrap();
1522                        let cache_diff = diff_map.remove(&child_idx).unwrap();
1523                        for child in parent.children.iter_mut() {
1524                            if child.arena == child_idx {
1525                                B::apply_cache_diff(&mut child.cache, &cache_diff);
1526                                break;
1527                            }
1528                        }
1529
1530                        (ArenaIndex::Internal(parent_idx), cache_diff)
1531                    }
1532                    ArenaIndex::Internal(_) => {
1533                        let node = self.in_nodes.get(child_idx.unwrap_internal()).unwrap();
1534                        let Some(parent_idx) = node.parent else {
1535                            continue;
1536                        };
1537                        let (child, parent) = self.get2_mut(child_idx, parent_idx);
1538                        let cache_diff = child.calc_cache(
1539                            &mut parent.children[child.parent_slot as usize].cache,
1540                            diff_map.remove(&child_idx),
1541                        );
1542
1543                        (parent_idx, cache_diff)
1544                    }
1545                };
1546
1547                visit_set.insert(parent_idx);
1548                if let Some(e) = diff_map.get_mut(&parent_idx) {
1549                    B::merge_cache_diff(e, &cache_diff);
1550                } else {
1551                    diff_map.insert(parent_idx, cache_diff);
1552                }
1553            }
1554        }
1555
1556        self.in_nodes
1557            .get(self.root.unwrap_internal())
1558            .unwrap()
1559            .calc_cache(&mut self.root_cache, None);
1560    }
1561
1562    /// Removed deleted children. `deleted` means they are removed from the arena.
1563    fn filter_deleted_children(&mut self, internal_node: ArenaIndex) {
1564        let node = self
1565            .in_nodes
1566            .get_mut(internal_node.unwrap_internal())
1567            .unwrap();
1568        // PERF: I hate this pattern...
1569        let mut children = take(&mut node.children);
1570        children.retain(|x| match x.arena {
1571            ArenaIndex::Leaf(leaf) => self.leaf_nodes.contains(leaf),
1572            ArenaIndex::Internal(index) => self.in_nodes.contains(index),
1573        });
1574        let node = self
1575            .in_nodes
1576            .get_mut(internal_node.unwrap_internal())
1577            .unwrap();
1578        node.children = children;
1579    }
1580
1581    pub fn iter(&self) -> impl Iterator<Item = &B::Elem> + '_ {
1582        let mut path = self.first_path().unwrap_or_default();
1583        path.pop();
1584        let idx = path.last().copied().unwrap_or(Idx::new(self.root, 0));
1585        debug_assert!(matches!(idx.arena, ArenaIndex::Internal(_)));
1586        let node = self.get_internal(idx.arena);
1587        let mut iter = node.children.iter();
1588        core::iter::from_fn(move || loop {
1589            if path.is_empty() {
1590                return None;
1591            }
1592
1593            match iter.next() {
1594                None => {
1595                    if !self.next_sibling(&mut path) {
1596                        return None;
1597                    }
1598
1599                    let idx = *path.last().unwrap();
1600                    debug_assert!(matches!(idx.arena, ArenaIndex::Internal(_)));
1601                    let node = self.get_internal(idx.arena);
1602                    iter = node.children.iter();
1603                }
1604                Some(elem) => {
1605                    let leaf = self.leaf_nodes.get(elem.arena.unwrap_leaf()).unwrap();
1606                    return Some(&leaf.elem);
1607                }
1608            }
1609        })
1610    }
1611
1612    pub fn drain(&mut self, range: Range<QueryResult>) -> iter::Drain<B> {
1613        iter::Drain::new(self, Some(range.start), Some(range.end))
1614    }
1615
1616    pub fn drain_by_query<Q: Query<B>>(&mut self, range: Range<Q::QueryArg>) -> iter::Drain<B> {
1617        let start = self.query::<Q>(&range.start);
1618        let end = self.query::<Q>(&range.end);
1619        iter::Drain::new(self, start, end)
1620    }
1621
1622    fn first_path(&self) -> Option<NodePath> {
1623        let mut index = self.root;
1624        let mut node = self.in_nodes.get(index.unwrap_internal()).unwrap();
1625        if node.is_empty() {
1626            return None;
1627        }
1628
1629        let mut path = NodePath::new();
1630        loop {
1631            path.push(Idx::new(index, 0)).unwrap();
1632            match index {
1633                ArenaIndex::Leaf(_) => {
1634                    break;
1635                }
1636                ArenaIndex::Internal(_) => {
1637                    index = node.children[0].arena;
1638                    if let ArenaIndex::Internal(i) = index {
1639                        node = self.in_nodes.get(i).unwrap();
1640                    };
1641                }
1642            }
1643        }
1644
1645        Some(path)
1646    }
1647
1648    fn last_path(&self) -> Option<NodePath> {
1649        let mut path = NodePath::new();
1650        let mut index = self.root;
1651        let mut node = self.in_nodes.get(index.unwrap_internal()).unwrap();
1652        let mut pos_in_parent = 0;
1653        if node.is_empty() {
1654            return None;
1655        }
1656
1657        loop {
1658            path.push(Idx::new(index, pos_in_parent)).unwrap();
1659            match index {
1660                ArenaIndex::Leaf(_) => {
1661                    break;
1662                }
1663                ArenaIndex::Internal(_) => {
1664                    pos_in_parent = node.children.len() as u8 - 1;
1665                    index = node.children[node.children.len() - 1].arena;
1666                    if let ArenaIndex::Internal(i) = index {
1667                        node = self.in_nodes.get(i).unwrap();
1668                    }
1669                }
1670            }
1671        }
1672
1673        Some(path)
1674    }
1675
1676    pub fn first_leaf(&self) -> Option<LeafIndex> {
1677        let mut index = self.root;
1678        let mut node = self.in_nodes.get(index.unwrap_internal()).unwrap();
1679        loop {
1680            index = node.children.first()?.arena;
1681            match index {
1682                ArenaIndex::Leaf(leaf) => {
1683                    return Some(leaf.into());
1684                }
1685                ArenaIndex::Internal(index) => {
1686                    node = self.in_nodes.get(index).unwrap();
1687                }
1688            }
1689        }
1690    }
1691
1692    pub fn last_leaf(&self) -> Option<LeafIndex> {
1693        let mut index = self.root;
1694        let mut node = self.in_nodes.get(index.unwrap_internal()).unwrap();
1695        loop {
1696            index = node.children.last()?.arena;
1697            match index {
1698                ArenaIndex::Leaf(leaf) => {
1699                    return Some(leaf.into());
1700                }
1701                ArenaIndex::Internal(index) => {
1702                    node = self.in_nodes.get(index).unwrap();
1703                }
1704            }
1705        }
1706    }
1707
1708    pub fn range<Q>(&self, range: Range<Q::QueryArg>) -> Option<Range<QueryResult>>
1709    where
1710        Q: Query<B>,
1711    {
1712        if self.is_empty() {
1713            return None;
1714        }
1715
1716        Some(self.query::<Q>(&range.start).unwrap()..self.query::<Q>(&range.end).unwrap())
1717    }
1718
1719    pub fn iter_range(
1720        &self,
1721        range: impl RangeBounds<Cursor>,
1722    ) -> impl Iterator<Item = ElemSlice<'_, B::Elem>> + '_ {
1723        let start = match range.start_bound() {
1724            std::ops::Bound::Included(start) => *start,
1725            std::ops::Bound::Excluded(_) => unreachable!(),
1726            std::ops::Bound::Unbounded => self.start_cursor().unwrap(),
1727        };
1728        let (inclusive, end) = match range.end_bound() {
1729            std::ops::Bound::Included(end) => (true, *end),
1730            std::ops::Bound::Excluded(end) => (false, *end),
1731            std::ops::Bound::Unbounded => (true, self.end_cursor().unwrap()),
1732        };
1733        self._iter_range(start, end, inclusive)
1734    }
1735
1736    fn _iter_range(
1737        &self,
1738        start: Cursor,
1739        end: Cursor,
1740        inclusive_end: bool,
1741    ) -> impl Iterator<Item = ElemSlice<'_, B::Elem>> + '_ {
1742        let node_iter = iter::Iter::new(
1743            self,
1744            self.get_path(start.leaf.into()),
1745            self.get_path(end.leaf.into()),
1746        );
1747        node_iter.filter_map(move |(path, node)| {
1748            let leaf = LeafIndex(path.last().unwrap().arena.unwrap_leaf());
1749            if end.leaf == leaf && end.offset == 0 && !inclusive_end {
1750                return None;
1751            }
1752
1753            Some(ElemSlice {
1754                cursor: Cursor { leaf, offset: 0 },
1755                elem: &node.elem,
1756                start: if start.leaf == leaf {
1757                    Some(start.offset)
1758                } else {
1759                    None
1760                },
1761                end: if end.leaf == leaf {
1762                    Some(end.offset)
1763                } else {
1764                    None
1765                },
1766            })
1767        })
1768    }
1769
1770    pub fn start_cursor(&self) -> Option<Cursor> {
1771        Some(Cursor {
1772            leaf: self.first_leaf()?,
1773            offset: 0,
1774        })
1775    }
1776
1777    pub fn end_cursor(&self) -> Option<Cursor> {
1778        let leaf = self.last_leaf()?;
1779        let node = self.get_leaf(leaf.into());
1780        Some(Cursor {
1781            leaf,
1782            offset: node.elem.rle_len(),
1783        })
1784    }
1785
1786    /// Split the internal node at path into two nodes recursively upwards.
1787    ///
1788    // at call site the cache at path can be out-of-date.
1789    // the cache will be up-to-date after this method
1790    fn split(&mut self, node_idx: ArenaIndex) {
1791        self.split_at(node_idx, None)
1792    }
1793
1794    fn split_at(&mut self, node_idx: ArenaIndex, at: Option<usize>) {
1795        let (node_parent, node_parent_slot, this_cache, right_child) =
1796            self.split_node(node_idx, at);
1797
1798        self.inner_insert_node(
1799            node_parent,
1800            node_parent_slot as usize,
1801            this_cache,
1802            right_child,
1803        );
1804        // don't need to recursive update cache
1805    }
1806
1807    fn split_node(
1808        &mut self,
1809        node_idx: ArenaIndex,
1810        at: Option<usize>,
1811    ) -> (Option<ArenaIndex>, u8, <B as BTreeTrait>::Cache, Child<B>) {
1812        let node = self.in_nodes.get_mut(node_idx.unwrap_internal()).unwrap();
1813        let node_parent = node.parent;
1814        let node_parent_slot = node.parent_slot;
1815        let right: Node<B> = Node {
1816            parent: node.parent,
1817            parent_slot: u8::MAX,
1818            children: HeaplessVec::new(),
1819        };
1820
1821        // split
1822        let split = at.unwrap_or(node.children.len() / 2);
1823        let right_children = HeaplessVec::from_slice(&node.children[split..]).unwrap();
1824        delete_range(&mut node.children, split..);
1825
1826        // update cache
1827        let mut right_cache = B::Cache::default();
1828        let right_arena_idx = self.in_nodes.insert(right);
1829        let this_cache = {
1830            let node = self.get_internal_mut(node_idx);
1831            let mut cache = Default::default();
1832            node.calc_cache(&mut cache, None);
1833            cache
1834        };
1835
1836        // update children's parent info
1837        for (i, child) in right_children.iter().enumerate() {
1838            if matches!(child.arena, ArenaIndex::Internal(_)) {
1839                let child = self.get_internal_mut(child.arena);
1840                child.parent = Some(ArenaIndex::Internal(right_arena_idx));
1841                child.parent_slot = i as u8;
1842            } else {
1843                self.get_leaf_mut(child.arena).parent = right_arena_idx;
1844            }
1845        }
1846
1847        let right = self.in_nodes.get_mut(right_arena_idx).unwrap();
1848        right.children = right_children;
1849        // update parent cache
1850        right.calc_cache(&mut right_cache, None);
1851        let right_child = Child {
1852            arena: ArenaIndex::Internal(right_arena_idx),
1853            cache: right_cache,
1854        };
1855        (node_parent, node_parent_slot, this_cache, right_child)
1856    }
1857
1858    // call site should ensure the cache is up-to-date after this method
1859    fn inner_insert_node(
1860        &mut self,
1861        parent_idx: Option<ArenaIndex>,
1862        index: usize,
1863        new_cache: B::Cache,
1864        node: Child<B>,
1865    ) {
1866        if let Some(parent_idx) = parent_idx {
1867            let parent = self.get_internal_mut(parent_idx);
1868            parent.children[index].cache = new_cache;
1869            parent.children.insert(index + 1, node).unwrap();
1870            let is_full = parent.is_full();
1871            self.update_children_parent_slot_from(parent_idx, index + 1);
1872            if is_full {
1873                self.split(parent_idx);
1874            }
1875        } else {
1876            self.split_root(new_cache, node);
1877        }
1878    }
1879
1880    /// Update the `parent_slot` fields in `children[index..]`
1881    fn update_children_parent_slot_from(&mut self, parent_idx: ArenaIndex, index: usize) {
1882        let parent = self.get_internal_mut(parent_idx);
1883        if parent.children.len() <= index || parent.is_child_leaf() {
1884            return;
1885        }
1886
1887        // PERF: Is there a way to avoid `take` like this?
1888        let children = take(&mut parent.children);
1889        for (i, child) in children[index..].iter().enumerate() {
1890            let idx = index + i;
1891            let child = self.get_internal_mut(child.arena);
1892            child.parent_slot = idx as u8;
1893        }
1894        let parent = self.get_internal_mut(parent_idx);
1895        parent.children = children;
1896    }
1897
1898    /// right's cache should be up-to-date
1899    fn split_root(&mut self, new_cache: B::Cache, right: Child<B>) {
1900        let root_idx = self.root;
1901        // set right parent
1902        let right_node = &mut self.get_internal_mut(right.arena);
1903        right_node.parent_slot = 1;
1904        right_node.parent = Some(root_idx);
1905        let root = self.get_internal_mut(self.root);
1906        // let left be root
1907        let mut left_node: Node<B> = core::mem::replace(
1908            root,
1909            Node {
1910                parent: None,
1911                parent_slot: 0,
1912                children: Default::default(),
1913            },
1914        );
1915        left_node.parent_slot = 0;
1916        // set left parent
1917        left_node.parent = Some(root_idx);
1918
1919        // push left and right to root.children
1920        root.children = Default::default();
1921        let left_children = left_node.children.clone();
1922        let left_arena = self.in_nodes.insert(left_node);
1923        let left = Child::new(ArenaIndex::Internal(left_arena), new_cache);
1924        let mut cache = std::mem::take(&mut self.root_cache);
1925        let root = self.get_internal_mut(self.root);
1926        root.children.push(left).unwrap();
1927        root.children.push(right).unwrap();
1928
1929        // update new root cache
1930        root.calc_cache(&mut cache, None);
1931
1932        for (i, child) in left_children.iter().enumerate() {
1933            if child.is_internal() {
1934                let node = self.get_internal_mut(child.arena);
1935                node.parent = Some(ArenaIndex::Internal(left_arena));
1936                node.parent_slot = i as u8;
1937            } else {
1938                self.get_leaf_mut(child.arena).parent = left_arena;
1939            }
1940        }
1941
1942        self.root_cache = cache;
1943    }
1944
1945    #[inline]
1946    pub fn get_internal_mut(&mut self, index: ArenaIndex) -> &mut Node<B> {
1947        self.in_nodes.get_mut(index.unwrap_internal()).unwrap()
1948    }
1949
1950    #[inline]
1951    pub fn get_leaf_mut(&mut self, index: ArenaIndex) -> &mut LeafNode<B::Elem> {
1952        self.leaf_nodes.get_mut(index.unwrap_leaf()).unwrap()
1953    }
1954
1955    #[inline]
1956    fn get2_mut(&mut self, a: ArenaIndex, b: ArenaIndex) -> (&mut Node<B>, &mut Node<B>) {
1957        let (a, b) = self
1958            .in_nodes
1959            .get2_mut(a.unwrap_internal(), b.unwrap_internal());
1960        (a.unwrap(), b.unwrap())
1961    }
1962
1963    /// # Panic
1964    ///
1965    /// If the given index is not valid or deleted
1966    #[inline]
1967    pub fn get_internal(&self, index: ArenaIndex) -> &Node<B> {
1968        self.in_nodes.get(index.unwrap_internal()).unwrap()
1969    }
1970
1971    #[inline]
1972    pub fn get_leaf(&self, index: ArenaIndex) -> &LeafNode<B::Elem> {
1973        self.leaf_nodes.get(index.unwrap_leaf()).unwrap()
1974    }
1975
1976    /// The given node is lack of children.
1977    /// We should merge it into its neighbor or borrow from its neighbor.
1978    ///
1979    /// Given a random neighbor is neither full or lack, it's guaranteed
1980    /// that we can either merge into or borrow from it without breaking
1981    /// the balance rule.
1982    ///
1983    /// - The caches in parent's subtree should be up-to-date when calling this.
1984    /// - The caches in the parent node will be updated
1985    fn handle_lack_recursively(&mut self, node_idx: ArenaIndex) {
1986        let mut lack_info = self.handle_lack_single_layer(node_idx);
1987        while let Some(parent) = lack_info.parent_lack {
1988            lack_info = self.handle_lack_single_layer(parent);
1989        }
1990    }
1991
1992    /// The given node is lack of children. This method doesn't handle parent's lack.
1993    ///
1994    /// - The caches in parent's subtree should be up-to-date when calling this.
1995    /// - The caches in the parent node will be updated
1996    fn handle_lack_single_layer(&mut self, node_idx: ArenaIndex) -> LackInfo {
1997        if self.root == node_idx {
1998            self.try_reduce_levels();
1999            return LackInfo { parent_lack: None };
2000        }
2001
2002        let node = self.get_internal(node_idx);
2003        let parent_idx = node.parent.unwrap();
2004        let parent = self.get_internal(parent_idx);
2005        debug_assert_eq!(parent.children[node.parent_slot as usize].arena, node_idx);
2006        if node.children.is_empty() {
2007            let slot = node.parent_slot as usize;
2008            self.get_internal_mut(parent_idx).children.remove(slot);
2009            self.in_nodes.remove(node_idx.unwrap_internal());
2010            self.update_children_parent_slot_from(parent_idx, slot);
2011            return LackInfo {
2012                parent_lack: Some(parent_idx),
2013            };
2014        }
2015        let ans = match self.pair_neighbor(node_idx) {
2016            Some((a_idx, b_idx)) => {
2017                let parent = self.get_internal_mut(parent_idx);
2018                let mut a_cache = std::mem::take(&mut parent.children[a_idx.arr as usize].cache);
2019                let mut b_cache = std::mem::take(&mut parent.children[b_idx.arr as usize].cache);
2020                let mut re_parent = FxHashMap::default();
2021
2022                let (a, b) = self
2023                    .in_nodes
2024                    .get2_mut(a_idx.arena.unwrap_internal(), b_idx.arena.unwrap_internal());
2025                let a = a.unwrap();
2026                let b = b.unwrap();
2027                let ans = if a.len() + b.len() >= MAX_CHILDREN_NUM {
2028                    // move partially
2029                    if a.len() < b.len() {
2030                        // move part of b's children to a
2031                        let move_len = (b.len() - a.len()) / 2;
2032                        for child in &b.children[..move_len] {
2033                            re_parent.insert(child.arena, (a_idx.arena, a.children.len()));
2034                            a.children.push(child.clone()).unwrap();
2035                        }
2036                        delete_range(&mut b.children, ..move_len);
2037                        for (i, child) in b.children.iter().enumerate() {
2038                            re_parent.insert(child.arena, (b_idx.arena, i));
2039                        }
2040                    } else {
2041                        // move part of a's children to b
2042                        let move_len = (a.len() - b.len()) / 2;
2043                        for (i, child) in b.children.iter().enumerate() {
2044                            re_parent.insert(child.arena, (b_idx.arena, i + move_len));
2045                        }
2046                        let mut b_children =
2047                            HeaplessVec::from_slice(&a.children[a.children.len() - move_len..])
2048                                .unwrap();
2049                        for child in take(&mut b.children) {
2050                            b_children.push(child).unwrap();
2051                        }
2052                        b.children = b_children;
2053                        for (i, child) in b.children.iter().enumerate() {
2054                            re_parent.insert(child.arena, (b_idx.arena, i));
2055                        }
2056                        let len = a.children.len();
2057                        delete_range(&mut a.children, len - move_len..);
2058                    }
2059                    a.calc_cache(&mut a_cache, None);
2060                    b.calc_cache(&mut b_cache, None);
2061                    let parent = self.get_internal_mut(parent_idx);
2062                    parent.children[a_idx.arr as usize].cache = a_cache;
2063                    parent.children[b_idx.arr as usize].cache = b_cache;
2064                    LackInfo {
2065                        parent_lack: if parent.is_lack() {
2066                            Some(parent_idx)
2067                        } else {
2068                            None
2069                        },
2070                    }
2071                } else {
2072                    // merge
2073                    let is_parent_lack = if node_idx == a_idx.arena {
2074                        // merge b to a, delete b
2075                        for (i, child) in b.children.iter().enumerate() {
2076                            re_parent.insert(child.arena, (a_idx.arena, a.children.len() + i));
2077                        }
2078
2079                        for child in take(&mut b.children) {
2080                            a.children.push(child).unwrap();
2081                        }
2082
2083                        a.calc_cache(&mut a_cache, None);
2084                        let parent = self.get_internal_mut(parent_idx);
2085                        parent.children[a_idx.arr as usize].cache = a_cache;
2086                        parent.children.remove(b_idx.arr as usize);
2087                        let is_lack = parent.is_lack();
2088                        self.purge(b_idx.arena);
2089                        self.update_children_parent_slot_from(parent_idx, b_idx.arr as usize);
2090                        is_lack
2091                    } else {
2092                        // merge a to b, delete a
2093                        for (i, child) in a.children.iter().enumerate() {
2094                            re_parent.insert(child.arena, (b_idx.arena, i));
2095                        }
2096                        for (i, child) in b.children.iter().enumerate() {
2097                            re_parent.insert(child.arena, (b_idx.arena, i + a.children.len()));
2098                        }
2099
2100                        for child in take(&mut b.children) {
2101                            a.children.push(child).unwrap();
2102                        }
2103
2104                        b.children = take(&mut a.children);
2105                        b.calc_cache(&mut b_cache, None);
2106                        let parent = self.get_internal_mut(parent_idx);
2107                        parent.children[b_idx.arr as usize].cache = b_cache;
2108                        parent.children.remove(a_idx.arr as usize);
2109                        let is_lack = parent.is_lack();
2110                        self.purge(a_idx.arena);
2111                        self.update_children_parent_slot_from(parent_idx, a_idx.arr as usize);
2112                        is_lack
2113                    };
2114
2115                    LackInfo {
2116                        parent_lack: if is_parent_lack {
2117                            Some(parent_idx)
2118                        } else {
2119                            None
2120                        },
2121                    }
2122                };
2123
2124                // FIXME: make this work
2125                if cfg!(debug_assertions) {
2126                    // let (a, b) = self
2127                    //     .in_nodes
2128                    //     .get2_mut(a_idx.arena.unwrap_internal(), b_idx.arena.unwrap_internal());
2129                    // if let Some(a) = a {
2130                    //     assert!(!a.is_lack() && !a.is_full());
2131                    // }
2132                    // if let Some(b) = b {
2133                    //     assert!(!b.is_lack() && !b.is_full());
2134                    // }
2135                }
2136
2137                for (child, (parent, slot)) in re_parent {
2138                    match child {
2139                        ArenaIndex::Leaf(_) => {
2140                            let child = self.get_leaf_mut(child);
2141                            child.parent = parent.unwrap_internal();
2142                        }
2143                        ArenaIndex::Internal(_) => {
2144                            let child = self.get_internal_mut(child);
2145                            child.parent = Some(parent);
2146                            child.parent_slot = slot as u8;
2147                        }
2148                    }
2149                }
2150                ans
2151            }
2152            None => LackInfo {
2153                parent_lack: Some(parent_idx),
2154            },
2155        };
2156        ans
2157    }
2158
2159    fn try_reduce_levels(&mut self) {
2160        let mut reduced = false;
2161        while self.get_internal(self.root).children.len() == 1 {
2162            let root = self.get_internal(self.root);
2163            if root.is_child_leaf() {
2164                break;
2165            }
2166
2167            let child_arena = root.children[0].arena;
2168            let child = self.in_nodes.remove(child_arena.unwrap_internal()).unwrap();
2169            let root = self.get_internal_mut(self.root);
2170            let _ = core::mem::replace(root, child);
2171            reduced = true;
2172            // root cache should be the same as child cache because there is only one child
2173        }
2174        if reduced {
2175            let root_idx = self.root;
2176            let root = self.get_internal_mut(self.root);
2177            root.parent = None;
2178            root.parent_slot = u8::MAX;
2179            self.reset_children_parent_pointer(root_idx);
2180        }
2181    }
2182
2183    fn reset_children_parent_pointer(&mut self, parent_idx: ArenaIndex) {
2184        let parent = self.in_nodes.get(parent_idx.unwrap_internal()).unwrap();
2185        let children = parent.children.clone();
2186        for child in children {
2187            match child.arena {
2188                ArenaIndex::Leaf(_) => {
2189                    let child = self.get_leaf_mut(child.arena);
2190                    child.parent = parent_idx.unwrap_internal();
2191                }
2192                ArenaIndex::Internal(_) => {
2193                    let child = self.get_internal_mut(child.arena);
2194                    child.parent = Some(parent_idx);
2195                }
2196            }
2197        }
2198    }
2199
2200    fn pair_neighbor(&self, this: ArenaIndex) -> Option<(Idx, Idx)> {
2201        let node = self.get_internal(this);
2202        let arr = node.parent_slot as usize;
2203        let parent = self.get_internal(node.parent.unwrap());
2204
2205        if arr == 0 {
2206            parent
2207                .children
2208                .get(1)
2209                .map(|x| (Idx::new(this, arr as u8), Idx::new(x.arena, 1)))
2210        } else {
2211            parent
2212                .children
2213                .get(arr - 1)
2214                .map(|x| (Idx::new(x.arena, arr as u8 - 1), Idx::new(this, arr as u8)))
2215        }
2216    }
2217
2218    /// Sometimes we cannot use diff because no only the given node is changed, but also its siblings.
2219    /// For example, after delete a range of nodes, we cannot use the diff from child to infer the diff of parent.
2220    pub fn recursive_update_cache(
2221        &mut self,
2222        mut node_idx: ArenaIndex,
2223        can_use_diff: bool,
2224        cache_diff: Option<B::CacheDiff>,
2225    ) {
2226        if let ArenaIndex::Leaf(index) = node_idx {
2227            let leaf = self.leaf_nodes.get(index).unwrap();
2228            let cache = B::get_elem_cache(&leaf.elem);
2229            node_idx = leaf.parent();
2230            let node = self.get_internal_mut(node_idx);
2231            node.children
2232                .iter_mut()
2233                .find(|x| x.arena.unwrap_leaf() == index)
2234                .unwrap()
2235                .cache = cache;
2236        }
2237
2238        if can_use_diff {
2239            if let Some(diff) = cache_diff {
2240                return self.recursive_update_cache_with_diff(node_idx, diff);
2241            }
2242        }
2243
2244        let mut this_idx = node_idx;
2245        let mut node = self.get_internal_mut(node_idx);
2246        let mut this_arr = node.parent_slot;
2247        if can_use_diff {
2248            if node.parent.is_some() {
2249                let parent_idx = node.parent.unwrap();
2250                let (parent, this) = self.get2_mut(parent_idx, this_idx);
2251                let diff =
2252                    this.calc_cache(&mut parent.children[this_arr as usize].cache, cache_diff);
2253                return self.recursive_update_cache_with_diff(parent_idx, diff);
2254            }
2255        } else {
2256            while node.parent.is_some() {
2257                let parent_idx = node.parent.unwrap();
2258                let (parent, this) = self.get2_mut(parent_idx, this_idx);
2259                this.calc_cache(&mut parent.children[this_arr as usize].cache, None);
2260                this_idx = parent_idx;
2261                this_arr = parent.parent_slot;
2262                node = parent;
2263            }
2264        }
2265
2266        let mut root_cache = std::mem::take(&mut self.root_cache);
2267        let root = self.root_mut();
2268        root.calc_cache(
2269            &mut root_cache,
2270            if can_use_diff { cache_diff } else { None },
2271        );
2272        self.root_cache = root_cache;
2273    }
2274
2275    fn recursive_update_cache_with_diff(&mut self, node_idx: ArenaIndex, diff: B::CacheDiff) {
2276        let mut node = self.get_internal_mut(node_idx);
2277        let mut this_arr = node.parent_slot;
2278        while node.parent.is_some() {
2279            let parent_idx = node.parent.unwrap();
2280            let parent = self.get_internal_mut(parent_idx);
2281            B::apply_cache_diff(&mut parent.children[this_arr as usize].cache, &diff);
2282            this_arr = parent.parent_slot;
2283            node = parent;
2284        }
2285
2286        B::apply_cache_diff(&mut self.root_cache, &diff);
2287    }
2288
2289    fn purge(&mut self, index: ArenaIndex) {
2290        let mut stack = vec![index];
2291        while let Some(x) = stack.pop() {
2292            if let ArenaIndex::Leaf(index) = x {
2293                self.leaf_nodes.remove(index);
2294
2295                continue;
2296            }
2297
2298            let Some(node) = self.in_nodes.remove(x.unwrap()) else {
2299                continue;
2300            };
2301
2302            for x in node.children.iter() {
2303                stack.push(x.arena);
2304            }
2305        }
2306    }
2307
2308    /// find the next sibling at the same level
2309    ///
2310    /// return false if there is no next sibling
2311    #[must_use]
2312    fn next_sibling(&self, path: &mut [Idx]) -> bool {
2313        if path.len() <= 1 {
2314            return false;
2315        }
2316
2317        let depth = path.len();
2318        let parent_idx = path[depth - 2];
2319        let this_idx = path[depth - 1];
2320        let parent = self.get_internal(parent_idx.arena);
2321        match parent.children.get(this_idx.arr as usize + 1) {
2322            Some(next) => {
2323                path[depth - 1] = Idx::new(next.arena, this_idx.arr + 1);
2324            }
2325            None => {
2326                if !self.next_sibling(&mut path[..depth - 1]) {
2327                    return false;
2328                }
2329
2330                let parent = self.get_internal(path[depth - 2].arena);
2331                path[depth - 1] = Idx::new(parent.children[0].arena, 0);
2332            }
2333        }
2334
2335        true
2336    }
2337
2338    fn next_same_level_in_node(&self, node_idx: ArenaIndex) -> Option<ArenaIndex> {
2339        match node_idx {
2340            ArenaIndex::Leaf(_) => {
2341                let leaf_idx = node_idx.unwrap_leaf();
2342                let leaf1 = self.leaf_nodes.get(leaf_idx).unwrap();
2343                let parent1 = self.get_internal(leaf1.parent());
2344                let (leaf, parent, index) =
2345                    (leaf1, parent1, Self::get_leaf_slot(leaf_idx, parent1));
2346                if index + 1 < parent.children.len() {
2347                    Some(parent.children[index + 1].arena)
2348                } else if let Some(parent_next) = self.next_same_level_in_node(leaf.parent()) {
2349                    let parent_next = self.get_internal(parent_next);
2350                    Some(parent_next.children.first().unwrap().arena)
2351                } else {
2352                    None
2353                }
2354            }
2355            ArenaIndex::Internal(_) => {
2356                let node = self.get_internal(node_idx);
2357                let parent = self.get_internal(node.parent?);
2358                if let Some(next) = parent.children.get(node.parent_slot as usize + 1) {
2359                    Some(next.arena)
2360                } else if let Some(parent_next) = self.next_same_level_in_node(node.parent?) {
2361                    let parent_next = self.get_internal(parent_next);
2362                    parent_next.children.first().map(|x| x.arena)
2363                } else {
2364                    None
2365                }
2366            }
2367        }
2368    }
2369
2370    fn prev_same_level_in_node(&self, node_idx: ArenaIndex) -> Option<ArenaIndex> {
2371        match node_idx {
2372            ArenaIndex::Leaf(leaf_idx) => {
2373                let leaf = self.leaf_nodes.get(leaf_idx).unwrap();
2374                let parent = self.get_internal(leaf.parent());
2375                let index = Self::get_leaf_slot(leaf_idx, parent);
2376                if index > 0 {
2377                    Some(parent.children[index - 1].arena)
2378                } else if let Some(parent_next) = self.prev_same_level_in_node(leaf.parent()) {
2379                    let parent_next = self.get_internal(parent_next);
2380                    Some(parent_next.children.last().unwrap().arena)
2381                } else {
2382                    None
2383                }
2384            }
2385            ArenaIndex::Internal(_) => {
2386                let node = self.get_internal(node_idx);
2387                let parent = self.get_internal(node.parent?);
2388                if node.parent_slot > 0 {
2389                    let Some(next) = parent.children.get(node.parent_slot as usize - 1) else {
2390                        unreachable!()
2391                    };
2392                    Some(next.arena)
2393                } else if let Some(parent_prev) = self.prev_same_level_in_node(node.parent?) {
2394                    let parent_prev = self.get_internal(parent_prev);
2395                    parent_prev.children.last().map(|x| x.arena)
2396                } else {
2397                    None
2398                }
2399            }
2400        }
2401    }
2402
2403    /// find the next element in the tree
2404    pub fn next_elem(&self, path: Cursor) -> Option<Cursor> {
2405        self.next_same_level_in_node(path.leaf.into())
2406            .map(|x| Cursor {
2407                leaf: x.unwrap_leaf().into(),
2408                offset: 0,
2409            })
2410    }
2411
2412    pub fn prev_elem(&self, path: Cursor) -> Option<Cursor> {
2413        self.prev_same_level_in_node(path.leaf.into())
2414            .map(|x| Cursor {
2415                leaf: x.unwrap_leaf().into(),
2416                offset: 0,
2417            })
2418    }
2419
2420    #[inline(always)]
2421    pub fn root_cache(&self) -> &B::Cache {
2422        &self.root_cache
2423    }
2424
2425    /// This method will release the memory back to OS.
2426    /// Currently, it's just `*self = Self::new()`
2427    #[inline(always)]
2428    pub fn clear(&mut self) {
2429        *self = Self::new();
2430    }
2431
2432    #[inline(always)]
2433    fn root_mut(&mut self) -> &mut Node<B> {
2434        self.get_internal_mut(self.root)
2435    }
2436
2437    #[inline(always)]
2438    pub fn is_empty(&self) -> bool {
2439        self.get_internal(self.root).is_empty()
2440    }
2441
2442    fn get_path(&self, idx: ArenaIndex) -> NodePath {
2443        let mut path = NodePath::new();
2444        let mut node_idx = idx;
2445        while node_idx != self.root {
2446            match node_idx {
2447                ArenaIndex::Leaf(inner_node_idx) => {
2448                    let node = self.leaf_nodes.get(inner_node_idx).unwrap();
2449                    let parent = self.in_nodes.get(node.parent).unwrap();
2450                    let index = Self::get_leaf_slot(inner_node_idx, parent);
2451                    path.push(Idx::new(node_idx, index as u8)).unwrap();
2452                    node_idx = ArenaIndex::Internal(node.parent);
2453                }
2454                ArenaIndex::Internal(_) => {
2455                    let node = self.get_internal(node_idx);
2456                    path.push(Idx::new(node_idx, node.parent_slot)).unwrap();
2457                    node_idx = node.parent.unwrap();
2458                }
2459            }
2460        }
2461        path.push(Idx::new(self.root, 0)).unwrap();
2462        path.reverse();
2463        path
2464    }
2465
2466    pub fn push(&mut self, elem: B::Elem) -> Cursor {
2467        let mut is_full = false;
2468        let mut parent_idx = self.root;
2469        let mut update_cache_idx = parent_idx;
2470        let cache = B::get_elem_cache(&elem);
2471        let ans = if self.is_empty() {
2472            let data = self.alloc_leaf_child(elem, parent_idx.unwrap());
2473            let parent = self.in_nodes.get_mut(parent_idx.unwrap()).unwrap();
2474            let ans = data.arena;
2475            parent.children.push(data).unwrap();
2476            Cursor {
2477                leaf: ans.unwrap().into(),
2478                offset: 0,
2479            }
2480        } else {
2481            let leaf_idx = self.last_leaf().unwrap();
2482            let leaf = self.leaf_nodes.get_mut(leaf_idx.0).unwrap();
2483            parent_idx = leaf.parent();
2484            if leaf.elem.can_merge(&elem) {
2485                update_cache_idx = leaf_idx.into();
2486                let offset = leaf.elem.rle_len();
2487                leaf.elem.merge_right(&elem);
2488                Cursor {
2489                    leaf: leaf_idx,
2490                    offset,
2491                }
2492            } else {
2493                let data = self.alloc_leaf_child(elem, parent_idx.unwrap());
2494                let parent = self.in_nodes.get_mut(parent_idx.unwrap()).unwrap();
2495                let ans = data.arena;
2496                update_cache_idx = parent_idx;
2497                parent.children.push(data).unwrap();
2498                is_full = parent.is_full();
2499                Cursor {
2500                    leaf: ans.unwrap().into(),
2501                    offset: 0,
2502                }
2503            }
2504        };
2505
2506        self.recursive_update_cache(
2507            update_cache_idx,
2508            B::USE_DIFF,
2509            if B::USE_DIFF {
2510                Some(B::new_cache_to_diff(&cache))
2511            } else {
2512                None
2513            },
2514        );
2515        if is_full {
2516            self.split(parent_idx);
2517        }
2518
2519        ans
2520    }
2521
2522    pub fn prepend(&mut self, elem: B::Elem) -> Cursor {
2523        let Some(leaf_idx) = self.first_leaf() else {
2524            let parent_idx = self.root;
2525            let data = self.alloc_leaf_child(elem, parent_idx.unwrap());
2526            let parent = self.in_nodes.get_mut(parent_idx.unwrap()).unwrap();
2527            let ans = data.arena;
2528            parent.children.push(data).unwrap();
2529            return Cursor {
2530                leaf: ans.unwrap().into(),
2531                offset: 0,
2532            };
2533        };
2534        let leaf = self.leaf_nodes.get_mut(leaf_idx.0).unwrap();
2535        let parent_idx = leaf.parent();
2536        let mut is_full = false;
2537        let ans = if elem.can_merge(&leaf.elem) {
2538            leaf.elem.merge_left(&elem);
2539            Cursor {
2540                leaf: leaf_idx,
2541                offset: 0,
2542            }
2543        } else {
2544            let parent_idx = leaf.parent;
2545            let data = self.alloc_leaf_child(elem, parent_idx);
2546            let parent = self.in_nodes.get_mut(parent_idx).unwrap();
2547            let ans = data.arena;
2548            parent.children.insert(0, data).unwrap();
2549            is_full = parent.is_full();
2550            Cursor {
2551                leaf: ans.unwrap().into(),
2552                offset: 0,
2553            }
2554        };
2555
2556        self.recursive_update_cache(leaf_idx.into(), B::USE_DIFF, None);
2557        if is_full {
2558            self.split(parent_idx);
2559        }
2560
2561        ans
2562    }
2563
2564    /// compare the position of a and b
2565    pub fn compare_pos(&self, a: Cursor, b: Cursor) -> Ordering {
2566        if a.leaf == b.leaf {
2567            return a.offset.cmp(&b.offset);
2568        }
2569
2570        let leaf_a = self.leaf_nodes.get(a.leaf.0).unwrap();
2571        let leaf_b = self.leaf_nodes.get(b.leaf.0).unwrap();
2572        let mut node_a = self.get_internal(leaf_a.parent());
2573        if leaf_a.parent == leaf_b.parent {
2574            for child in node_a.children.iter() {
2575                if child.arena.unwrap() == a.leaf.0 {
2576                    return Ordering::Less;
2577                }
2578                if child.arena.unwrap() == b.leaf.0 {
2579                    return Ordering::Greater;
2580                }
2581            }
2582        }
2583
2584        let mut node_b = self.get_internal(leaf_b.parent());
2585        while node_a.parent != node_b.parent {
2586            node_a = self.get_internal(node_a.parent.unwrap());
2587            node_b = self.get_internal(node_b.parent.unwrap());
2588        }
2589
2590        node_a.parent_slot.cmp(&node_b.parent_slot)
2591    }
2592
2593    /// Iterate the caches of previous nodes/elements.
2594    /// This method will visit as less caches as possible.
2595    /// For example, if all nodes in a subtree need to be visited, we will only visit the root cache.
2596    ///
2597    /// f: (node_cache, previous_sibling_elem, (this_elem, offset))
2598    pub fn visit_previous_caches<F>(&self, cursor: Cursor, mut f: F)
2599    where
2600        F: FnMut(PreviousCache<'_, B>),
2601    {
2602        // the last index of path points to the leaf element
2603        let path = self.get_path(cursor.leaf.into());
2604        let mut path_index = 0;
2605        let mut child_index = 0;
2606        let mut node = self.get_internal(path[path_index].arena);
2607        'outer: loop {
2608            if path_index + 1 >= path.len() {
2609                break;
2610            }
2611
2612            while child_index == path.get(path_index + 1).map(|x| x.arr).unwrap() {
2613                path_index += 1;
2614                if path_index + 1 < path.len() {
2615                    node = self.get_internal(path[path_index].arena);
2616                    child_index = 0;
2617                } else {
2618                    break 'outer;
2619                }
2620            }
2621
2622            f(PreviousCache::NodeCache(
2623                &node.children[child_index as usize].cache,
2624            ));
2625            child_index += 1;
2626        }
2627
2628        let node = self.leaf_nodes.get(cursor.leaf.0).unwrap();
2629        f(PreviousCache::ThisElemAndOffset {
2630            elem: &node.elem,
2631            offset: cursor.offset,
2632        });
2633    }
2634
2635    pub fn diagnose_balance(&self) {
2636        let mut size_counter: FxHashMap<usize, usize> = Default::default();
2637        for (_, node) in self.in_nodes.iter() {
2638            *size_counter.entry(node.children.len()).or_default() += 1;
2639        }
2640        dbg!(size_counter);
2641
2642        let mut size_counter: FxHashMap<usize, usize> = Default::default();
2643        for (_, node) in self.leaf_nodes.iter() {
2644            *size_counter.entry(node.elem.rle_len()).or_default() += 1;
2645        }
2646        dbg!(size_counter);
2647    }
2648
2649    /// Iterate over the leaf elements in the tree if the filter returns true for all its ancestors' caches, including its own cache.
2650    pub fn iter_with_filter<'a, R: Default + Copy + AddAssign + 'a>(
2651        &'a self,
2652        mut f: impl FnMut(&B::Cache) -> (bool, R) + 'a,
2653    ) -> impl Iterator<Item = (R, &'_ B::Elem)> + '_ {
2654        let mut queue = VecDeque::new();
2655        queue.push_back((self.root, R::default()));
2656        std::iter::from_fn(move || {
2657            while let Some((node_idx, mut r)) = queue.pop_front() {
2658                match node_idx {
2659                    ArenaIndex::Leaf(leaf) => {
2660                        let node = self.leaf_nodes.get(leaf).unwrap();
2661                        return Some((r, &node.elem));
2662                    }
2663                    ArenaIndex::Internal(idx) => {
2664                        let node = self.in_nodes.get(idx).unwrap();
2665                        for child in node.children.iter() {
2666                            let (drill, new_r) = f(&child.cache);
2667                            if drill {
2668                                queue.push_back((child.arena, r));
2669                            }
2670                            r += new_r;
2671                        }
2672                    }
2673                }
2674            }
2675
2676            None
2677        })
2678    }
2679
2680    /// This method allows users to update the caches and the elements with a filter.
2681    ///
2682    /// If `f` returns true for a node, it will drill down into the subtree whose root is the node.
2683    ///
2684    /// It's the caller's responsibility to ensure the invariance of caches being up to date.
2685    pub fn update_cache_and_elem_with_filter<'a>(
2686        &'a mut self,
2687        mut f: impl FnMut(&mut B::Cache) -> bool + 'a,
2688        mut g: impl FnMut(&mut B::Elem) + 'a,
2689    ) {
2690        let mut stack = vec![self.root];
2691        while let Some(node_idx) = stack.pop() {
2692            match node_idx {
2693                ArenaIndex::Leaf(leaf) => {
2694                    let node = self.leaf_nodes.get_mut(leaf).unwrap();
2695                    g(&mut node.elem);
2696                }
2697                ArenaIndex::Internal(idx) => {
2698                    let node = self.in_nodes.get_mut(idx).unwrap();
2699                    for child in node.children.iter_mut() {
2700                        if f(&mut child.cache) {
2701                            stack.push(child.arena);
2702                        }
2703                    }
2704                }
2705            }
2706        }
2707    }
2708
2709    pub fn depth(&self) -> usize {
2710        let mut depth = 0;
2711        let mut index = self.root;
2712        let mut node = self.in_nodes.get(index.unwrap_internal()).unwrap();
2713        loop {
2714            depth += 1;
2715            index = node.children.first().unwrap().arena;
2716            match index {
2717                ArenaIndex::Leaf(_) => return depth,
2718                ArenaIndex::Internal(index) => {
2719                    node = self.in_nodes.get(index).unwrap();
2720                }
2721            }
2722        }
2723    }
2724
2725    pub fn internal_avg_children_num(&self) -> f64 {
2726        let mut sum = 0;
2727        for (_, node) in self.in_nodes.iter() {
2728            sum += node.children.len();
2729        }
2730        sum as f64 / self.in_nodes.len() as f64
2731    }
2732}
2733
2734fn merge_adj<E: Mergeable + Debug>(data: &mut Vec<E>) {
2735    // Merge adjacent elements
2736    let mut i = 0;
2737    let last = data.len() - 1;
2738    let mut to_delete_start = 0;
2739    let mut del_len = 0;
2740    while i < last {
2741        if data[i].can_merge(&data[i + 1]) {
2742            let (a, b) = arref::mut_twice(data.as_mut_slice(), i, i + 1).unwrap();
2743            a.merge_right(b);
2744            if del_len == 0 {
2745                to_delete_start = i + 1;
2746            }
2747
2748            data.swap(i + 1, to_delete_start + del_len);
2749            del_len += 1;
2750            i += 1;
2751        }
2752        i += 1;
2753    }
2754
2755    if del_len > 0 {
2756        data.drain(to_delete_start..to_delete_start + del_len);
2757    }
2758}
2759
2760pub enum PreviousCache<'a, B: BTreeTrait> {
2761    NodeCache(&'a B::Cache),
2762    PrevSiblingElem(&'a B::Elem),
2763    ThisElemAndOffset { elem: &'a B::Elem, offset: usize },
2764}
2765
2766#[inline(always)]
2767fn add_leaf_dirty_map<T>(leaf: ArenaIndex, dirty_map: &mut LeafDirtyMap<T>, leaf_diff: T) {
2768    dirty_map.insert(leaf, leaf_diff);
2769}
2770
2771impl<B: BTreeTrait> BTree<B> {
2772    pub fn check(&self) {
2773        // check cache
2774        let mut leaf_level = None;
2775        for (index, node) in self.in_nodes.iter() {
2776            if index != self.root.unwrap() {
2777                assert!(!node.is_empty());
2778            }
2779
2780            for (i, child_info) in node.children.iter().enumerate() {
2781                if matches!(child_info.arena, ArenaIndex::Internal(_)) {
2782                    assert!(!node.is_child_leaf());
2783                    let child = self.get_internal(child_info.arena);
2784                    let mut cache = Default::default();
2785                    child.calc_cache(&mut cache, None);
2786                    assert_eq!(child.parent_slot, i as u8);
2787                    assert_eq!(child.parent, Some(ArenaIndex::Internal(index)));
2788                    assert_eq!(
2789                        cache, child_info.cache,
2790                        "index={:?} child_index={:?}",
2791                        index, child_info.arena
2792                    );
2793                }
2794            }
2795
2796            if let Some(parent) = node.parent {
2797                let parent = self.get_internal(parent);
2798                assert_eq!(
2799                    parent.children[node.parent_slot as usize].arena,
2800                    ArenaIndex::Internal(index)
2801                );
2802                self.get_path(ArenaIndex::Internal(index));
2803            } else {
2804                assert_eq!(index, self.root.unwrap_internal())
2805            }
2806
2807            // if index != self.root.unwrap() {
2808            //     assert!(!node.is_lack(), "len={}\n", node.len());
2809            // }
2810            //
2811            // assert!(!node.is_full(), "len={}", node.len());
2812        }
2813
2814        let root = self.get_internal(self.root);
2815        let mut root_cache = Default::default();
2816        root.calc_cache(&mut root_cache, None);
2817        assert_eq!(&self.root_cache, &root_cache);
2818
2819        for (leaf_index, leaf_node) in self.leaf_nodes.iter() {
2820            let mut length = 1;
2821            let mut node_idx = leaf_node.parent;
2822            while node_idx != self.root.unwrap() {
2823                let node = self.get_internal(ArenaIndex::Internal(node_idx));
2824                length += 1;
2825                node_idx = node.parent.unwrap().unwrap();
2826            }
2827            match leaf_level {
2828                Some(expected) => {
2829                    if length != expected {
2830                        dbg!(leaf_index, leaf_node);
2831                        assert_eq!(length, expected);
2832                    }
2833                }
2834                None => {
2835                    leaf_level = Some(length);
2836                }
2837            }
2838
2839            let cache = B::get_elem_cache(&leaf_node.elem);
2840            let parent = self.get_internal(leaf_node.parent());
2841            assert_eq!(
2842                parent
2843                    .children
2844                    .iter()
2845                    .find(|x| x.arena.unwrap_leaf() == leaf_index)
2846                    .unwrap()
2847                    .cache,
2848                cache
2849            );
2850            self.get_path(ArenaIndex::Leaf(leaf_index));
2851        }
2852    }
2853}
2854
2855impl<B: BTreeTrait, T: Into<B::Elem>> FromIterator<T> for BTree<B> {
2856    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2857        let mut tree = Self::new();
2858        let iter = iter.into_iter();
2859        let min_size = iter.size_hint().0;
2860        tree.leaf_nodes.reserve(min_size);
2861        let max_child_size = MAX_CHILDREN_NUM - 2;
2862
2863        struct TempInternalNode<B: BTreeTrait> {
2864            children: HeaplessVec<Child<B>, MAX_CHILDREN_NUM>,
2865            cache: B::Cache,
2866            arena_index: RawArenaIndex,
2867        }
2868
2869        let parent_num = (min_size + max_child_size - 1) / max_child_size;
2870        let mut internal_nodes: Vec<TempInternalNode<B>> = Vec::with_capacity(parent_num);
2871        let index = tree.in_nodes.insert(Default::default());
2872        internal_nodes.push(TempInternalNode {
2873            children: Default::default(),
2874            cache: Default::default(),
2875            arena_index: index,
2876        });
2877
2878        // create all leaf nodes and their parents
2879        for elem in iter {
2880            let parent = match internal_nodes.last_mut() {
2881                Some(last) if last.children.len() < max_child_size => last,
2882                Some(last) => {
2883                    // calculate cache
2884                    B::calc_cache_internal(&mut last.cache, &last.children);
2885                    let index = tree.in_nodes.insert(Default::default());
2886                    internal_nodes.push(TempInternalNode {
2887                        children: Default::default(),
2888                        cache: Default::default(),
2889                        arena_index: index,
2890                    });
2891                    internal_nodes.last_mut().unwrap()
2892                }
2893                _ => unreachable!(),
2894            };
2895
2896            let leaf = LeafNode {
2897                elem: elem.into(),
2898                parent: parent.arena_index,
2899            };
2900
2901            let cache = B::get_elem_cache(&leaf.elem);
2902            let leaf_index = tree.leaf_nodes.insert(leaf);
2903            parent
2904                .children
2905                .push(Child {
2906                    arena: ArenaIndex::Leaf(leaf_index),
2907                    cache,
2908                })
2909                .unwrap();
2910        }
2911
2912        // recursively create the internal nodes in higher level, until we reach root
2913        while internal_nodes.len() > 1 {
2914            let parent_num = (internal_nodes.len() + max_child_size - 1) / max_child_size;
2915            let children = std::mem::replace(&mut internal_nodes, Vec::with_capacity(parent_num));
2916            let index = tree.in_nodes.insert(Default::default());
2917            internal_nodes.push(TempInternalNode {
2918                children: Default::default(),
2919                cache: Default::default(),
2920                arena_index: index,
2921            });
2922
2923            let mut parent_slot = 0;
2924            // eprintln!(
2925            //     "children.len={} max_child_size={}",
2926            //     children.len(),
2927            //     max_child_size
2928            // );
2929            for mut child in children {
2930                let parent = match internal_nodes.last_mut() {
2931                    Some(last) if last.children.len() < max_child_size => last,
2932                    Some(last) => {
2933                        // calculate cache
2934                        B::calc_cache_internal(&mut last.cache, &last.children);
2935                        let index = tree.in_nodes.insert(Default::default());
2936                        internal_nodes.push(TempInternalNode {
2937                            children: Default::default(),
2938                            cache: Default::default(),
2939                            arena_index: index,
2940                        });
2941                        internal_nodes.last_mut().unwrap()
2942                    }
2943                    _ => unreachable!(),
2944                };
2945
2946                B::calc_cache_internal(&mut child.cache, &child.children);
2947                let child_node = tree.in_nodes.get_mut(child.arena_index).unwrap();
2948                child_node.children = child.children;
2949                child_node.parent = Some(ArenaIndex::Internal(parent.arena_index));
2950                child_node.parent_slot = parent_slot;
2951                parent_slot = (parent_slot + 1) % (max_child_size as u8);
2952                parent
2953                    .children
2954                    .push(Child {
2955                        arena: ArenaIndex::Internal(child.arena_index),
2956                        cache: child.cache,
2957                    })
2958                    .unwrap();
2959            }
2960
2961            debug_assert_eq!(parent_num, internal_nodes.len());
2962        }
2963
2964        debug_assert_eq!(internal_nodes.len(), 1);
2965        let node = internal_nodes.remove(0);
2966        B::calc_cache_internal(&mut tree.root_cache, &node.children);
2967        tree.in_nodes.remove(tree.root.unwrap());
2968        tree.root = ArenaIndex::Internal(node.arena_index);
2969        let root = tree.root.unwrap();
2970        tree.in_nodes.get_mut(root).unwrap().children = node.children;
2971        tree
2972    }
2973}
2974
2975struct SplitInfo {
2976    new_pos: Option<Cursor>,
2977    left_neighbour: Option<LeafIndex>,
2978    parent_idx: RawArenaIndex,
2979    insert_slot: usize,
2980    new_leaf: Option<ArenaIndex>,
2981}
2982
2983impl<B: BTreeTrait> Default for BTree<B> {
2984    fn default() -> Self {
2985        Self::new()
2986    }
2987}
2988
2989fn delete_range<T: Clone, const N: usize>(
2990    arr: &mut heapless::Vec<T, N>,
2991    range: impl RangeBounds<usize>,
2992) {
2993    let start = match range.start_bound() {
2994        std::ops::Bound::Included(x) => *x,
2995        std::ops::Bound::Excluded(x) => x + 1,
2996        std::ops::Bound::Unbounded => 0,
2997    };
2998    let end = match range.end_bound() {
2999        std::ops::Bound::Included(x) => x + 1,
3000        std::ops::Bound::Excluded(x) => *x,
3001        std::ops::Bound::Unbounded => arr.len(),
3002    };
3003
3004    if start == end {
3005        return;
3006    }
3007
3008    if end - start == 1 {
3009        arr.remove(start);
3010        return;
3011    }
3012
3013    let mut ans = heapless::Vec::from_slice(&arr[..start]).unwrap();
3014    ans.extend_from_slice(&arr[end..]).unwrap();
3015    *arr = ans;
3016}