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    pub fn visit_sorted_keys<E>(
312        &self,
313        keys: &[K],
314        mut visit: impl FnMut(&K, Option<V>) -> std::result::Result<(), E>,
315    ) -> Result<std::result::Result<(), E>> {
316        if let [key] = keys {
317            return Ok(visit(key, self.get(key)?));
318        }
319        self.healthy()?;
320        self.visit_subtree(self.root.borrow().top, 0, keys, &mut visit)
321    }
322
323    fn visit_subtree<E>(
324        &self,
325        pointer: Option<Pointer>,
326        depth: usize,
327        mut keys: &[K],
328        visit: &mut impl FnMut(&K, Option<V>) -> std::result::Result<(), E>,
329    ) -> Result<std::result::Result<(), E>> {
330        if keys.is_empty() {
331            return Ok(Ok(()));
332        }
333        let Some(pointer) = pointer else {
334            for key in keys {
335                if let Err(error) = visit(key, None) {
336                    return Ok(Err(error));
337                }
338            }
339            return Ok(Ok(()));
340        };
341        let node = self.read_node(pointer, depth)?;
342        // Partition at separators in ascending order. Start at the first requested
343        // slot so even a pair of distant probes only descends into relevant children.
344        let first = node.search(&keys[0])?.unwrap_or_else(|slot| slot);
345        for slot in first..node.len() {
346            let separator = K::from_bytes(Cow::Borrowed(node.key_bytes(slot)));
347            let split = keys.partition_point(|key| key < &separator);
348            if let Err(error) = self.visit_subtree(
349                node.children.get(slot).copied(),
350                depth + 1,
351                &keys[..split],
352                visit,
353            )? {
354                return Ok(Err(error));
355            }
356            keys = &keys[split..];
357            if keys.first() == Some(&separator) {
358                if let Err(error) = visit(&keys[0], Some(self.decode_hit(Rc::clone(&node), slot)?))
359                {
360                    return Ok(Err(error));
361                }
362                keys = &keys[1..];
363            }
364            if keys.is_empty() {
365                return Ok(Ok(()));
366            }
367        }
368        self.visit_subtree(node.children.last().copied(), depth + 1, keys, visit)
369    }
370    pub fn contains_key(&self, key: &K) -> Result<bool> {
371        Ok(self.find(key)?.is_some())
372    }
373    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>> {
374        self.healthy()?;
375        let key_bytes = key.to_bytes().into_owned();
376        K::BOUND.check(&key_bytes);
377        let bytes = value.into_bytes();
378        V::BOUND.check(&bytes);
379        let mut tx = Transaction::new(self);
380        let (top, split, old) = tx.insert(tx.root.top, &key, key_bytes, bytes, 0)?;
381        tx.root.top = Some(if let Some((entry, right)) = split {
382            tx.save(
383                None,
384                &Node {
385                    entries: vec![entry],
386                    children: vec![top, right],
387                },
388            )?
389        } else {
390            top
391        });
392        drop(key);
393        let old = old.map(decode).transpose()?;
394        tx.commit()?;
395        Ok(old)
396    }
397    pub fn remove(&mut self, key: &K) -> Result<Option<V>> {
398        self.healthy()?;
399        let mut tx = Transaction::new(self);
400        let old = tx.remove_key(key)?;
401        let value = old.map(decode).transpose()?;
402        tx.commit()?;
403        Ok(value)
404    }
405    pub fn remove_many(&mut self, keys: std::collections::BTreeSet<K>) -> Result<u64> {
406        self.healthy()?;
407        let mut removed = 0;
408        let mut keys = keys.into_iter().peekable();
409        while keys.peek().is_some() {
410            let mut tx = Transaction::new(self);
411            for key in keys.by_ref().take(32) {
412                removed += u64::from(tx.remove_key(&key)?.is_some());
413            }
414            tx.commit()?;
415        }
416        Ok(removed)
417    }
418    pub fn clear(&mut self) -> Result<()> {
419        self.healthy()?;
420        let mut tx = Transaction::new(self);
421        tx.root.top = None;
422        tx.root.length = 0;
423        tx.root.cursor = record::HEADER_BYTES;
424        tx.root.free.fill(None);
425        tx.commit()
426    }
427    fn seek_path(&self, bound: &Bound<K>, forward: bool) -> Result<Vec<Frame>> {
428        self.healthy()?;
429        let mut path = Vec::new();
430        let mut pointer = self.root.borrow().top;
431        while let Some(p) = pointer {
432            ensure(
433                path.len() < MAX_DEPTH,
434                Error::Corrupt("map cursor exceeds height bound"),
435            )?;
436            let node = self.read_node(p, path.len())?;
437            let index = match bound {
438                Bound::Unbounded => {
439                    if forward {
440                        0
441                    } else {
442                        node.len()
443                    }
444                }
445                Bound::Included(k) => match node.search(k)? {
446                    Ok(i) => {
447                        if forward {
448                            i
449                        } else {
450                            i + 1
451                        }
452                    }
453                    Err(i) => i,
454                },
455                Bound::Excluded(k) => match node.search(k)? {
456                    Ok(i) => {
457                        if forward {
458                            i + 1
459                        } else {
460                            i
461                        }
462                    }
463                    Err(i) => i,
464                },
465            };
466            pointer = node.children.get(index).copied();
467            path.push(Frame {
468                node,
469                index,
470                descend: false,
471            });
472        }
473        Ok(path)
474    }
475    fn advance_path(
476        &self,
477        path: &mut Vec<Frame>,
478        forward: bool,
479        keys_only: bool,
480    ) -> Result<Option<(K, Option<Value>)>> {
481        self.healthy()?;
482        while let Some(frame) = path.last_mut() {
483            if frame.descend {
484                frame.descend = false;
485                let mut child = frame.node.children.get(frame.index).copied();
486                while let Some(p) = child {
487                    ensure(
488                        path.len() < MAX_DEPTH,
489                        Error::Corrupt("map cursor exceeds height bound"),
490                    )?;
491                    let node = self.read_node(p, path.len())?;
492                    let index = if forward { 0 } else { node.len() };
493                    child = node.children.get(index).copied();
494                    path.push(Frame {
495                        node,
496                        index,
497                        descend: false,
498                    });
499                }
500                continue;
501            }
502            let index = if forward {
503                frame.index
504            } else {
505                if frame.index == 0 {
506                    path.pop();
507                    continue;
508                }
509                frame.index - 1
510            };
511            if index >= frame.node.len() {
512                path.pop();
513                continue;
514            }
515            let bytes = frame.node.key_bytes(index);
516            K::BOUND.check(bytes);
517            let key = K::from_bytes(Cow::Borrowed(bytes));
518            let value = (!keys_only).then(|| frame.node.value(index));
519            frame.index = if forward { index + 1 } else { index };
520            // A caller may stop at this entry. Read the following subtree only
521            // when another step in this direction is actually requested.
522            frame.descend = !frame.node.children.is_empty();
523            return Ok(Some((key, value)));
524        }
525        Ok(None)
526    }
527    pub fn range(&self, bounds: impl RangeBounds<K>) -> TreeIter<'_, K, V, M> {
528        let lower = bounds.start_bound().cloned();
529        let upper = bounds.end_bound().cloned();
530        let invalid = match (&lower, &upper) {
531            (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => {
532                a > b
533                    || (a == b
534                        && matches!((&lower, &upper), (Bound::Excluded(_), Bound::Excluded(_))))
535            }
536            _ => false,
537        };
538        TreeIter {
539            tree: self,
540            lower,
541            upper,
542            front: None,
543            back: None,
544            exhausted: false,
545            invalid,
546            keys_only: false,
547        }
548    }
549    pub fn keys_range(
550        &self,
551        bounds: impl RangeBounds<K>,
552    ) -> impl DoubleEndedIterator<Item = K> + '_ {
553        let mut iter = self.range(bounds);
554        iter.keys_only = true;
555        iter.map(MapEntry::into_key)
556    }
557}
558struct Frame {
559    node: Rc<ReadNode>,
560    index: usize,
561    descend: bool,
562}
563fn decode<T: Storable>(bytes: Vec<u8>) -> Result<T> {
564    T::BOUND.check(&bytes);
565    Ok(T::from_bytes(Cow::Owned(bytes)))
566}
567
568type Split = Option<(Entry, Pointer)>;
569struct Transaction<'a, K, V, M: Memory> {
570    tree: &'a Tree<K, V, M>,
571    root: Root,
572    writes: BTreeMap<u64, Vec<u8>>,
573}
574impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> Transaction<'a, K, V, M> {
575    fn new(tree: &'a Tree<K, V, M>) -> Self {
576        Self {
577            tree,
578            root: tree.root.borrow().clone(),
579            writes: BTreeMap::new(),
580        }
581    }
582    fn remove_key(&mut self, key: &K) -> Result<Option<Vec<u8>>> {
583        let Some(top) = self.root.top else {
584            return Ok(None);
585        };
586        let (changed, old) = self.remove(top, key, 0)?;
587        let Some(old) = old else { return Ok(None) };
588
589        if let Some(node) = changed {
590            self.root.top = if node.entries.is_empty() {
591                self.free(top)?;
592                node.children.first().copied()
593            } else {
594                Some(self.save(Some(top), &node)?)
595            };
596        }
597        self.root.length -= 1;
598        Ok(Some(old))
599    }
600    fn bytes(&self, p: Pointer, magic: [u8; 8]) -> Result<Vec<u8>> {
601        p.check(self.root.cursor)?;
602        if let Some(bytes) = self.writes.get(&p.offset) {
603            Ok(bytes.clone())
604        } else {
605            record::read_bytes(&self.tree.memory, p.offset, p.capacity(), magic)
606        }
607    }
608    fn node(&self, p: Pointer, depth: usize) -> Result<Node> {
609        Ok(self.read_node(p, depth)?.owned())
610    }
611    fn read_node(&self, p: Pointer, depth: usize) -> Result<Rc<ReadNode>> {
612        if let Some(bytes) = self.writes.get(&p.offset) {
613            Ok(Rc::new(ReadNode::decode::<K, V>(
614                bytes.clone(),
615                self.root.cursor,
616                p.unit,
617            )?))
618        } else {
619            self.tree.read_node(p, depth)
620        }
621    }
622    fn value(&self, v: &Value) -> Result<Vec<u8>> {
623        let bytes = match v {
624            Value::Inline(b) => b.clone(),
625            Value::External(p) => {
626                p.check(self.root.cursor)?;
627                if let Some(bytes) = self.writes.get(&p.offset) {
628                    record::decode_payload(VALUE, bytes)?.to_vec()
629                } else {
630                    record::read_payload(&self.tree.memory, p.offset, p.capacity(), VALUE)?
631                }
632            }
633        };
634        V::BOUND.check(&bytes);
635        Ok(bytes)
636    }
637    fn free(&mut self, p: Pointer) -> Result<()> {
638        let index = usize::from(p.order);
639        self.writes.insert(
640            p.offset,
641            record::encode_payload(FREE, &link_bytes(self.root.free[index]))?,
642        );
643        self.root.free[index] = Some(p);
644        Ok(())
645    }
646    fn allocate(&mut self, order: usize) -> Result<Pointer> {
647        ensure(order < BINS, Error::Budget)?;
648        for bin in order..BINS {
649            if let Some(mut p) = self.root.free[bin] {
650                let next: Option<Pointer> = decode_link(
651                    record::decode_payload(FREE, &self.bytes(p, FREE)?)?,
652                    self.root.cursor,
653                    p.unit,
654                )?;
655                if let Some(next) = next {
656                    next.check(self.root.cursor)?;
657                    ensure(
658                        next.order == p.order && next != p,
659                        Error::Corrupt("map free-list link"),
660                    )?;
661                }
662                self.root.free[bin] = next;
663                // Return only the requested capacity. Each unused half remains
664                // an ordinary free-list block, staged with the same mutation.
665                while usize::from(p.order) > order {
666                    p.order -= 1;
667                    let sibling = Pointer {
668                        offset: p.offset + p.capacity(),
669                        ..p
670                    };
671                    self.free(sibling)?;
672                }
673                return Ok(p);
674            }
675        }
676        let p = Pointer {
677            offset: self.root.cursor,
678            order: u8::try_from(order).unwrap(),
679            unit: self.root.options.allocation_unit_bytes,
680        };
681        self.root.cursor = self
682            .root
683            .cursor
684            .checked_add(p.capacity())
685            .ok_or(Error::Budget)?;
686        Ok(p)
687    }
688    fn save_bytes(
689        &mut self,
690        previous: Option<Pointer>,
691        bytes: Vec<u8>,
692        minimum: usize,
693    ) -> Result<Pointer> {
694        let allocation_len = bytes.len().max(minimum);
695        let units = allocation_len.div_ceil(usize::from(self.root.options.allocation_unit_bytes));
696        let order = FIRST_ORDER + units.next_power_of_two().trailing_zeros() as usize;
697        let p = if let Some(p) = previous.filter(|p| p.capacity() >= allocation_len as u64) {
698            // Reclaim only into already reusable smaller capacity. Splitting the
699            // live block itself loses its large size class and causes unbounded
700            // growth under repeated large/small replacements without coalescing.
701            let smaller_available =
702                (order..usize::from(p.order)).any(|order| self.root.free[order].is_some());
703            if usize::from(p.order) >= order + 2 && smaller_available {
704                let smaller = self.allocate(order)?;
705                self.free(p)?;
706                smaller
707            } else {
708                p
709            }
710        } else {
711            if let Some(p) = previous {
712                self.free(p)?;
713            }
714            self.allocate(order)?
715        };
716        self.writes.insert(p.offset, bytes);
717        Ok(p)
718    }
719    fn save(&mut self, p: Option<Pointer>, node: &Node) -> Result<Pointer> {
720        self.save_node_bytes(p, node.encode()?)
721    }
722    fn save_node_bytes(&mut self, p: Option<Pointer>, bytes: Vec<u8>) -> Result<Pointer> {
723        let target = self.root.options.node_target_bytes;
724        let minimum = match (record::bound::<K>(), record::bound::<V>()) {
725            (Some((key, _)), Some((value, fixed))) => {
726                // Upstream targets 3/4 of a full bounded node. Size our own frame:
727                // header, child pointers, then length-prefixed keys and tagged values.
728                let value_bytes = if fixed && value > INLINE as u32 {
729                    9 // external pointer
730                } else {
731                    u64::from(value).min(INLINE as u64)
732                };
733                let full_node = record::PREFIX as u64
734                    + 2
735                    + (MAX_ENTRIES as u64 + 1) * 9
736                    + MAX_ENTRIES as u64 * (5 + u64::from(key) + value_bytes);
737                // Wide codec declarations alone should never force a large reservation.
738                (full_node * 3 / 4).min(u64::from(target)) as usize
739            }
740            _ => usize::from(target),
741        };
742        self.save_bytes(p, bytes, minimum)
743    }
744    fn save_value(&mut self, previous: Option<&Value>, bytes: Vec<u8>) -> Result<Value> {
745        let old = match previous {
746            Some(Value::External(p)) => Some(*p),
747            _ => None,
748        };
749        if bytes.len() <= INLINE {
750            if let Some(p) = old {
751                self.free(p)?;
752            }
753            Ok(Value::Inline(bytes))
754        } else {
755            Ok(Value::External(self.save_bytes(
756                old,
757                record::encode_payload(VALUE, &bytes)?,
758                0,
759            )?))
760        }
761    }
762    fn insert(
763        &mut self,
764        p: Option<Pointer>,
765        key: &K,
766        key_bytes: Vec<u8>,
767        bytes: Vec<u8>,
768        depth: usize,
769    ) -> Result<(Pointer, Split, Option<Vec<u8>>)> {
770        ensure(
771            depth < MAX_DEPTH,
772            Error::Corrupt("map path exceeds height bound"),
773        )?;
774        let read = p.map(|p| self.read_node(p, depth)).transpose()?;
775        let search = read.as_ref().map_or(Ok(Err(0)), |node| node.search(key))?;
776        let (mut node, old) = match search {
777            Ok(i) => {
778                let read = read.as_ref().unwrap();
779                let previous = read.value(i);
780                let old = self.value(&previous)?;
781                let value = self.save_value(Some(&previous), bytes)?;
782                let same_pointer =
783                    matches!((&previous,&value),(Value::External(a),Value::External(b)) if a==b);
784                if same_pointer {
785                    return Ok((p.unwrap(), None, Some(old)));
786                }
787                if let (Value::Inline(_), Value::Inline(bytes)) = (&previous, &value) {
788                    let next = self.save_node_bytes(p, read.replace_inline(i, bytes)?)?;
789                    return Ok((next, None, Some(old)));
790                }
791                let mut node = read.owned();
792                node.entries[i].value = value;
793                (node, Some(old))
794            }
795            Err(i) => {
796                if let Some(child) = read.as_ref().and_then(|node| node.children.get(i)).copied() {
797                    let (next, split, old) =
798                        self.insert(Some(child), key, key_bytes, bytes, depth + 1)?;
799                    if split.is_none() && next == child {
800                        return Ok((p.unwrap(), None, old));
801                    }
802                    let mut node = read.as_ref().unwrap().owned();
803                    node.children[i] = next;
804                    if let Some((entry, right)) = split {
805                        node.entries.insert(i, entry);
806                        node.children.insert(i + 1, right);
807                    }
808                    (node, old)
809                } else {
810                    let value = self.save_value(None, bytes)?;
811                    let mut node = read
812                        .as_ref()
813                        .map_or_else(Node::default, |node| node.owned());
814                    node.entries.insert(
815                        i,
816                        Entry {
817                            key: key_bytes,
818                            value,
819                        },
820                    );
821                    self.root.length = self.root.length.checked_add(1).ok_or(Error::Budget)?;
822                    (node, None)
823                }
824            }
825        };
826        let split = if node.entries.len() > MAX_ENTRIES {
827            let right_entries = node.entries.split_off(DEGREE + 1);
828            let median = node.entries.pop().unwrap();
829            let children = if node.children.is_empty() {
830                vec![]
831            } else {
832                node.children.split_off(DEGREE + 1)
833            };
834            let right = self.save(
835                None,
836                &Node {
837                    entries: right_entries,
838                    children,
839                },
840            )?;
841            Some((median, right))
842        } else {
843            None
844        };
845        Ok((self.save(p, &node)?, split, old))
846    }
847    // Return a modified node without encoding it: its parent may still repair
848    // an underflow. None means its persisted routing record remains unchanged.
849    fn remove(
850        &mut self,
851        p: Pointer,
852        key: &K,
853        depth: usize,
854    ) -> Result<(Option<Node>, Option<Vec<u8>>)> {
855        ensure(
856            depth < MAX_DEPTH,
857            Error::Corrupt("map path exceeds height bound"),
858        )?;
859        let read = self.read_node(p, depth)?;
860        match read.search(key)? {
861            Ok(i) => {
862                let mut node = read.owned();
863                let old = self.value(&node.entries[i].value)?;
864                if let Value::External(p) = node.entries[i].value {
865                    self.free(p)?;
866                }
867                if node.children.is_empty() {
868                    node.entries.remove(i);
869                } else {
870                    let child_pointer = node.children[i + 1];
871                    let (child, entry) = self.extract_min(child_pointer, depth + 1)?;
872                    node.entries[i] = entry;
873                    if let Some(child) = child {
874                        self.finish_child(&mut node, i + 1, child, depth)?;
875                    }
876                }
877                Ok((Some(node), Some(old)))
878            }
879            Err(i) => {
880                let Some(child_pointer) = read.children.get(i).copied() else {
881                    return Ok((None, None));
882                };
883                let (child, old) = self.remove(child_pointer, key, depth + 1)?;
884                let node = child
885                    .map(|child| self.changed_parent(&read, i, child, depth))
886                    .transpose()?
887                    .flatten();
888                Ok((node, old))
889            }
890        }
891    }
892    fn extract_min(&mut self, p: Pointer, depth: usize) -> Result<(Option<Node>, Entry)> {
893        ensure(
894            depth < MAX_DEPTH,
895            Error::Corrupt("map path exceeds height bound"),
896        )?;
897        let read = self.read_node(p, depth)?;
898        ensure(read.len() != 0, Error::Corrupt("empty successor node"))?;
899        if read.children.is_empty() {
900            let mut node = read.owned();
901            let entry = node.entries.remove(0);
902            Ok((Some(node), entry))
903        } else {
904            let (child, entry) = self.extract_min(read.children[0], depth + 1)?;
905            let node = child
906                .map(|child| self.changed_parent(&read, 0, child, depth))
907                .transpose()?
908                .flatten();
909            Ok((node, entry))
910        }
911    }
912    // Keep unchanged ancestors borrowed, including when the child was rewritten
913    // in place. Only a moved child or an underflow requires owning the parent.
914    fn changed_parent(
915        &mut self,
916        read: &ReadNode,
917        i: usize,
918        child: Node,
919        depth: usize,
920    ) -> Result<Option<Node>> {
921        if child.entries.len() >= MIN_ENTRIES {
922            let previous = read.children[i];
923            let next = self.save(Some(previous), &child)?;
924            if next == previous {
925                return Ok(None);
926            }
927            let mut parent = read.owned();
928            parent.children[i] = next;
929            Ok(Some(parent))
930        } else {
931            let mut parent = read.owned();
932            self.rebalance(&mut parent, i, child, depth)?;
933            Ok(Some(parent))
934        }
935    }
936    fn finish_child(
937        &mut self,
938        parent: &mut Node,
939        i: usize,
940        child: Node,
941        depth: usize,
942    ) -> Result<()> {
943        if child.entries.len() >= MIN_ENTRIES {
944            parent.children[i] = self.save(Some(parent.children[i]), &child)?;
945            Ok(())
946        } else {
947            self.rebalance(parent, i, child, depth)
948        }
949    }
950    fn rebalance(
951        &mut self,
952        parent: &mut Node,
953        i: usize,
954        mut child: Node,
955        parent_depth: usize,
956    ) -> Result<()> {
957        let depth = parent_depth + 1;
958        let p = parent.children[i];
959        let mut left = if i > 0 {
960            Some(self.node(parent.children[i - 1], depth)?)
961        } else {
962            None
963        };
964        if let Some(left) = &mut left {
965            ensure(
966                left.children.is_empty() == child.children.is_empty(),
967                Error::Corrupt("B-tree sibling levels"),
968            )?;
969            if left.entries.len() > MIN_ENTRIES {
970                child.entries.insert(
971                    0,
972                    std::mem::replace(&mut parent.entries[i - 1], left.entries.pop().unwrap()),
973                );
974                if let Some(p) = left.children.pop() {
975                    child.children.insert(0, p);
976                }
977                parent.children[i - 1] = self.save(Some(parent.children[i - 1]), left)?;
978                parent.children[i] = self.save(Some(p), &child)?;
979                return Ok(());
980            }
981        }
982        let mut right = if i + 1 < parent.children.len() {
983            Some(self.node(parent.children[i + 1], depth)?)
984        } else {
985            None
986        };
987        if let Some(right) = &mut right {
988            ensure(
989                right.children.is_empty() == child.children.is_empty(),
990                Error::Corrupt("B-tree sibling levels"),
991            )?;
992            if right.entries.len() > MIN_ENTRIES {
993                child.entries.push(std::mem::replace(
994                    &mut parent.entries[i],
995                    right.entries.remove(0),
996                ));
997                if !right.children.is_empty() {
998                    child.children.push(right.children.remove(0));
999                }
1000                parent.children[i + 1] = self.save(Some(parent.children[i + 1]), right)?;
1001                parent.children[i] = self.save(Some(p), &child)?;
1002                return Ok(());
1003            }
1004        }
1005        let (left_index, mut left, right) = if let Some(left) = left {
1006            (i - 1, left, child)
1007        } else {
1008            (
1009                i,
1010                child,
1011                right.ok_or(Error::Corrupt("B-tree missing separator"))?,
1012            )
1013        };
1014        ensure(
1015            left_index < parent.entries.len(),
1016            Error::Corrupt("B-tree missing separator"),
1017        )?;
1018        let left_p = parent.children[left_index];
1019        let right_p = parent.children[left_index + 1];
1020        left.entries.push(parent.entries.remove(left_index));
1021        left.entries.extend(right.entries);
1022        left.children.extend(right.children);
1023        self.free(right_p)?;
1024        parent.children[left_index] = self.save(Some(left_p), &left)?;
1025        parent.children.remove(left_index + 1);
1026        Ok(())
1027    }
1028    fn commit(self) -> Result<()> {
1029        let changed = self.root != *self.tree.root.borrow();
1030        let header = if changed {
1031            Some(self.root.encode()?)
1032        } else {
1033            None
1034        };
1035        if let Some(h) = &header {
1036            ensure(h.len() as u64 <= record::HEADER_BYTES, Error::Budget)?;
1037        }
1038        record::reserve(&self.tree.memory, self.root.cursor)?;
1039        self.tree.poisoned.set(true);
1040
1041        for (offset, bytes) in self.writes {
1042            self.tree.memory.write(offset, &bytes);
1043        }
1044        if let Some(h) = header {
1045            self.tree.memory.write(0, &h);
1046        }
1047        *self.tree.root.borrow_mut() = self.root;
1048        self.tree.poisoned.set(false);
1049        Ok(())
1050    }
1051}
1052///
1053/// `MapEntry`
1054///
1055/// An owned key and lazily decoded value from an ordered scan.
1056///
1057pub struct MapEntry<K, V> {
1058    key: K,
1059    bytes: Vec<u8>,
1060    value: PhantomData<V>,
1061}
1062impl<K, V: Storable> MapEntry<K, V> {
1063    /// Borrow the decoded key.
1064    pub const fn key(&self) -> &K {
1065        &self.key
1066    }
1067    /// Decode the value using its declared codec.
1068    ///
1069    /// # Panics
1070    /// Panics if the stored encoding violates the value codec or its bound.
1071    pub fn value(&self) -> V {
1072        V::BOUND.check(&self.bytes);
1073        V::from_bytes(Cow::Borrowed(&self.bytes))
1074    }
1075    /// Consume the entry and decode its value.
1076    ///
1077    /// # Panics
1078    /// Panics if the stored encoding violates the value codec or its bound.
1079    pub fn into_pair(self) -> (K, V) {
1080        (self.key, decode(self.bytes).expect("invalid map value"))
1081    }
1082    /// Consume the entry without decoding its value.
1083    pub fn into_key(self) -> K {
1084        self.key
1085    }
1086    /// Consume the entry and decode only its value.
1087    ///
1088    /// # Panics
1089    /// Panics if the stored encoding violates the value codec or its bound.
1090    pub fn into_value(self) -> V {
1091        decode(self.bytes).expect("invalid map value")
1092    }
1093}
1094
1095///
1096/// `TreeIter`
1097///
1098/// Lazy bidirectional traversal with bounded routing-node stacks. External values
1099/// are read only for in-range entries and decoded when requested by the caller.
1100///
1101pub struct TreeIter<'a, K, V, M: Memory> {
1102    tree: &'a Tree<K, V, M>,
1103    lower: Bound<K>,
1104    upper: Bound<K>,
1105    front: Option<Vec<Frame>>,
1106    back: Option<Vec<Frame>>,
1107    exhausted: bool,
1108    invalid: bool,
1109    keys_only: bool,
1110}
1111impl<K: Storable + Ord + Clone, V: Storable, M: Memory> TreeIter<'_, K, V, M> {
1112    /// Consume the next key at the front, skipping its external value.
1113    /// Subsequent entry or key reads continue from the updated range.
1114    ///
1115    /// # Panics
1116    /// Panics on invalid bounds, backing, routing record integrity or key codec failure.
1117    pub fn next_key(&mut self) -> Option<K> {
1118        self.advance(true, true).map(MapEntry::into_key)
1119    }
1120
1121    /// Consume the next key at the back, skipping its external value.
1122    ///
1123    /// # Panics
1124    /// Panics on invalid bounds, backing, routing record integrity or key codec failure.
1125    pub fn next_back_key(&mut self) -> Option<K> {
1126        self.advance(false, true).map(MapEntry::into_key)
1127    }
1128
1129    fn step(&mut self, forward: bool, keys_only: bool) -> Result<Option<MapEntry<K, V>>> {
1130        ensure(!self.invalid, Error::Bounds)?;
1131        self.tree.healthy()?;
1132        let empty = match (&self.lower, &self.upper) {
1133            (Bound::Included(a), Bound::Included(b)) => a > b,
1134            (Bound::Included(a) | Bound::Excluded(a), Bound::Included(b) | Bound::Excluded(b)) => {
1135                a >= b
1136            }
1137            _ => false,
1138        };
1139        if empty {
1140            return Ok(None);
1141        }
1142        let (path, bound) = if forward {
1143            (&mut self.front, &self.lower)
1144        } else {
1145            (&mut self.back, &self.upper)
1146        };
1147        if path.is_none() {
1148            *path = Some(self.tree.seek_path(bound, forward)?);
1149        }
1150        let entry = self
1151            .tree
1152            .advance_path(path.as_mut().unwrap(), forward, keys_only)?;
1153        if let Some((key, value)) = entry {
1154            let after = match &self.lower {
1155                Bound::Unbounded => true,
1156                Bound::Included(k) => key >= *k,
1157                Bound::Excluded(k) => key > *k,
1158            };
1159            let before = match &self.upper {
1160                Bound::Unbounded => true,
1161                Bound::Included(k) => key <= *k,
1162                Bound::Excluded(k) => key < *k,
1163            };
1164            ensure(
1165                if forward { after } else { before },
1166                Error::Corrupt("map cursor key order"),
1167            )?;
1168            if !(after && before) {
1169                return Ok(None);
1170            }
1171            if forward {
1172                self.lower = Bound::Excluded(key.clone());
1173            } else {
1174                self.upper = Bound::Excluded(key.clone());
1175            }
1176            return Ok(Some(MapEntry {
1177                key,
1178                bytes: value
1179                    .map(|value| self.tree.value(value))
1180                    .transpose()?
1181                    .unwrap_or_default(),
1182                value: PhantomData,
1183            }));
1184        }
1185        Ok(None)
1186    }
1187    fn advance(&mut self, forward: bool, keys_only: bool) -> Option<MapEntry<K, V>> {
1188        if self.exhausted {
1189            return None;
1190        }
1191        match self.step(forward, keys_only) {
1192            Ok(Some(entry)) => Some(entry),
1193            Ok(None) => {
1194                self.exhausted = true;
1195                None
1196            }
1197            Err(error) => {
1198                self.exhausted = true;
1199                panic!("invalid map entry: {error:?}")
1200            }
1201        }
1202    }
1203}
1204impl<K: Storable + Ord + Clone, V: Storable, M: Memory> Iterator for TreeIter<'_, K, V, M> {
1205    type Item = MapEntry<K, V>;
1206    fn next(&mut self) -> Option<Self::Item> {
1207        self.advance(true, self.keys_only)
1208    }
1209}
1210impl<K: Storable + Ord + Clone, V: Storable, M: Memory> DoubleEndedIterator
1211    for TreeIter<'_, K, V, M>
1212{
1213    fn next_back(&mut self) -> Option<Self::Item> {
1214        self.advance(false, self.keys_only)
1215    }
1216}
1217impl<K: Storable + Ord + Clone, V: Storable, M: Memory> std::iter::FusedIterator
1218    for TreeIter<'_, K, V, M>
1219{
1220}