Skip to main content

reddb_engine/storage/
btree.rs

1//! B+ Tree Implementation for Page-Based Storage
2//!
3//! A B+ tree optimized for disk I/O with the following properties:
4//! - All values stored in leaf nodes
5//! - Interior nodes only contain keys and child pointers
6//! - Leaf nodes form a doubly-linked list for range scans
7//! - Each node fits in a single 16 KiB page
8//!
9//! # Page Layout
10//!
11//! Interior Node:
12//! ```text
13//! ┌────────────────────────────────────────────────────────────┐
14//! │ PageHeader (32 bytes)                                      │
15//! ├────────────────────────────────────────────────────────────┤
16//! │ right_child: u32 - Rightmost child pointer                 │
17//! │ cells: [key_len: u16, key: [u8], child: u32]...           │
18//! └────────────────────────────────────────────────────────────┘
19//! ```
20//!
21//! Leaf Node:
22//! ```text
23//! ┌────────────────────────────────────────────────────────────┐
24//! │ PageHeader (32 bytes)                                      │
25//! ├────────────────────────────────────────────────────────────┤
26//! │ prev_leaf: u32 - Previous leaf (0 = none)                  │
27//! │ next_leaf: u32 - Next leaf (0 = none)                      │
28//! │ cells: [key_len: u16, val_len: u16, key: [u8], val: [u8]] │
29//! └────────────────────────────────────────────────────────────┘
30//! ```
31
32use std::cmp::Ordering;
33use std::sync::{Arc, RwLock};
34
35use super::page::{Page, PageType, HEADER_SIZE, PAGE_SIZE};
36use super::page_store::PageStore;
37use super::pager::PagerError;
38
39/// Maximum key size (to ensure at least 2 keys per node)
40pub const MAX_KEY_SIZE: usize = 1024;
41
42/// Hard upper bound on logical value size.
43///
44/// Per ADR 0023 (large-value overflow), values up to 256 MiB are stored
45/// transparently — inline below [`value_layout::OVERFLOW_THRESHOLD`],
46/// inline+compressed when LZ4 shrinks them under the same threshold, or
47/// spilled into an [`overflow::OverflowChain`] otherwise. Values above
48/// this ceiling are rejected with [`BTreeError::ValueTooLarge`] before
49/// any compression or page allocation runs.
50///
51/// Re-exported from [`value_layout::MAX_VALUE_SIZE`] so callers that
52/// historically read this constant (`unified::store::impl_pages`,
53/// `query::planner::stats_catalog`) continue to compile.
54pub const MAX_VALUE_SIZE: usize = value_layout::MAX_VALUE_SIZE;
55
56/// Minimum fill factor before merge (as percentage)
57pub const MIN_FILL_FACTOR: usize = 25;
58
59/// Offset of prev_leaf in leaf page
60const LEAF_PREV_OFFSET: usize = HEADER_SIZE;
61
62/// Offset of next_leaf in leaf page
63const LEAF_NEXT_OFFSET: usize = HEADER_SIZE + 4;
64
65/// Start of the slot array in leaf pages.
66///
67/// Slotted-page layout:
68/// ```text
69/// [PageHeader 32B][prev u32 | next u32 | 8B]
70/// [slot 0: u16][slot 1: u16]...[slot N-1: u16]  ← grows forward
71/// ... free space ...
72/// [cell N-1][cell N-2]...[cell 0]               ← grows backward from free_end
73/// ```
74/// Each cell is laid out as `[key_len:u16][val_len:u16][key][val]`.
75/// `page.cell_count()` is N; `page.free_end()` is the offset of the
76/// lowest (most recently written) cell. The slot array lives right
77/// after the leaf-chain links and each u16 slot is the absolute page
78/// offset of its cell.
79const LEAF_SLOT_ARRAY_OFFSET: usize = HEADER_SIZE + 8;
80
81// A split must still fit two maximum-key inline cells, including the value
82// flag, cell headers and slot pointers, after the native page-size change.
83const _: () = assert!(
84    2 * (MAX_KEY_SIZE + value_layout::OVERFLOW_THRESHOLD + 1 + 4 + 2)
85        <= PAGE_SIZE - LEAF_SLOT_ARRAY_OFFSET
86);
87
88/// Kept for source-compat with older code paths (e.g. interior-node
89/// helpers); equivalent to `LEAF_SLOT_ARRAY_OFFSET` for leaves.
90const LEAF_DATA_OFFSET: usize = LEAF_SLOT_ARRAY_OFFSET;
91
92/// Start of cell data in interior pages (right_child is in header)
93const INTERIOR_DATA_OFFSET: usize = HEADER_SIZE;
94
95/// B+ Tree error types
96#[derive(Debug, Clone)]
97pub enum BTreeError {
98    /// Key not found
99    NotFound,
100    /// Key already exists
101    DuplicateKey,
102    /// Key too large
103    KeyTooLarge(usize),
104    /// Value too large
105    ValueTooLarge(usize),
106    /// Tree is corrupted
107    Corrupted(String),
108    /// Pager error
109    Pager(String),
110    /// Internal lock was poisoned by a panicked thread
111    LockPoisoned(String),
112    /// Large-value layout encode/decode failed (overflow chain or LZ4).
113    ValueLayout(String),
114    /// Materializing a value would exceed the caller's read memory allowance.
115    ReadLimitExceeded {
116        required_bytes: usize,
117        limit_bytes: usize,
118    },
119}
120
121impl std::fmt::Display for BTreeError {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        match self {
124            Self::NotFound => write!(f, "Key not found"),
125            Self::DuplicateKey => write!(f, "Key already exists"),
126            Self::KeyTooLarge(size) => {
127                write!(f, "Key too large: {} bytes (max {})", size, MAX_KEY_SIZE)
128            }
129            Self::ValueTooLarge(size) => write!(
130                f,
131                "Value too large: {} bytes (max {})",
132                size, MAX_VALUE_SIZE
133            ),
134            Self::Corrupted(msg) => write!(f, "B-tree corrupted: {}", msg),
135            Self::Pager(msg) => write!(f, "Pager error: {}", msg),
136            Self::LockPoisoned(msg) => write!(f, "Lock poisoned: {}", msg),
137            Self::ValueLayout(msg) => write!(f, "Value layout: {}", msg),
138            Self::ReadLimitExceeded {
139                required_bytes,
140                limit_bytes,
141            } => write!(
142                f,
143                "B-tree read needs {required_bytes} bytes over read memory limit {limit_bytes}"
144            ),
145        }
146    }
147}
148
149impl From<value_layout::ValueLayoutError> for BTreeError {
150    fn from(e: value_layout::ValueLayoutError) -> Self {
151        match e {
152            value_layout::ValueLayoutError::ValueTooLarge(n) => Self::ValueTooLarge(n),
153            value_layout::ValueLayoutError::ReadLimitExceeded {
154                required_bytes,
155                limit_bytes,
156            } => Self::ReadLimitExceeded {
157                required_bytes,
158                limit_bytes,
159            },
160            other => Self::ValueLayout(other.to_string()),
161        }
162    }
163}
164
165impl std::error::Error for BTreeError {}
166
167impl From<PagerError> for BTreeError {
168    fn from(e: PagerError) -> Self {
169        Self::Pager(e.to_string())
170    }
171}
172
173impl From<super::page::PageError> for BTreeError {
174    fn from(e: super::page::PageError) -> Self {
175        Self::Corrupted(e.to_string())
176    }
177}
178
179/// Result type for B+ tree operations
180pub type BTreeResult<T> = Result<T, BTreeError>;
181
182/// B+ Tree cursor for iteration
183pub struct BTreeCursor<P: PageStore> {
184    /// A cursor can outlive the tree handle that created it.
185    _retirement_pin: Arc<()>,
186    /// Current leaf page ID
187    leaf_page_id: u32,
188    /// Current position within leaf
189    position: usize,
190    /// Pager reference
191    pager: Arc<page_proofs::TreePageStore<P>>,
192    /// A6 — true once we've issued a prefetch hint for the next leaf on
193    /// this leaf. Reset to false every time we move to a new leaf so the
194    /// hint fires once per leaf, at the halfway point.
195    prefetched_next: bool,
196    /// Published collection generations are immutable. Retain at most one
197    /// leaf while walking them; mutable-tree cursors keep re-reading pages.
198    immutable: bool,
199    immutable_leaf: Option<Box<Page>>,
200}
201
202/// Point lookups in ascending key order that keep the leaf of the last one.
203///
204/// `get` walks from the root for every key. A checkpoint asks about
205/// thousands of keys of one tree in order, most of them neighbours: this
206/// answers from the leaf in hand while the next key can only be there.
207/// It reads the tree as each leaf was when it was read, so it is for a caller
208/// that owns the tree's writes while it asks, as a checkpoint does.
209pub struct SortedProbe<'a, P: PageStore> {
210    tree: &'a BTree<P>,
211    leaf: Option<Page>,
212    last: Vec<u8>,
213}
214
215impl<P: PageStore> SortedProbe<'_, P> {
216    /// The value under `key`, which is not lower than the previous call's.
217    pub fn get(&mut self, key: &[u8], limit_bytes: usize) -> BTreeResult<Option<Vec<u8>>> {
218        if !self.holds(key)? {
219            self.leaf = self.tree.leaf_for(key)?;
220        }
221        let Some(page) = &self.leaf else {
222            return Ok(None);
223        };
224        match search_leaf(page, key)? {
225            SearchResult::Found(position) => {
226                let (_, stored) = read_leaf_cell_borrowed(page, position)?;
227                Ok(Some(decode_leaf_value(
228                    self.tree.pager.as_ref(),
229                    page,
230                    stored,
231                    limit_bytes,
232                )?))
233            }
234            SearchResult::NotFound(_) => Ok(None),
235        }
236    }
237
238    /// Whether `key` is in the tree; see [`Self::get`] for the order of keys.
239    pub fn contains(&mut self, key: &[u8]) -> BTreeResult<bool> {
240        if !self.holds(key)? {
241            self.leaf = self.tree.leaf_for(key)?;
242        }
243        Ok(match &self.leaf {
244            Some(page) => matches!(search_leaf(page, key)?, SearchResult::Found(_)),
245            None => false,
246        })
247    }
248
249    /// Whether the leaf in hand is the only one `key` can be in. Keys ascend,
250    /// so `key` is not before this leaf; it is not after it if the leaf holds
251    /// a key at least as high, or is the last one. A key that does not ascend
252    /// is looked up from the root like any first one.
253    fn holds(&mut self, key: &[u8]) -> BTreeResult<bool> {
254        let ascends = key >= self.last.as_slice();
255        self.last.clear();
256        self.last.extend_from_slice(key);
257        match &self.leaf {
258            Some(page) if ascends => leaf_holds_ascending(page, key),
259            _ => Ok(false),
260        }
261    }
262}
263
264/// Whether `key`, not lower than a key already routed to `page`, belongs to
265/// that leaf too: the leaf has a key at least as high, or no leaf follows it.
266fn leaf_holds_ascending(page: &Page, key: &[u8]) -> BTreeResult<bool> {
267    if leaf_right_sibling(page) == 0 {
268        return Ok(true);
269    }
270    let cells = usize::from(page.cell_count());
271    Ok(cells > 0 && key <= read_leaf_cell_borrowed(page, cells - 1)?.0)
272}
273
274impl<P: PageStore> BTreeCursor<P> {
275    /// Copy the position of an immutable cursor without advancing the original.
276    pub(crate) fn fork_immutable(&self) -> Self {
277        assert!(self.immutable, "only immutable cursors may be forked");
278        Self {
279            _retirement_pin: Arc::clone(&self._retirement_pin),
280            leaf_page_id: self.leaf_page_id,
281            position: self.position,
282            pager: Arc::clone(&self.pager),
283            prefetched_next: self.prefetched_next,
284            immutable: true,
285            immutable_leaf: self.immutable_leaf.clone(),
286        }
287    }
288
289    /// Only collection readers whose host pins an immutable published root
290    /// may retain a leaf across calls. This is not a mutable-tree snapshot.
291    pub(crate) fn with_immutable_leaves(mut self) -> Self {
292        self.immutable = true;
293        self
294    }
295
296    fn prepare_immutable_leaf(&mut self) -> BTreeResult<bool> {
297        if self.leaf_page_id == 0 {
298            return Ok(false);
299        }
300        if self.immutable_leaf.is_none() {
301            let page = self.pager.read_page(self.leaf_page_id)?;
302            if page.page_type()? != PageType::BTreeLeaf {
303                return Err(BTreeError::Corrupted(
304                    "cursor reached a non-leaf page".into(),
305                ));
306            }
307            self.immutable_leaf = Some(Box::new(page));
308        }
309        let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
310        if self.position < usize::from(page.cell_count()) {
311            return Ok(true);
312        }
313        let next = read_next_leaf(page);
314        if next == 0 {
315            self.leaf_page_id = 0;
316            self.immutable_leaf = None;
317            return Ok(false);
318        }
319        let next_page = self.pager.read_page(next)?;
320        if next_page.page_type()? != PageType::BTreeLeaf || next_page.cell_count() == 0 {
321            return Err(BTreeError::Corrupted(
322                "leaf chain reached an invalid leaf".into(),
323            ));
324        }
325        let first_key = read_leaf_cell_borrowed(&next_page, 0)?.0;
326        if leaf_high_key(page)?
327            .as_ref()
328            .is_some_and(|key| first_key <= key.as_slice())
329        {
330            return Err(BTreeError::Corrupted(
331                "leaf chain does not advance its key range".into(),
332            ));
333        }
334        **self.immutable_leaf.as_mut().expect("loaded immutable leaf") = next_page;
335        self.leaf_page_id = next;
336        self.position = 0;
337        self.prefetched_next = false;
338        Ok(true)
339    }
340
341    /// Inspect the next key without materializing its value or advancing.
342    #[cfg(feature = "full")]
343    pub(crate) fn peek_key_with<T>(
344        &mut self,
345        visit: impl FnOnce(&[u8]) -> T,
346    ) -> BTreeResult<Option<T>> {
347        if self.immutable {
348            if !self.prepare_immutable_leaf()? {
349                return Ok(None);
350            }
351            let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
352            return Ok(Some(visit(read_leaf_cell_borrowed(page, self.position)?.0)));
353        }
354        let Some(page) = self.prepare_next_leaf()? else {
355            return Ok(None);
356        };
357        Ok(Some(visit(
358            read_leaf_cell_borrowed(&page, self.position)?.0,
359        )))
360    }
361
362    /// Inspect the next key without materializing its value or advancing.
363    pub fn peek_key(&mut self) -> BTreeResult<Option<Vec<u8>>> {
364        if self.immutable {
365            if !self.prepare_immutable_leaf()? {
366                return Ok(None);
367            }
368            let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
369            return Ok(Some(
370                read_leaf_cell_borrowed(page, self.position)?.0.to_vec(),
371            ));
372        }
373        let Some(page) = self.prepare_next_leaf()? else {
374            return Ok(None);
375        };
376        Ok(Some(read_leaf_cell(&page, self.position)?.0))
377    }
378
379    /// Skip a shadowed or deleted base record without reading its overflow value.
380    pub fn skip_next(&mut self) -> BTreeResult<bool> {
381        if self.immutable {
382            if !self.prepare_immutable_leaf()? {
383                return Ok(false);
384            }
385            self.position += 1;
386            return Ok(true);
387        }
388        if self.prepare_next_leaf()?.is_none() {
389            return Ok(false);
390        }
391        self.position += 1;
392        Ok(true)
393    }
394
395    fn prepare_next_leaf(&mut self) -> BTreeResult<Option<Page>> {
396        if self.leaf_page_id == 0 {
397            return Ok(None);
398        }
399        let page = self.pager.read_page(self.leaf_page_id)?;
400        if page.page_type()? != PageType::BTreeLeaf {
401            return Err(BTreeError::Corrupted(
402                "cursor reached a non-leaf page".into(),
403            ));
404        }
405        if self.position < usize::from(page.cell_count()) {
406            return Ok(Some(page));
407        }
408        let next = read_next_leaf(&page);
409        if next == 0 {
410            self.leaf_page_id = 0;
411            return Ok(None);
412        }
413        let next_page = self.pager.read_page(next)?;
414        if next_page.page_type()? != PageType::BTreeLeaf || next_page.cell_count() == 0 {
415            return Err(BTreeError::Corrupted(
416                "leaf chain reached an invalid leaf".into(),
417            ));
418        }
419        let first_key = read_leaf_cell(&next_page, 0)?.0;
420        if leaf_high_key(&page)?
421            .as_ref()
422            .is_some_and(|key| first_key <= *key)
423        {
424            return Err(BTreeError::Corrupted(
425                "leaf chain does not advance its key range".into(),
426            ));
427        }
428        self.leaf_page_id = next;
429        self.position = 0;
430        self.prefetched_next = false;
431        Ok(Some(next_page))
432    }
433
434    /// Read one value within the caller's materialization allowance.
435    pub fn next_with_budget(
436        &mut self,
437        limit_bytes: usize,
438    ) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
439        self.next_impl(limit_bytes)
440    }
441
442    /// Move to next entry
443    pub fn next(&mut self) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
444        self.next_impl(usize::MAX)
445    }
446
447    fn next_impl(&mut self, limit_bytes: usize) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
448        if self.immutable {
449            return self.next_immutable(limit_bytes);
450        }
451        if self.leaf_page_id == 0 {
452            return Ok(None);
453        }
454
455        let page = self.pager.read_page(self.leaf_page_id)?;
456        if page.page_type()? != PageType::BTreeLeaf {
457            return Err(BTreeError::Corrupted(
458                "cursor reached a non-leaf page".into(),
459            ));
460        }
461        let cell_count = page.cell_count() as usize;
462
463        // A6 — prefetch the next leaf when we cross the halfway point of
464        // the current one. The hint fires at most once per leaf (guarded
465        // by `prefetched_next`) so the syscall overhead is amortized over
466        // ~half a leaf's worth of entries. The kernel uses the hint to
467        // start DMA-ing the next page while we finish the current one.
468        if !self.prefetched_next && self.position >= cell_count / 2 && cell_count > 0 {
469            let next_leaf = read_next_leaf(&page);
470            if next_leaf != 0 {
471                self.pager.prefetch_hint(next_leaf);
472            }
473            self.prefetched_next = true;
474        }
475
476        // Check if we have more cells in current page
477        if self.position < cell_count {
478            let (key, stored) = read_leaf_cell_borrowed(&page, self.position)?;
479            let value = decode_leaf_value(self.pager.as_ref(), &page, stored, limit_bytes)?;
480            self.position += 1;
481            return Ok(Some((key.to_vec(), value)));
482        }
483
484        // Move to next leaf
485        let next_leaf = read_next_leaf(&page);
486        if next_leaf == 0 {
487            self.leaf_page_id = 0;
488            return Ok(None);
489        }
490        let previous_high_key = leaf_high_key(&page)?;
491
492        self.leaf_page_id = next_leaf;
493        self.position = 0;
494        self.prefetched_next = false; // reset for the new leaf
495
496        // Read from new leaf
497        let page = self.pager.read_page(self.leaf_page_id)?;
498        if page.page_type()? != PageType::BTreeLeaf {
499            return Err(BTreeError::Corrupted(
500                "leaf chain reached a non-leaf page".into(),
501            ));
502        }
503        if page.cell_count() == 0 {
504            return Ok(None);
505        }
506
507        let (key, stored) = read_leaf_cell_borrowed(&page, 0)?;
508        // Every leaf transition must advance the key range. This bounds a
509        // corrupt cyclic chain without growing a visited-page set or an
510        // unbounded checkpoint buffer (#2376).
511        if previous_high_key
512            .as_ref()
513            .is_some_and(|previous| key <= previous.as_slice())
514        {
515            self.leaf_page_id = 0;
516            return Err(BTreeError::Corrupted(
517                "leaf chain does not advance its key range".into(),
518            ));
519        }
520        let value = decode_leaf_value(self.pager.as_ref(), &page, stored, limit_bytes)?;
521        self.position = 1;
522        Ok(Some((key.to_vec(), value)))
523    }
524
525    fn next_immutable(&mut self, limit_bytes: usize) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
526        if !self.prepare_immutable_leaf()? {
527            return Ok(None);
528        }
529        let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
530        if !self.prefetched_next && self.position >= usize::from(page.cell_count()) / 2 {
531            let next = read_next_leaf(page);
532            if next != 0 {
533                self.pager.prefetch_hint(next);
534            }
535            self.prefetched_next = true;
536        }
537        let (key, stored) = read_leaf_cell_borrowed(page, self.position)?;
538        let value = decode_leaf_value(self.pager.as_ref(), page, stored, limit_bytes)?;
539        self.position += 1;
540        Ok(Some((key.to_vec(), value)))
541    }
542
543    /// Peek at current entry without advancing
544    pub fn peek(&self) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
545        if self.leaf_page_id == 0 {
546            return Ok(None);
547        }
548
549        let page = self.pager.read_page(self.leaf_page_id)?;
550        let cell_count = page.cell_count() as usize;
551
552        if self.position >= cell_count {
553            return Ok(None);
554        }
555
556        let (key, stored) = read_leaf_cell(&page, self.position)?;
557        let value = value_layout::decode(self.pager.as_ref(), &stored)?;
558        Ok(Some((key, value)))
559    }
560}
561
562/// B+ Tree implementation
563pub struct BTree<P: PageStore> {
564    retirement_pin: Arc<()>,
565    /// Pager for page I/O
566    pager: Arc<page_proofs::TreePageStore<P>>,
567    /// Root page ID (0 = empty tree)
568    root_page_id: RwLock<u32>,
569    /// D2 fastpath: cached rightmost leaf (page_id, high_key).
570    ///
571    /// When the next key to insert is strictly greater than `high_key`,
572    /// skip `find_leaf` (tree descent from root) and go directly to the
573    /// cached page. Invalidated on splits and deletes.
574    ///
575    /// Mirrors `BTPageCacheIsValid` / `BTREE_FASTPATH_MIN_LEVEL` in
576    /// `nbtinsert.c:31`.
577    rightmost_leaf: RwLock<Option<(u32, Vec<u8>)>>,
578    /// Serialises structural writers (insert / upsert / delete / bulk).
579    ///
580    /// Writers copy a page, modify the copy and write it back, and there
581    /// are no page latches, so two writers on one tree would lose each
582    /// other's leaf updates or tear a split (#2376). Reentrant because the
583    /// public mutators call each other (`upsert` -> `insert`, the bulk
584    /// paths -> `insert_encoded`). Readers do not take it.
585    writer: parking_lot::ReentrantMutex<()>,
586}
587
588#[path = "btree/impl.rs"]
589mod btree_impl;
590
591#[path = "btree/reclaim.rs"]
592mod reclaim;
593
594mod page_proofs;
595
596#[cfg(test)]
597#[path = "btree/read_budget_tests.rs"]
598mod read_budget_tests;
599
600#[path = "btree/lehman_yao.rs"]
601pub mod lehman_yao;
602
603mod reference_dictionary;
604#[path = "btree/value_layout.rs"]
605pub mod value_layout;
606// ==================== Search Helpers ====================
607
608enum SearchResult {
609    Found(usize),
610    NotFound(usize),
611}
612
613fn search_leaf(page: &Page, key: &[u8]) -> BTreeResult<SearchResult> {
614    let cell_count = page.cell_count() as usize;
615
616    // Binary search
617    let mut low = 0;
618    let mut high = cell_count;
619
620    while low < high {
621        let mid = (low + high) / 2;
622        let (cell_key, _) = read_leaf_cell_borrowed(page, mid)?;
623
624        match cell_key.cmp(key) {
625            Ordering::Less => low = mid + 1,
626            Ordering::Greater => high = mid,
627            Ordering::Equal => return Ok(SearchResult::Found(mid)),
628        }
629    }
630
631    Ok(SearchResult::NotFound(low))
632}
633
634fn find_child(page: &Page, key: &[u8]) -> BTreeResult<u32> {
635    // The child of the first separator above `key`. Every descent of every
636    // tree operation comes through here: it used to walk the separators in
637    // order and copy each one it looked at.
638    let mut low = 0;
639    let mut high = page.cell_count() as usize;
640    while low < high {
641        let mid = (low + high) / 2;
642        let (cell_key, _) = read_interior_cell_borrowed(page, mid)?;
643        if key < cell_key {
644            high = mid;
645        } else {
646            low = mid + 1;
647        }
648    }
649    if low < page.cell_count() as usize {
650        return Ok(read_interior_cell_borrowed(page, low)?.1);
651    }
652
653    // Key is >= all keys, use right child
654    Ok(page.right_child())
655}
656
657fn find_first_child(page: &Page) -> BTreeResult<u32> {
658    if page.cell_count() == 0 {
659        return Ok(page.right_child());
660    }
661    let (_, child) = read_interior_cell(page, 0)?;
662    Ok(child)
663}
664
665fn leaf_min_bytes() -> usize {
666    (PAGE_SIZE - LEAF_DATA_OFFSET) * MIN_FILL_FACTOR / 100
667}
668
669fn interior_min_bytes() -> usize {
670    (PAGE_SIZE - INTERIOR_DATA_OFFSET) * MIN_FILL_FACTOR / 100
671}
672
673/// Bytes consumed by one leaf entry in the slotted layout: one u16
674/// slot in the pointer array plus the cell itself (`[key_len:u16]
675/// [val_len:u16][key][val]`).
676fn leaf_entry_size(entry: &(Vec<u8>, Vec<u8>)) -> usize {
677    2 + 4 + entry.0.len() + entry.1.len()
678}
679
680fn leaf_entries_size(entries: &[(Vec<u8>, Vec<u8>)]) -> usize {
681    reference_dictionary::Occupancy::from_entries(entries).bytes
682}
683
684/// What `leaf_entries_size` returns for the page's entries, read from the
685/// slots without copying a cell.
686fn leaf_used_bytes(page: &Page) -> BTreeResult<usize> {
687    let mut bytes = 0;
688    for index in 0..page.cell_count() as usize {
689        let (key, value) = read_leaf_cell_borrowed(page, index)?;
690        bytes += 2 + 4 + key.len() + value.len();
691    }
692    Ok(bytes)
693}
694
695#[inline]
696fn leaf_slot_offset_for(index: usize) -> usize {
697    LEAF_SLOT_ARRAY_OFFSET + index * 2
698}
699
700#[inline]
701fn leaf_read_slot(page: &Page, index: usize) -> BTreeResult<usize> {
702    let data = page.as_bytes();
703    let slot_pos = leaf_slot_offset_for(index);
704    if slot_pos + 2 > PAGE_SIZE {
705        return Err(BTreeError::Corrupted("slot array overflows page".into()));
706    }
707    Ok(u16::from_le_bytes([data[slot_pos], data[slot_pos + 1]]) as usize)
708}
709
710#[inline]
711fn leaf_write_slot(page: &mut Page, index: usize, cell_offset: u16) -> BTreeResult<()> {
712    let data = page.as_bytes_mut();
713    let slot_pos = leaf_slot_offset_for(index);
714    if slot_pos + 2 > PAGE_SIZE {
715        return Err(BTreeError::Corrupted("slot array overflows page".into()));
716    }
717    data[slot_pos..slot_pos + 2].copy_from_slice(&cell_offset.to_le_bytes());
718    Ok(())
719}
720
721#[inline]
722fn leaf_slots_end(page: &Page) -> usize {
723    LEAF_SLOT_ARRAY_OFFSET + (page.cell_count() as usize) * 2
724}
725
726#[inline]
727fn leaf_cells_start(page: &Page) -> usize {
728    let end = page.free_end() as usize;
729    if end == 0 {
730        PAGE_SIZE
731    } else {
732        end
733    }
734}
735
736#[inline]
737fn leaf_free_bytes(page: &Page) -> usize {
738    let slot_end = leaf_slots_end(page);
739    let cells = leaf_cells_start(page);
740    cells.saturating_sub(slot_end)
741}
742
743fn interior_key_size(key: &[u8]) -> usize {
744    2 + key.len() + 4
745}
746
747fn interior_entries_size(keys: &[Vec<u8>]) -> usize {
748    keys.iter().map(|k| interior_key_size(k)).sum()
749}
750
751// ==================== Leaf Page Helpers ====================
752
753/// Read the cell at slot `index` in O(1). Follows the u16 slot pointer
754/// into the cell data area; the cell header is `[key_len:u16][val_len:u16]`
755/// followed by the raw key and value bytes.
756fn read_leaf_cell(page: &Page, index: usize) -> BTreeResult<(Vec<u8>, Vec<u8>)> {
757    let (key, value) = read_leaf_cell_borrowed(page, index)?;
758    let value = if reference_dictionary::shared(value) {
759        reference_dictionary::expand(page, value, true, usize::MAX)?
760    } else {
761        value.to_vec()
762    };
763    Ok((key.to_vec(), value))
764}
765
766fn decode_leaf_value<P: PageStore>(
767    pager: &P,
768    page: &Page,
769    stored: &[u8],
770    limit: usize,
771) -> BTreeResult<Vec<u8>> {
772    if reference_dictionary::shared(stored) {
773        reference_dictionary::expand(page, stored, false, limit)
774    } else {
775        Ok(value_layout::decode_with_budget(pager, stored, limit)?)
776    }
777}
778
779fn read_leaf_cell_borrowed(page: &Page, index: usize) -> BTreeResult<(&[u8], &[u8])> {
780    let cell_count = page.cell_count() as usize;
781    if index >= cell_count {
782        return Err(BTreeError::Corrupted("Cell index out of range".into()));
783    }
784    let offset = leaf_read_slot(page, index)?;
785    let data = page.as_bytes();
786    if offset + 4 > PAGE_SIZE {
787        return Err(BTreeError::Corrupted("cell header out of range".into()));
788    }
789    let key_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
790    let val_len = u16::from_le_bytes([data[offset + 2], data[offset + 3]]) as usize;
791    let end = offset + 4 + key_len + val_len;
792    if end > PAGE_SIZE {
793        return Err(BTreeError::Corrupted("cell body out of range".into()));
794    }
795    let key = &data[offset + 4..offset + 4 + key_len];
796    let value = &data[offset + 4 + key_len..end];
797    Ok((key, value))
798}
799
800fn read_leaf_entries(page: &Page) -> BTreeResult<Vec<(Vec<u8>, Vec<u8>)>> {
801    let cell_count = page.cell_count() as usize;
802    let mut entries = Vec::with_capacity(cell_count);
803    for i in 0..cell_count {
804        entries.push(read_leaf_cell(page, i)?);
805    }
806    Ok(entries)
807}
808
809/// Wipe and re-lay an entire leaf in slotted form. Used by the split
810/// path (which hands us a pre-sorted `entries` vector) and by
811/// `clear_leaf_cells` under the hood. Entries are appended at the end
812/// of the free area so the highest-index slot ends up at the lowest
813/// offset — same shape the single-key insert path produces.
814fn write_leaf_entries(page: &mut Page, entries: &[(Vec<u8>, Vec<u8>)]) -> BTreeResult<()> {
815    clear_leaf_cells(page);
816    let mut names = std::collections::HashMap::new();
817    for (i, (k, v)) in entries.iter().enumerate() {
818        let cell_offset =
819            append_leaf_cell(page, k, v, leaf_slot_offset_for(i + 1), Some(&mut names))?;
820        leaf_write_slot(page, i, cell_offset as u16)?;
821    }
822    page.set_cell_count(entries.len() as u16);
823    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + entries.len() * 2) as u16);
824    Ok(())
825}
826
827fn append_leaf_cell<'a>(
828    page: &mut Page,
829    key: &[u8],
830    value: &'a [u8],
831    slot_end: usize,
832    cache: Option<&mut std::collections::HashMap<&'a [u8], u16>>,
833) -> BTreeResult<usize> {
834    let packed = reference_dictionary::pack(page, value, cache)?;
835    let size = 4 + key.len() + packed.len();
836    let start = leaf_cells_start(page);
837    if slot_end + size > start {
838        return Err(BTreeError::Corrupted("leaf rebuild overflowed page".into()));
839    }
840    let at = start - size;
841    let cell = &mut page.as_bytes_mut()[at..start];
842    cell[..2].copy_from_slice(&(key.len() as u16).to_le_bytes());
843    cell[2..4].copy_from_slice(&(packed.len() as u16).to_le_bytes());
844    cell[4..4 + key.len()].copy_from_slice(key);
845    packed.write(&mut cell[4 + key.len()..]);
846    page.set_free_end(at as u16);
847    reference_dictionary::account_insert(page, size + 2);
848    Ok(at)
849}
850
851fn can_insert_leaf(page: &Page, key: &[u8], value: &[u8]) -> bool {
852    let needed = 2 + 4 + key.len() + value.len();
853    leaf_free_bytes(page) >= needed
854}
855
856/// Insert `(key, value)` into the slotted leaf in O(log M) search +
857/// O(M) slot-array memmove. Cell data is appended at the tail of the
858/// free area (backward from `free_end`); the slot pointer is inserted
859/// Overwrite the value portion of cell at `index` in-place. Valid when
860/// `new_value.len() <= existing_value.len()` — the caller
861/// (typically `BTree::upsert`) checks this before calling.
862///
863/// Same-length writes are trivial (byte copy). Shrinks update the cell's
864/// `v_len` header and leave the trailing bytes as dead space until the
865/// page is naturally rewritten; the slotted layout keeps cells
866/// addressable by their own offset+len so the gap is harmless.
867///
868/// Fixed-size column updates (SET score = X on a typed schema) hit this
869/// path, avoiding the delete + re-insert + rebalance cycle that
870/// dominates bulk_update.
871pub(crate) fn overwrite_leaf_value(
872    page: &mut Page,
873    index: usize,
874    new_value: &[u8],
875) -> BTreeResult<()> {
876    let cell_offset = leaf_read_slot(page, index)?;
877    let data = page.as_bytes();
878    if cell_offset + 4 > data.len() {
879        return Err(BTreeError::Corrupted(
880            "leaf cell header out of bounds".into(),
881        ));
882    }
883    let k_len = u16::from_le_bytes([data[cell_offset], data[cell_offset + 1]]) as usize;
884    let old_v_len = u16::from_le_bytes([data[cell_offset + 2], data[cell_offset + 3]]) as usize;
885    if new_value.len() > old_v_len {
886        return Err(BTreeError::Corrupted(
887            "overwrite_leaf_value: new value larger than slot".into(),
888        ));
889    }
890    let value_start = cell_offset + 4 + k_len;
891    if value_start + new_value.len() > data.len() {
892        return Err(BTreeError::Corrupted(
893            "leaf cell value out of bounds".into(),
894        ));
895    }
896    let data = page.as_bytes_mut();
897    // Update the v_len header if the value shrank. read_leaf_cell reads
898    // v_len from this header so the shortened value deserializes correctly.
899    if new_value.len() != old_v_len {
900        let new_len = new_value.len() as u16;
901        data[cell_offset + 2..cell_offset + 4].copy_from_slice(&new_len.to_le_bytes());
902    }
903    data[value_start..value_start + new_value.len()].copy_from_slice(new_value);
904    reference_dictionary::account_removal(page, old_v_len - new_value.len());
905    Ok(())
906}
907
908/// at the sorted position.
909fn insert_into_leaf(page: &mut Page, key: &[u8], value: &[u8]) -> BTreeResult<()> {
910    // 1. Binary search the slot array to find the insertion index.
911    let cell_count = page.cell_count() as usize;
912    let mut low = 0;
913    let mut high = cell_count;
914    while low < high {
915        let mid = (low + high) / 2;
916        let (cell_key, _) = read_leaf_cell_borrowed(page, mid)?;
917        match cell_key.cmp(key) {
918            Ordering::Less => low = mid + 1,
919            Ordering::Greater => high = mid,
920            Ordering::Equal => {
921                // Duplicate keys are tolerated by the B-tree (caller
922                // decides semantics); append after the existing run.
923                low = mid + 1;
924                break;
925            }
926        }
927    }
928    let insert_pos = low;
929
930    // 2. Reserve the cell at the tail of the free area.
931    let cell_offset =
932        append_leaf_cell(page, key, value, leaf_slot_offset_for(cell_count + 1), None)?;
933
934    // 3. Shift the slot-array tail right by one slot, then write the
935    //    new pointer into the freed slot. This is a single memmove on
936    //    a couple dozen u16s — far cheaper than the O(M²) rebuild.
937    {
938        let shift_from = leaf_slot_offset_for(insert_pos);
939        let shift_to = shift_from + 2;
940        let shift_len = (cell_count - insert_pos) * 2;
941        if shift_len > 0 {
942            let data = page.as_bytes_mut();
943            data.copy_within(shift_from..shift_from + shift_len, shift_to);
944        }
945    }
946    leaf_write_slot(page, insert_pos, cell_offset as u16)?;
947
948    // 4. Bump counters.
949    page.set_cell_count((cell_count + 1) as u16);
950    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + (cell_count + 1) * 2) as u16);
951    Ok(())
952}
953
954/// Remove the slot at `index`. Cell bytes are left in place (lazy
955/// compaction); the slot-array tail is shifted left to close the gap.
956/// The caller is expected to call `clear_leaf_cells` + rebuild if the
957/// page wants its free space reclaimed.
958fn delete_from_leaf(page: &mut Page, index: usize) -> BTreeResult<()> {
959    let cell_count = page.cell_count() as usize;
960    if index >= cell_count {
961        return Err(BTreeError::Corrupted("delete index out of range".into()));
962    }
963    if page.right_child() != 0 {
964        let (key, stored) = read_leaf_cell_borrowed(page, index)?;
965        reference_dictionary::account_removal(page, 6 + key.len() + stored.len());
966    }
967    if index + 1 < cell_count {
968        let shift_from = leaf_slot_offset_for(index + 1);
969        let shift_to = leaf_slot_offset_for(index);
970        let shift_len = (cell_count - index - 1) * 2;
971        let data = page.as_bytes_mut();
972        data.copy_within(shift_from..shift_from + shift_len, shift_to);
973    }
974    page.set_cell_count((cell_count - 1) as u16);
975    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + (cell_count - 1) * 2) as u16);
976    Ok(())
977}
978
979/// Reset the leaf to an empty slotted state — cell count 0, free
980/// cursors at the extremes. Zeroes the slot array + cell data area so
981/// stale bytes never leak through a corrupted read.
982fn clear_leaf_cells(page: &mut Page) {
983    page.set_right_child(0);
984    {
985        let data = page.as_bytes_mut();
986        for byte in &mut data[LEAF_SLOT_ARRAY_OFFSET..] {
987            *byte = 0;
988        }
989    }
990    page.set_cell_count(0);
991    page.set_free_start(LEAF_SLOT_ARRAY_OFFSET as u16);
992    page.set_free_end(PAGE_SIZE as u16);
993}
994
995fn init_leaf_links(page: &mut Page, prev: u32, next: u32) {
996    let data = page.as_bytes_mut();
997    data[LEAF_PREV_OFFSET..LEAF_PREV_OFFSET + 4].copy_from_slice(&prev.to_le_bytes());
998    data[LEAF_NEXT_OFFSET..LEAF_NEXT_OFFSET + 4].copy_from_slice(&next.to_le_bytes());
999}
1000
1001fn read_next_leaf(page: &Page) -> u32 {
1002    let data = page.as_bytes();
1003    u32::from_le_bytes([
1004        data[LEAF_NEXT_OFFSET],
1005        data[LEAF_NEXT_OFFSET + 1],
1006        data[LEAF_NEXT_OFFSET + 2],
1007        data[LEAF_NEXT_OFFSET + 3],
1008    ])
1009}
1010
1011/// Returns the right-sibling page ID for a leaf page.
1012/// 0 means this is the rightmost leaf — used by the D2 fastpath cache.
1013#[inline]
1014fn leaf_right_sibling(page: &Page) -> u32 {
1015    read_next_leaf(page)
1016}
1017
1018/// Returns the maximum (last) key stored in a leaf page, or `None` if empty.
1019/// This is the Lehman-Yao "high_key" — any key > this value belongs on a
1020/// right-sibling page. Reads only the last slot so it is O(1).
1021fn leaf_high_key(page: &Page) -> BTreeResult<Option<Vec<u8>>> {
1022    let cell_count = page.cell_count() as usize;
1023    if cell_count == 0 {
1024        return Ok(None);
1025    }
1026    let (key, _) = read_leaf_cell(page, cell_count - 1)?;
1027    Ok(Some(key))
1028}
1029
1030fn set_prev_leaf(page: &mut Page, prev: u32) {
1031    let data = page.as_bytes_mut();
1032    data[LEAF_PREV_OFFSET..LEAF_PREV_OFFSET + 4].copy_from_slice(&prev.to_le_bytes());
1033}
1034
1035fn set_next_leaf(page: &mut Page, next: u32) {
1036    let data = page.as_bytes_mut();
1037    data[LEAF_NEXT_OFFSET..LEAF_NEXT_OFFSET + 4].copy_from_slice(&next.to_le_bytes());
1038}
1039
1040// ==================== Interior Page Helpers ====================
1041//
1042// Slotted-page layout mirroring the leaf format:
1043//
1044// ```text
1045// [PageHeader 32B]
1046// [slot 0: u16][slot 1: u16]...[slot N-1: u16]  ← grows forward
1047// ... free space ...
1048// [cell N-1][cell N-2]...[cell 0]               ← grows backward from free_end
1049// ```
1050//
1051// Each cell is `[key_len:u16][key][child:u32]`. The right-most child
1052// pointer lives in `PageHeader.right_child` exactly as before.
1053
1054#[inline]
1055fn interior_slot_offset_for(index: usize) -> usize {
1056    INTERIOR_DATA_OFFSET + index * 2
1057}
1058
1059#[inline]
1060fn interior_read_slot(page: &Page, index: usize) -> BTreeResult<usize> {
1061    let data = page.as_bytes();
1062    let slot_pos = interior_slot_offset_for(index);
1063    if slot_pos + 2 > PAGE_SIZE {
1064        return Err(BTreeError::Corrupted(
1065            "interior slot array overflows page".into(),
1066        ));
1067    }
1068    Ok(u16::from_le_bytes([data[slot_pos], data[slot_pos + 1]]) as usize)
1069}
1070
1071#[inline]
1072fn interior_write_slot(page: &mut Page, index: usize, cell_offset: u16) -> BTreeResult<()> {
1073    let data = page.as_bytes_mut();
1074    let slot_pos = interior_slot_offset_for(index);
1075    if slot_pos + 2 > PAGE_SIZE {
1076        return Err(BTreeError::Corrupted(
1077            "interior slot array overflows page".into(),
1078        ));
1079    }
1080    data[slot_pos..slot_pos + 2].copy_from_slice(&cell_offset.to_le_bytes());
1081    Ok(())
1082}
1083
1084#[inline]
1085fn interior_cells_start(page: &Page) -> usize {
1086    let end = page.free_end() as usize;
1087    if end == 0 {
1088        PAGE_SIZE
1089    } else {
1090        end
1091    }
1092}
1093
1094#[inline]
1095fn interior_free_bytes(page: &Page) -> usize {
1096    let slot_end = INTERIOR_DATA_OFFSET + (page.cell_count() as usize) * 2;
1097    interior_cells_start(page).saturating_sub(slot_end)
1098}
1099
1100fn read_interior_cell(page: &Page, index: usize) -> BTreeResult<(Vec<u8>, u32)> {
1101    let (key, child) = read_interior_cell_borrowed(page, index)?;
1102    Ok((key.to_vec(), child))
1103}
1104
1105/// Where `child` sits among an interior page's children, in the order
1106/// `read_interior_keys_children` lists them, with the separator to its left
1107/// (none for the first child). Copies no key.
1108fn interior_child_slot(page: &Page, child: u32) -> BTreeResult<Option<(usize, Option<&[u8]>)>> {
1109    let cell_count = page.cell_count() as usize;
1110    let mut left = None;
1111    for index in 0..cell_count {
1112        let (key, id) = read_interior_cell_borrowed(page, index)?;
1113        if id == child {
1114            return Ok(Some((index, left)));
1115        }
1116        left = Some(key);
1117    }
1118    let right_child = page.right_child();
1119    if right_child == child && (cell_count > 0 || right_child != 0) {
1120        return Ok(Some((cell_count, left)));
1121    }
1122    Ok(None)
1123}
1124
1125fn read_interior_cell_borrowed(page: &Page, index: usize) -> BTreeResult<(&[u8], u32)> {
1126    let cell_count = page.cell_count() as usize;
1127    if index >= cell_count {
1128        return Err(BTreeError::Corrupted("Cell index out of range".into()));
1129    }
1130    let offset = interior_read_slot(page, index)?;
1131    let data = page.as_bytes();
1132    if offset + 2 > PAGE_SIZE {
1133        return Err(BTreeError::Corrupted(
1134            "interior cell header out of range".into(),
1135        ));
1136    }
1137    let key_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
1138    let end = offset + 2 + key_len + 4;
1139    if end > PAGE_SIZE {
1140        return Err(BTreeError::Corrupted(
1141            "interior cell body out of range".into(),
1142        ));
1143    }
1144    let key = &data[offset + 2..offset + 2 + key_len];
1145    let child = u32::from_le_bytes([
1146        data[offset + 2 + key_len],
1147        data[offset + 2 + key_len + 1],
1148        data[offset + 2 + key_len + 2],
1149        data[offset + 2 + key_len + 3],
1150    ]);
1151    Ok((key, child))
1152}
1153
1154fn read_interior_keys_children(page: &Page) -> BTreeResult<(Vec<Vec<u8>>, Vec<u32>)> {
1155    let cell_count = page.cell_count() as usize;
1156    let mut keys = Vec::with_capacity(cell_count);
1157    let mut children = Vec::with_capacity(cell_count + 1);
1158
1159    for i in 0..cell_count {
1160        let (key, child) = read_interior_cell(page, i)?;
1161        keys.push(key);
1162        children.push(child);
1163    }
1164
1165    if cell_count == 0 {
1166        let right_child = page.right_child();
1167        if right_child != 0 {
1168            children.push(right_child);
1169        }
1170    } else {
1171        children.push(page.right_child());
1172    }
1173
1174    Ok((keys, children))
1175}
1176
1177/// Bulk-write an interior page from scratch in slotted form. Used by
1178/// the split path. `keys` and `children` follow the B+ tree contract:
1179/// `children.len() == keys.len() + 1`, with the last child landing in
1180/// `PageHeader.right_child` (as before).
1181fn write_interior_entries(page: &mut Page, keys: &[Vec<u8>], children: &[u32]) -> BTreeResult<()> {
1182    if !keys.is_empty() && children.len() != keys.len() + 1 {
1183        return Err(BTreeError::Corrupted(
1184            "Interior keys/children length mismatch".into(),
1185        ));
1186    }
1187
1188    clear_interior_cells(page);
1189    if keys.is_empty() {
1190        let right_child = children.first().copied().unwrap_or(0);
1191        page.set_right_child(right_child);
1192        return Ok(());
1193    }
1194
1195    for (i, key) in keys.iter().enumerate() {
1196        let cell_size = 2 + key.len() + 4;
1197        let cells_start = interior_cells_start(page);
1198        let slot_end = INTERIOR_DATA_OFFSET + (i + 1) * 2;
1199        if slot_end + cell_size > cells_start {
1200            return Err(BTreeError::Corrupted(
1201                "interior rebuild overflowed page".into(),
1202            ));
1203        }
1204        let cell_offset = cells_start - cell_size;
1205        {
1206            let data = page.as_bytes_mut();
1207            data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
1208            data[cell_offset + 2..cell_offset + 2 + key.len()].copy_from_slice(key);
1209            data[cell_offset + 2 + key.len()..cell_offset + 2 + key.len() + 4]
1210                .copy_from_slice(&children[i].to_le_bytes());
1211        }
1212        page.set_free_end(cell_offset as u16);
1213        interior_write_slot(page, i, cell_offset as u16)?;
1214    }
1215    page.set_cell_count(keys.len() as u16);
1216    page.set_free_start((INTERIOR_DATA_OFFSET + keys.len() * 2) as u16);
1217    page.set_right_child(*children.last().ok_or_else(|| {
1218        BTreeError::Corrupted("write_interior_entries: children empty with non-empty keys".into())
1219    })?);
1220    Ok(())
1221}
1222
1223fn can_insert_interior(page: &Page, key: &[u8]) -> bool {
1224    let needed = 2 + 2 + key.len() + 4;
1225    interior_free_bytes(page) >= needed
1226}
1227
1228/// Insert a `(key, left_child)` separator into the interior page.
1229/// `right_child` replaces whatever child used to sit to the right of
1230/// the inserted key (either a middle child's pointer or the page's
1231/// `right_child` when the key is the new maximum).
1232fn insert_into_interior(
1233    page: &mut Page,
1234    key: &[u8],
1235    left_child: u32,
1236    right_child: u32,
1237) -> BTreeResult<()> {
1238    // 1. Binary search the slot array for the insert position.
1239    let cell_count = page.cell_count() as usize;
1240    let mut low = 0;
1241    let mut high = cell_count;
1242    while low < high {
1243        let mid = (low + high) / 2;
1244        let (cell_key, _) = read_interior_cell_borrowed(page, mid)?;
1245        match cell_key.cmp(key) {
1246            Ordering::Less => low = mid + 1,
1247            Ordering::Greater | Ordering::Equal => high = mid,
1248        }
1249    }
1250    let insert_pos = low;
1251
1252    // 2. Redirect the previous owner of the split to `right_child`.
1253    //    If the insertion is at the tail, the previous owner was the
1254    //    page's right_child pointer; otherwise it was the child slot
1255    //    of the cell currently at `insert_pos`.
1256    if insert_pos < cell_count {
1257        let old_offset = interior_read_slot(page, insert_pos)?;
1258        let data = page.as_bytes();
1259        let key_len = u16::from_le_bytes([data[old_offset], data[old_offset + 1]]) as usize;
1260        let child_pos = old_offset + 2 + key_len;
1261        let data = page.as_bytes_mut();
1262        data[child_pos..child_pos + 4].copy_from_slice(&right_child.to_le_bytes());
1263    } else {
1264        page.set_right_child(right_child);
1265    }
1266
1267    // 3. Reserve the new cell at the tail of the free area.
1268    let cell_size = 2 + key.len() + 4;
1269    let slot_end_after = INTERIOR_DATA_OFFSET + (cell_count + 1) * 2;
1270    let cells_start = interior_cells_start(page);
1271    if slot_end_after + cell_size > cells_start {
1272        return Err(BTreeError::Corrupted("interior page full".into()));
1273    }
1274    let cell_offset = cells_start - cell_size;
1275    {
1276        let data = page.as_bytes_mut();
1277        data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
1278        data[cell_offset + 2..cell_offset + 2 + key.len()].copy_from_slice(key);
1279        data[cell_offset + 2 + key.len()..cell_offset + 2 + key.len() + 4]
1280            .copy_from_slice(&left_child.to_le_bytes());
1281    }
1282    page.set_free_end(cell_offset as u16);
1283
1284    // 4. Shift the slot-array tail right by one slot, write the new
1285    //    pointer into the freed slot, bump counters.
1286    {
1287        let shift_from = interior_slot_offset_for(insert_pos);
1288        let shift_to = shift_from + 2;
1289        let shift_len = (cell_count - insert_pos) * 2;
1290        if shift_len > 0 {
1291            let data = page.as_bytes_mut();
1292            data.copy_within(shift_from..shift_from + shift_len, shift_to);
1293        }
1294    }
1295    interior_write_slot(page, insert_pos, cell_offset as u16)?;
1296    page.set_cell_count((cell_count + 1) as u16);
1297    page.set_free_start((INTERIOR_DATA_OFFSET + (cell_count + 1) * 2) as u16);
1298    Ok(())
1299}
1300
1301fn clear_interior_cells(page: &mut Page) {
1302    {
1303        let data = page.as_bytes_mut();
1304        for byte in &mut data[INTERIOR_DATA_OFFSET..] {
1305            *byte = 0;
1306        }
1307    }
1308    page.set_cell_count(0);
1309    page.set_free_start(INTERIOR_DATA_OFFSET as u16);
1310    page.set_free_end(PAGE_SIZE as u16);
1311}