Skip to main content

ic_storage/adapter/tree/
mod.rs

1//! Owned degree-six B-tree. The multi-entry search, split/borrow/merge design and
2//! selective payload access follow the established B-tree techniques used by
3//! ic-stable-structures 0.7.2 (see the historical provenance in SOURCES.md). This is a new checked
4//! format, not an implementation of its durable layout or compatibility reader.
5//! Routing records contain small inline values; larger values have separate
6//! checksummed records. Mutations stage bytes and reserve before publication.
7use super::{
8    BTreeMapOptions, Memory, Storable,
9    error::{CollectionError as Error, Result, ensure},
10    record,
11};
12
13use std::{
14    borrow::Cow,
15    cell::{Cell, RefCell},
16    collections::BTreeMap,
17    marker::PhantomData,
18    ops::{Bound, RangeBounds},
19    rc::Rc,
20};
21mod framing;
22use framing::{decode_link, link_bytes};
23mod read;
24use read::ReadNode;
25
26pub const MAGIC: [u8; 9] = *b"ICPMAP001";
27const NODE: [u8; 8] = *b"ICBTND01";
28const VALUE: [u8; 8] = *b"ICBTVAL1";
29const FREE: [u8; 8] = *b"ICFREE01";
30const BINS: usize = 32;
31const MAX_DEPTH: usize = 32;
32const DEGREE: usize = 6;
33const MAX_ENTRIES: usize = DEGREE * 2 - 1;
34const MIN_ENTRIES: usize = DEGREE - 1;
35const INLINE: usize = 32;
36// Order eight is the smallest block in the original pointer format.
37const FIRST_ORDER: usize = 8;
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40struct Pointer {
41    offset: u64,
42    order: u8,
43    // Inherited from the header when decoding a pointer; never encoded per link.
44    unit: u16,
45}
46impl Pointer {
47    fn capacity(self) -> u64 {
48        u64::from(self.unit) << (usize::from(self.order) - FIRST_ORDER)
49    }
50    fn check(self, cursor: u64) -> Result<()> {
51        ensure(
52            (8..32).contains(&self.order),
53            Error::Corrupt("tree block order"),
54        )?;
55        ensure(
56            self.offset >= record::HEADER_BYTES
57                && self
58                    .offset
59                    .checked_add(self.capacity())
60                    .is_some_and(|end| end <= cursor),
61            Error::Corrupt("tree block bounds"),
62        )
63    }
64    fn put(self, bytes: &mut Vec<u8>) {
65        bytes.extend_from_slice(&self.offset.to_le_bytes());
66        bytes.push(self.order);
67    }
68}
69#[derive(Clone, PartialEq, Eq)]
70struct Root {
71    options: BTreeMapOptions,
72    top: Option<Pointer>,
73    length: u64,
74    cursor: u64,
75    free: Vec<Option<Pointer>>,
76    key_bound: Option<(u32, bool)>,
77    value_bound: Option<(u32, bool)>,
78}
79#[derive(Clone)]
80enum Value {
81    Inline(Vec<u8>),
82    External(Pointer),
83}
84#[derive(Clone)]
85struct Entry {
86    key: Vec<u8>,
87    value: Value,
88}
89#[derive(Clone, Default)]
90struct Node {
91    entries: Vec<Entry>,
92    children: Vec<Pointer>,
93}
94impl Node {
95    fn encode(&self) -> Result<Vec<u8>> {
96        ensure(
97            self.entries.len() <= MAX_ENTRIES,
98            Error::Corrupt("B-tree node capacity"),
99        )?;
100        ensure(
101            self.children.is_empty() || self.children.len() == self.entries.len() + 1,
102            Error::Corrupt("B-tree child count"),
103        )?;
104        let capacity =
105            self.entries
106                .iter()
107                .try_fold(2 + self.children.len() * 9, |size, entry| {
108                    let value_size = match &entry.value {
109                        Value::Inline(v) => v.len(),
110                        Value::External(_) => 9,
111                    };
112                    size.checked_add(5)
113                        .and_then(|n| n.checked_add(entry.key.len()))
114                        .and_then(|n| n.checked_add(value_size))
115                        .ok_or(Error::Budget)
116                })?;
117        record::encode_payload_with(NODE, capacity, |bytes| {
118            bytes.extend_from_slice(&[
119                u8::try_from(self.entries.len()).unwrap(),
120                u8::from(!self.children.is_empty()),
121            ]);
122            for p in &self.children {
123                p.put(bytes);
124            }
125            for entry in &self.entries {
126                bytes.extend_from_slice(
127                    &u32::try_from(entry.key.len())
128                        .map_err(|_| Error::Budget)?
129                        .to_le_bytes(),
130                );
131                bytes.extend_from_slice(&entry.key);
132                match &entry.value {
133                    Value::Inline(value) => {
134                        bytes.push(u8::try_from(value.len()).unwrap());
135                        bytes.extend_from_slice(value);
136                    }
137                    Value::External(p) => {
138                        bytes.push(255);
139                        p.put(bytes);
140                    }
141                }
142            }
143            Ok(())
144        })
145    }
146}
147struct Reader<'a>(&'a [u8]);
148impl<'a> Reader<'a> {
149    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
150        ensure(n <= self.0.len(), Error::Corrupt("truncated B-tree node"))?;
151        let (a, b) = self.0.split_at(n);
152        self.0 = b;
153        Ok(a)
154    }
155    fn byte(&mut self) -> Result<u8> {
156        Ok(self.take(1)?[0])
157    }
158    fn pointer(&mut self, cursor: u64, unit: u16) -> Result<Pointer> {
159        let offset = u64::from_le_bytes(self.take(8)?.try_into().unwrap());
160        let p = Pointer {
161            offset,
162            order: self.byte()?,
163            unit,
164        };
165        p.check(cursor)?;
166        Ok(p)
167    }
168}
169
170pub struct Tree<K, V, M: Memory> {
171    pub memory: M,
172    root: RefCell<Root>,
173    poisoned: Cell<bool>,
174    types: PhantomData<(K, V)>,
175}
176impl<K: Storable + Ord + Clone, V: Storable, M: Memory> Tree<K, V, M> {
177    pub fn reset(memory: M, options: BTreeMapOptions) -> Result<Self> {
178        ensure(options.valid(), Error::Bounds)?;
179        let root = Root {
180            options,
181            top: None,
182            length: 0,
183            cursor: record::HEADER_BYTES,
184            free: vec![None; BINS],
185            key_bound: record::bound::<K>(),
186            value_bound: record::bound::<V>(),
187        };
188        let bytes = root.encode()?;
189        ensure(bytes.len() as u64 <= record::HEADER_BYTES, Error::Budget)?;
190        record::reserve(&memory, record::HEADER_BYTES)?;
191        memory.write(0, &bytes);
192        Ok(Self {
193            memory,
194            root: RefCell::new(root),
195            poisoned: Cell::new(false),
196            types: PhantomData,
197        })
198    }
199    pub fn load(memory: M) -> Result<Self> {
200        let root: Root = Root::decode(&record::read_map_header(&memory, &MAGIC)?)?;
201        ensure(
202            root.key_bound == record::bound::<K>() && root.value_bound == record::bound::<V>(),
203            Error::Corrupt("map codec bound changed"),
204        )?;
205        ensure(
206            root.free.len() == BINS
207                && root.cursor >= record::HEADER_BYTES
208                && root.cursor
209                    <= memory
210                        .size()
211                        .checked_mul(crate::WASM_PAGE_SIZE_BYTES)
212                        .ok_or(Error::Budget)?,
213            Error::Corrupt("map allocator bounds"),
214        )?;
215        ensure(
216            root.top.is_none() == (root.length == 0),
217            Error::Corrupt("map root/count disagree"),
218        )?;
219        if let Some(p) = root.top {
220            p.check(root.cursor)?;
221        }
222        for (order, p) in root.free.iter().enumerate() {
223            if let Some(p) = p {
224                p.check(root.cursor)?;
225                ensure(
226                    usize::from(p.order) == order,
227                    Error::Corrupt("free block order"),
228                )?;
229            }
230        }
231        Ok(Self {
232            memory,
233            root: RefCell::new(root),
234            poisoned: Cell::new(false),
235            types: PhantomData,
236        })
237    }
238    fn healthy(&self) -> Result<()> {
239        ensure(!self.poisoned.get(), Error::Poisoned)?;
240        // A different allocation can poison the shared governed backing. This
241        // also covers iterator entries already held in a routing frame.
242        let capacity = self
243            .memory
244            .size()
245            .checked_mul(crate::WASM_PAGE_SIZE_BYTES)
246            .ok_or(Error::Budget)?;
247        ensure(
248            self.root.borrow().cursor <= capacity,
249            Error::Corrupt("map allocator bounds"),
250        )
251    }
252    pub fn options(&self) -> BTreeMapOptions {
253        self.root.borrow().options
254    }
255    pub fn len(&self) -> u64 {
256        self.healthy().expect("map owner is poisoned");
257        self.root.borrow().length
258    }
259    fn read_node(&self, p: Pointer, depth: usize) -> Result<Rc<ReadNode>> {
260        let cursor = self.root.borrow().cursor;
261        p.check(cursor)?;
262        ensure(depth < MAX_DEPTH, Error::Corrupt("B-tree depth"))?;
263        let node = Rc::new(ReadNode::decode::<K, V>(
264            record::read_bytes(&self.memory, p.offset, p.capacity(), NODE)?,
265            cursor,
266            p.unit,
267        )?);
268        Ok(node)
269    }
270    fn value(&self, v: Value) -> Result<Vec<u8>> {
271        let bytes = match v {
272            Value::Inline(bytes) => bytes,
273            Value::External(p) => {
274                p.check(self.root.borrow().cursor)?;
275                record::read_payload(&self.memory, p.offset, p.capacity(), VALUE)?
276            }
277        };
278        V::BOUND.check(&bytes);
279        Ok(bytes)
280    }
281    fn find(&self, key: &K) -> Result<Option<(Rc<ReadNode>, usize)>> {
282        self.healthy()?;
283        let mut p = self.root.borrow().top;
284        for depth in 0..MAX_DEPTH {
285            let Some(current) = p else { return Ok(None) };
286            let node = self.read_node(current, depth)?;
287            match node.search(key)? {
288                Ok(i) => return Ok(Some((node, i))),
289                Err(i) => p = node.children.get(i).copied(),
290            }
291        }
292        Err(Error::Corrupt("map path exceeds height bound"))
293    }
294    pub fn get(&self, key: &K) -> Result<Option<V>> {
295        let Some((node, index)) = self.find(key)? else {
296            return Ok(None);
297        };
298        self.decode_hit(node, index).map(Some)
299    }
300    fn decode_hit(&self, node: Rc<ReadNode>, index: usize) -> Result<V> {
301        if let Some(bytes) = node.inline_value(index) {
302            V::BOUND.check(bytes);
303            Ok(V::from_bytes(Cow::Borrowed(bytes)))
304        } else {
305            let value = node.value(index);
306            drop(node);
307            decode(self.value(value)?)
308        }
309    }
310
311    #[cfg(feature = "test-support")]
312    pub fn visit_sorted_keys(
313        &self,
314        keys: &[K],
315        mut visit: impl FnMut(&K, Option<V>),
316    ) -> Result<()> {
317        if let [key] = keys {
318            visit(key, self.get(key)?);
319            return Ok(());
320        }
321        self.healthy()?;
322        self.visit_subtree(self.root.borrow().top, 0, keys, &mut visit)
323    }
324
325    #[cfg(feature = "test-support")]
326    fn visit_subtree(
327        &self,
328        pointer: Option<Pointer>,
329        depth: usize,
330        mut keys: &[K],
331        visit: &mut impl FnMut(&K, Option<V>),
332    ) -> Result<()> {
333        if keys.is_empty() {
334            return Ok(());
335        }
336        let Some(pointer) = pointer else {
337            for key in keys {
338                visit(key, None);
339            }
340            return Ok(());
341        };
342        let node = self.read_node(pointer, depth)?;
343        // Partition at separators in ascending order. Start at the first requested
344        // slot so even a pair of distant probes only descends into relevant children.
345        let first = node.search(&keys[0])?.unwrap_or_else(|slot| slot);
346        for slot in first..node.len() {
347            let separator = K::from_bytes(Cow::Borrowed(node.key_bytes(slot)));
348            let split = keys.partition_point(|key| key < &separator);
349            self.visit_subtree(
350                node.children.get(slot).copied(),
351                depth + 1,
352                &keys[..split],
353                visit,
354            )?;
355            keys = &keys[split..];
356            if keys.first() == Some(&separator) {
357                visit(&keys[0], Some(self.decode_hit(Rc::clone(&node), slot)?));
358                keys = &keys[1..];
359            }
360            if keys.is_empty() {
361                return Ok(());
362            }
363        }
364        self.visit_subtree(node.children.last().copied(), depth + 1, keys, visit)
365    }
366    pub fn contains_key(&self, key: &K) -> Result<bool> {
367        Ok(self.find(key)?.is_some())
368    }
369    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>> {
370        self.healthy()?;
371        let key_bytes = key.to_bytes().into_owned();
372        K::BOUND.check(&key_bytes);
373        let bytes = value.into_bytes();
374        V::BOUND.check(&bytes);
375        let mut tx = Transaction::new(self);
376        let (top, split, old) = tx.insert(tx.root.top, &key, key_bytes, bytes, 0)?;
377        tx.root.top = Some(if let Some((entry, right)) = split {
378            tx.save(
379                None,
380                &Node {
381                    entries: vec![entry],
382                    children: vec![top, right],
383                },
384            )?
385        } else {
386            top
387        });
388        drop(key);
389        let old = old.map(decode).transpose()?;
390        tx.commit()?;
391        Ok(old)
392    }
393    pub fn remove(&mut self, key: &K) -> Result<Option<V>> {
394        self.healthy()?;
395        let mut tx = Transaction::new(self);
396        let old = tx.remove_key(key)?;
397        let value = old.map(decode).transpose()?;
398        tx.commit()?;
399        Ok(value)
400    }
401    pub fn remove_many(&mut self, keys: std::collections::BTreeSet<K>) -> Result<u64> {
402        self.healthy()?;
403        let mut removed = 0;
404        let mut keys = keys.into_iter().peekable();
405        while keys.peek().is_some() {
406            let mut tx = Transaction::new(self);
407            for key in keys.by_ref().take(32) {
408                removed += u64::from(tx.remove_key(&key)?.is_some());
409            }
410            tx.commit()?;
411        }
412        Ok(removed)
413    }
414    pub fn clear(&mut self) -> Result<()> {
415        self.healthy()?;
416        let mut tx = Transaction::new(self);
417        tx.root.top = None;
418        tx.root.length = 0;
419        tx.root.cursor = record::HEADER_BYTES;
420        tx.root.free.fill(None);
421        tx.commit()
422    }
423    fn seek_path(&self, bound: &Bound<K>, forward: bool) -> Result<Vec<Frame>> {
424        self.healthy()?;
425        let mut path = Vec::new();
426        let mut pointer = self.root.borrow().top;
427        while let Some(p) = pointer {
428            ensure(
429                path.len() < MAX_DEPTH,
430                Error::Corrupt("map cursor exceeds height bound"),
431            )?;
432            let node = self.read_node(p, path.len())?;
433            let index = match bound {
434                Bound::Unbounded => {
435                    if forward {
436                        0
437                    } else {
438                        node.len()
439                    }
440                }
441                Bound::Included(k) => match node.search(k)? {
442                    Ok(i) => {
443                        if forward {
444                            i
445                        } else {
446                            i + 1
447                        }
448                    }
449                    Err(i) => i,
450                },
451                Bound::Excluded(k) => match node.search(k)? {
452                    Ok(i) => {
453                        if forward {
454                            i + 1
455                        } else {
456                            i
457                        }
458                    }
459                    Err(i) => i,
460                },
461            };
462            pointer = node.children.get(index).copied();
463            path.push(Frame {
464                node,
465                index,
466                descend: false,
467            });
468        }
469        Ok(path)
470    }
471    fn advance_path(
472        &self,
473        path: &mut Vec<Frame>,
474        forward: bool,
475        keys_only: bool,
476    ) -> Result<Option<(K, Option<Value>)>> {
477        self.healthy()?;
478        while let Some(frame) = path.last_mut() {
479            if frame.descend {
480                frame.descend = false;
481                let mut child = frame.node.children.get(frame.index).copied();
482                while let Some(p) = child {
483                    ensure(
484                        path.len() < MAX_DEPTH,
485                        Error::Corrupt("map cursor exceeds height bound"),
486                    )?;
487                    let node = self.read_node(p, path.len())?;
488                    let index = if forward { 0 } else { node.len() };
489                    child = node.children.get(index).copied();
490                    path.push(Frame {
491                        node,
492                        index,
493                        descend: false,
494                    });
495                }
496                continue;
497            }
498            let index = if forward {
499                frame.index
500            } else {
501                if frame.index == 0 {
502                    path.pop();
503                    continue;
504                }
505                frame.index - 1
506            };
507            if index >= frame.node.len() {
508                path.pop();
509                continue;
510            }
511            let bytes = frame.node.key_bytes(index);
512            K::BOUND.check(bytes);
513            let key = K::from_bytes(Cow::Borrowed(bytes));
514            let value = (!keys_only).then(|| frame.node.value(index));
515            frame.index = if forward { index + 1 } else { index };
516            // A caller may stop at this entry. Read the following subtree only
517            // when another step in this direction is actually requested.
518            frame.descend = !frame.node.children.is_empty();
519            return Ok(Some((key, value)));
520        }
521        Ok(None)
522    }
523    pub fn range(&self, bounds: impl RangeBounds<K>) -> TreeIter<'_, K, V, M> {
524        let lower = bounds.start_bound().cloned();
525        let upper = bounds.end_bound().cloned();
526        let invalid = match (&lower, &upper) {
527            (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => {
528                a > b
529                    || (a == b
530                        && matches!((&lower, &upper), (Bound::Excluded(_), Bound::Excluded(_))))
531            }
532            _ => false,
533        };
534        TreeIter {
535            tree: self,
536            lower,
537            upper,
538            front: None,
539            back: None,
540            exhausted: false,
541            invalid,
542            keys_only: false,
543        }
544    }
545    pub fn keys_range(
546        &self,
547        bounds: impl RangeBounds<K>,
548    ) -> impl DoubleEndedIterator<Item = K> + '_ {
549        let mut iter = self.range(bounds);
550        iter.keys_only = true;
551        iter.map(MapEntry::into_key)
552    }
553}
554struct Frame {
555    node: Rc<ReadNode>,
556    index: usize,
557    descend: bool,
558}
559fn decode<T: Storable>(bytes: Vec<u8>) -> Result<T> {
560    T::BOUND.check(&bytes);
561    Ok(T::from_bytes(Cow::Owned(bytes)))
562}
563
564type Split = Option<(Entry, Pointer)>;
565struct Transaction<'a, K, V, M: Memory> {
566    tree: &'a Tree<K, V, M>,
567    root: Root,
568    writes: BTreeMap<u64, Vec<u8>>,
569}
570impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> Transaction<'a, K, V, M> {
571    fn new(tree: &'a Tree<K, V, M>) -> Self {
572        Self {
573            tree,
574            root: tree.root.borrow().clone(),
575            writes: BTreeMap::new(),
576        }
577    }
578    fn remove_key(&mut self, key: &K) -> Result<Option<Vec<u8>>> {
579        let Some(top) = self.root.top else {
580            return Ok(None);
581        };
582        let (changed, old) = self.remove(top, key, 0)?;
583        let Some(old) = old else { return Ok(None) };
584
585        if let Some(node) = changed {
586            self.root.top = if node.entries.is_empty() {
587                self.free(top)?;
588                node.children.first().copied()
589            } else {
590                Some(self.save(Some(top), &node)?)
591            };
592        }
593        self.root.length -= 1;
594        Ok(Some(old))
595    }
596    fn bytes(&self, p: Pointer, magic: [u8; 8]) -> Result<Vec<u8>> {
597        p.check(self.root.cursor)?;
598        if let Some(bytes) = self.writes.get(&p.offset) {
599            Ok(bytes.clone())
600        } else {
601            record::read_bytes(&self.tree.memory, p.offset, p.capacity(), magic)
602        }
603    }
604    fn node(&self, p: Pointer, depth: usize) -> Result<Node> {
605        Ok(self.read_node(p, depth)?.owned())
606    }
607    fn read_node(&self, p: Pointer, depth: usize) -> Result<Rc<ReadNode>> {
608        if let Some(bytes) = self.writes.get(&p.offset) {
609            Ok(Rc::new(ReadNode::decode::<K, V>(
610                bytes.clone(),
611                self.root.cursor,
612                p.unit,
613            )?))
614        } else {
615            self.tree.read_node(p, depth)
616        }
617    }
618    fn value(&self, v: &Value) -> Result<Vec<u8>> {
619        let bytes = match v {
620            Value::Inline(b) => b.clone(),
621            Value::External(p) => {
622                p.check(self.root.cursor)?;
623                if let Some(bytes) = self.writes.get(&p.offset) {
624                    record::decode_payload(VALUE, bytes)?.to_vec()
625                } else {
626                    record::read_payload(&self.tree.memory, p.offset, p.capacity(), VALUE)?
627                }
628            }
629        };
630        V::BOUND.check(&bytes);
631        Ok(bytes)
632    }
633    fn free(&mut self, p: Pointer) -> Result<()> {
634        let index = usize::from(p.order);
635        self.writes.insert(
636            p.offset,
637            record::encode_payload(FREE, &link_bytes(self.root.free[index]))?,
638        );
639        self.root.free[index] = Some(p);
640        Ok(())
641    }
642    fn allocate(&mut self, order: usize) -> Result<Pointer> {
643        ensure(order < BINS, Error::Budget)?;
644        for bin in order..BINS {
645            if let Some(mut p) = self.root.free[bin] {
646                let next: Option<Pointer> = decode_link(
647                    record::decode_payload(FREE, &self.bytes(p, FREE)?)?,
648                    self.root.cursor,
649                    p.unit,
650                )?;
651                if let Some(next) = next {
652                    next.check(self.root.cursor)?;
653                    ensure(
654                        next.order == p.order && next != p,
655                        Error::Corrupt("map free-list link"),
656                    )?;
657                }
658                self.root.free[bin] = next;
659                // Return only the requested capacity. Each unused half remains
660                // an ordinary free-list block, staged with the same mutation.
661                while usize::from(p.order) > order {
662                    p.order -= 1;
663                    let sibling = Pointer {
664                        offset: p.offset + p.capacity(),
665                        ..p
666                    };
667                    self.free(sibling)?;
668                }
669                return Ok(p);
670            }
671        }
672        let p = Pointer {
673            offset: self.root.cursor,
674            order: u8::try_from(order).unwrap(),
675            unit: self.root.options.allocation_unit_bytes,
676        };
677        self.root.cursor = self
678            .root
679            .cursor
680            .checked_add(p.capacity())
681            .ok_or(Error::Budget)?;
682        Ok(p)
683    }
684    fn save_bytes(
685        &mut self,
686        previous: Option<Pointer>,
687        bytes: Vec<u8>,
688        minimum: usize,
689    ) -> Result<Pointer> {
690        let allocation_len = bytes.len().max(minimum);
691        let units = allocation_len.div_ceil(usize::from(self.root.options.allocation_unit_bytes));
692        let order = FIRST_ORDER + units.next_power_of_two().trailing_zeros() as usize;
693        let p = if let Some(p) = previous.filter(|p| p.capacity() >= allocation_len as u64) {
694            // Reclaim only into already reusable smaller capacity. Splitting the
695            // live block itself loses its large size class and causes unbounded
696            // growth under repeated large/small replacements without coalescing.
697            let smaller_available =
698                (order..usize::from(p.order)).any(|order| self.root.free[order].is_some());
699            if usize::from(p.order) >= order + 2 && smaller_available {
700                let smaller = self.allocate(order)?;
701                self.free(p)?;
702                smaller
703            } else {
704                p
705            }
706        } else {
707            if let Some(p) = previous {
708                self.free(p)?;
709            }
710            self.allocate(order)?
711        };
712        self.writes.insert(p.offset, bytes);
713        Ok(p)
714    }
715    fn save(&mut self, p: Option<Pointer>, node: &Node) -> Result<Pointer> {
716        self.save_node_bytes(p, node.encode()?)
717    }
718    fn save_node_bytes(&mut self, p: Option<Pointer>, bytes: Vec<u8>) -> Result<Pointer> {
719        let target = self.root.options.node_target_bytes;
720        let minimum = match (record::bound::<K>(), record::bound::<V>()) {
721            (Some((key, _)), Some((value, fixed))) => {
722                // Upstream targets 3/4 of a full bounded node. Size our own frame:
723                // header, child pointers, then length-prefixed keys and tagged values.
724                let value_bytes = if fixed && value > INLINE as u32 {
725                    9 // external pointer
726                } else {
727                    u64::from(value).min(INLINE as u64)
728                };
729                let full_node = record::PREFIX as u64
730                    + 2
731                    + (MAX_ENTRIES as u64 + 1) * 9
732                    + MAX_ENTRIES as u64 * (5 + u64::from(key) + value_bytes);
733                // Wide codec declarations alone should never force a large reservation.
734                (full_node * 3 / 4).min(u64::from(target)) as usize
735            }
736            _ => usize::from(target),
737        };
738        self.save_bytes(p, bytes, minimum)
739    }
740    fn save_value(&mut self, previous: Option<&Value>, bytes: Vec<u8>) -> Result<Value> {
741        let old = match previous {
742            Some(Value::External(p)) => Some(*p),
743            _ => None,
744        };
745        if bytes.len() <= INLINE {
746            if let Some(p) = old {
747                self.free(p)?;
748            }
749            Ok(Value::Inline(bytes))
750        } else {
751            Ok(Value::External(self.save_bytes(
752                old,
753                record::encode_payload(VALUE, &bytes)?,
754                0,
755            )?))
756        }
757    }
758    fn insert(
759        &mut self,
760        p: Option<Pointer>,
761        key: &K,
762        key_bytes: Vec<u8>,
763        bytes: Vec<u8>,
764        depth: usize,
765    ) -> Result<(Pointer, Split, Option<Vec<u8>>)> {
766        ensure(
767            depth < MAX_DEPTH,
768            Error::Corrupt("map path exceeds height bound"),
769        )?;
770        let read = p.map(|p| self.read_node(p, depth)).transpose()?;
771        let search = read.as_ref().map_or(Ok(Err(0)), |node| node.search(key))?;
772        let (mut node, old) = match search {
773            Ok(i) => {
774                let read = read.as_ref().unwrap();
775                let previous = read.value(i);
776                let old = self.value(&previous)?;
777                let value = self.save_value(Some(&previous), bytes)?;
778                let same_pointer =
779                    matches!((&previous,&value),(Value::External(a),Value::External(b)) if a==b);
780                if same_pointer {
781                    return Ok((p.unwrap(), None, Some(old)));
782                }
783                if let (Value::Inline(_), Value::Inline(bytes)) = (&previous, &value) {
784                    let next = self.save_node_bytes(p, read.replace_inline(i, bytes)?)?;
785                    return Ok((next, None, Some(old)));
786                }
787                let mut node = read.owned();
788                node.entries[i].value = value;
789                (node, Some(old))
790            }
791            Err(i) => {
792                if let Some(child) = read.as_ref().and_then(|node| node.children.get(i)).copied() {
793                    let (next, split, old) =
794                        self.insert(Some(child), key, key_bytes, bytes, depth + 1)?;
795                    if split.is_none() && next == child {
796                        return Ok((p.unwrap(), None, old));
797                    }
798                    let mut node = read.as_ref().unwrap().owned();
799                    node.children[i] = next;
800                    if let Some((entry, right)) = split {
801                        node.entries.insert(i, entry);
802                        node.children.insert(i + 1, right);
803                    }
804                    (node, old)
805                } else {
806                    let value = self.save_value(None, bytes)?;
807                    let mut node = read
808                        .as_ref()
809                        .map_or_else(Node::default, |node| node.owned());
810                    node.entries.insert(
811                        i,
812                        Entry {
813                            key: key_bytes,
814                            value,
815                        },
816                    );
817                    self.root.length = self.root.length.checked_add(1).ok_or(Error::Budget)?;
818                    (node, None)
819                }
820            }
821        };
822        let split = if node.entries.len() > MAX_ENTRIES {
823            let right_entries = node.entries.split_off(DEGREE + 1);
824            let median = node.entries.pop().unwrap();
825            let children = if node.children.is_empty() {
826                vec![]
827            } else {
828                node.children.split_off(DEGREE + 1)
829            };
830            let right = self.save(
831                None,
832                &Node {
833                    entries: right_entries,
834                    children,
835                },
836            )?;
837            Some((median, right))
838        } else {
839            None
840        };
841        Ok((self.save(p, &node)?, split, old))
842    }
843    // Return a modified node without encoding it: its parent may still repair
844    // an underflow. None means its persisted routing record remains unchanged.
845    fn remove(
846        &mut self,
847        p: Pointer,
848        key: &K,
849        depth: usize,
850    ) -> Result<(Option<Node>, Option<Vec<u8>>)> {
851        ensure(
852            depth < MAX_DEPTH,
853            Error::Corrupt("map path exceeds height bound"),
854        )?;
855        let read = self.read_node(p, depth)?;
856        match read.search(key)? {
857            Ok(i) => {
858                let mut node = read.owned();
859                let old = self.value(&node.entries[i].value)?;
860                if let Value::External(p) = node.entries[i].value {
861                    self.free(p)?;
862                }
863                if node.children.is_empty() {
864                    node.entries.remove(i);
865                } else {
866                    let child_pointer = node.children[i + 1];
867                    let (child, entry) = self.extract_min(child_pointer, depth + 1)?;
868                    node.entries[i] = entry;
869                    if let Some(child) = child {
870                        self.finish_child(&mut node, i + 1, child, depth)?;
871                    }
872                }
873                Ok((Some(node), Some(old)))
874            }
875            Err(i) => {
876                let Some(child_pointer) = read.children.get(i).copied() else {
877                    return Ok((None, None));
878                };
879                let (child, old) = self.remove(child_pointer, key, depth + 1)?;
880                let node = child
881                    .map(|child| self.changed_parent(&read, i, child, depth))
882                    .transpose()?
883                    .flatten();
884                Ok((node, old))
885            }
886        }
887    }
888    fn extract_min(&mut self, p: Pointer, depth: usize) -> Result<(Option<Node>, Entry)> {
889        ensure(
890            depth < MAX_DEPTH,
891            Error::Corrupt("map path exceeds height bound"),
892        )?;
893        let read = self.read_node(p, depth)?;
894        ensure(read.len() != 0, Error::Corrupt("empty successor node"))?;
895        if read.children.is_empty() {
896            let mut node = read.owned();
897            let entry = node.entries.remove(0);
898            Ok((Some(node), entry))
899        } else {
900            let (child, entry) = self.extract_min(read.children[0], depth + 1)?;
901            let node = child
902                .map(|child| self.changed_parent(&read, 0, child, depth))
903                .transpose()?
904                .flatten();
905            Ok((node, entry))
906        }
907    }
908    // Keep unchanged ancestors borrowed, including when the child was rewritten
909    // in place. Only a moved child or an underflow requires owning the parent.
910    fn changed_parent(
911        &mut self,
912        read: &ReadNode,
913        i: usize,
914        child: Node,
915        depth: usize,
916    ) -> Result<Option<Node>> {
917        if child.entries.len() >= MIN_ENTRIES {
918            let previous = read.children[i];
919            let next = self.save(Some(previous), &child)?;
920            if next == previous {
921                return Ok(None);
922            }
923            let mut parent = read.owned();
924            parent.children[i] = next;
925            Ok(Some(parent))
926        } else {
927            let mut parent = read.owned();
928            self.rebalance(&mut parent, i, child, depth)?;
929            Ok(Some(parent))
930        }
931    }
932    fn finish_child(
933        &mut self,
934        parent: &mut Node,
935        i: usize,
936        child: Node,
937        depth: usize,
938    ) -> Result<()> {
939        if child.entries.len() >= MIN_ENTRIES {
940            parent.children[i] = self.save(Some(parent.children[i]), &child)?;
941            Ok(())
942        } else {
943            self.rebalance(parent, i, child, depth)
944        }
945    }
946    fn rebalance(
947        &mut self,
948        parent: &mut Node,
949        i: usize,
950        mut child: Node,
951        parent_depth: usize,
952    ) -> Result<()> {
953        let depth = parent_depth + 1;
954        let p = parent.children[i];
955        let mut left = if i > 0 {
956            Some(self.node(parent.children[i - 1], depth)?)
957        } else {
958            None
959        };
960        if let Some(left) = &mut left {
961            ensure(
962                left.children.is_empty() == child.children.is_empty(),
963                Error::Corrupt("B-tree sibling levels"),
964            )?;
965            if left.entries.len() > MIN_ENTRIES {
966                child.entries.insert(
967                    0,
968                    std::mem::replace(&mut parent.entries[i - 1], left.entries.pop().unwrap()),
969                );
970                if let Some(p) = left.children.pop() {
971                    child.children.insert(0, p);
972                }
973                parent.children[i - 1] = self.save(Some(parent.children[i - 1]), left)?;
974                parent.children[i] = self.save(Some(p), &child)?;
975                return Ok(());
976            }
977        }
978        let mut right = if i + 1 < parent.children.len() {
979            Some(self.node(parent.children[i + 1], depth)?)
980        } else {
981            None
982        };
983        if let Some(right) = &mut right {
984            ensure(
985                right.children.is_empty() == child.children.is_empty(),
986                Error::Corrupt("B-tree sibling levels"),
987            )?;
988            if right.entries.len() > MIN_ENTRIES {
989                child.entries.push(std::mem::replace(
990                    &mut parent.entries[i],
991                    right.entries.remove(0),
992                ));
993                if !right.children.is_empty() {
994                    child.children.push(right.children.remove(0));
995                }
996                parent.children[i + 1] = self.save(Some(parent.children[i + 1]), right)?;
997                parent.children[i] = self.save(Some(p), &child)?;
998                return Ok(());
999            }
1000        }
1001        let (left_index, mut left, right) = if let Some(left) = left {
1002            (i - 1, left, child)
1003        } else {
1004            (
1005                i,
1006                child,
1007                right.ok_or(Error::Corrupt("B-tree missing separator"))?,
1008            )
1009        };
1010        ensure(
1011            left_index < parent.entries.len(),
1012            Error::Corrupt("B-tree missing separator"),
1013        )?;
1014        let left_p = parent.children[left_index];
1015        let right_p = parent.children[left_index + 1];
1016        left.entries.push(parent.entries.remove(left_index));
1017        left.entries.extend(right.entries);
1018        left.children.extend(right.children);
1019        self.free(right_p)?;
1020        parent.children[left_index] = self.save(Some(left_p), &left)?;
1021        parent.children.remove(left_index + 1);
1022        Ok(())
1023    }
1024    fn commit(self) -> Result<()> {
1025        let changed = self.root != *self.tree.root.borrow();
1026        let header = if changed {
1027            Some(self.root.encode()?)
1028        } else {
1029            None
1030        };
1031        if let Some(h) = &header {
1032            ensure(h.len() as u64 <= record::HEADER_BYTES, Error::Budget)?;
1033        }
1034        record::reserve(&self.tree.memory, self.root.cursor)?;
1035        self.tree.poisoned.set(true);
1036
1037        for (offset, bytes) in self.writes {
1038            self.tree.memory.write(offset, &bytes);
1039        }
1040        if let Some(h) = header {
1041            self.tree.memory.write(0, &h);
1042        }
1043        *self.tree.root.borrow_mut() = self.root;
1044        self.tree.poisoned.set(false);
1045        Ok(())
1046    }
1047}
1048///
1049/// `MapEntry`
1050///
1051/// An owned key and lazily decoded value from an ordered scan.
1052///
1053pub struct MapEntry<K, V> {
1054    key: K,
1055    bytes: Vec<u8>,
1056    value: PhantomData<V>,
1057}
1058impl<K, V: Storable> MapEntry<K, V> {
1059    /// Borrow the decoded key.
1060    pub const fn key(&self) -> &K {
1061        &self.key
1062    }
1063    /// Decode the value using its declared codec.
1064    ///
1065    /// # Panics
1066    /// Panics if the stored encoding violates the value codec or its bound.
1067    pub fn value(&self) -> V {
1068        V::BOUND.check(&self.bytes);
1069        V::from_bytes(Cow::Borrowed(&self.bytes))
1070    }
1071    /// Consume the entry and decode its value.
1072    ///
1073    /// # Panics
1074    /// Panics if the stored encoding violates the value codec or its bound.
1075    pub fn into_pair(self) -> (K, V) {
1076        (self.key, decode(self.bytes).expect("invalid map value"))
1077    }
1078    /// Consume the entry without decoding its value.
1079    pub fn into_key(self) -> K {
1080        self.key
1081    }
1082    /// Consume the entry and decode only its value.
1083    ///
1084    /// # Panics
1085    /// Panics if the stored encoding violates the value codec or its bound.
1086    pub fn into_value(self) -> V {
1087        decode(self.bytes).expect("invalid map value")
1088    }
1089}
1090
1091///
1092/// `TreeIter`
1093///
1094/// Lazy bidirectional traversal with bounded routing-node stacks. External values
1095/// are read only for in-range entries and decoded when requested by the caller.
1096///
1097pub struct TreeIter<'a, K, V, M: Memory> {
1098    tree: &'a Tree<K, V, M>,
1099    lower: Bound<K>,
1100    upper: Bound<K>,
1101    front: Option<Vec<Frame>>,
1102    back: Option<Vec<Frame>>,
1103    exhausted: bool,
1104    invalid: bool,
1105    keys_only: bool,
1106}
1107impl<K: Storable + Ord + Clone, V: Storable, M: Memory> TreeIter<'_, K, V, M> {
1108    fn step(&mut self, forward: bool) -> Result<Option<MapEntry<K, V>>> {
1109        ensure(!self.invalid, Error::Bounds)?;
1110        self.tree.healthy()?;
1111        let empty = match (&self.lower, &self.upper) {
1112            (Bound::Included(a), Bound::Included(b)) => a > b,
1113            (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => {
1114                a >= b
1115            }
1116            _ => false,
1117        };
1118        if empty {
1119            return Ok(None);
1120        }
1121        let (path, bound) = if forward {
1122            (&mut self.front, &self.lower)
1123        } else {
1124            (&mut self.back, &self.upper)
1125        };
1126        if path.is_none() {
1127            *path = Some(self.tree.seek_path(bound, forward)?);
1128        }
1129        let entry = self
1130            .tree
1131            .advance_path(path.as_mut().unwrap(), forward, self.keys_only)?;
1132        if let Some((key, value)) = entry {
1133            let after = match &self.lower {
1134                Bound::Unbounded => true,
1135                Bound::Included(k) => key >= *k,
1136                Bound::Excluded(k) => key > *k,
1137            };
1138            let before = match &self.upper {
1139                Bound::Unbounded => true,
1140                Bound::Included(k) => key <= *k,
1141                Bound::Excluded(k) => key < *k,
1142            };
1143            ensure(
1144                if forward { after } else { before },
1145                Error::Corrupt("map cursor key order"),
1146            )?;
1147            if !(after && before) {
1148                return Ok(None);
1149            }
1150            if forward {
1151                self.lower = Bound::Excluded(key.clone());
1152            } else {
1153                self.upper = Bound::Excluded(key.clone());
1154            }
1155            return Ok(Some(MapEntry {
1156                key,
1157                bytes: value
1158                    .map(|value| self.tree.value(value))
1159                    .transpose()?
1160                    .unwrap_or_default(),
1161                value: PhantomData,
1162            }));
1163        }
1164        Ok(None)
1165    }
1166    fn advance(&mut self, forward: bool) -> Option<Result<MapEntry<K, V>>> {
1167        if self.exhausted {
1168            return None;
1169        }
1170        match self.step(forward) {
1171            Ok(Some(entry)) => Some(Ok(entry)),
1172            Ok(None) => {
1173                self.exhausted = true;
1174                None
1175            }
1176            Err(error) => {
1177                self.exhausted = true;
1178                Some(Err(error))
1179            }
1180        }
1181    }
1182}
1183impl<K: Storable + Ord + Clone, V: Storable, M: Memory> Iterator for TreeIter<'_, K, V, M> {
1184    type Item = MapEntry<K, V>;
1185    fn next(&mut self) -> Option<Self::Item> {
1186        self.advance(true)
1187            .map(|entry| entry.expect("invalid map entry"))
1188    }
1189}
1190impl<K: Storable + Ord + Clone, V: Storable, M: Memory> DoubleEndedIterator
1191    for TreeIter<'_, K, V, M>
1192{
1193    fn next_back(&mut self) -> Option<Self::Item> {
1194        self.advance(false)
1195            .map(|entry| entry.expect("invalid map entry"))
1196    }
1197}
1198impl<K: Storable + Ord + Clone, V: Storable, M: Memory> std::iter::FusedIterator
1199    for TreeIter<'_, K, V, M>
1200{
1201}