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